diff --git a/.config/nextest-guests.toml b/.config/nextest-guests.toml new file mode 100644 index 0000000000..4a97fd855c --- /dev/null +++ b/.config/nextest-guests.toml @@ -0,0 +1,25 @@ +# The extension guests' nextest profiles (ADR 0393 D1). Each guest is its own workspace, so nextest finds no +# config of its own: the gate's `guests` check prefixes this file with a `[store]` table (the repository root's +# `target/nextest`) and appends a `[profile.

.junit]` path per guest, then passes the result with +# `--config-file`. The bodies are `.config/nextest.toml`'s, line for line (a gate test holds them in step); its package +# overrides and JUnit tables stay there (they name root packages, and nextest refuses to parse them against a guest +# manifest). + +[profile.default] +retries = 0 +fail-fast = true +slow-timeout = { period = "30s", terminate-after = 2 } +status-level = "fail" + +[profile.ci] +retries = 1 +fail-fast = false +slow-timeout = { period = "60s", terminate-after = 3 } +status-level = "all" + +[profile.gate] +retries = 0 +fail-fast = false +slow-timeout = { period = "60s", terminate-after = 3 } +status-level = "fail" +final-status-level = "slow" diff --git a/.config/nextest.toml b/.config/nextest.toml index 1a2911935f..df9bae2095 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -38,6 +38,19 @@ path = "junit.xml" filter = "package(specforge-cli) & test(=extension_authoring::a_scaffolded_extension_builds_and_validates)" slow-timeout = { period = "60s", terminate-after = 10 } +# Applies one edit plan of as many creates as the `gsd import` operation cap +# (`MAX_OPS` in gsd/import/src/limits.rs, ADR 0391 D9): ~38 s at 2,000 on an +# idle machine, past the default 60 s bound when loaded. +[[profile.default.overrides]] +filter = "package(specforge-ops) & test(=plans::one_plan_of_many_creates_applies)" +slow-timeout = { period = "60s", terminate-after = 3 } + +# The X2 floor's negative control (ADR 0393 D8) collects the ledger twice with +# the real specforge: a cold wasm compile of the packs. +[[profile.default.overrides]] +filter = "package(gate) & test(=dogfood::tests::x2_floor_fails_a_ledger_copy_missing_one_case)" +slow-timeout = { period = "120s", terminate-after = 3 } + # absorb's end-to-end tests load `@gsd/core` and the old builtins cold on a # Windows runner, where a compile takes longer than the default kill bound # allows (ADR 0375 D4). Windows only: the Linux and macOS bounds are unchanged. diff --git a/.github/workflows/bootstrap.yml b/.github/workflows/bootstrap.yml index 9841ae75d7..48d67fa6eb 100644 --- a/.github/workflows/bootstrap.yml +++ b/.github/workflows/bootstrap.yml @@ -2,7 +2,7 @@ name: Bootstrap # A cold clone rebuilds every committed blob. It takes ~8 min uncached, so a PR runs it only when what the blobs # compile from changes (the paths every `inputs.json` records, plus the build tooling); main runs it on every push. -# A gsd input runs it too: `gsd/core/**`, `gsd/kit/**`, `gsd/.cargo/**` (the SDK patch) and `gsd/Cargo.lock`, which +# A gsd input runs it too: `gsd/core/**`, `gsd/import/**`, `gsd/kit/**`, `gsd/.cargo/**` (the SDK patch) and `gsd/Cargo.lock`, which # `@gsd/core`'s record hashes whole. A gate test holds these paths to every input any record lists. # A PR that misses it still has the `builtins` check (ci.yml), which compares each blob's recorded inputs. on: @@ -21,6 +21,7 @@ on: - "fixtures/**" - "examples/marketing/extension/**" - "gsd/core/**" + - "gsd/import/**" - "gsd/kit/**" - "gsd/Cargo.lock" - "gsd/.cargo/**" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 020766d0a8..faf3986284 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -111,6 +111,23 @@ jobs: # A PR runs the checks its diff reaches (quick's triggers); main runs the whole list. - name: Run the shard's checks run: cargo gate ci --only ${{ matrix.checks }} ${{ github.event_name == 'pull_request' && format('--since origin/{0}', github.base_ref) || '' }} + # The artifact's name is its directory, so the dogfood job's download lands where a local run writes (ADR 0393 D2). + - name: Keep the guests' JUnit reports for dogfood + if: github.event_name == 'push' && matrix.shard == 'specs' + uses: actions/upload-artifact@v4 + with: + name: junit-guests + path: target/nextest/ci/junit-guests + if-no-files-found: error + retention-days: 1 + - name: Keep the gsd JUnit report for dogfood + if: github.event_name == 'push' && matrix.shard == 'gsd' + uses: actions/upload-artifact@v4 + with: + name: junit-gsd + path: target/nextest/ci/junit-gsd + if-no-files-found: error + retention-days: 1 - name: Build-time budget shell: bash run: | @@ -375,8 +392,9 @@ jobs: echo "$line" dogfood: - # Each tests partition's nextest JUnit report lands in its own directory under target/nextest/ci (no - # merge-multiple: every partition writes junit.xml); dogfood merges them and judges the requirements' proof. + # Each tests partition's nextest JUnit report, the guests' (junit-guests) and the gsd one (junit-gsd) land in their + # own directories under target/nextest/ci (no merge-multiple: every partition writes junit.xml); dogfood merges + # them and judges the requirements' proof. name: Check list (dogfood) needs: [ci, tests] if: github.event_name == 'push' @@ -397,9 +415,13 @@ jobs: prefix-key: ${{ env.CACHE_PREFIX }} shared-key: specs save-if: false + # dogfood runs the X2 floor's negative control under nextest (ADR 0393 D8). + - uses: taiki-e/install-action@v2 + with: + tool: nextest - uses: actions/download-artifact@v4 with: - pattern: junit-tests-* + pattern: junit-* path: target/nextest/ci - name: Run dogfood run: cargo gate ci --only dogfood diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index a08f6c34ad..7a278e4f33 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -6,7 +6,7 @@ How SpecForge is built. For what it is and why it exists, start with the [README The compiler is a **pure typed-graph engine**. It knows how to parse `keyword name { fields }` blocks, resolve references, detect orphans and cycles, and emit a validated graph — but it carries **no domain vocabulary**. Every entity kind, edge type, and validation rule comes from an extension. If a new domain required a compiler change, the architecture would have failed. -Fifteen extensions ship as builtins, embedded in the binary. A first-party builtin is `@specforge/`; a builtin of a family is `@/` (`@code/core`), its crate `extensions//`, and its codes print namespaced (`code/E101`, [ADR 0328](docs/adr/0328-a-builtin-is-embedded-and-a-non-specforge-builtin-catalogues-its-codes.md)). `@gsd/core` is the one builtin outside `extensions/`: its crate is `gsd/core`, and its codes print namespaced `gsd/…` ([ADR 0366](docs/adr/0366-gsd-core-is-vendored-as-a-builtin-with-a-size-allowance-of-its-own.md)). Enable one with `specforge add ` (or `specforge init --extensions ...`); it is recorded in `specforge.json`, with nothing to download: +Twenty-eight extensions ship as builtins, embedded in the binary. A first-party builtin is `@specforge/`; a builtin of a family is `@/` (`@code/core`), its crate `extensions//`, and its codes print namespaced (`code/E101`, [ADR 0328](docs/adr/0328-a-builtin-is-embedded-and-a-non-specforge-builtin-catalogues-its-codes.md)). Two builtins live outside `extensions/`, in the gsd workspace: `@gsd/core`, whose crate is `gsd/core` and whose codes print namespaced `gsd/…` ([ADR 0366](docs/adr/0366-gsd-core-is-vendored-as-a-builtin-with-a-size-allowance-of-its-own.md)), and `@gsd/import`, whose crate is `gsd/import` ([ADR 0391](docs/adr/0391-gsd-import-reads-a-planning-folder-once-into-one-edit-plan.md)). Enable one with `specforge add ` (or `specforge init --extensions ...`); it is recorded in `specforge.json`, with nothing to download: | Extension | Entity kinds | Purpose | |-----------|-------------|---------| @@ -17,14 +17,27 @@ Fifteen extensions ship as builtins, embedded in the binary. A first-party built | **`@specforge/testing`** | — | Test vocabulary: which kinds accept `verify` obligations and of which kinds (W004/W009). Enabled with `@specforge/software`; test-runner extensions build on it ([ADR 0002](docs/adr/0002-test-runner-extensions.md)). | | **`@specforge/cargo-test`** | — | Rust test runner: `specforge collect` runs `cargo test` (after you approve the command once per project) and records which entities the `#[specforge_test]`-annotated tests prove. Enabled by `init` in a Cargo project; `specforge add` also enables `@specforge/testing`. | | **`@specforge/vitest`** | — | vitest runner: `specforge collect` runs the project's own vitest (after you approve the command once per project) and records which entities tests name in their `meta.specforge`. Enabled by `init` in a vitest project; `specforge add` also enables `@specforge/testing`. | -| **`@code/core`** | test · test_run (collector-written) | The neutral base of test facts ([ADR 0329](docs/adr/0329-code-core-holds-test-facts-and-their-ids.md)): the kinds a runner pack collects into, and the checks of the references a spec writes to them (`code/E101`, `code/W102`, `code/W401`, `code/I402`). Declares no collector. | +| **`@code/core`** | test · test_run · item · package · coverage · api_item · static_finding · dependency · vulnerability (collector-written) | The neutral base of code facts ([ADR 0329](docs/adr/0329-code-core-holds-test-facts-and-their-ids.md)): the kinds a runner, source or manifest pack collects into, the report kinds a standard report's reader mints ([ADR 0388](docs/adr/0388-x2-is-the-share-of-test-ids-a-standard-report-saw.md)), and the checks of the references a spec writes to them (`code/E101`, `code/W102`, `code/W401`, `code/I402`) and of what a report leaves unmapped (`code/W104` to `code/W107`). Declares no collector. | | **`@specforge/checks`** | — | The generic value checkers: files, formats, check digits, links and git, each family behind a setting ([ADR 0338](docs/adr/0338-one-foundation-extension-holds-the-generic-value-checkers.md)). | | **`@javascript/node-test`** | — | node --test runner: `specforge collect` runs the project's own node test runner (after you approve the command once per project) and records its tests as `test`/`test_run` facts, cited as `js:/#`. `specforge add` also enables `@code/core`. | | **`@rust/cargo`** | — | Reads every `Cargo.toml` with cargo's own manifest model into `package` facts (`pkg:cargo/`): version, edition, targets, the project packages it depends on. Runs nothing ([ADR 0348](docs/adr/0348-a-collector-declares-a-config-file-and-the-rust-packs.md)). `specforge add` also enables `@code/core`. | | **`@rust/source`** | — | Walks each cargo target's module tree and has the host's reader parse it into `item` facts (`rust:::`), a test function with the id nextest gives it and the entity its `#[specforge_test]` names. `specforge add` also enables `@rust/cargo`. | | **`@rust/test`** | — | nextest runner: `specforge collect` runs `cargo-nextest` (after you approve the command and the config file it reads, once per project) and records its tests as `test`/`test_run` facts, cited as `rust:#`; an ignored test is held as `skipped`. `specforge add` also enables `@rust/source`. | | **`@javascript/source`** | — | Has the host's reader parse a JavaScript or TypeScript project's source (test files and generated output left out) into `item` facts (`js:/::[.]`), whether an importer reaches each, and a `package` fact per named `package.json` (`pkg:npm/`). Runs nothing. `specforge add` also enables `@code/core`. | +| **`@rust/coverage`** | — | Runs `cargo-llvm-cov` over nextest (after you approve the command once per project) and records its LCOV as `coverage` facts of the items each line lands in; a file outside the project is skipped and shown as W203 ([ADR 0389](docs/adr/0389-report-packs-run-standard-tools-and-doctor-names-a-missing-one.md)). `specforge add` also enables `@rust/source`. | +| **`@rust/lint`** | — | Runs `cargo-clippy` (after approval), captures its JSON messages and records each diagnostic as a `static_finding` fact citing the item holding it. `specforge add` also enables `@rust/source`. | +| **`@rust/deps`** | — | Runs `cargo-cyclonedx` (after approval), reads each BOM it wrote fresh, and records `dependency` facts; runs `osv-scanner` on `Cargo.lock` and records `vulnerability` facts. `specforge add` also enables `@rust/source`. | +| **`@rust/api`** | — | Runs `cargo-public-api` (after approval), captures its text and records the crate's public API as `api_item` facts. `specforge add` also enables `@rust/source`. | +| **`@rust/proof`** | — | Runs Kani (after approval, Linux x86_64 and macOS only), captures its output and records each proof harness as a `test`/`test_run` fact, `rust:#`, placed at its function; a cut-off output is refused, never half-read. `specforge add` also enables `@rust/source`. | +| **`@javascript/coverage`** | — | Runs c8 around the project's own `npm test` (after approval) and records its LCOV as `coverage` facts. `specforge add` also enables `@javascript/source`. | +| **`@javascript/lint`** | — | Runs ESLint with its SARIF formatter (after approval) and records each result as a `static_finding` fact. `specforge add` also enables `@javascript/source`. | +| **`@javascript/deps`** | — | Runs cyclonedx-npm on `package-lock.json` (after approval) for `dependency` facts, and `osv-scanner` for `vulnerability` facts. `specforge add` also enables `@javascript/source`. | +| **`@javascript/api`** | — | Runs api-extractor (after approval) on a config file the host writes and records the package's public API as `api_item` facts. `specforge add` also enables `@javascript/source`. | +| **`@javascript/vitest`** | — | vitest runner: runs `vitest run` with its JUnit reporter (after approval) and records its tests as `test`/`test_run` facts, `js:/#`; the legacy `@specforge/vitest` stays beside it. `specforge add` also enables `@javascript/source`. | +| **`@javascript/jest`** | — | jest runner: runs jest with jest-junit through an env file the host writes (after approval) and records its tests as `test`/`test_run` facts. `specforge add` also enables `@javascript/source`. | +| **`@javascript/playwright`** | — | Playwright runner: runs `playwright test` (after approval), captures its JUnit and records its tests as `test`/`test_run` facts. `specforge add` also enables `@javascript/source`. | | **`@gsd/core`** | requirement · milestone · phase · plan · task · summary · verification · … (61 kinds, scoped) | The GSD spec framework as one extension: its roadmap, plans, execution, verification and UAT kinds, its judged rules and codes, settings and profiles, and the prompts, agents, skills, slash commands and hooks it installs into a coding agent's host ([ADR 0366](docs/adr/0366-gsd-core-is-vendored-as-a-builtin-with-a-size-allowance-of-its-own.md), [ADR 0370](docs/adr/0370-gsd-core-holds-exactly-gsd-cores-kinds-and-fields.md)). | +| **`@gsd/import`** | — (one command) | `specforge gsd import` reads a GSD `.planning/` once into one edit plan writing `spec/gsd/`, with a report of everything it does not map ([ADR 0391](docs/adr/0391-gsd-import-reads-a-planning-folder-once-into-one-edit-plan.md)). Its required peer is `@gsd/core`. | Anyone can author and publish their own extension ([Extension Protocol](docs/extension-protocol.md)); the open Graph Protocol is the moat, not the implementation. The full catalog is in the [extension inventory](docs/extension-inventory.md). diff --git a/CONTEXT.md b/CONTEXT.md index 00e21e6836..6e182ed0b7 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -557,7 +557,8 @@ Terms the code, the specs and the docs use with one meaning. Architecture decisi (`specforge_project::ExtensionLoad`: `NoRuntime`, or what was loaded `In` a runtime). - **Builtin**: a component this specforge embeds, a row of `BUILTINS`, loaded by name (`specforge add @code/core`), whatever its scope. Its crate is `extensions/

` (named `@specforge/`), `extensions//` - (named `@/`), or `gsd/core` for `@gsd/core`, the one builtin outside `extensions/` (ADR 0366), and + (named `@/`), or `gsd/core` for `@gsd/core` and `gsd/import` for `@gsd/import`, the two builtins outside `extensions/` + (ADR 0366, ADR 0391), and holds a `wasm/` dir. Not the same as first party: a builtin outside `@specforge/` catalogues its codes and prints them namespaced, as a third party's do (`code/E101`, ADR 0328). - **First-party extension**: an extension of the `@specforge/` scope. Its codes are bare, in the static catalogue that @@ -566,7 +567,13 @@ Terms the code, the specs and the docs use with one meaning. Architecture decisi (`extensions/code/`); its builtins are named `@/`. The family `specforge` is refused (ADR 0328 D3). - **Extension library**: a crate in an extension family with no `wasm/` dir: an rlib named `specforge--`, never embedded, that builtins link (`extensions/code/junit`, `extensions/code/facts`). Editing it re-vendors the - builtins that link it. + builtins that link it. The six report readers are `specforge-code-lcov`, `-api`, `-sarif`, `-cyclonedx` and `-osv` + (`extensions/code/{lcov,api,sarif,cyclonedx,osv}`, linking code-facts, ADR 0388) and `specforge-code-kani` + (`extensions/code/kani`, Kani's regular output, linking nothing). The report packs link them (ADR 0389), so editing + a reader re-vendors exactly the packs that link it; `specforge-code-kani` feeds `@rust/proof` only. +- **X2**: the share of items carrying a test id whose id a test fact holds, that is, a standard test report saw it, + whatever its status. `cargo gate full`'s dogfood check prints it for SpecForge, taskboard and ledger, with no floor + (`gate/src/x2.rs`, ADR 0388). - **Builtin's name**: the name a builtin this specforge embeds declares. Only that builtin loads under it: a `.wasm` file entry whose component declares it is refused by the load's admit (E028), and add, update, init, publish, extension validate and extension init refuse a candidate declaring it (`extension_conflict`). One predicate, `Builtins::contains` (ADR 0028 D7, ADR 0214). - **Load key**: the key the runtime holds an entry's component under while its declaration is read: a builtin's or a locked entry's name, a `.wasm` file entry's `file:`, a candidate's `__candidate`. Every name the load admits is a package name and no temporary key is one, so a load never replaces another entry's extension (`load_key`, ADR 0223). - **Extension inventory**: every extension a project has, one row per name: enabled by a diff --git a/Cargo.lock b/Cargo.lock index adc4adb4ea..150bd571d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1258,9 +1258,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -5708,9 +5708,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/crates/app/ops/src/analysis/analyze.rs b/crates/app/ops/src/analysis/analyze.rs index 98c36d4837..afefda1cfb 100644 --- a/crates/app/ops/src/analysis/analyze.rs +++ b/crates/app/ops/src/analysis/analyze.rs @@ -382,12 +382,14 @@ pub fn analyze( } // An analyze pass reads what changed as the compile it analyzes takes it (ADR 0376 D6). let delta = view.project().pass_delta(); + // A pass's declared file reads go through the view's containment: a bounded one refuses a hard link (ADR 0146). + let disk = view.containment().file_reads_disk(); if let Some(runtime) = view.runtime() { let context = PassContext { test_results: report.as_deref(), proved_claims: proved.as_ref().map(|_| &proved_claims), judgements: Some(view.project().judgements()), - files: Some(view.env().file_source(&specforge_registry::PlainDisk)), + files: Some(view.env().file_source(&disk)), delta: delta.as_deref(), ..PassContext::of(view.entities()) }; diff --git a/crates/app/ops/src/analysis/collect/collector.rs b/crates/app/ops/src/analysis/collect/collector.rs index a8234366e6..beab5c2cfb 100644 --- a/crates/app/ops/src/analysis/collect/collector.rs +++ b/crates/app/ops/src/analysis/collect/collector.rs @@ -7,7 +7,7 @@ use specforge_effects::Uses; use specforge_effects::git::{Git, Located}; use specforge_protocol_types::{ CONFIG_PLACEHOLDER, ExtensionDeclaration, FILTER_PLACEHOLDER, Input, Inputs, Operation, - PortScope, ProcessConfig, REPORT_PLACEHOLDER, + PortScope, ProcessConfig, REPORT_PLACEHOLDER, is_report_name, is_wild, }; use std::path::Path; @@ -41,8 +41,10 @@ pub struct Collector { /// The arguments its process capability appends after `run` when a caller passes a filter (ADR 0360), `{filter}` /// in one of them the caller's text: empty when it takes none. pub filter: Vec, - /// What installs its program, said when the program is not found (ADR 0348 D4). + /// What installs its programs, said when one is not found (ADR 0348 D4). pub install: Option, + /// The other programs its command runs beside `run`'s first, which doctor looks up too (ADR 0389 D3). + pub requires: Vec, } impl Collector { @@ -114,6 +116,7 @@ fn collector( config: process.and_then(|p| p.config.clone()), filter: process.map(|p| p.filter.clone()).unwrap_or_default(), install: c.install.clone(), + requires: c.requires.clone(), } } @@ -143,6 +146,16 @@ fn in_a_repository(git: Option<&dyn Git>, root: &Path) -> bool { git.is_some_and(|git| !matches!(git.locate(root), Located::NotARepository)) } +/// The collectors a collect run here would detect, a repository asked of `git`: what doctor probes the programs of. +pub fn detected_here( + declarations: &[ExtensionDeclaration], + root: &Path, + git: Option<&dyn Git>, +) -> Vec { + let all = collectors(declarations); + detect(&all, root, git).into_iter().cloned().collect() +} + /// The scopes a collect run here would use, per extension: each detected collector's process capability (ADR 0335 /// D2), a repository asked of `git`: what `specforge grants` and doctor call in use. pub fn uses_here( @@ -201,9 +214,19 @@ pub(super) fn wildcard(pattern: &str, name: &str) -> bool { true } -/// The report location, held. An extension may only declare a relative name without `..` -/// ([`crate::containment::declared`], E058); where the name lands is the request's containment -/// (a symlink that leaves the project is `outside_root`). +/// The collector's report when it is a glob (ADR 0389): one of its `/`-separated segments holds `*` or `?`. +pub(super) fn report_glob(collector: &Collector) -> Option<&str> { + collector + .report + .as_deref() + .filter(|report| report.split('/').any(is_wild)) +} + +/// The report location, held: the report itself, or for a glob its literal base directory (the segments before the +/// first wildcard; the project root when there are none). An extension may only declare a relative name without `..` +/// ([`crate::containment::declared`], E058); where the name lands is the request's containment (a symlink that leaves +/// the project is `outside_root`). A glob names files the tool writes itself, so one whose last segment is not a +/// literal file name, or a command told its report (`{report}`) or a captured output, which need one file, is E058. pub(super) fn report_path( collector: &Collector, root: &Path, @@ -222,7 +245,47 @@ pub(super) fn report_path( ), )); }; - Ok(containment.resolve(&root.join(relative))?) + if report_glob(collector).is_none() { + return Ok(containment.resolve(&root.join(relative))?); + } + // The registry refuses this declaration (E030); a collector built from one anyway reads nothing. + if !is_report_name(report) { + return Err(OpError::coded( + OpErrorKind::PreconditionFailed, + codes::E058, + format!( + "collector '{}' of {} declares the report glob '{report}': a report glob must end in a literal file \ + name, so it names the files one tool writes", + collector.name, collector.extension + ), + )); + } + if collector.told_its_report() || collector.capture.is_some() { + return Err(OpError::coded( + OpErrorKind::PreconditionFailed, + codes::E058, + format!( + "collector '{}' of {} declares the report glob '{report}' and also {}: a report glob names files the \ + tool writes itself, so there is no single file to name", + collector.name, + collector.extension, + if collector.capture.is_some() { + "captures its output" + } else { + "tells its command `{report}`" + } + ), + )); + } + let base: Vec<&str> = report + .split('/') + .take_while(|segment| !is_wild(segment)) + .collect(); + let base = match base.join("/") { + literal if literal.is_empty() => root.to_path_buf(), + literal => root.join(literal), + }; + Ok(containment.resolve(&base)?) } /// E058 for a report asked of a collector that reads through its ports. diff --git a/crates/app/ops/src/analysis/collect/dispatch.rs b/crates/app/ops/src/analysis/collect/dispatch.rs index 02679571f0..26d7c83429 100644 --- a/crates/app/ops/src/analysis/collect/dispatch.rs +++ b/crates/app/ops/src/analysis/collect/dispatch.rs @@ -4,8 +4,12 @@ use super::collector::Collector; use crate::view::ProjectView; use crate::{Containment, Held, OpError, OpErrorKind}; use specforge_common::codes; +use specforge_effects::process::OUTPUT_CAP; +use specforge_project::file_reads::{FileSource, glob_paths}; use specforge_protocol_types::Operation; -use specforge_protocol_types::{CollectInput, CollectOutput, CollectReportFile, Fact, RawGraph}; +use specforge_protocol_types::{ + CollectInput, CollectOutput, CollectReportFile, FILE_READ_MAX, Fact, GLOB_VISITS_MAX, RawGraph, +}; use specforge_wasm::{CallError, CallFailure, ExtensionCalls, PortCall}; use std::path::{Path, PathBuf}; use std::time::SystemTime; @@ -35,31 +39,98 @@ pub(super) fn read_report( since: Option, containment: &Containment, ) -> Result, OpError> { - let fresh = |path: &PathBuf| { - since.is_none_or(|since| { - std::fs::metadata(path) - .and_then(|m| m.modified()) - .is_ok_and(|modified| modified >= since) - }) - }; let mut held = Vec::new(); if report.real.is_dir() { - for path in json_files(&report.real).into_iter().filter(fresh) { + for path in json_files(&report.real) + .into_iter() + .filter(|path| fresh(path, since)) + { let name = path.file_name().unwrap_or_default(); held.push(report.entry(containment, Path::new(name))?); } } else if report.real.is_file() { held.push(report.clone()); } + read_held(&held, root, containment) +} + +/// Read every project file `glob` matches (ADR 0389), listed by the walk `Input::files` globs take +/// ([`glob_paths`]: ADR 0293 D4), only those modified at or after `since` when given. Each match is held by +/// `containment` before it is opened: one that lands outside (a link out of the project) is skipped, never read, and +/// its project path is returned beside the files, for a W203 to name. A walk cut short is E045 naming the cap; a read +/// that fails is E045. +pub(super) fn read_glob( + glob: &str, + project: &FileSource<'_>, + root: &Path, + since: Option, + containment: &Containment, +) -> Result<(Vec, Vec), OpError> { + let listed = glob_paths(project, glob); + if listed.truncated { + return Err(OpError::coded( + OpErrorKind::SchemaMismatch, + codes::E045, + format!( + "the report glob '{glob}' reaches past the walk's cap of {GLOB_VISITS_MAX} entries or {FILE_READ_MAX} files; \ + name a narrower glob" + ), + )); + } + let mut outside = Vec::new(); + let mut held: Vec = Vec::new(); + for path in &listed.files { + match containment.resolve(&root.join(path)) { + Ok(file) if fresh(&file.real, since) => held.push(file), + Ok(_) => {} + Err(_) => outside.push(path.clone()), + } + } + Ok((read_held(&held, root, containment)?, outside)) +} + +/// Whether the file at `path` was modified at or after `since` (always, with no `since`). +fn fresh(path: &Path, since: Option) -> bool { + since.is_none_or(|since| { + std::fs::metadata(path) + .and_then(|m| m.modified()) + .is_ok_and(|modified| modified >= since) + }) +} + +/// The most bytes one collector's report files hold together: what a captured standard output may hold +/// ([`OUTPUT_CAP`]), so a directory or a glob of many files reads no more than one capture. +pub const REPORT_BYTES_MAX: u64 = OUTPUT_CAP; + +/// The text of each `held` file as a report, named as a project path of `root`, read through `containment`: a +/// bounded one refuses a file with several names, which a hard link from outside the project could have made +/// (ADR 0146). A read that fails, text that is not UTF-8, or files past [`REPORT_BYTES_MAX`] together, is E045. +fn read_held( + held: &[Held], + root: &Path, + containment: &Containment, +) -> Result, OpError> { + let mut total: u64 = 0; held.iter() .map(|file| { - let content = file.read_to_string().map_err(|e| { + let content = containment.read_held(file).and_then(utf8).map_err(|e| { OpError::coded( OpErrorKind::SchemaMismatch, codes::E045, format!("failed to read report {}: {e}", file.named.display()), ) })?; + total = total.saturating_add(content.len() as u64); + if total > REPORT_BYTES_MAX { + return Err(OpError::coded( + OpErrorKind::SchemaMismatch, + codes::E045, + format!( + "the report files reach past {REPORT_BYTES_MAX} bytes together at {}; name a narrower report", + file.named.display() + ), + )); + } Ok(CollectReportFile { path: file.shown(root).into_string(), content, @@ -68,6 +139,16 @@ pub(super) fn read_report( .collect() } +/// `bytes` as text: bytes that are not UTF-8 are `InvalidData`, worded as `regular::read_to_string` words them. +fn utf8(bytes: Vec) -> std::io::Result { + String::from_utf8(bytes).map_err(|_| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + "stream did not contain valid UTF-8", + ) + }) +} + /// Hand the report files, and the captured standard output if any, to the /// collector's pure export: the protocol's `CollectInput` in, its /// `CollectOutput` out. Err: the export trapped, or answered something diff --git a/crates/app/ops/src/analysis/collect/evidence.rs b/crates/app/ops/src/analysis/collect/evidence.rs index 97bba82c96..c09f7f41cf 100644 --- a/crates/app/ops/src/analysis/collect/evidence.rs +++ b/crates/app/ops/src/analysis/collect/evidence.rs @@ -5,25 +5,31 @@ use super::collector::{ ConfigFile, capture_path, captures_stdout, command_line, config_file, read_capture, - reads_no_report, report_path, + reads_no_report, report_glob, report_path, }; -use super::dispatch::read_report; +use super::dispatch::{read_glob, read_report}; use super::{Collector, Mode, fail}; use crate::machine::{CollectorCommand, CollectorMachine, Ran, RunFailure, RunnerOutput}; use crate::{Containment, Held, OpError, OpErrorKind}; use specforge_common::codes; +use specforge_project::file_reads::FileSource; use specforge_protocol_types::CollectReportFile; use std::path::{Path, PathBuf}; +use std::time::SystemTime; /// A collector's declared report location and captured output, held. pub(super) struct Declared { + /// The report, or a glob's literal base directory. report: Held, + /// The report glob, when the report is one (ADR 0389). + glob: Option, capture: Option, } impl Declared { /// `collector`'s declared report and capture, held by `containment`: E058 for a report name that is not - /// relative-without-`..` or an unknown capture; `outside_root` for one that lands outside. + /// relative-without-`..`, an unknown capture, or a glob a single path is asked of; `outside_root` for one that + /// lands outside. fn of(collector: &Collector, root: &Path, containment: &Containment) -> Result { let report = report_path(collector, root, containment)?; let capturing = captures_stdout(collector) @@ -33,7 +39,36 @@ impl Declared { } else { None }; - Ok(Declared { report, capture }) + Ok(Declared { + report, + glob: report_glob(collector).map(str::to_string), + capture, + }) + } + + /// The report files: every match of the glob, else the file or the directory's `*.json` files; only those modified + /// since `since` when given. Beside them, the glob's matches that land outside the project, not read. + fn read( + &self, + root: &Path, + since: Option, + containment: &Containment, + project: &FileSource<'_>, + ) -> Result<(Vec, Vec), OpError> { + match &self.glob { + Some(glob) => read_glob(glob, project, root, since, containment), + None => Ok(( + read_report(&self.report, root, since, containment)?, + Vec::new(), + )), + } + } + + /// Where the report is, as a message names it: the glob, else the declared location. + fn shown(&self) -> String { + self.glob + .clone() + .unwrap_or_else(|| self.report.named.display().to_string()) } /// The captured output, if the collector captures one and it is there. @@ -70,6 +105,8 @@ pub(super) struct Evidence { pub(super) exit_code: Option, /// Whether the collector's command ran. pub(super) ran: bool, + /// The report glob's matches that land outside the project (a link out of it), not read (ADR 0389 D6). + pub(super) unread: Vec, } impl<'m> Source<'m> { @@ -120,15 +157,18 @@ impl<'m> Source<'m> { } /// Gather the evidence: under `Run`, announce then run (E045 when it cannot start or its capture cannot be - /// written), then read. No report file and no captured output is E045, worded for the source. + /// written), then read; a report glob is listed over `project`. No report file and no captured output is E045, + /// worded for the source. pub(super) fn gather( &self, collector: &Collector, root: &Path, containment: &Containment, + project: &FileSource<'_>, machine: &dyn CollectorMachine, announce: &mut dyn FnMut(&Collector, &[String]), ) -> Result { + let mut unread = Vec::new(); let (files, stdout, exit_code, ran) = match self { Source::Run { output, @@ -140,8 +180,7 @@ impl<'m> Source<'m> { let ran = run_command( machine, root, - (&declared.report, !collector.told_its_report()), - declared.capture.as_ref(), + (declared, !collector.told_its_report()), config.as_ref(), argv, *output, @@ -150,11 +189,13 @@ impl<'m> Source<'m> { let message = failure.said(collector, argv); fail(OpErrorKind::SchemaMismatch, codes::E045, message) })?; - let files = read_report(&declared.report, root, Some(ran.started), containment)?; + let files; + (files, unread) = declared.read(root, Some(ran.started), containment, project)?; (files, declared.stdout(), ran.exit_code, true) } Source::Written(declared) => { - let files = read_report(&declared.report, root, None, containment)?; + let files; + (files, unread) = declared.read(root, None, containment, project)?; (files, declared.stdout(), None, false) } Source::Given(paths) => { @@ -174,17 +215,18 @@ impl<'m> Source<'m> { && files.is_empty() && stdout.as_deref().is_none_or(str::is_empty) { - return Err(fail( - OpErrorKind::SchemaMismatch, - codes::E045, - self.nothing_found(collector), - )); + let mut message = self.nothing_found(collector); + if !unread.is_empty() { + message.push_str(&format!("; {}", super::warnings::unread_paths(&unread))); + } + return Err(fail(OpErrorKind::SchemaMismatch, codes::E045, message)); } Ok(Evidence { files, stdout, exit_code, ran, + unread, }) } @@ -194,12 +236,12 @@ impl<'m> Source<'m> { Source::Run { declared, .. } => format!( "{} produced no report at {} (did the tests build?)", collector.name, - declared.report.named.display() + declared.shown() ), Source::Written(declared) => format!( "no {} report at {}; run the tests to write one (`specforge collect` runs them)", collector.name, - declared.report.named.display() + declared.shown() ), Source::Given(_) => "the report files given don't exist".to_string(), Source::Outcomes => format!("{} read no outcome", collector.name), @@ -245,18 +287,21 @@ impl From for NotRan { /// there) and filtered by modification time when it's read. The config file the command reads is written /// fresh before it starts (ADR 0348 D2). A captured standard output still reaches the chosen output as it's /// produced, and is also written to `capture`. Every file it removes, creates or writes is a held one, and the -/// report, the capture and the config are names the run owns: a link at one is replaced, never followed. +/// report, the capture and the config are names the run owns: a link at one is replaced, never followed. A report +/// glob's files are the tool's: nothing is removed or created for them, and the command is told its base directory, +/// never in `SPECFORGE_REPORT` (ADR 0389). fn run_command( machine: &dyn CollectorMachine, root: &Path, - (report, report_in_env): (&Held, bool), - capture: Option<&Held>, + (declared, told_nothing): (&Declared, bool), config: Option<&ConfigFile>, argv: &[String], output: RunnerOutput, ) -> Result { + let (report, capture) = (&declared.report, declared.capture.as_ref()); + let owned = declared.glob.is_none(); // The report's name is the run's (ADR 0171): a file or a link at it is unlinked, never what a link names. - if !report.real.is_dir() { + if owned && !report.real.is_dir() { match report.remove() { Err(e) if e.kind() != std::io::ErrorKind::NotFound => { return Err(format!("{}: {e}", report.named.display()).into()); @@ -264,7 +309,9 @@ fn run_command( _ => {} } } - for file in std::iter::once(report) + for file in owned + .then_some(report) + .into_iter() .chain(capture) .chain(config.map(|config| &config.held)) { @@ -287,7 +334,7 @@ fn run_command( argv, dir: root, report: &report.at, - report_in_env, + report_in_env: owned && told_nothing, output, }; machine diff --git a/crates/app/ops/src/analysis/collect/mod.rs b/crates/app/ops/src/analysis/collect/mod.rs index b3860cd28e..3ca50705ac 100644 --- a/crates/app/ops/src/analysis/collect/mod.rs +++ b/crates/app/ops/src/analysis/collect/mod.rs @@ -23,14 +23,15 @@ mod facts; mod merge; mod order; mod process; +mod warnings; pub use crate::machine::{ CollectorCommand, CollectorMachine, REPORT_ENV, Ran, RunFailure, RunnerOutput, }; use collector::detect; -pub use collector::{Collector, collectors, uses_here}; -pub use dispatch::dispatch; +pub use collector::{Collector, collectors, detected_here, uses_here}; use dispatch::dispatch_over; +pub use dispatch::{REPORT_BYTES_MAX, dispatch}; use evidence::{Evidence, Source}; pub use merge::MergeStats; use merge::{KnownEntities, merge}; @@ -298,13 +299,23 @@ pub fn collect( let mut served = order::Served::new(root, containment, &available); // The syntax cache writes that failed over every collector, and the first one's error: W200 once. let (mut unwritten, mut unwritable) = (0, None); + // A report glob is listed by the walk `Input::files` globs take (ADR 0389), over the plain disk. + let project = view.env().file_source(&specforge_registry::PlainDisk); for (collector, source) in planned { let Evidence { files, stdout, exit_code, ran, - } = match source.gather(collector, root, containment, machine, &mut *announce) { + unread, + } = match source.gather( + collector, + root, + containment, + &project, + machine, + &mut *announce, + ) { Ok(evidence) => evidence, // Detection chose it, so the project did not ask for it: no evidence skips it (ADR 0331). Err(error) if chosen == Chosen::Detected && error.code == codes::E045.id() => { @@ -313,6 +324,7 @@ pub fn collect( } Err(error) => return Err(error.into()), }; + diagnostics.extend(warnings::unread(collector, &unread)); let lent = crate::extension::lend::port_call( view, @@ -339,6 +351,7 @@ pub fn collect( } failed })?; + diagnostics.extend(warnings::warned(collector, &collected.warnings)); let mut syntax = None; if let Some(lent) = lent { diagnostics.extend(lent.take_denials()); diff --git a/crates/app/ops/src/analysis/collect/tests.rs b/crates/app/ops/src/analysis/collect/tests.rs index 39ca9e6be5..fc5c043520 100644 --- a/crates/app/ops/src/analysis/collect/tests.rs +++ b/crates/app/ops/src/analysis/collect/tests.rs @@ -25,6 +25,7 @@ fn collector(report: &str) -> Collector { config: None, filter: Vec::new(), install: None, + requires: Vec::new(), } } @@ -99,6 +100,7 @@ fn collected(entries: &[(&str, &str, TestStatus)]) -> CollectOutput { unlinked: Vec::new(), plan: None, facts: Vec::new(), + warnings: Vec::new(), } } diff --git a/crates/app/ops/src/analysis/collect/warnings.rs b/crates/app/ops/src/analysis/collect/warnings.rs new file mode 100644 index 0000000000..03be3ab3f3 --- /dev/null +++ b/crates/app/ops/src/analysis/collect/warnings.rs @@ -0,0 +1,76 @@ +//! A collector's warnings (ADR 0389): the lines its export returns about what it read but could not use, each one +//! W203 naming the collector, escaped, at most [`WARNINGS_SHOWN`] of them and then one counting the rest; and the host's +//! own W203 naming the report glob matches it did not read. + +use super::Collector; +use specforge_common::remedy::printable; +use specforge_common::{Diagnostic, codes}; + +/// The most W203 lines one collector reports before one more counts the rest. +const WARNINGS_SHOWN: usize = 100; + +/// W203 for each of `collector`'s warning `lines`, up to [`WARNINGS_SHOWN`], then one counting the lines not shown. +pub(super) fn warned(collector: &Collector, lines: &[String]) -> Vec { + let mut warned: Vec = lines + .iter() + .take(WARNINGS_SHOWN) + .map(|line| { + Diagnostic::new( + codes::W203, + format!( + "collector '{}' of {} warns: {}", + collector.name, + collector.extension, + printable(line) + ), + ) + }) + .collect(); + if let Some(more) = lines.len().checked_sub(WARNINGS_SHOWN).filter(|n| *n > 0) { + warned.push(Diagnostic::new( + codes::W203, + format!( + "collector '{}' of {} returned {more} more warnings, not shown", + collector.name, collector.extension + ), + )); + } + warned +} + +/// The most report glob matches one W203 names before it counts the rest. +const UNREAD_SHOWN: usize = 5; + +/// One W203 naming the report glob matches of `collector` that land outside the project and were not read (ADR 0389 +/// D6): the first [`UNREAD_SHOWN`], then how many more; none when every match was read. +pub(super) fn unread(collector: &Collector, paths: &[String]) -> Option { + (!paths.is_empty()).then(|| { + Diagnostic::new( + codes::W203, + format!( + "collector '{}' of {}: {}", + collector.name, + collector.extension, + unread_paths(paths) + ), + ) + }) +} + +/// ` report glob match(es) land outside ...: ` and the first [`UNREAD_SHOWN`] of `paths`, escaped, then how many +/// more: what the W203 says, and what E045 adds when no other match was read. +pub(super) fn unread_paths(paths: &[String]) -> String { + let mut named: Vec = paths + .iter() + .take(UNREAD_SHOWN) + .map(|path| printable(path).into_owned()) + .collect(); + if paths.len() > UNREAD_SHOWN { + named.push(format!("and {} more", paths.len() - UNREAD_SHOWN)); + } + format!( + "{} report glob match(es) land outside the project through a link, so they were not read: {}", + paths.len(), + named.join(", ") + ) +} diff --git a/crates/app/ops/src/analysis/doctor.rs b/crates/app/ops/src/analysis/doctor.rs index e343c1df90..b9ee6f55fb 100644 --- a/crates/app/ops/src/analysis/doctor.rs +++ b/crates/app/ops/src/analysis/doctor.rs @@ -205,6 +205,13 @@ pub enum About { /// The SMT solver `specforge analyze --prove` asks does not run here: the /// W098 it reports. Toolchain, + /// A program a collector detected here runs that this machine lacks (`tool_missing`, ADR 0389 D3): the + /// collectors it stops and the codes no collector can then judge. + Tools { + program: String, + collectors: Vec, + codes: Vec, + }, /// What the extensions may make the host do here (ADR 0335 D2): the consent store cannot be used (W186), or /// a run here uses effects this machine has not approved (W170). Grants, @@ -234,6 +241,7 @@ pub enum Part { Conflict, Shadowing, Toolchain, + Tools, Grants, Host, } @@ -256,6 +264,7 @@ impl About { About::Conflict { .. } => Part::Conflict, About::Shadowing { .. } => Part::Shadowing, About::Toolchain => Part::Toolchain, + About::Tools { .. } => Part::Tools, About::Grants => Part::Grants, About::Host { .. } => Part::Host, } @@ -365,6 +374,17 @@ impl DoctorReport { self } + /// This report with one info finding per program a collector detected here runs that `process` does not find + /// (ADR 0389 D3): never a failure. A view without a root adds nothing. + pub fn with_tools( + mut self, + view: &ProjectView, + process: &dyn specforge_effects::Process, + ) -> Self { + self.findings.extend(tools::probe(view, process)); + self + } + /// The one document both surfaces return: `{ok, extensions_ok, /// cache_status, installed_count, z3_available, extensions, /// enhancements, conflicts: [message…], findings: [...]}`. @@ -637,3 +657,4 @@ fn remediation(diag: &Diagnostic, codes: &Codebook, fallback: impl FnOnce() -> S pub mod on_path; #[cfg(test)] mod tests; +mod tools; diff --git a/crates/app/ops/src/analysis/doctor/tools.rs b/crates/app/ops/src/analysis/doctor/tools.rs new file mode 100644 index 0000000000..c2dbf5577b --- /dev/null +++ b/crates/app/ops/src/analysis/doctor/tools.rs @@ -0,0 +1,249 @@ +//! The programs the collectors detected here run (ADR 0389 D3): its argv's first, or the `npx` or `node` script it +//! names, and each program it `requires`. `specforge doctor` asks the process port's `which` for each (an `npx` +//! program also in the `node_modules/.bin` of the root and of each npm workspace package inside the project, never +//! above the root) and says, once per program it does not find, which collectors that stops and which codes no collector can +//! then judge, derived from each collector's `answers` and each code's `facts` in the code book: a code that judges a +//! kind a runnable collector still answers is not named. An info note, never a failure; a program that is found says +//! nothing. Nothing is run. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use specforge_common::remedy::printable; +use specforge_effects::Process; +use specforge_protocol_types::{is_install_line, is_program_name, is_wild}; + +use super::{About, Finding, FindingStatus}; +use crate::Containment; +use crate::analysis::collect::detected_here; +use crate::view::ProjectView; + +/// The finding code of a program a detected collector runs that this machine lacks. +const TOOL_MISSING: &str = "tool_missing"; + +/// What one missing program stops. +#[derive(Default)] +struct Missing { + collectors: BTreeSet, + /// The kinds its collectors answer. + kinds: Vec, + installs: Vec, +} + +/// One info finding per program a collector detected in `view`'s project runs that `process` does not find. The codes +/// it names are the ones that judge a kind its collectors answer and no kind a runnable detected collector answers (one +/// whose program is found, or that runs none): another collector still answering a kind keeps its codes judged. +pub(super) fn probe(view: &ProjectView, process: &dyn Process) -> Vec { + let Some(root) = view.root() else { + return Vec::new(); + }; + let git = view.env().git(); + let codes = view.registries().codes(); + let lookup = Lookup { + root, + containment: view.containment(), + process, + bin_dirs: bin_dirs(root, view.containment()), + }; + let mut missing: BTreeMap = BTreeMap::new(); + let mut answered: Vec = Vec::new(); + for collector in detected_here(view.registries().declarations(), root, git.as_deref()) { + let lacking: Vec = lookup + .program(&collector.run) + .into_iter() + .chain(lookup.required(&collector.requires)) + .collect(); + if lacking.is_empty() { + answered.extend(collector.answers); + continue; + } + for program in lacking { + let entry = missing.entry(printable(&program).into_owned()).or_default(); + entry.collectors.insert(format!( + "{} ({})", + printable(&collector.name), + printable(&collector.extension) + )); + entry.kinds.extend(collector.answers.iter().cloned()); + if let Some(line) = collector.install.as_deref().filter(|l| is_install_line(l)) { + let line = printable(line).into_owned(); + if !entry.installs.contains(&line) { + entry.installs.push(line); + } + } + } + } + missing + .into_iter() + .map(|(program, m)| { + let off = codes.switched_off(&m.kinds, &answered); + finding(program, m, off) + }) + .collect() +} + +/// Where doctor looks a program up: PATH through the process port, and files under the project root, held by its +/// containment (a link out of the project reads as absent). It reads nothing above the root and runs nothing. +struct Lookup<'a> { + root: &'a Path, + containment: &'a Containment, + process: &'a dyn Process, + /// The project-relative directories whose `node_modules/.bin` an `npx` program may be in ([`bin_dirs`]). + bin_dirs: Vec, +} + +impl Lookup<'_> { + fn found(&self, program: &str) -> bool { + self.process.which(program).is_some() + } + + /// Whether the declared relative path `relative` is a file under the root. + fn under_root(&self, relative: &str) -> bool { + crate::containment::declared(Path::new(relative)).is_some_and(|p| { + self.containment + .resolve(&self.root.join(p)) + .is_ok_and(|held| held.real.is_file()) + }) + } + + /// The program `run` needs that this machine lacks; none when it has it, or `run` is empty (ADR 0389 D3). `npx + /// -- ` needs ``, in a `node_modules/.bin` of [`Lookup::bin_dirs`] or on PATH; `node + /// node_modules//...` needs `node` and that script under the root, else names the package; anything else + /// needs its first item on PATH. + fn program(&self, run: &[String]) -> Option { + let first = run.first()?; + match first.as_str() { + "npx" => { + if let Some(bin) = run.iter().skip_while(|arg| *arg != "--").nth(1) { + let local = |name: &str| { + self.bin_dirs + .iter() + .any(|dir| self.under_root(&format!("{dir}node_modules/.bin/{name}"))) + }; + let present = local(bin) || local(&format!("{bin}.cmd")) || self.found(bin); + return (!present).then(|| bin.clone()); + } + } + "node" => { + if !self.found("node") { + return Some("node".into()); + } + let script = run[1..] + .iter() + .find(|arg| arg.starts_with("node_modules/"))?; + if self.under_root(script) { + return None; + } + if crate::containment::declared(Path::new(script)).is_none() { + return Some(script.clone()); + } + // The package directory: `jest`, or a scoped `@acme/tool`. + let mut segments = script["node_modules/".len()..].split('/'); + let package = match segments.next() { + Some(scope) if scope.starts_with('@') => { + format!("{scope}/{}", segments.next().unwrap_or_default()) + } + name => name.unwrap_or_default().to_string(), + }; + return Some(package); + } + _ => {} + } + (!self.found(first)).then(|| first.clone()) + } + + /// The programs of a collector's `requires` that PATH lacks; a name that is no bare program name is W021's and + /// never looked up. + fn required(&self, requires: &[String]) -> Vec { + requires + .iter() + .filter(|program| is_program_name(program) && !self.found(program)) + .cloned() + .collect() + } +} + +/// The project-relative directories, each ending `/` (the root `""`), whose `node_modules/.bin` may hold an `npx` +/// program: the root, then each npm workspace package directory the root `package.json` names (`workspaces`, a list or +/// `{"packages": [...]}`), inside the project. shortcut: a pattern is a literal directory or one ending `/*` (every +/// directory directly under it); `**` and inner wildcards are not expanded, upgrade when a monorepo needs them. +fn bin_dirs(root: &Path, containment: &Containment) -> Vec { + let mut dirs = vec![String::new()]; + let Ok((_, bytes)) = containment.read(&root.join("package.json")) else { + return dirs; + }; + let Ok(manifest) = serde_json::from_slice::(&bytes) else { + return dirs; + }; + let workspaces = manifest.get("workspaces"); + let patterns = workspaces + .and_then(serde_json::Value::as_array) + .or_else(|| workspaces?.get("packages")?.as_array()); + let inside = |dir: &str| { + !dir.split('/').any(is_wild) + && crate::containment::declared(Path::new(dir)).is_some() + && containment + .resolve(&root.join(dir)) + .is_ok_and(|held| held.real.is_dir()) + }; + for pattern in patterns + .into_iter() + .flatten() + .filter_map(serde_json::Value::as_str) + { + let pattern = pattern + .strip_prefix("./") + .unwrap_or(pattern) + .trim_end_matches('/'); + match pattern.strip_suffix("/*") { + Some(parent) if inside(parent) => { + let mut names: Vec = std::fs::read_dir(root.join(parent)) + .into_iter() + .flatten() + .flatten() + .filter_map(|entry| entry.file_name().into_string().ok()) + .filter(|name| inside(&format!("{parent}/{name}"))) + .collect(); + names.sort(); + dirs.extend(names.into_iter().map(|name| format!("{parent}/{name}/"))); + } + None if inside(pattern) => dirs.push(format!("{pattern}/")), + _ => {} + } + } + dirs +} + +/// The finding about `program`, missing, which switches off `codes`. +fn finding(program: String, missing: Missing, codes: Vec) -> Finding { + let collectors: Vec = missing.collectors.into_iter().collect(); + let mut check = format!( + "`{program}` is not found here, so collector {} cannot run", + collectors.join(", ") + ); + if !codes.is_empty() { + check.push_str(&format!( + "; no collector that runs here answers what {} judge, so they are not judged here", + codes.join(", ") + )); + } + let remediation = if missing.installs.is_empty() { + format!("install `{program}` and put it on PATH") + } else { + missing.installs.join("; ") + }; + Finding { + about: About::Tools { + program, + collectors, + codes, + }, + check, + status: FindingStatus::Info, + code: TOOL_MISSING.into(), + remediation, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/ops/src/analysis/doctor/tools/tests.rs b/crates/app/ops/src/analysis/doctor/tools/tests.rs new file mode 100644 index 0000000000..5928b57cbe --- /dev/null +++ b/crates/app/ops/src/analysis/doctor/tools/tests.rs @@ -0,0 +1,486 @@ +use super::*; +use crate::analysis::doctor::{DoctorReport, Part, diagnose}; +use crate::testing::{ScriptedSolver, Viewed}; +use specforge_effects::testing::FakeProcess; +use specforge_extension_sdk::{ContributionsBuilder, ExtensionMeta}; +use specforge_project::testing::Assembled; +use specforge_protocol_types::ExtensionDeclaration; +use specforge_test_macros::test as specforge_test; + +/// `extension` with one collector `name` detected on `Cargo.toml`, running `run`, answering `answers`. +fn runner( + extension: &str, + name: &str, + run: &[&str], + answers: &[&str], + install: Option<&str>, +) -> ExtensionDeclaration { + let mut c = ContributionsBuilder::new(ExtensionMeta::new(extension, "1.0.0")); + c.collector(name, |collector| { + collector + .detect_files(&["Cargo.toml"]) + .run(run) + .answers(answers); + if let Some(line) = install { + collector.install(line); + } + // `{config}` in an argv is sound only beside the config file it names. + if run.iter().any(|arg| arg.contains("{config}")) { + collector.config("jest.json", "{\"output\": \"{report}\"}"); + } + collector.collect(|_| Ok(Default::default())); + }); + c.declaration() +} + +/// `@acme/core`, cataloguing codes judging collected kinds: W104 coverage, W108 proof. +fn judge() -> ExtensionDeclaration { + let mut c = ContributionsBuilder::new(ExtensionMeta::new("@acme/core", "1.0.0")); + c.code("W104", |d| { + d.title("Coverage on no item") + .explanation("Serve the item.") + .facts(&["coverage"]); + }); + c.code("W108", |d| { + d.title("Proof on no item") + .explanation("Serve the item.") + .facts(&["proof"]); + }); + c.declaration() +} + +fn cov() -> ExtensionDeclaration { + runner( + "@acme/cov", + "cov", + &["cargo-llvm-cov", "llvm-cov"], + &["coverage"], + Some("cargo install cargo-llvm-cov --locked"), + ) +} + +/// The report of a project loading `declarations` and holding the empty `files`, diagnosed under `process`. +fn diagnosed( + declarations: Vec, + files: &[&str], + process: &FakeProcess, +) -> DoctorReport { + let fixture = Assembled::new().declarations(declarations); + for file in files { + fixture.write(file, ""); + } + let view = fixture.view(); + diagnose(&view, &ScriptedSolver::ready()).with_tools(&view, process) +} + +fn tools(report: &DoctorReport) -> Vec<&Finding> { + report.about(Part::Tools).collect() +} + +/// The missing programs `run`, by `@x/run`'s one collector, gives in a project holding `Cargo.toml` and `files`. +fn missing(run: &[&str], files: &[&str], process: &FakeProcess) -> Vec { + let mut held = vec!["Cargo.toml"]; + held.extend(files); + let report = diagnosed( + vec![runner("@x/run", "run", run, &[], None)], + &held, + process, + ); + tools(&report) + .iter() + .map(|f| match &f.about { + About::Tools { program, .. } => program.clone(), + other => panic!("{other:?}"), + }) + .collect() +} + +const API_EXTRACTOR: &[&str] = &["npx", "--no", "--", "api-extractor", "run"]; + +#[specforge_test(requirement = "FEATURE-021")] +fn npx_names_the_program_after_its_double_dash() { + assert_eq!( + missing(API_EXTRACTOR, &[], &FakeProcess::new()), + ["api-extractor"] + ); + let npx_only = FakeProcess::new().on_path("npx", "/usr/bin/npx"); + assert_eq!( + missing(API_EXTRACTOR, &[], &npx_only), + ["api-extractor"], + "npx on PATH says nothing of the program it would run" + ); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn an_npx_program_in_node_modules_bin_or_on_path_is_present() { + for bin in [ + "node_modules/.bin/api-extractor", + "node_modules/.bin/api-extractor.cmd", + ] { + assert!( + missing(API_EXTRACTOR, &[bin], &FakeProcess::new()).is_empty(), + "{bin}" + ); + } + let on_path = FakeProcess::new().on_path("api-extractor", "/usr/bin/api-extractor"); + assert!(missing(API_EXTRACTOR, &[], &on_path).is_empty()); +} + +/// The missing programs of `API_EXTRACTOR` in a project holding `Cargo.toml` and `files` with their contents. +fn missing_among(files: &[(&str, &str)]) -> Vec { + let fixture = + Assembled::new().declarations(vec![runner("@x/run", "run", API_EXTRACTOR, &[], None)]); + fixture.write("Cargo.toml", ""); + for (file, contents) in files { + fixture.write(file, contents); + } + let view = fixture.view(); + let report = diagnose(&view, &ScriptedSolver::ready()).with_tools(&view, &FakeProcess::new()); + tools(&report) + .iter() + .map(|f| match &f.about { + About::Tools { program, .. } => program.clone(), + other => panic!("{other:?}"), + }) + .collect() +} + +#[specforge_test(requirement = "FEATURE-021")] +fn an_npx_program_in_a_workspace_packages_node_modules_bin_is_present() { + let bin = "node_modules/.bin/api-extractor"; + for (manifest, dir) in [ + (r#"{"workspaces": ["packages/*"]}"#, "packages/a/"), + (r#"{"workspaces": ["./tools/lint/"]}"#, "tools/lint/"), + (r#"{"workspaces": {"packages": ["apps/*"]}}"#, "apps/web/"), + ] { + let at = format!("{dir}{bin}"); + assert!( + missing_among(&[("package.json", manifest), (&at, "")]).is_empty(), + "{manifest} {at}" + ); + } + // A package the workspaces do not name, a pattern leaving the root, or a deeper glob is not looked in. + for (manifest, dir) in [ + (r#"{"workspaces": ["packages/*"]}"#, "other/a/"), + (r#"{"workspaces": ["../beside"]}"#, "beside/"), + (r#"{"workspaces": ["packages/**"]}"#, "packages/a/"), + ] { + let at = format!("{dir}{bin}"); + assert_eq!( + missing_among(&[("package.json", manifest), (&at, "")]), + ["api-extractor"], + "{manifest} {at}" + ); + } +} + +/// `@x/cov`, running `cargo-llvm-cov llvm-cov nextest` and so requiring `cargo-nextest`, answering coverage. +fn cov_with_nextest() -> ExtensionDeclaration { + let mut c = ContributionsBuilder::new(ExtensionMeta::new("@x/cov", "1.0.0")); + c.collector("cov", |k| { + k.detect_files(&["Cargo.toml"]) + .run(&["cargo-llvm-cov", "llvm-cov", "nextest"]) + .requires(&["cargo-nextest"]) + .install("cargo install cargo-llvm-cov cargo-nextest --locked") + .answers(&["coverage"]) + .collect(|_| Ok(Default::default())); + }); + c.declaration() +} + +#[specforge_test(requirement = "FEATURE-021")] +fn a_required_program_missing_is_its_own_finding_with_the_collectors_install_line() { + let llvm_cov = FakeProcess::new().on_path("cargo-llvm-cov", "/usr/bin/cargo-llvm-cov"); + + let report = diagnosed( + vec![cov_with_nextest(), judge()], + &["Cargo.toml"], + &llvm_cov, + ); + + let found = tools(&report); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!( + found[0].about, + About::Tools { + program: "cargo-nextest".into(), + collectors: vec!["cov (@x/cov)".into()], + codes: vec!["acme/W104".into()], + } + ); + assert_eq!( + found[0].remediation, + "cargo install cargo-llvm-cov cargo-nextest --locked" + ); + + let both = llvm_cov.on_path("cargo-nextest", "/usr/bin/cargo-nextest"); + let report = diagnosed(vec![cov_with_nextest(), judge()], &["Cargo.toml"], &both); + assert!(tools(&report).is_empty(), "{:?}", tools(&report)); +} + +const JEST: &[&str] = &[ + "node", + "--env-file={config}", + "node_modules/jest/bin/jest.js", +]; + +#[specforge_test(requirement = "FEATURE-021")] +fn a_node_script_missing_from_node_modules_names_its_package() { + let node = FakeProcess::new().on_path("node", "/usr/bin/node"); + assert_eq!(missing(JEST, &[], &node), ["jest"]); + assert!(missing(JEST, &["node_modules/jest/bin/jest.js"], &node).is_empty()); + let scoped = &["node", "node_modules/@acme/tool/cli.js"]; + assert_eq!(missing(scoped, &[], &node), ["@acme/tool"]); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn without_node_the_program_is_node() { + assert_eq!( + missing( + JEST, + &["node_modules/jest/bin/jest.js"], + &FakeProcess::new() + ), + ["node"] + ); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn a_script_path_leaving_the_root_is_never_probed_and_reads_as_missing() { + let node = FakeProcess::new().on_path("node", "/usr/bin/node"); + let escaping = &["node", "node_modules/../../x.js"]; + + assert_eq!(missing(escaping, &[], &node), ["node_modules/../../x.js"]); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn collectors_sharing_a_missing_program_give_one_finding_with_the_union_of_codes() { + let a = runner("@x/a", "a", &["cargo-kani"], &["proof"], None); + let b = runner("@x/b", "b", &["cargo-kani"], &["coverage"], None); + + let report = diagnosed(vec![b, a, judge()], &["Cargo.toml"], &FakeProcess::new()); + + let found = tools(&report); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!( + found[0].about, + About::Tools { + program: "cargo-kani".into(), + collectors: vec!["a (@x/a)".into(), "b (@x/b)".into()], + codes: vec!["acme/W104".into(), "acme/W108".into()], + } + ); + assert_eq!( + found[0].remediation, + "install `cargo-kani` and put it on PATH" + ); +} + +/// The codes of the one tools finding of `report`. +fn codes_of(report: &DoctorReport) -> Vec { + let found = tools(report); + let [finding] = &found[..] else { + panic!("one finding: {found:?}"); + }; + let About::Tools { codes, .. } = &finding.about else { + panic!("{:?}", finding.about); + }; + codes.clone() +} + +#[specforge_test(requirement = "FEATURE-021")] +fn a_kind_a_present_collector_still_answers_keeps_its_codes_judged() { + // c8 still answers coverage, so losing cargo-llvm-cov switches no code off. + let c8 = runner( + "@acme/jscov", + "jscov", + &["npx", "--no", "--", "c8"], + &["coverage"], + None, + ); + let process = FakeProcess::new().on_path("c8", "/usr/bin/c8"); + + let report = diagnosed(vec![cov(), c8, judge()], &["Cargo.toml"], &process); + + assert_eq!(codes_of(&report), Vec::::new()); + let check = &tools(&report)[0].check; + assert!(check.contains("`cargo-llvm-cov`"), "{check}"); + assert!(!check.contains("not judged"), "{check}"); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn a_code_judging_a_kind_still_answered_is_not_named() { + let mut c = ContributionsBuilder::new(ExtensionMeta::new("@acme/core", "1.0.0")); + c.code("W104", |d| { + d.title("Coverage on no item") + .explanation("Serve the item.") + .facts(&["coverage"]); + }); + c.code("E101", |d| { + d.title("Fact on no item") + .explanation("Serve the item.") + .facts(&["coverage", "item"]); + }); + // A source reader that runs no program still answers item. + c.collector("items", |k| { + k.detect_files(&["Cargo.toml"]) + .answers(&["item"]) + .collect(|_| Ok(Default::default())); + }); + + let report = diagnosed( + vec![cov(), c.declaration()], + &["Cargo.toml"], + &FakeProcess::new(), + ); + + assert_eq!(codes_of(&report), ["acme/W104"]); + assert!( + tools(&report)[0].check.contains("acme/W104"), + "{}", + tools(&report)[0].check + ); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn a_missing_program_whose_kinds_no_code_judges_still_gets_a_finding() { + let deps = runner("@x/deps", "deps", &["osv-scanner"], &["dependency"], None); + + let report = diagnosed(vec![deps, judge()], &["Cargo.toml"], &FakeProcess::new()); + + let found = tools(&report); + assert_eq!(found.len(), 1, "{found:?}"); + let About::Tools { codes, .. } = &found[0].about else { + panic!("{:?}", found[0].about); + }; + assert!(codes.is_empty(), "{codes:?}"); + assert!(!found[0].check.contains("not judged"), "{}", found[0].check); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn ten_missing_programs_leave_doctor_healthy() { + let programs: Vec = (0..10).map(|i| format!("tool-{i}")).collect(); + let declarations: Vec = programs + .iter() + .map(|program| runner(&format!("@x/{program}"), program, &[program], &[], None)) + .collect(); + + let report = diagnosed(declarations, &["Cargo.toml"], &FakeProcess::new()); + + assert_eq!(tools(&report).len(), 10); + assert!(report.ok(), "tool notes never fail doctor"); + assert_eq!(report.about(Part::Toolchain).count(), 0); + assert!(report.z3_available()); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn a_missing_program_is_one_info_finding_naming_its_collectors_and_codes() { + let report = diagnosed(vec![cov(), judge()], &["Cargo.toml"], &FakeProcess::new()); + + let found = tools(&report); + assert_eq!(found.len(), 1, "{found:?}"); + let finding = found[0]; + assert_eq!(finding.status, FindingStatus::Info); + assert_eq!(finding.code, "tool_missing"); + let About::Tools { + program, + collectors, + codes, + } = &finding.about + else { + panic!("{:?}", finding.about); + }; + assert_eq!(program, "cargo-llvm-cov"); + assert_eq!(collectors, &["cov (@acme/cov)"]); + assert_eq!(codes, &["acme/W104"]); + assert!( + finding.check.contains("`cargo-llvm-cov`"), + "{}", + finding.check + ); + assert!(finding.check.contains(&codes[0]), "{}", finding.check); + assert_eq!(finding.remediation, "cargo install cargo-llvm-cov --locked"); + assert!(report.ok(), "a missing tool never fails doctor"); + assert!(report.z3_available(), "a tool note is no toolchain finding"); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn a_declaration_string_with_control_characters_is_printed_escaped() { + // A third-party declaration whose program sets the terminal's title and writes lines of its own, and whose + // install line clears the screen and adds a command on a line of its own (T-11-09). + let program = "tool\u{1b}]0;owned\u{7}\nline\r"; + let install = "cargo install tool\u{1b}[2J\nrm -rf ~\r"; + let report = diagnosed( + vec![ + runner("@x/run", "run", &[program], &["coverage"], Some(install)), + judge(), + ], + &["Cargo.toml"], + &FakeProcess::new(), + ); + + let found = tools(&report); + assert_eq!(found.len(), 1, "{found:?}"); + let About::Tools { + program: named, + collectors, + codes, + } = &found[0].about + else { + panic!("{:?}", found[0].about); + }; + assert_eq!(named, "tool\\u{1b}]0;owned\\u{7}\\nline\\r"); + let shown = [ + named.as_str(), + &collectors.join(" "), + &codes.join(" "), + &found[0].check, + &found[0].remediation, + ] + .join(" "); + for raw in ['\u{1b}', '\u{7}', '\n', '\r'] { + assert!(!shown.contains(raw), "{raw:?} in {shown:?}"); + } + // The install line is refused, not escaped: the finding names the program instead. + assert_eq!( + found[0].remediation, + format!("install `{named}` and put it on PATH") + ); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn a_program_on_path_says_nothing() { + let process = FakeProcess::new().on_path("cargo-llvm-cov", "/usr/bin/cargo-llvm-cov"); + + let report = diagnosed(vec![cov(), judge()], &["Cargo.toml"], &process); + + assert!(tools(&report).is_empty(), "{:?}", tools(&report)); + assert!(process.requests().is_empty(), "doctor runs nothing"); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn a_collector_not_detected_here_is_not_probed() { + let report = diagnosed(vec![cov(), judge()], &[], &FakeProcess::new()); + + assert!(tools(&report).is_empty(), "{:?}", tools(&report)); +} + +#[specforge_test(requirement = "FEATURE-021")] +fn the_document_carries_the_tool_finding_and_its_fields() { + let report = diagnosed(vec![cov(), judge()], &["Cargo.toml"], &FakeProcess::new()); + + let document = serde_json::to_value(report.document()).unwrap(); + let finding = document["findings"] + .as_array() + .unwrap() + .iter() + .find(|f| f["about"] == "tools") + .expect("a tools finding"); + assert_eq!(finding["program"], "cargo-llvm-cov"); + assert_eq!( + finding["collectors"], + serde_json::json!(["cov (@acme/cov)"]) + ); + assert_eq!(finding["codes"].as_array().unwrap().len(), 1); + assert_eq!(finding["status"], "info"); +} diff --git a/crates/app/ops/src/authoring/apply/command.rs b/crates/app/ops/src/authoring/apply/command.rs index 4a110dd364..e319d49b26 100644 --- a/crates/app/ops/src/authoring/apply/command.rs +++ b/crates/app/ops/src/authoring/apply/command.rs @@ -133,6 +133,7 @@ pub fn execute_with( } else { let origin = Origin::Command { extension: command.extension().to_string(), + imports: command.imports(), }; match apply_plan_with(view, plan, &origin, dry_run, caller, rules, calendar) { Ok(edited) if edited.wrote.previewed() => PlanOutcome::Previewed(edited), diff --git a/crates/app/ops/src/authoring/apply/flags.rs b/crates/app/ops/src/authoring/apply/flags.rs index 4577d3be1c..507d1117ba 100644 --- a/crates/app/ops/src/authoring/apply/flags.rs +++ b/crates/app/ops/src/authoring/apply/flags.rs @@ -777,7 +777,7 @@ fn refuse( /// Whether `origin` may set a harness value of a field `declaring` declares: a command, collector or hook of that /// extension, or of one whose handshake names it a peer dependency. pub(crate) fn may_write_harness(view: &ProjectView<'_>, origin: &Origin, declaring: &str) -> bool { - let (Origin::Command { extension } + let (Origin::Command { extension, .. } | Origin::Collector { extension } | Origin::Hook { extension }) = origin else { diff --git a/crates/app/ops/src/authoring/apply/mod.rs b/crates/app/ops/src/authoring/apply/mod.rs index 84d232a220..8c48027cd0 100644 --- a/crates/app/ops/src/authoring/apply/mod.rs +++ b/crates/app/ops/src/authoring/apply/mod.rs @@ -23,7 +23,7 @@ pub use collector::apply_collected; pub use command::{CommandRun, PlanOutcome, execute, execute_with}; pub use judged::HostJudgedRules; -use crate::authoring::edit::{EditField, Edited, Step, plan_steps}; +use crate::authoring::edit::{EditField, Edited, Lands, Step, plan_steps}; use crate::authoring::planned::PlannedChange; use crate::view::ProjectView; use crate::{Caller, OpError, OpErrorKind, Refusal, Writes, Wrote}; @@ -95,8 +95,9 @@ pub enum Surface { /// Who asked for a write. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Origin { - /// A command of `extension` answered the plan. - Command { extension: String }, + /// A command of `extension` answered the plan. `imports`: the command declares it imports what was recorded + /// outside the spec, so its plan is judged for host errors only (ADR 0392). + Command { extension: String, imports: bool }, /// A collector of `extension` answered the plan. Collector { extension: String }, /// A hook of `extension` answered the plan. @@ -176,8 +177,13 @@ pub fn apply_plan_with( steps.insert(at + inserted, step); } revision::against_compile(view.project(), &lowered.files)?; - let host_only = matches!(origin, Origin::Collector { .. }); - let planned = plan_steps(view, &steps, host_only)?; + // History an extension's rule cannot unmake: a collected fact (ADR 0303) and an import (ADR 0392). + let lands = match origin { + Origin::Collector { .. } => Lands::Extensions, + Origin::Command { imports: true, .. } => Lands::ThirdParty, + _ => Lands::Nothing, + }; + let planned = plan_steps(view, &steps, lands)?; let report = planned.report().clone(); let wrote = Wrote::unless_preview(dry_run, || { let change = planned.change().clone().serialized(); @@ -194,7 +200,7 @@ pub fn apply_plan_with( change.apply_checked(caller, || { revision::against_disk(&sources, caller, &files)?; verdict::against_disk(project, &verdicts)?; - rejudge(project, &change, &files, host_only) + rejudge(project, &change, &files, lands) }) })?; Ok(Edited { report, wrote }) @@ -344,7 +350,7 @@ fn rejudge( project: &CompiledProject, change: &PlannedChange, files: &std::collections::BTreeMap, - host_only: bool, + lands: Lands, ) -> Result<(), OpError> { let own: BTreeSet = files.keys().cloned().collect(); if !project.sources_moved(&own) { @@ -360,7 +366,7 @@ fn rejudge( &after, project.environment().registries(), change, - host_only, + lands, ) .map_err(|refusal| refusal.error) } diff --git a/crates/app/ops/src/authoring/apply/verdict.rs b/crates/app/ops/src/authoring/apply/verdict.rs index 30e0672a0e..e63d5a2403 100644 --- a/crates/app/ops/src/authoring/apply/verdict.rs +++ b/crates/app/ops/src/authoring/apply/verdict.rs @@ -251,7 +251,7 @@ pub(crate) fn check( format!("'{}' is no outcome of the rule '{}'", op.outcome, op.rule), )); } - if !matches!(origin, Origin::Command { extension } if *extension == rule.extension) { + if !matches!(origin, Origin::Command { extension, .. } if *extension == rule.extension) { return Err(refused( op, "origin", diff --git a/crates/app/ops/src/authoring/edit/mod.rs b/crates/app/ops/src/authoring/edit/mod.rs index acc0035950..9c993ca5dd 100644 --- a/crates/app/ops/src/authoring/edit/mod.rs +++ b/crates/app/ops/src/authoring/edit/mod.rs @@ -24,6 +24,7 @@ pub use skeleton::{Skeleton, Skeletons, Slot, SlotOf}; use specforge_project::harness::compose; pub use steps::{Step, plan, plan_steps}; pub use typed::takes_json; +pub use validate::Lands; use crate::authoring::format::{Configs, Place}; use crate::authoring::planned::PlannedChange; diff --git a/crates/app/ops/src/authoring/edit/steps.rs b/crates/app/ops/src/authoring/edit/steps.rs index 3cd72b81e9..13c5be827f 100644 --- a/crates/app/ops/src/authoring/edit/steps.rs +++ b/crates/app/ops/src/authoring/edit/steps.rs @@ -3,6 +3,7 @@ //! that compile and merges its texts, and the edits after it are planned over a compile of the merged texts. use super::declared::Declared; +use super::validate::Lands; use super::{Edit, EditField, EditPlan, EditReport, Planner, describe, validate}; use crate::Refusal; use crate::authoring::format::{Configs, Forms}; @@ -75,14 +76,14 @@ pub(super) fn relocated(path: &str, moves: &[(String, String)]) -> String { /// through the view's disk (ADR 0169). pub fn plan(view: &ProjectView<'_>, edits: &[Edit]) -> Result> { let steps: Vec = edits.iter().cloned().map(Step::Edit).collect(); - plan_steps(view, &steps, false) + plan_steps(view, &steps, Lands::Nothing) } -/// [`plan`] over steps, renames among them. `host_only`: an extension's error is no error the plan adds (ADR 0303). +/// [`plan`] over steps, renames among them. `lands`: the errors the plan may add (ADR 0303, ADR 0392). pub fn plan_steps( view: &ProjectView<'_>, steps: &[Step], - host_only: bool, + lands: Lands, ) -> Result> { crate::config::refuse_rewrite(view.env().config_problems())?; view.project_root()?; @@ -115,7 +116,7 @@ pub fn plan_steps( })?; at = end; } - conclude(view, carry, host_only) + conclude(view, carry, lands) } /// A run of edits, planned over the project as the steps before left it; the refusal names the edit's place in the run. @@ -230,7 +231,7 @@ fn rename_step( fn conclude( view: &ProjectView<'_>, carry: Carry, - host_only: bool, + lands: Lands, ) -> Result> { let project = view.project(); let Carry { @@ -275,7 +276,7 @@ fn conclude( let added = if change.is_empty() { Vec::new() } else { - validate::check(view, &change, &declared, host_only)? + validate::check(view, &change, &declared, lands)? }; let report = EditReport { entities: change.entities(), diff --git a/crates/app/ops/src/authoring/edit/validate.rs b/crates/app/ops/src/authoring/edit/validate.rs index ed78024557..c907ece13e 100644 --- a/crates/app/ops/src/authoring/edit/validate.rs +++ b/crates/app/ops/src/authoring/edit/validate.rs @@ -15,7 +15,7 @@ use super::steps::relocated; use crate::authoring::planned::PlannedChange; use crate::view::ProjectView; use crate::{OpError, OpErrorKind, Refusal}; -use specforge_common::{Diagnostic, DiagnosticList, Severity, codes}; +use specforge_common::{Codebook, Diagnostic, DiagnosticList, Severity, codes}; use specforge_diagnostics::CodeRef; use specforge_graph::{GraphDelta, compute_graph_delta_over}; use specforge_project::CompiledProject; @@ -127,15 +127,44 @@ fn revealed( } } +/// Which of the errors a plan adds are written rather than refused (E080): the plan records history, which an +/// extension's rule cannot unmake. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Lands { + /// None: every error the plan adds refuses it (a typed edit; a command's or a hook's plan). + Nothing, + /// Every extension's error, whatever its code: a collector's plan (ADR 0303). + Extensions, + /// An extension's rule about authored entities, its own catalogued code (`gsd.security/E101`, `gsd/E312`): an + /// importing command's plan (ADR 0392, `Codebook::authored_rule`). Every other error still refuses: the host's + /// own, a `@specforge/*` builtin's (the E016 a path's value check reports), and one that judges the records + /// against the facts collected from the tree (`code/E101`, a reference naming no collected fact). + ThirdParty, +} + +impl Lands { + /// Whether `d`, an error the plan adds, is written rather than refused; `codes` is the loaded extensions' catalog. + pub(crate) fn lands(self, d: &Diagnostic, codes: &Codebook) -> bool { + match self { + Lands::Nothing => false, + Lands::Extensions => d.origin().is_some(), + Lands::ThirdParty => d + .origin() + .is_some_and(|origin| codes.authored_rule(origin, &d.code)), + } + } +} + /// The diagnostics of `after` that `before` does not have, one by one: (errors, warnings and infos). A diagnostic -/// `judged` names is never an error here, whatever its severity. `moved` relocates the subjects of `before`. -/// `host_only`: an extension's diagnostic is never an error here either (ADR 0303). +/// `judged` names is never an error here, whatever its severity. `moved` relocates the subjects of `before`. An error +/// `lands` writes, read against the catalog `codes`, is not one either (ADR 0303, ADR 0392). pub(crate) fn added( before: &[Diagnostic], after: Vec, judged: impl Fn(&Diagnostic) -> bool, moved: &Moves, - host_only: bool, + lands: Lands, + codes: &Codebook, ) -> (Vec, Vec) { let mut had: HashMap = HashMap::new(); for d in before { @@ -149,10 +178,7 @@ pub(crate) fn added( } match had.get_mut(&key(&d, &[])) { Some(n) if *n > 0 => *n -= 1, - _ if d.severity == Severity::Error - && !judged(&d) - && !(host_only && d.origin().is_some()) => - { + _ if d.severity == Severity::Error && !judged(&d) && !lands.lands(&d, codes) => { errors.push(d) } _ => rest.push(d), @@ -167,14 +193,15 @@ pub(crate) fn refuse_new_errors( after: &CompiledProject, registries: &RegistryBuild, change: &PlannedChange, - host_only: bool, + lands: Lands, ) -> Result<(), Refusal> { let (errors, _) = added( &before.judged_diagnostics(), after.diagnostics(), not_added(before, after, Some(change)), change.moved(), - host_only, + lands, + registries.codes(), ); if errors.is_empty() { Ok(()) @@ -191,7 +218,7 @@ pub fn check( view: &ProjectView<'_>, change: &PlannedChange, declared: &Declared, - host_only: bool, + lands: Lands, ) -> Result, Refusal> { let before = view.project().judged_diagnostics(); let texts = change.after(); @@ -205,7 +232,8 @@ pub fn check( post.diagnostics(), not_added(view.project(), &post, Some(change)), change.moved(), - host_only, + lands, + view.registries().codes(), ); if !errors.is_empty() { return Err(new_errors(errors, view.registries().codes())); @@ -222,7 +250,7 @@ pub fn check( Err(undeclared(&beyond)) } -fn new_errors(errors: Vec, codes: &specforge_common::Codebook) -> Refusal { +fn new_errors(errors: Vec, codes: &Codebook) -> Refusal { let mut message = format!( "the edit would leave the project with {} error{} it does not have; nothing was written", errors.len(), @@ -308,7 +336,14 @@ mod tests { let mut pending = Diagnostic::new(codes::W167, "an interrupted write is pending rollback"); // A preset that raises W167 makes it an error of the edited project. pending.severity = Severity::Error; - let (errors, rest) = added(&[], vec![pending], |_| false, &[], false); + let (errors, rest) = added( + &[], + vec![pending], + |_| false, + &[], + Lands::Nothing, + &Codebook::default(), + ); assert!(errors.is_empty() && rest.is_empty()); } @@ -326,7 +361,8 @@ mod tests { vec![error("gsd/E501"), error("gsd/E999")], judged, &[], - false, + Lands::Nothing, + &Codebook::default(), ); assert_eq!(errors.len(), 1); assert_eq!(errors[0].code, "gsd/E999"); @@ -338,7 +374,8 @@ mod tests { vec![error("gsd/E501")], judged, &[], - false, + Lands::Nothing, + &Codebook::default(), ); assert!(errors.is_empty() && rest.is_empty()); } @@ -372,7 +409,8 @@ mod tests { vec![finding("v1.0/01/01-01/TR2")], |_| false, &[], - false, + Lands::Nothing, + &Codebook::default(), ); assert_eq!(errors.len(), 1); } @@ -384,11 +422,30 @@ mod tests { let moves = [("v1.0/01".to_string(), "v1.0/02".to_string())]; let after = vec![finding("v1.0/02/01-01/TR1")]; assert!( - added(&before, after.clone(), |_| false, &moves, false) - .0 - .is_empty() + added( + &before, + after.clone(), + |_| false, + &moves, + Lands::Nothing, + &Codebook::default() + ) + .0 + .is_empty() + ); + assert_eq!( + added( + &before, + after, + |_| false, + &[], + Lands::Nothing, + &Codebook::default() + ) + .0 + .len(), + 1 ); - assert_eq!(added(&before, after, |_| false, &[], false).0.len(), 1); } fn finding(entity: &str) -> Diagnostic { @@ -404,13 +461,71 @@ mod tests { } #[specforge_test(requirement = "FEATURE-128")] - fn host_only_ignores_an_extensions_error_and_keeps_a_host_one() { + fn a_collectors_plan_lands_an_extensions_error_and_keeps_a_host_one() { let host = Diagnostic::untyped("E003", Severity::Error, "unresolved"); let ext = finding("v1.0/01/01-01/TR1"); - let (errors, _) = added(&[], vec![host, ext.clone()], |_| false, &[], true); + let (errors, _) = added( + &[], + vec![host, ext.clone()], + |_| false, + &[], + Lands::Extensions, + &Codebook::default(), + ); assert_eq!(errors.len(), 1); assert_eq!(errors[0].code, "E003"); - assert_eq!(added(&[], vec![ext], |_| false, &[], false).0.len(), 1); + assert_eq!( + added( + &[], + vec![ext], + |_| false, + &[], + Lands::Nothing, + &Codebook::default() + ) + .0 + .len(), + 1 + ); + } + + #[specforge_test(requirement = "FEATURE-131")] + fn an_import_lands_an_authored_rule_error_and_keeps_every_other() { + let entry = |local: &str, facts: &[&str]| specforge_diagnostics::ExtensionCode { + local: local.into(), + title: "t".into(), + explanation: "e".into(), + docs: None, + machine: false, + reported_while: None, + settled_later: false, + facts: facts.iter().map(|kind| kind.to_string()).collect(), + }; + let mut book = Codebook::default(); + book.add("@gsd/core", vec![entry("E502", &[])]).unwrap(); + book.add("@code/core", vec![entry("E101", &["test"])]) + .unwrap(); + let host = Diagnostic::untyped("E003", Severity::Error, "unresolved"); + let path = Diagnostic::from_extension("@specforge/checks", "E016", Severity::Error, "gone"); + // A builtin outside `@specforge/` that judges collected facts: a reference naming no fact refuses (WR-A01). + let dangling = + Diagnostic::from_extension("@code/core", "code/E101", Severity::Error, "no fact"); + let uncatalogued = + Diagnostic::from_extension("@gsd/core", "gsd/E999", Severity::Error, "not listed"); + let rule = finding("v1.0/01/01-01/TR1"); + let (errors, _) = added( + &[], + vec![host, path.clone(), dangling, uncatalogued, rule.clone()], + |_| false, + &[], + Lands::ThirdParty, + &book, + ); + let codes: Vec<&str> = errors.iter().map(|d| d.code.as_str()).collect(); + assert_eq!(codes, ["E003", "E016", "code/E101", "gsd/E999"]); + assert!(Lands::ThirdParty.lands(&rule, &book)); + // A collector's plan lands the first-party extension's error too (ADR 0303). + assert!(Lands::Extensions.lands(&path, &book) && !Lands::ThirdParty.lands(&path, &book)); } #[specforge_test(requirement = "FEATURE-131")] diff --git a/crates/app/ops/src/authoring/migrate.rs b/crates/app/ops/src/authoring/migrate.rs index fc32f0c5c3..b3c04d2bfe 100644 --- a/crates/app/ops/src/authoring/migrate.rs +++ b/crates/app/ops/src/authoring/migrate.rs @@ -30,7 +30,7 @@ use specforge_wasm::WasmRuntime; use std::collections::{BTreeMap, HashMap}; use std::path::Path; -use crate::authoring::edit::validate::{added, not_added}; +use crate::authoring::edit::validate::{Lands, added, not_added}; use crate::authoring::format::{Configs, Forms, Place}; use crate::change::{ProjectChange, unreadable, unwritable}; use crate::{Caller, Held, OpError, OpErrorKind, ReadFailure, Refusal, Writes, Wrote}; @@ -375,7 +375,8 @@ pub fn judge( verdict.post_diagnostics.clone(), judged, &[], - false, + Lands::Nothing, + post.environment().registries().codes(), ) .0 .len(); diff --git a/crates/app/ops/src/containment/disk.rs b/crates/app/ops/src/containment/disk.rs index 9a8cda986a..f844c23cad 100644 --- a/crates/app/ops/src/containment/disk.rs +++ b/crates/app/ops/src/containment/disk.rs @@ -3,7 +3,7 @@ //! file checked (ADR 0104, ADR 0112 D1). use std::io; -use std::path::Path; +use std::path::{Path, PathBuf}; use specforge_registry::{Disk, PlainDisk}; @@ -40,3 +40,31 @@ impl Disk for ContainedDisk { } } } + +/// The plain file system, each file read through one containment: what a declared file read (`Input::files`, ADR 0293) +/// of a call or an analyze pass reads through. It lists, tells a directory and resolves a link as the plain disk does, +/// so the shared walk still sees a linked directory and the path check still sees where a link lands; a read is the +/// containment's, so a bounded one refuses a file with several names (ADR 0146), as a report read does (ADR 0390 D12). +pub struct FileReadsDisk(pub(crate) ContainedDisk); + +impl Disk for FileReadsDisk { + fn exists(&self, path: &Path) -> bool { + PlainDisk.exists(path) + } + + fn list(&self, dir: &Path) -> Option> { + PlainDisk.list(dir) + } + + fn read(&self, path: &Path) -> io::Result> { + self.0.read(path) + } + + fn is_dir(&self, path: &Path) -> bool { + PlainDisk.is_dir(path) + } + + fn canonical(&self, path: &Path) -> Option { + PlainDisk.canonical(path) + } +} diff --git a/crates/app/ops/src/containment/disk_tests.rs b/crates/app/ops/src/containment/disk_tests.rs index 29e81ecdae..7e558e31ff 100644 --- a/crates/app/ops/src/containment/disk_tests.rs +++ b/crates/app/ops/src/containment/disk_tests.rs @@ -79,6 +79,27 @@ fn an_unbounded_containment_reads_a_file_with_two_names() { assert_eq!(disk.read(&base.join("proj/hard")).unwrap(), b"SECRETWORD"); } +/// The declared file reads' disk walks as the plain one (it sees where a link lands) and reads as the containment. +#[test] +fn the_file_reads_disk_resolves_links_plainly_and_refuses_a_second_name_when_bounded() { + let (_dir, base) = scene(); + let root = base.join("proj"); + std::fs::write(base.join("outside/secret"), "SECRETWORD").unwrap(); + std::fs::hard_link(base.join("outside/secret"), root.join("hard")).unwrap(); + std::os::unix::fs::symlink(base.join("outside"), root.join("away")).unwrap(); + let disk = Containment::within(&root).file_reads_disk(); + assert_eq!( + disk.canonical(&root.join("away")), + Some(base.join("outside")) + ); + assert!(disk.is_dir(&root.join("away"))); + let error = disk.read(&root.join("hard")).unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput); + assert!(!error.to_string().contains("SECRETWORD"), "{error}"); + let unbounded = Containment::unbounded().file_reads_disk(); + assert_eq!(unbounded.read(&root.join("hard")).unwrap(), b"SECRETWORD"); +} + #[test] fn a_directory_is_not_refused_for_its_link_count() { let (_dir, base) = scene(); diff --git a/crates/app/ops/src/containment/mod.rs b/crates/app/ops/src/containment/mod.rs index 212b17464b..a4bd1325eb 100644 --- a/crates/app/ops/src/containment/mod.rs +++ b/crates/app/ops/src/containment/mod.rs @@ -10,7 +10,7 @@ mod disk; mod file; -pub use disk::ContainedDisk; +pub use disk::{ContainedDisk, FileReadsDisk}; pub use file::{ReadFailure, declared}; use std::collections::BTreeMap; @@ -92,6 +92,12 @@ impl Containment { ContainedDisk(self.clone()) } + /// The disk a declared file read (`Input::files`) reads through: walked as the plain disk, each file read + /// through this containment, so a bounded one refuses a file with several names (ADR 0146). + pub fn file_reads_disk(&self) -> FileReadsDisk { + FileReadsDisk(self.disk()) + } + /// The same kind of bound for a project inside this one: `within(dir)` when bounded, /// unbounded when unbounded. A change bounds its writes to its own project (ADR 0092 D8). pub fn narrowed(&self, dir: &Path) -> Self { diff --git a/crates/app/ops/src/extension/command.rs b/crates/app/ops/src/extension/command.rs index 2fec2cd207..861a9dc176 100644 --- a/crates/app/ops/src/extension/command.rs +++ b/crates/app/ops/src/extension/command.rs @@ -212,6 +212,11 @@ impl ExtensionCommand { self.declaration.human } + /// Whether it imports what was recorded outside the spec: its plan is judged for host errors only (ADR 0392). + pub fn imports(&self) -> bool { + self.declaration.imports + } + /// The declaring extension's short name, which routes its commands. pub fn short(&self) -> &str { &self.short diff --git a/crates/app/ops/src/extension/inputs.rs b/crates/app/ops/src/extension/inputs.rs index 8e90c971ca..dafa20781a 100644 --- a/crates/app/ops/src/extension/inputs.rs +++ b/crates/app/ops/src/extension/inputs.rs @@ -27,16 +27,18 @@ impl<'v, 'p> Serve<'v, 'p> { } } - /// The facts of each `files` input, by read name. A call runs once: they are read from the plain disk (ADR 0293). + /// The facts of each `files` input, by read name. A call runs once: they are read from the plain disk (ADR 0293), + /// each file through the view's containment, so a bounded one refuses a hard link (ADR 0146). pub(crate) fn files(&self) -> FileMap { let reads = self.inputs.files(); if reads.is_empty() { return FileMap::default(); } + let disk = self.view.containment().file_reads_disk(); specforge_project::file_reads::read( &reads, self.view.entities(), - &self.view.env().file_source(&specforge_registry::PlainDisk), + &self.view.env().file_source(&disk), ) } diff --git a/crates/app/ops/src/read/explain.rs b/crates/app/ops/src/read/explain.rs index 103604cd8b..148b34fe91 100644 --- a/crates/app/ops/src/read/explain.rs +++ b/crates/app/ops/src/read/explain.rs @@ -138,6 +138,7 @@ mod tests { machine: false, reported_while: None, settled_later: false, + facts: Vec::new(), }) .collect(); book.add(extension, entries).unwrap(); diff --git a/crates/app/ops/tests/javascript_report_packs.rs b/crates/app/ops/tests/javascript_report_packs.rs new file mode 100644 index 0000000000..5760492535 --- /dev/null +++ b/crates/app/ops/tests/javascript_report_packs.rs @@ -0,0 +1,481 @@ +//! The JavaScript report and runner packs end to end (ADR 0389): `@javascript/coverage`, `@javascript/lint`, +//! `@javascript/deps`, `@javascript/api`, `@javascript/vitest`, `@javascript/jest` and `@javascript/playwright` from +//! their real blobs collect the fixture workspace `tests/fixtures/javascript-source`, a scripted machine standing in +//! for each tool, beside the legacy `@specforge/vitest` (owner decision D4). Each report is a short inline text in the +//! format of its pack's own fixture (the recordings of c8, ESLint's SARIF formatter, cyclonedx-npm, osv-scanner, +//! api-extractor, vitest, jest-junit and Playwright). +#![allow( + clippy::unwrap_used, + reason = "a test's unwrap is its assertion: a None or an Err fails the test" +)] + +use std::sync::Arc; +use std::time::Duration; + +use specforge_effects::testing::MemoryConsent; +use specforge_effects::{EffectsMode, Ports}; +use specforge_ops::analysis::collect::{Mode, Outcome, Request, RunnerOutput, collect}; +use specforge_ops::asking::Asking; +use specforge_ops::testing::{ScriptedMachine, ScriptedRun}; +use specforge_ops::{Caller, Containment}; +use specforge_project::testing::TestProject; +use specforge_protocol_types::Fact; + +/// `@javascript/source`, the seven packs, the legacy vitest pack with the peer it requires, and +/// `@specforge/software`, whose behaviors the fixture's spec declares. +const PACKS: [&str; 12] = [ + "@specforge/software", + "@code/core", + "@javascript/source", + "@javascript/coverage", + "@javascript/lint", + "@javascript/deps", + "@javascript/api", + "@javascript/vitest", + "@javascript/jest", + "@javascript/playwright", + "@specforge/testing", + "@specforge/vitest", +]; +const FIXTURE: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/javascript-source" +); +/// The workspace's one test file, in the package `@acme/core`. +const TEST_FILE: &str = "packages/core/test/board.test.ts"; + +/// The fixture workspace with the files each pack is detected by, the packs enabled, and `@javascript/source`'s +/// packages and items collected and stored, as a collect of every detected collector stores them first. +fn fixture() -> TestProject { + let p = TestProject::copy_of(FIXTURE) + .files(&[ + ( + "package-lock.json", + r#"{"name": "app", "lockfileVersion": 3, "packages": {}}"#, + ), + ("eslint.config.js", "export default [];\n"), + ("tsconfig.json", "{}\n"), + ("vitest.config.ts", "export default {};\n"), + ("jest.config.js", "module.exports = {};\n"), + ("playwright.config.ts", "export default {};\n"), + ]) + .enabling(&PACKS); + // It runs no command: nothing is scripted. + let mut outcome = collected(&p, "javascript-source", &ScriptedMachine::new()); + let compiled = p.compile(); + let view = specforge_ops::view::ProjectView::of(&compiled); + let dry_run = false; + specforge_ops::authoring::apply::apply_collected( + &view, + Vec::new(), + std::mem::take(&mut outcome.facts), + dry_run, + specforge_ops::testing::caller(), + ) + .unwrap(); + p +} + +/// A machine whose one run does `run` and exits 0. +fn machine(run: ScriptedRun) -> ScriptedMachine { + ScriptedMachine::new().answering(ScriptedRun { + exit_code: Some(0), + ..run + }) +} + +/// A run that writes `report` at the report location. +fn writing(report: &str) -> ScriptedRun { + ScriptedRun { + files: vec![("".into(), report.to_string())], + ..ScriptedRun::default() + } +} + +/// Collect `runner` of `p` through `machine`, everything approved. +fn collected(p: &TestProject, runner: &str, machine: &ScriptedMachine) -> Outcome { + let compiled = p.compile(); + let view = specforge_ops::view::ProjectView::of(&compiled); + // The disk, as the CLI lends it: the syntax import reads through the host's own reader. + let ports = Ports { + fs: Arc::new(specforge_fs::LocalFs), + ..specforge_effects::testing::ports() + }; + let consent = MemoryConsent::approving_everything(); + let containment = Containment::unbounded(); + collect( + &view, + Request { + runner: Some(runner), + mode: Mode::Run(RunnerOutput::Discard), + announce: &mut |_, _| {}, + filter: None, + caller: Caller::new(&containment, Asking::Nobody).lending( + &ports, + &consent, + EffectsMode::Online, + ), + }, + machine, + &consent, + ) + .map_err(|refusal| format!("{}: {}", refusal.error.code, refusal.error.message)) + .unwrap() +} + +/// The facts `collector` answered of `kind`. +fn facts<'o>(outcome: &'o Outcome, collector: &str, kind: &str) -> Vec<&'o Fact> { + outcome + .facts + .stores + .iter() + .filter(|s| s.collector == collector) + .flat_map(|s| &s.facts) + .filter(|f| f.kind == kind) + .collect() +} + +fn ids(facts: &[&Fact]) -> Vec { + facts.iter().map(|f| f.id.clone()).collect() +} + +/// The messages of `outcome`'s diagnostics with `code`. +fn said(outcome: &Outcome, code: &str) -> Vec { + outcome + .diagnostics + .iter() + .filter(|d| d.code == code) + .map(|d| d.message.clone()) + .collect() +} + +#[specforge_test_macros::test(requirement = "FEATURE-151")] +fn the_legacy_vitest_is_detected_beside_javascript_vitest() { + let p = fixture(); + let compiled = p.compile(); + let errors: Vec = compiled + .diagnostics() + .iter() + .filter(|d| d.code.starts_with('E')) + .map(|d| format!("{}: {}", d.code, d.message)) + .collect(); + assert!(errors.is_empty(), "{errors:?}"); + let view = specforge_ops::view::ProjectView::of(&compiled); + let detected = specforge_ops::analysis::collect::detected_here( + view.registries().declarations(), + p.root(), + None, + ); + let named = |name: &str| { + detected + .iter() + .find(|c| c.name == name) + .map(|c| c.extension.clone()) + }; + assert_eq!(named("vitest").as_deref(), Some("@specforge/vitest")); + assert_eq!( + named("javascript-vitest").as_deref(), + Some("@javascript/vitest") + ); +} + +#[specforge_test_macros::test(requirement = "FEATURE-144")] +fn javascript_coverage_records_the_lines_of_an_item() { + let p = fixture(); + // c8's LCOV: the two body lines of `add`. + let lcov = + "TN:\nSF:packages/core/src/index.ts\nFN:2,add\nFNDA:1,add\nDA:2,1\nDA:3,1\nend_of_record\n"; + let outcome = collected(&p, "javascript-coverage", &machine(writing(lcov))); + let coverage = facts(&outcome, "javascript-coverage", "coverage"); + assert_eq!(ids(&coverage), ["cov:js:@acme/core/src/index.ts::add"]); + assert_eq!(coverage[0].fields["lines_hit"], 2); +} + +/// ESLint's SARIF: one `no-unused-vars` result at line 2 of `view.tsx`. +const SARIF: &str = r#"{ + "version": "2.1.0", + "runs": [{ + "tool": {"driver": {"name": "ESLint", "version": "10.15.0", "rules": [{"id": "no-unused-vars"}]}}, + "results": [{ + "level": "error", + "message": {"text": "'title' is defined but never used."}, + "ruleId": "no-unused-vars", + "locations": [{"physicalLocation": { + "artifactLocation": {"uri": "packages/core/src/view.tsx"}, + "region": {"startLine": 2, "startColumn": 3, "endLine": 2, "endColumn": 9} + }}] + }] + }] +}"#; + +#[specforge_test_macros::test(requirement = "FEATURE-145")] +fn javascript_lint_records_a_finding_at_its_item() { + let p = fixture(); + let outcome = collected(&p, "javascript-lint", &machine(writing(SARIF))); + let findings = facts(&outcome, "javascript-lint", "static_finding"); + assert_eq!(findings.len(), 1, "{:?}", ids(&findings)); + assert_eq!( + findings[0].fields["item"], + "js:@acme/core/src/view.tsx::View" + ); +} + +/// cyclonedx-npm's BOM of the root package `app`: its one dependency, lodash. +const BOM: &str = r#"{ + "bomFormat": "CycloneDX", + "specVersion": "1.6", + "version": 1, + "metadata": {"component": {"type": "application", "name": "app", "version": "0.0.0", + "bom-ref": "app@0.0.0", "purl": "pkg:npm/app@0.0.0"}}, + "components": [{"type": "library", "name": "lodash", "version": "4.17.15", + "bom-ref": "lodash@4.17.15", "purl": "pkg:npm/lodash@4.17.15"}], + "dependencies": [{"ref": "app@0.0.0", "dependsOn": ["lodash@4.17.15"]}, {"ref": "lodash@4.17.15"}] +}"#; + +/// osv-scanner's report: one advisory of lodash in the npm lockfile, and a PyPI package of another lockfile, an +/// ecosystem no pack collects. +const OSV: &str = r#"{ + "results": [ + { + "source": {"path": "package-lock.json", "type": "lockfile"}, + "packages": [{ + "package": {"name": "lodash", "version": "4.17.15", "ecosystem": "npm"}, + "vulnerabilities": [{ + "id": "GHSA-35jh-r3h4-6jhm", + "aliases": ["CVE-2021-23337"], + "summary": "Command Injection in lodash", + "affected": [{"package": {"ecosystem": "npm", "name": "lodash", "purl": "pkg:npm/lodash"}}], + "database_specific": {"severity": "HIGH"} + }], + "groups": [{"ids": ["GHSA-35jh-r3h4-6jhm"]}] + }] + }, + { + "source": {"path": "tools/requirements.txt", "type": "lockfile"}, + "packages": [{ + "package": {"name": "requests", "version": "2.0.0", "ecosystem": "PyPI"}, + "vulnerabilities": [{"id": "PYSEC-2099-1", "summary": "An invented advisory"}], + "groups": [{"ids": ["PYSEC-2099-1"]}] + }] + } + ] +}"#; + +#[specforge_test_macros::test(requirement = "FEATURE-147")] +#[specforge_test_macros::test(requirement = "FEATURE-128")] +fn javascript_deps_records_dependencies_and_vulnerabilities_and_warns_of_a_skipped_entry() { + let p = fixture(); + let sbom = collected(&p, "javascript-sbom", &machine(writing(BOM))); + assert_eq!( + ids(&facts(&sbom, "javascript-sbom", "dependency")), + ["dep:pkg:npm/app/pkg%3Anpm%2Flodash%404.17.15"] + ); + + let osv = collected(&p, "javascript-osv", &machine(writing(OSV))); + let vulnerabilities = facts(&osv, "javascript-osv", "vulnerability"); + assert_eq!(vulnerabilities.len(), 1, "{:?}", ids(&vulnerabilities)); + assert_eq!(vulnerabilities[0].fields["package"], "pkg:npm/app"); + assert_eq!(vulnerabilities[0].fields["osv_id"], "GHSA-35jh-r3h4-6jhm"); + let warned = said(&osv, "W203"); + assert_eq!(warned.len(), 1, "{warned:?}"); + assert!( + warned[0].contains("'javascript-osv'") + && warned[0].contains("'requests' 2.0.0 in 'tools/requirements.txt'"), + "{warned:?}" + ); +} + +/// api-extractor's doc model of `@acme/core`: its function `add`. +const DOC_MODEL: &str = r#"{ + "metadata": {"toolPackage": "@microsoft/api-extractor", "toolVersion": "7.60.1", "schemaVersion": 1011}, + "kind": "Package", + "canonicalReference": "@acme/core!", + "name": "@acme/core", + "members": [{ + "kind": "EntryPoint", + "canonicalReference": "@acme/core!", + "name": "", + "members": [{ + "kind": "Function", + "canonicalReference": "@acme/core!add:function(1)", + "excerptTokens": [{"kind": "Content", "text": "export declare function add(a: number, b: number): number;"}], + "fileUrlPath": "dist/index.d.ts", + "releaseTag": "Public", + "name": "add" + }] + }] +}"#; + +#[specforge_test_macros::test(requirement = "FEATURE-149")] +fn javascript_api_writes_its_config_and_records_the_doc_model() { + let p = fixture(); + let outcome = collected(&p, "javascript-api", &machine(writing(DOC_MODEL))); + let config = p.read(".specforge/reports/javascript-api.api-extractor.json"); + assert!( + config.contains(r#""apiJsonFilePath": ""#) + && config.contains("javascript-api.api.json") + && !config.contains("{report}"), + "{config}" + ); + let api = facts(&outcome, "javascript-api", "api_item"); + assert_eq!(ids(&api), ["api:js:%40acme%2Fcore::add"]); + assert_eq!(api[0].fields["item"], "js:@acme/core/src/index.ts::add"); +} + +/// api-extractor's recordings of `@demo/widget` (the API reader's fixtures): the committed report before a break, and +/// the doc model and report of the run that breaks it. +const TAGGED_REPORT: &str = include_str!( + "../../../../extensions/code/api/fixtures/api-extractor-7.60.1.widget-tagged.api.md" +); +const CHANGED_MODEL: &str = include_str!( + "../../../../extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.api.json" +); +const CHANGED_REPORT: &str = include_str!( + "../../../../extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.api.md" +); + +/// Each `api_item`'s name path (its id after `::`) and its `change`. +fn changes(outcome: &Outcome) -> Vec<(String, Option)> { + facts(outcome, "javascript-api", "api_item") + .iter() + .map(|f| { + let name = f.id.split_once("::").map_or("", |(_, name)| name); + let change = f.fields.get("change").and_then(|c| c.as_str()); + (name.to_string(), change.map(str::to_string)) + }) + .collect() +} + +#[specforge_test_macros::test(requirement = "FEATURE-149")] +fn javascript_api_reads_the_committed_report_and_not_temp() { + let p = fixture(); + // The committed report, stamped before the run: the accepted side is read whatever its age, unlike a report. + p.write("etc/widget.api.md", TAGGED_REPORT); + std::fs::File::options() + .write(true) + .open(p.root().join("etc/widget.api.md")) + .unwrap() + .set_modified(ScriptedMachine::started() - Duration::from_secs(1)) + .unwrap(); + // api-extractor's own copy of this run's report: fresh, and never the accepted side. + p.write("temp/widget.api.md", CHANGED_REPORT); + + let outcome = collected(&p, "javascript-api", &machine(writing(CHANGED_MODEL))); + let against_etc = changes(&outcome); + for (name, change) in [("create", "changed"), ("trial", "removed")] { + assert!( + against_etc.contains(&(name.to_string(), Some(change.to_string()))), + "{name} {change}: {against_etc:?}" + ); + } + assert_eq!(said(&outcome, "W203"), Vec::::new()); + + p.remove("etc/widget.api.md"); + let outcome = collected(&p, "javascript-api", &machine(writing(CHANGED_MODEL))); + let only_temp = changes(&outcome); + assert!(!only_temp.is_empty()); + assert!( + only_temp.iter().all(|(_, change)| change.is_none()), + "{only_temp:?}" + ); + assert_eq!(said(&outcome, "W203"), Vec::::new()); +} + +/// The `test` facts `collector` answered: (id, status). +fn tests_of(outcome: &Outcome, collector: &str) -> Vec<(String, String)> { + facts(outcome, collector, "test") + .iter() + .map(|f| { + ( + f.id.clone(), + f.fields["status"].as_str().unwrap().to_string(), + ) + }) + .collect() +} + +/// Two cases of `board`, `adds` passed and `fails` failed, each test id under the workspace's test file. +fn assert_two_cases(outcome: &Outcome, collector: &str) { + let tests = tests_of(outcome, collector); + assert_eq!(tests.len(), 2, "{tests:?}"); + for (id, _) in &tests { + assert!( + id.starts_with("js:@acme/core/test/board.test.ts#"), + "{tests:?}" + ); + } + let status = |name: &str| { + tests + .iter() + .find(|(id, _)| id.ends_with(name)) + .map(|(_, status)| status.as_str()) + }; + assert_eq!(status("adds"), Some("passed"), "{tests:?}"); + assert_eq!(status("fails"), Some("failed"), "{tests:?}"); +} + +#[specforge_test_macros::test(requirement = "FEATURE-151")] +fn javascript_vitest_records_its_junit_cases() { + let p = fixture(); + let junit = format!( + r#" + + + + + + AssertionError: expected 1 to be 2 + + + +"# + ); + let outcome = collected(&p, "javascript-vitest", &machine(writing(&junit))); + assert_two_cases(&outcome, "javascript-vitest"); +} + +#[specforge_test_macros::test(requirement = "FEATURE-152")] +fn javascript_jest_writes_its_env_file_and_records_its_junit_cases() { + let p = fixture(); + let junit = format!( + r#" + + + + + + Error: expect(received).toBe(expected) + + + +"# + ); + let outcome = collected(&p, "javascript-jest", &machine(writing(&junit))); + let env = p.read(".specforge/reports/javascript-jest.jest-junit.env.toml"); + assert!( + env.contains("JEST_JUNIT_OUTPUT_FILE = \"") + && env.contains("javascript-jest.xml") + && env.contains("JEST_JUNIT_ADD_FILE_ATTRIBUTE = \"true\""), + "{env}" + ); + assert_two_cases(&outcome, "javascript-jest"); +} + +#[specforge_test_macros::test(requirement = "FEATURE-153")] +fn javascript_playwright_records_its_captured_junit_cases() { + let p = fixture(); + let junit = format!( + "\n\ +\n\ +\n\n\ +\n\ +Error\n\n\ +\n\n" + ); + let run = ScriptedRun { + stdout: Some(junit), + ..ScriptedRun::default() + }; + let outcome = collected(&p, "javascript-playwright", &machine(run)); + assert_two_cases(&outcome, "javascript-playwright"); +} diff --git a/crates/app/ops/tests/javascript_source.rs b/crates/app/ops/tests/javascript_source.rs index 0ad219956d..12c16e2968 100644 --- a/crates/app/ops/tests/javascript_source.rs +++ b/crates/app/ops/tests/javascript_source.rs @@ -166,6 +166,7 @@ fn a_fixture_workspace_collects_its_items_with_ids_kinds_and_locations() { expected.extend( [ "js:@acme/core/src/view.tsx::View", + "js:@acme/core/test/board.test.ts::adds", "js:app/packages/cli/bin/cli.mjs::main", "js:app/scripts/legacy.cjs::build", "js:app/scripts/legacy.cjs::clean", @@ -176,7 +177,7 @@ fn a_fixture_workspace_collects_its_items_with_ids_kinds_and_locations() { assert_eq!( ids(&outcome, "item"), expected, - "nothing from test/, coverage/ or *.min.js" + "from test/ only its test call, nothing from coverage/ or *.min.js" ); let add = fact(&outcome, &core("add")); @@ -222,7 +223,7 @@ fn a_fixture_workspace_collects_its_items_with_ids_kinds_and_locations() { } #[specforge_test_macros::test(requirement = "FEATURE-056")] -fn a_test_file_mints_no_item_beside_its_runners_test() { +fn a_test_call_is_an_item_whose_test_id_is_its_runners_test() { let p = project(FIXTURE, true); let outcome = collected_with( &p, @@ -236,11 +237,23 @@ fn a_test_file_mints_no_item_beside_its_runners_test() { .map(|f| f.id.as_str()) .collect(); assert_eq!(tests, ["js:@acme/core/test/board.test.ts#adds"]); + // The call `test("adds", …)` is the one item of its file: the helper `function adds()` beside it is none. let from_tests: Vec<&str> = ids(&outcome, "item") .into_iter() .filter(|id| id.contains("/test/")) .collect(); - assert!(from_tests.is_empty(), "{from_tests:?}"); + assert_eq!(from_tests, ["js:@acme/core/test/board.test.ts::adds"]); + let call = fact(&outcome, from_tests[0]); + assert_eq!(call.fields["kind"], json!(["function"])); + assert_eq!(call.fields["attrs"], json!(["test"])); + assert_eq!( + call.fields["test_id"], tests[0], + "node-test's id for the case" + ); + assert_eq!( + call.at[0].start_line, 7, + "the call's line, not the helper's" + ); } #[specforge_test_macros::test(requirement = "FEATURE-056")] @@ -300,7 +313,7 @@ fn the_items_point_at_their_package_fact() { .unwrap(); let compiled = p.compile(); let items = compiled.graph().nodes_by_kind("item"); - assert_eq!(items.len(), 17); + assert_eq!(items.len(), 18, "seventeen source items and one test call"); let code: Vec = compiled .diagnostics() .iter() diff --git a/crates/app/ops/tests/operations/collect/mod.rs b/crates/app/ops/tests/operations/collect/mod.rs index 9a0e7632fc..420cff8b8b 100644 --- a/crates/app/ops/tests/operations/collect/mod.rs +++ b/crates/app/ops/tests/operations/collect/mod.rs @@ -16,9 +16,11 @@ mod ports; mod reads; mod refusals; mod report_first; +mod report_globs; mod report_paths; mod retained; mod runs; +mod warnings; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -226,6 +228,15 @@ impl Runner { self } + /// Its export also returns the warning `line` (ADR 0389). + pub fn warning(mut self, line: &str) -> Self { + let Answer::Output(output) = &mut self.answer else { + panic!("a trapping runner warns of nothing"); + }; + output.warnings.push(line.to_string()); + self + } + /// Its export traps. pub fn trapping(mut self) -> Self { self.answer = Answer::Trap; diff --git a/crates/app/ops/tests/operations/collect/report_globs.rs b/crates/app/ops/tests/operations/collect/report_globs.rs new file mode 100644 index 0000000000..71183c7f1c --- /dev/null +++ b/crates/app/ops/tests/operations/collect/report_globs.rs @@ -0,0 +1,313 @@ +//! A collector's report may be a glob over project files the tool writes itself (ADR 0389): after a run the host +//! hands the export every fresh match of the shared walk (ADR 0293 D4), each held by containment. + +use super::{Fixture, Machine, Runner, paths}; +use specforge_ops::analysis::collect::{CollectField, Mode, Outcome, RunnerOutput}; +use specforge_ops::asking::Asking; +use specforge_ops::testing::{ScriptedMachine, ScriptedRun}; +use specforge_ops::{Containment, Refusal}; +use specforge_test_macros::test as specforge_test; + +const GLOB: &str = "**/rust-sbom.cdx.json"; + +/// Collector `acme` reporting `GLOB`, run as `acme` (no `{report}`). +fn sbom() -> Runner { + Runner::new("acme").run(&["acme"]).report(GLOB) +} + +/// A run writing `files` (relative to the project root, a glob's base) and exiting 0. +fn writing(files: &[&str]) -> ScriptedRun { + ScriptedRun { + files: files + .iter() + .map(|path| ((*path).into(), "{}".to_string())) + .collect(), + exit_code: Some(0), + ..ScriptedRun::default() + } +} + +/// Run `acme`, named, with every capability approved. +fn run(fx: &Fixture, machine: &Machine) -> Result> { + fx.collect_with( + Some("acme"), + Mode::Run(RunnerOutput::Discard), + &Containment::unbounded(), + Asking::Nobody, + machine, + ) +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_report_glob_hands_over_every_match_the_run_wrote_sorted() { + let fx = Fixture::new(vec![sbom()]); + let machine = Machine::new() + .approving_everything() + .answering(writing(&["b/c/rust-sbom.cdx.json", "a/rust-sbom.cdx.json"])); + + run(&fx, &machine).unwrap(); + + assert_eq!( + paths(&fx.dispatched()[0]), + ["a/rust-sbom.cdx.json", "b/c/rust-sbom.cdx.json"] + ); +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_match_older_than_the_run_is_not_handed_over_and_nothing_is_removed() { + let fx = Fixture::new(vec![sbom()]); + fx.write("old/rust-sbom.cdx.json", "{}"); + std::fs::File::options() + .write(true) + .open(fx.root().join("old/rust-sbom.cdx.json")) + .unwrap() + .set_modified(ScriptedMachine::started() - std::time::Duration::from_secs(1)) + .unwrap(); + let machine = Machine::new() + .approving_everything() + .answering(writing(&["a/rust-sbom.cdx.json"])); + + run(&fx, &machine).unwrap(); + + assert_eq!(paths(&fx.dispatched()[0]), ["a/rust-sbom.cdx.json"]); + assert!(fx.exists("old/rust-sbom.cdx.json"), "nothing is removed"); +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_report_glob_skips_build_output_and_enters_no_link() { + let fx = Fixture::new(vec![sbom()]); + #[cfg(unix)] + let outside = tempfile::tempdir().unwrap(); + #[cfg(unix)] + { + std::fs::write(outside.path().join("rust-sbom.cdx.json"), "{}").unwrap(); + std::os::unix::fs::symlink(outside.path(), fx.root().join("linked")).unwrap(); + } + let machine = Machine::new().approving_everything().answering(writing(&[ + "target/debug/rust-sbom.cdx.json", + "node_modules/x/rust-sbom.cdx.json", + "a/rust-sbom.cdx.json", + ])); + + run(&fx, &machine).unwrap(); + + assert_eq!(paths(&fx.dispatched()[0]), ["a/rust-sbom.cdx.json"]); +} + +#[cfg(unix)] +#[specforge_test(requirement = "FEATURE-128")] +fn a_match_linking_out_of_the_project_is_not_read_and_named_in_a_w203() { + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("bom.json"), "{\"secret\": 1}").unwrap(); + let linked = |fx: &Fixture| { + std::fs::create_dir(fx.root().join("a")).unwrap(); + std::os::unix::fs::symlink( + outside.path().join("bom.json"), + fx.root().join("a/rust-sbom.cdx.json"), + ) + .unwrap(); + }; + let collect = |fx: &Fixture, machine: &Machine| { + fx.collect_with( + Some("acme"), + Mode::Run(RunnerOutput::Discard), + &Containment::within(fx.root()), + Asking::Nobody, + machine, + ) + }; + + let fx = Fixture::new(vec![sbom()]); + linked(&fx); + let machine = Machine::new() + .approving_everything() + .answering(writing(&["b/rust-sbom.cdx.json"])); + let outcome = collect(&fx, &machine).unwrap(); + assert_eq!(paths(&fx.dispatched()[0]), ["b/rust-sbom.cdx.json"]); + let warned: Vec<&str> = outcome + .diagnostics + .iter() + .filter(|d| d.code == "W203") + .map(|d| d.message.as_str()) + .collect(); + assert_eq!(warned.len(), 1, "{warned:?}"); + assert!( + warned[0].contains("'acme'") && warned[0].contains("a/rust-sbom.cdx.json"), + "{}", + warned[0] + ); + + // The only match links out: the "no report" refusal names it. + let fx = Fixture::new(vec![sbom()]); + linked(&fx); + let machine = Machine::new() + .approving_everything() + .answering(writing(&[])); + let refusal = collect(&fx, &machine).unwrap_err(); + assert_eq!(refusal.error.code, "E045", "{refusal:?}"); + assert!( + refusal.error.message.contains("produced no report") + && refusal.error.message.contains("a/rust-sbom.cdx.json"), + "{}", + refusal.error.message + ); +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_hard_linked_report_is_refused_in_a_bounded_containment() { + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("bom.json"), "{\"secret\": 1}").unwrap(); + // The project's only match is a second name of a file outside it: the run writes nothing. + let linked = || { + let fx = Fixture::new(vec![sbom()]); + std::fs::create_dir(fx.root().join("a")).unwrap(); + std::fs::hard_link( + outside.path().join("bom.json"), + fx.root().join("a/rust-sbom.cdx.json"), + ) + .unwrap(); + let machine = Machine::new() + .approving_everything() + .answering(writing(&[])); + (fx, machine) + }; + + let (fx, machine) = linked(); + let refusal = fx + .collect_with( + Some("acme"), + Mode::Run(RunnerOutput::Discard), + &Containment::within(fx.root()), + Asking::Nobody, + &machine, + ) + .unwrap_err(); + assert_eq!(refusal.error.code, "E045", "{refusal:?}"); + assert!( + refusal.error.message.contains("failed to read report") + && refusal.error.message.contains("rust-sbom.cdx.json"), + "{}", + refusal.error.message + ); + assert!(fx.dispatched().is_empty(), "the collector receives nothing"); + + // The CLI runs unbounded (ADR 0092 D6): the same link is read. + let (fx, machine) = linked(); + run(&fx, &machine).unwrap(); + assert_eq!(paths(&fx.dispatched()[0]), ["a/rust-sbom.cdx.json"]); +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_report_glob_with_a_report_placeholder_or_a_capture_is_e058() { + let told = Runner::new("acme").report(GLOB); + let configured = sbom() + .run(&["acme", "--config", "{config}"]) + .configuring("acme.toml", "out = \"{report}\""); + let captured = sbom().capturing_stdout(); + for runner in [told, configured, captured] { + let fx = Fixture::new(vec![runner]); + let machine = Machine::new().approving_everything(); + let refusal = run(&fx, &machine).unwrap_err(); + assert_eq!(refusal.error.code, "E058", "{refusal:?}"); + assert!( + refusal.error.message.contains("'acme'"), + "{}", + refusal.error.message + ); + assert!(machine.runs().is_empty(), "{:?}", machine.runs()); + } +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_report_glob_matching_nothing_or_past_the_walk_cap_is_e045() { + let fx = Fixture::new(vec![sbom()]); + let machine = Machine::new() + .approving_everything() + .answering(writing(&["a/other.json"])); + let refusal = run(&fx, &machine).unwrap_err(); + assert_eq!(refusal.error.code, "E045"); + assert!( + refusal.error.message.contains("produced no report"), + "{refusal:?}" + ); + + let fx = Fixture::new(vec![sbom()]); + std::fs::create_dir(fx.root().join("many")).unwrap(); + for i in 0..20_001 { + std::fs::write(fx.root().join(format!("many/{i}")), "").unwrap(); + } + let machine = Machine::new() + .approving_everything() + .answering(writing(&["a/rust-sbom.cdx.json"])); + let refusal = run(&fx, &machine).unwrap_err(); + assert_eq!(refusal.error.code, "E045"); + assert!( + refusal.error.message.contains("20000"), + "{}", + refusal.error.message + ); +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_report_glob_runs_with_its_base_as_the_report_and_no_report_variable() { + let fx = Fixture::new(vec![sbom()]); + let machine = Machine::new() + .approving_everything() + .answering(writing(&["a/rust-sbom.cdx.json"])); + + run(&fx, &machine).unwrap(); + + let runs = machine.runs(); + assert_eq!(runs[0].report, fx.root()); + assert!(!runs[0].report_in_env); + + let fx = Fixture::new(vec![ + Runner::new("acme").run(&["acme"]).report("out/**/a.json"), + ]); + let machine = Machine::new() + .approving_everything() + .answering(writing(&["x/a.json"])); + run(&fx, &machine).unwrap(); + assert_eq!(machine.runs()[0].report, fx.root().join("out")); + assert_eq!(paths(&fx.dispatched()[0]), ["out/x/a.json"]); +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_report_glob_ending_in_a_wildcard_is_e058_and_nothing_runs() { + for glob in ["**/*", "**/*.pem", "**/.env*", "keys/?.json"] { + let fx = Fixture::new(vec![Runner::new("acme").run(&["acme"]).report(glob)]); + fx.write("a/id.pem", "secret"); + let machine = Machine::new().approving_everything(); + let refusal = run(&fx, &machine).unwrap_err(); + assert_eq!(refusal.error.code, "E058", "{glob}: {refusal:?}"); + assert!( + refusal.error.message.contains("literal file name"), + "{}", + refusal.error.message + ); + assert!(machine.runs().is_empty(), "{:?}", machine.runs()); + assert!(fx.dispatched().is_empty(), "{glob}"); + } +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_report_over_the_byte_cap_is_e045_naming_it() { + let fx = Fixture::new(vec![sbom()]); + let half = specforge_ops::analysis::collect::REPORT_BYTES_MAX / 2 + 1; + for dir in ["a", "b"] { + std::fs::create_dir(fx.root().join(dir)).unwrap(); + let file = std::fs::File::create(fx.root().join(dir).join("rust-sbom.cdx.json")).unwrap(); + file.set_len(half).unwrap(); + } + let machine = Machine::new() + .approving_everything() + .answering(writing(&[])); + let refusal = run(&fx, &machine).unwrap_err(); + assert_eq!(refusal.error.code, "E045", "{refusal:?}"); + assert!( + refusal.error.message.contains("67108864"), + "{}", + refusal.error.message + ); + assert!(fx.dispatched().is_empty()); +} diff --git a/crates/app/ops/tests/operations/collect/warnings.rs b/crates/app/ops/tests/operations/collect/warnings.rs new file mode 100644 index 0000000000..6bbb7ea746 --- /dev/null +++ b/crates/app/ops/tests/operations/collect/warnings.rs @@ -0,0 +1,61 @@ +//! A collector's warnings (ADR 0389): each line its export returns under `warnings` is one W203 naming the +//! collector, escaped, at most 100 per collector and then one counting the rest. + +use specforge_common::{Diagnostic, Severity}; +use specforge_test_macros::test as specforge_test; + +use super::{Fixture, Machine, Runner}; + +/// Collect `runner` from its existing report: the W203 diagnostics of the outcome. +fn warned(runner: Runner) -> Vec { + let fixture = Fixture::new(vec![runner]); + fixture.write("out/acme.json", "{}"); + let outcome = fixture + .no_run(Some("acme"), &Machine::new()) + .expect("the collect runs"); + outcome + .diagnostics + .into_iter() + .filter(|d| d.code == "W203") + .collect() +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_warning_line_is_one_w203_naming_the_collector() { + let line = "skipped 1 file outside the project: /elsewhere/a.rs"; + let warned = warned(Runner::new("acme").warning(line)); + assert_eq!(warned.len(), 1, "{warned:?}"); + assert_eq!(warned[0].severity, Severity::Warning); + let message = &warned[0].message; + assert!(message.contains("'acme'"), "{message}"); + assert!(message.contains("@acme/acme"), "{message}"); + assert!(message.contains(line), "{message}"); +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_warning_line_prints_escaped() { + let warned = warned(Runner::new("acme").warning("\u{1b}[31mred")); + assert_eq!(warned.len(), 1, "{warned:?}"); + assert!(!warned[0].message.contains('\u{1b}'), "{:?}", warned[0]); + assert!( + warned[0].message.contains("\\u{1b}[31mred"), + "{:?}", + warned[0] + ); +} + +#[specforge_test(requirement = "FEATURE-128")] +fn past_a_hundred_warning_lines_one_w203_counts_the_rest() { + let runner = (0..150).fold(Runner::new("acme"), |runner, i| { + runner.warning(&format!("line {i}")) + }); + let warned = warned(runner); + assert_eq!(warned.len(), 101); + assert!(warned[99].message.ends_with("line 99"), "{:?}", warned[99]); + assert!(warned[100].message.contains("50 more"), "{:?}", warned[100]); +} + +#[specforge_test(requirement = "FEATURE-128")] +fn a_collector_answering_no_warnings_gives_no_w203() { + assert!(warned(Runner::new("acme").proving("a", "t")).is_empty()); +} diff --git a/crates/app/ops/tests/operations/context_records.rs b/crates/app/ops/tests/operations/context_records.rs index 99cf3e7f0e..5689dca558 100644 --- a/crates/app/ops/tests/operations/context_records.rs +++ b/crates/app/ops/tests/operations/context_records.rs @@ -68,6 +68,7 @@ fn apply(project: &TestProject, origin: &Origin, ops: Value) -> String { fn gsd() -> Origin { Origin::Command { extension: GSD_JUDGED.to_string(), + imports: false, } } @@ -175,6 +176,7 @@ fn a_record_is_refused_for_an_unknown_route_an_unrecorded_kind_another_origin_or let before = spec(&project); let other = Origin::Command { extension: "@acme/other".to_string(), + imports: false, }; for (origin, ops, reason) in [ ( diff --git a/crates/app/ops/tests/operations/extension_calls.rs b/crates/app/ops/tests/operations/extension_calls.rs index 10f7b48718..5a20aa55f5 100644 --- a/crates/app/ops/tests/operations/extension_calls.rs +++ b/crates/app/ops/tests/operations/extension_calls.rs @@ -82,6 +82,7 @@ fn collector() -> Collector { config: None, filter: Vec::new(), install: None, + requires: Vec::new(), } } diff --git a/crates/app/ops/tests/operations/harness.rs b/crates/app/ops/tests/operations/harness.rs index 983c459477..30f5056a3e 100644 --- a/crates/app/ops/tests/operations/harness.rs +++ b/crates/app/ops/tests/operations/harness.rs @@ -300,6 +300,7 @@ fn a_typed_edit_of_a_context_field_is_refused_context_field() { Origin::mcp(), Origin::Command { extension: specforge_project::testing::GSD_JUDGED.to_string(), + imports: false, }, ]; for origin in &origins { diff --git a/crates/app/ops/tests/operations/imports.rs b/crates/app/ops/tests/operations/imports.rs new file mode 100644 index 0000000000..6944a0e09a --- /dev/null +++ b/crates/app/ops/tests/operations/imports.rs @@ -0,0 +1,171 @@ +//! A command that declares `imports` copies history recorded outside the spec, so its plan is judged for host errors +//! only (ADR 0392): an extension's rule error about authored entities lands; a host error, a first-party +//! (`@specforge/*`) extension's error and one that judges collected facts still refuse the whole plan. A collector's +//! plan (ADR 0303) lands that first-party error too; an import's does not. A command that does not declare it is +//! refused for every error (E080). `@t/core`'s `import` declares it, `record` does not; the guard pass reports E087 +//! while a phase's goal is [`GUARDED`], and E901, a code that judges collected facts, while another phase's goal is +//! [`RACED`] too. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use specforge_project::testing::{ + CORE, GSD_WRITES_EXTENSIONS, GUARDED, GsdWrites, RACED, TestProject, component_runtime, + gsd_writes_answer, +}; +use specforge_test_macros::test as specforge_test; +use specforge_wasm::testing::InProcessRuntime; + +use crate::plans::{MILESTONE, Ran, compiled, project, revision, run_command, set}; + +/// The plan that leaves the project with an extension's error: phase `03`'s goal set to [`GUARDED`]. +fn guarded(p: &TestProject) -> Value { + json!([set( + "v1.0/03", + "goal", + json!(GUARDED), + &revision(p, "m.spec") + )]) +} + +/// The plan that leaves the project with a host error: a decision whose phase is no entity. +fn dangling() -> Value { + json!([{"op": "create", "kind": "decision", "id": "D-01", "title": "D", "file": "d.spec", + "revision": "absent", "fields": {"phase": "99", "origin": "context"}}]) +} + +/// The runtime in which `@t/core`'s command `id` answers `ops`, its guard on. +fn runtime(id: &str, ops: Value) -> Arc { + Arc::new( + GsdWrites::new() + .guarding_a_goal() + .answering(CORE, &format!("cmd__{id}"), gsd_writes_answer(0, ops)) + .runtime(), + ) +} + +/// `@t/core`'s command `id` answering `ops`, its guard on. +fn ran(p: &TestProject, id: &str, ops: Value) -> Ran { + let runtime = runtime(id, ops); + run_command(p, &compiled(p, &runtime), &runtime, "core", id) +} + +/// `import` answering [`guarded`], another writer landing `z.spec` (`landed`) after the compile: the plan is judged +/// again over the disk, under the write lock. +fn imported_after(p: &TestProject, landed: &str) -> Ran { + let runtime = runtime("import", guarded(p)); + let compiled = compiled(p, &runtime); + std::fs::write(p.root().join("z.spec"), landed).unwrap(); + run_command(p, &compiled, &runtime, "core", "import") +} + +/// The code a plan was refused with, if it was. +fn refusal(ran: &Ran) -> Option<&str> { + ran.refusal.as_ref().map(|(code, _)| code.as_str()) +} + +/// The codes of the errors a refusal (E080) names. +fn refused_codes(ran: &Ran) -> Vec { + let Some((_, data)) = &ran.refusal else { + return Vec::new(); + }; + data["diagnostics"] + .as_array() + .into_iter() + .flatten() + .filter_map(|d| d["code"].as_str().map(str::to_string)) + .collect() +} + +#[specforge_test(requirement = "FEATURE-131")] +fn an_imports_plan_keeps_an_extensions_error() { + let p = project(); + let ran = ran(&p, "import", guarded(&p)); + + assert_eq!(refusal(&ran), None); + assert_eq!(ran.wrote, ["m.spec"]); + let written = std::fs::read_to_string(p.root().join("m.spec")).unwrap(); + assert!(written.contains(GUARDED), "{written}"); +} + +#[specforge_test(requirement = "FEATURE-131")] +fn an_imports_plan_that_adds_a_host_error_is_refused() { + let p = project(); + let ran = ran(&p, "import", dangling()); + + assert_eq!(refusal(&ran), Some("E080")); + assert!(ran.wrote.is_empty(), "{:?}", ran.wrote); + assert!(!p.root().join("d.spec").exists()); +} + +#[specforge_test(requirement = "FEATURE-131")] +fn a_command_that_does_not_declare_imports_is_refused_for_both() { + let p = project(); + let extension = ran(&p, "record", guarded(&p)); + let host = ran(&p, "record", dangling()); + + assert_eq!(refusal(&extension), Some("E080")); + assert_eq!(refusal(&host), Some("E080")); + assert!(extension.wrote.is_empty() && host.wrote.is_empty()); +} + +/// A first-party extension's error refuses an import (ADR 0392, ADR 0391 D9): a phase's goal is a file +/// `@specforge/checks` reads, and the import names one that does not exist, so `@specforge/checks` reports E016 with +/// its origin and a bare code. +#[specforge_test(requirement = "FEATURE-131")] +fn an_imports_plan_that_adds_a_first_party_extensions_error_is_refused() { + let mut extensions = GSD_WRITES_EXTENSIONS.to_vec(); + extensions.push("@specforge/checks"); + let p = TestProject::new() + .config(|c| { + c["name"] = "p".into(); + c["checks"] = json!({ "fields": { "phase.goal": ["@specforge/checks:file"] } }); + }) + .enabling(&extensions) + .installing_enabled() + .file("m.spec", MILESTONE); + let ops = json!([set( + "v1.0/03", + "goal", + json!("missing.md"), + &revision(&p, "m.spec") + )]); + let runtime = Arc::new( + GsdWrites::new() + .answering(CORE, "cmd__import", gsd_writes_answer(0, ops)) + .runtime() + .beside(component_runtime()), + ); + let ran = run_command(&p, &compiled(&p, &runtime), &runtime, "core", "import"); + + assert_eq!(refusal(&ran), Some("E080")); + assert_eq!(refused_codes(&ran), ["E016"]); + assert!(ran.wrote.is_empty(), "{:?}", ran.wrote); +} + +/// The re-judgement under the write lock lands what the plan's check landed: another writer's file moved the disk +/// after the compile, and the import's extension rule error is still written. +#[specforge_test(requirement = "FEATURE-131")] +fn the_re_judge_under_the_lock_keeps_an_imports_rule_error() { + let p = project(); + let ran = imported_after(&p, "phase 04 \"Four\" {\n milestone v1.0\n}\n"); + + assert_eq!(refusal(&ran), None); + let written = std::fs::read_to_string(p.root().join("m.spec")).unwrap(); + assert!(written.contains(GUARDED), "{written}"); +} + +/// The re-judgement under the write lock refuses what an import may not land: only the disk as the other writer +/// left it (a phase whose goal is [`RACED`]) adds E901, a code that judges collected facts, so only that judgement +/// sees it, and a collector's rule there would have written it. +#[specforge_test(requirement = "FEATURE-131")] +fn the_re_judge_under_the_lock_refuses_what_an_import_may_not_land() { + let p = project(); + let landed = format!("phase 04 \"Four\" {{\n milestone v1.0\n goal \"{RACED}\"\n}}\n"); + let ran = imported_after(&p, &landed); + + assert_eq!(refusal(&ran), Some("E080")); + assert_eq!(refused_codes(&ran), ["t/E901"]); + let written = std::fs::read_to_string(p.root().join("m.spec")).unwrap(); + assert!(!written.contains(GUARDED), "{written}"); +} diff --git a/crates/app/ops/tests/operations/judged_inputs.rs b/crates/app/ops/tests/operations/judged_inputs.rs index ae1bfff272..a4c4a67ce5 100644 --- a/crates/app/ops/tests/operations/judged_inputs.rs +++ b/crates/app/ops/tests/operations/judged_inputs.rs @@ -45,6 +45,7 @@ fn record(project: &specforge_project::testing::TestProject, basis: &Value) -> S .unwrap(); let origin = Origin::Command { extension: GSD_JUDGED.to_string(), + imports: false, }; match apply_plan_with( &view, diff --git a/crates/app/ops/tests/operations/main.rs b/crates/app/ops/tests/operations/main.rs index 627d376b04..bc93a32e2c 100644 --- a/crates/app/ops/tests/operations/main.rs +++ b/crates/app/ops/tests/operations/main.rs @@ -59,6 +59,7 @@ mod held_spelling; mod hooks; mod host_support; mod human; +mod imports; mod infer; mod infer_guide; mod infer_sources; diff --git a/crates/app/ops/tests/operations/migrate.rs b/crates/app/ops/tests/operations/migrate.rs index f666c0b26a..995c45162b 100644 --- a/crates/app/ops/tests/operations/migrate.rs +++ b/crates/app/ops/tests/operations/migrate.rs @@ -140,11 +140,11 @@ fn a_header_only_migration_of_the_frozen_spec_keeps_its_graph() { "{:?}", outcome.structural_differences() ); - assert!( - outcome.verdict.post_errors().next().is_none(), - "{:?}", - outcome.verdict.post_errors().collect::>() - ); + // `@code/core` 1.2.0 declares `coverage` (ADR 0388): the unedited corpus's `term coverage` is its one error. + let errors: Vec<_> = outcome.verdict.post_errors().collect(); + let pinned = errors.len() == 1 && errors[0].message.contains("ID 'coverage' collides"); + assert!(pinned, "{errors:?}"); + assert_eq!(errors[0].code, "E013", "{errors:?}"); } #[specforge_test(requirement = "FEATURE-122")] diff --git a/crates/app/ops/tests/operations/owner_reveals.rs b/crates/app/ops/tests/operations/owner_reveals.rs index eda2a51f5e..da720bc357 100644 --- a/crates/app/ops/tests/operations/owner_reveals.rs +++ b/crates/app/ops/tests/operations/owner_reveals.rs @@ -111,7 +111,7 @@ fn refused(project: &CompiledProject, field: &str) -> Option { /// The added errors `steps` are refused with, planned over `project`: their codes, or `None` when it is not refused. fn refused_steps(project: &CompiledProject, steps: &[Step]) -> Option> { - let refusal = edit::plan_steps(&ProjectView::of(project), steps, false).err()?; + let refusal = edit::plan_steps(&ProjectView::of(project), steps, edit::Lands::Nothing).err()?; assert_eq!( refusal.error.code.to_string(), "E080", diff --git a/crates/app/ops/tests/operations/plans.rs b/crates/app/ops/tests/operations/plans.rs index 11ad68f7cf..2206313d3e 100644 --- a/crates/app/ops/tests/operations/plans.rs +++ b/crates/app/ops/tests/operations/plans.rs @@ -8,6 +8,8 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; +use specforge_extension_sdk::DeclaredCategory; +use specforge_extension_sdk::prelude::{ContributionsBuilder, ExtensionMeta}; use specforge_ops::authoring::apply::{PlanOutcome, Surface, execute}; use specforge_ops::extension::command::{CommandFormat, ExtensionCommands}; use specforge_ops::view::ProjectView; @@ -428,6 +430,112 @@ fn a_harness_value_is_set_only_by_its_extension_or_a_peer() { assert_eq!(error.error.code, "harness_field"); } +/// A create of the UAT test `U9` in the new file `03-09.spec`, scoped as [`ONE`] is and holding the harness value +/// `result` `pass`: the op `gsd import` answers for a recorded result (ADR 0391 D7, assumption A7). +fn create_u9() -> Value { + json!([{"op": "create", "kind": "uat_test", "id": "U9", "title": "U9", "file": "03-09.spec", + "revision": "absent", "fields": {"phase": "03", "result": "pass"}}]) +} + +/// The create landed: the file holds the entity and the ledger its `result` line. +fn holds_u9(p: &TestProject) { + let text = std::fs::read_to_string(p.root().join("03-09.spec")).unwrap(); + assert!( + text.contains("uat_test U9") && text.contains("result"), + "{text}" + ); + assert!( + ledger(p).contains(&line("v1.0/03/U9", "result", "\"pass\"")), + "{}", + ledger(p) + ); +} + +#[specforge_test(requirement = "FEATURE-131")] +fn a_peer_creates_an_entity_holding_a_harness_value() { + let p = project(); + assert_eq!(refused(&p, UI, "ui", "mark", create_u9()), None); + holds_u9(&p); + let q = project(); + let runtime = serving(&[(OTHER, "cmd__record", 0, create_u9())]); + let ran = run_command(&q, &compiled(&q, &runtime), &runtime, "other", "record"); + assert_eq!( + ran.refusal.map(|(code, _)| code).as_deref(), + Some("harness_field") + ); + assert!(ran.wrote.is_empty(), "{:?}", ran.wrote); +} + +/// `@gsd/import`'s operation cap (ADR 0391 D9), `MAX_OPS` read from the guest's own source, so this test measures the +/// cap the importer enforces, not a copy of it: 2,000 creates apply in ~38 s; 5,000 took 218 s, 10,000 passed 60 s. +fn importer_max_ops() -> usize { + let path = specforge_repo_root::repo_root().join("gsd/import/src/limits.rs"); + let source = std::fs::read_to_string(&path).unwrap(); + source + .lines() + .find_map(|line| line.strip_prefix("pub const MAX_OPS: usize = ")) + .and_then(|value| value.trim_end_matches(';').replace('_', "").parse().ok()) + .unwrap_or_else(|| panic!("{} declares no `pub const MAX_OPS: usize`", path.display())) +} + +#[specforge_test(requirement = "FEATURE-131")] +fn one_plan_of_many_creates_applies() { + let max_ops = importer_max_ops(); + let p = TestProject::new() + .config(|c| c["name"] = "p".into()) + .enabling(&GSD_WRITES_EXTENSIONS) + .installing_enabled() + .file("m.spec", MILESTONE); + let ops: Vec = (1..=max_ops) + .map(|n| { + json!({"op": "create", "kind": "uat_test", "id": format!("U{n}"), "title": "U", + "file": format!("bulk/{}.spec", (n - 1) / 100), "revision": "absent", + "fields": {"phase": "03"}}) + }) + .collect(); + let runtime = serving(&[(UI, "cmd__mark", 0, Value::Array(ops))]); + let ran = run_command(&p, &compiled(&p, &runtime), &runtime, "ui", "mark"); + assert_eq!(ran.refusal, None); + let mut wrote = ran.wrote; + wrote.sort_unstable(); + let mut expected: Vec = (0..max_ops.div_ceil(100)) + .map(|k| format!("bulk/{k}.spec")) + .collect(); + expected.sort_unstable(); + assert_eq!(wrote, expected); +} + +/// An extension that names [`CORE`] an optional peer, with one writing command `mark`. +const OPTIONAL: &str = "@t/optional"; + +fn optional() -> ContributionsBuilder { + let mut c = ContributionsBuilder::new(ExtensionMeta::new(OPTIONAL, "1.0.0")); + c.optional_peer(CORE, "^1.0"); + let mark = json!({"id": "mark", "title": "mark", "description": "mark", "export": "cmd__mark", + "args": [], "writes": true}); + c.raw_category(DeclaredCategory::Surfaces, json!([{"commands": [mark]}])); + c +} + +#[specforge_test(requirement = "FEATURE-131")] +fn an_optional_peer_creates_an_entity_holding_a_harness_value() { + let mut enabled = GSD_WRITES_EXTENSIONS.to_vec(); + enabled.push(OPTIONAL); + let p = TestProject::new() + .config(|c| c["name"] = "p".into()) + .enabling(&enabled) + .installing_enabled() + .file("m.spec", MILESTONE); + let runtime = Arc::new(GsdWrites::new().runtime().with(optional).answer_raw( + OPTIONAL, + "cmd__mark", + gsd_writes_answer(0, create_u9()), + )); + let ran = run_command(&p, &compiled(&p, &runtime), &runtime, "optional", "mark"); + assert_eq!(ran.refusal, None); + holds_u9(&p); +} + #[specforge_test(requirement = "FEATURE-131")] fn a_plan_from_a_command_that_does_not_declare_writes_is_refused() { let p = project(); diff --git a/crates/app/ops/tests/operations/prompt_judges.rs b/crates/app/ops/tests/operations/prompt_judges.rs index 901a3e4e1d..f413113cb7 100644 --- a/crates/app/ops/tests/operations/prompt_judges.rs +++ b/crates/app/ops/tests/operations/prompt_judges.rs @@ -87,6 +87,7 @@ fn record(project: &TestProject, extension: &str, judge: &str) -> String { .unwrap(); let origin = Origin::Command { extension: extension.to_string(), + imports: false, }; match apply_plan_with( &view, diff --git a/crates/app/ops/tests/operations/settled_later.rs b/crates/app/ops/tests/operations/settled_later.rs index ff92c76139..bec4600021 100644 --- a/crates/app/ops/tests/operations/settled_later.rs +++ b/crates/app/ops/tests/operations/settled_later.rs @@ -184,7 +184,7 @@ fn reported(project: &CompiledProject) -> Vec { /// E080 refuses it with (`Err`). fn planned(spec: &str, steps: &[Step]) -> Result, Vec> { let compiled = project(spec).compile_in(runtime()); - match edit::plan_steps(&ProjectView::of(&compiled), steps, false) { + match edit::plan_steps(&ProjectView::of(&compiled), steps, edit::Lands::Nothing) { Ok(plan) => Ok(plan .report() .added diff --git a/crates/app/ops/tests/operations/verdicts.rs b/crates/app/ops/tests/operations/verdicts.rs index fe499ce1bb..dff599b85e 100644 --- a/crates/app/ops/tests/operations/verdicts.rs +++ b/crates/app/ops/tests/operations/verdicts.rs @@ -208,6 +208,7 @@ pub(crate) fn gsd_in( let plan: EditPlan = serde_json::from_value(json!({"ops": ops})).unwrap(); let origin = Origin::Command { extension: GSD_JUDGED.to_string(), + imports: false, }; match apply_plan_with( &view, diff --git a/crates/app/ops/tests/rust_packs.rs b/crates/app/ops/tests/rust_packs.rs index b24b51cbe8..f8e5ee40c8 100644 --- a/crates/app/ops/tests/rust_packs.rs +++ b/crates/app/ops/tests/rust_packs.rs @@ -570,3 +570,77 @@ fn the_source_guest_maps_the_fixture_within_its_fuel() { let outcome = collect_in(&compiled, None, &machine(None)).unwrap(); assert_eq!(facts(&outcome, "rust-source").len(), ITEMS.len()); } + +/// The fixture with `src/.rs` holding `source`, declared by its lib. +fn with_module(module: &str, source: &str) -> TestProject { + let lib = std::fs::read_to_string(format!("{FIXTURE}/src/lib.rs")).unwrap(); + fixture() + .file("src/lib.rs", format!("{lib}\nmod {module};\n")) + .file(&format!("src/{module}.rs"), source) +} + +#[specforge_test_macros::test(requirement = "FEATURE-004")] +#[specforge_test_macros::test(requirement = "FEATURE-114")] +fn a_test_compiled_out_on_the_host_is_skipped() { + let p = with_module( + "extra", + "#[cfg(windows)]\n#[test]\nfn only_on_windows() {}\n", + ); + let outcome = collected(&p, None, &machine(None)); + let id = "rust:adder#extra::only_on_windows"; + assert_eq!( + fact(&outcome, "rust-test", id).fields["status"], + "skipped", + "the recorded report lacks it: a unix host compiles it out" + ); + assert!( + !facts(&outcome, "rust-test") + .iter() + .any(|f| f.id == format!("run:{id}")), + "a test that never ran has no run" + ); +} + +#[specforge_test_macros::test(requirement = "FEATURE-002")] +#[specforge_test_macros::test(requirement = "FEATURE-113")] +fn a_guard_only_helper_is_no_test() { + let p = with_module( + "guard", + "#[specforge_test_macros::test(behavior = \"x\", __guard_only)]\nfn helper() {}\n", + ); + let outcome = collected(&p, None, &machine(None)); + let helper = fact(&outcome, "rust-source", "rust:adder::guard::helper"); + assert!( + !helper.fields.contains_key("test_id"), + "{:?}", + helper.fields + ); +} + +#[specforge_test_macros::test(requirement = "FEATURE-002")] +#[specforge_test_macros::test(requirement = "FEATURE-108")] +fn an_excluded_directory_holds_no_package() { + let manifest = "[package]\nname = \"subcrate\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"; + let with_sub = || { + fixture() + .file("sub/Cargo.toml", manifest) + .file("sub/src/lib.rs", "") + }; + let packages = |p: &TestProject| -> Vec { + facts( + &collected(p, Some("rust-cargo"), &machine(None)), + "rust-cargo", + ) + .iter() + .map(|f| f.id.clone()) + .collect() + }; + assert_eq!( + packages(&with_sub()), + ["pkg:cargo/adder", "pkg:cargo/subcrate"] + ); + let excluded = with_sub().config(|c| { + c["settings"] = serde_json::json!({"@rust/cargo": {"exclude": ["sub"]}}); + }); + assert_eq!(packages(&excluded), ["pkg:cargo/adder"]); +} diff --git a/crates/app/ops/tests/rust_report_packs.rs b/crates/app/ops/tests/rust_report_packs.rs new file mode 100644 index 0000000000..b87b48af7f --- /dev/null +++ b/crates/app/ops/tests/rust_report_packs.rs @@ -0,0 +1,443 @@ +//! The Rust report packs end to end (ADR 0389): `@rust/coverage`, `@rust/lint`, `@rust/deps`, `@rust/api` and +//! `@rust/proof` from their real blobs collect the fixture crate `tests/fixtures/rust-packs`, a scripted machine +//! standing in for each tool. Each report is a short inline text in the format of its pack's own fixture: LCOV for +//! cargo-llvm-cov, clippy's JSON messages, a CycloneDX BOM for cargo-cyclonedx, cargo-public-api's text and Kani's +//! regular output. +#![allow( + clippy::unwrap_used, + reason = "a test's unwrap is its assertion: a None or an Err fails the test" +)] + +use std::sync::Arc; +use std::time::Duration; + +use specforge_effects::testing::MemoryConsent; +use specforge_effects::{EffectsMode, Ports}; +use specforge_ops::analysis::collect::{Mode, Outcome, Request, RunnerOutput, collect}; +use specforge_ops::asking::Asking; +use specforge_ops::testing::{ScriptedMachine, ScriptedRun}; +use specforge_ops::{Caller, Containment}; +use specforge_project::testing::TestProject; +use specforge_protocol_types::Fact; + +/// The five report packs, the packs whose facts they read, and `@specforge/software`, whose behaviors the fixture's +/// tests name. +const PACKS: [&str; 9] = [ + "@specforge/software", + "@code/core", + "@rust/cargo", + "@rust/source", + "@rust/coverage", + "@rust/lint", + "@rust/deps", + "@rust/api", + "@rust/proof", +]; +const FIXTURE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/rust-packs"); + +/// The fixture crate, the report packs enabled, and the packages and items of `@rust/cargo` and `@rust/source` +/// collected and stored, as a collect of every detected collector stores them before a report pack runs. +fn fixture() -> TestProject { + let p = TestProject::copy_of(FIXTURE).enabling(&PACKS); + for collector in ["rust-cargo", "rust-source"] { + // Neither runs a command: nothing is scripted. + let mut outcome = collected(&p, collector, &ScriptedMachine::new()); + let compiled = p.compile(); + let view = specforge_ops::view::ProjectView::of(&compiled); + let dry_run = false; + specforge_ops::authoring::apply::apply_collected( + &view, + Vec::new(), + std::mem::take(&mut outcome.facts), + dry_run, + specforge_ops::testing::caller(), + ) + .unwrap(); + } + p +} + +/// A machine whose one run does `run` and exits 0. +fn machine(run: ScriptedRun) -> ScriptedMachine { + ScriptedMachine::new().answering(ScriptedRun { + exit_code: Some(0), + ..run + }) +} + +/// A run that writes `report` at the report location. +fn writing(report: &str) -> ScriptedRun { + ScriptedRun { + files: vec![("".into(), report.to_string())], + ..ScriptedRun::default() + } +} + +/// A run that prints `stdout`, which a capture pack reads. +fn printing(stdout: &str) -> ScriptedRun { + ScriptedRun { + stdout: Some(stdout.to_string()), + ..ScriptedRun::default() + } +} + +/// Collect `runner` of `p` through `machine`, everything approved, unbounded as the CLI; a refusal is its code and +/// message. +fn collect_or_refused( + p: &TestProject, + runner: &str, + machine: &ScriptedMachine, +) -> Result { + collect_within(p, runner, machine, &Containment::unbounded()) +} + +/// [`collect_or_refused`] inside `containment`. +fn collect_within( + p: &TestProject, + runner: &str, + machine: &ScriptedMachine, + containment: &Containment, +) -> Result { + let compiled = p.compile(); + // The view and the caller share the one containment, as an MCP call's do (ADR 0183). + let view = specforge_ops::view::ProjectView::of(&compiled).bounded_by(containment); + // The disk, as the CLI lends it: rust-source's reads go through the host's own reader. + let ports = Ports { + fs: Arc::new(specforge_fs::LocalFs), + ..specforge_effects::testing::ports() + }; + let consent = MemoryConsent::approving_everything(); + collect( + &view, + Request { + runner: Some(runner), + mode: Mode::Run(RunnerOutput::Discard), + announce: &mut |_, _| {}, + filter: None, + caller: Caller::new(containment, Asking::Nobody).lending( + &ports, + &consent, + EffectsMode::Online, + ), + }, + machine, + &consent, + ) + .map_err(|refusal| format!("{}: {}", refusal.error.code, refusal.error.message)) +} + +fn collected(p: &TestProject, runner: &str, machine: &ScriptedMachine) -> Outcome { + collect_or_refused(p, runner, machine).unwrap() +} + +/// The facts `collector` answered of `kind`. +fn facts<'o>(outcome: &'o Outcome, collector: &str, kind: &str) -> Vec<&'o Fact> { + outcome + .facts + .stores + .iter() + .filter(|s| s.collector == collector) + .flat_map(|s| &s.facts) + .filter(|f| f.kind == kind) + .collect() +} + +fn ids(facts: &[&Fact]) -> Vec { + facts.iter().map(|f| f.id.clone()).collect() +} + +/// The messages of `outcome`'s diagnostics with `code`. +fn said(outcome: &Outcome, code: &str) -> Vec { + outcome + .diagnostics + .iter() + .filter(|d| d.code == code) + .map(|d| d.message.clone()) + .collect() +} + +/// cargo-llvm-cov's LCOV of the fixture: two lines of `tests::adds` in `src/lib.rs`, and one record of the standard +/// library under `/rustc/`, outside the project. +const LCOV: &str = "TN:\n\ +SF:src/lib.rs\n\ +FN:14,_RNvNtCs1_5adder5tests4adds\n\ +FNDA:1,_RNvNtCs1_5adder5tests4adds\n\ +DA:14,1\n\ +DA:15,1\n\ +end_of_record\n\ +SF:/rustc/0123456789abcdef/library/core/src/ops/arith.rs\n\ +DA:1,1\n\ +end_of_record\n"; + +#[specforge_test_macros::test(requirement = "FEATURE-143")] +#[specforge_test_macros::test(requirement = "FEATURE-128")] +fn rust_coverage_records_coverage_and_warns_of_a_file_outside_the_project() { + let p = fixture(); + let outcome = collected(&p, "rust-coverage", &machine(writing(LCOV))); + let coverage = facts(&outcome, "rust-coverage", "coverage"); + assert_eq!(ids(&coverage), ["cov:rust:adder::tests::adds"]); + assert_eq!(coverage[0].fields["file"], "src/lib.rs"); + assert_eq!(coverage[0].fields["lines_hit"], 2); + let warned = said(&outcome, "W203"); + assert_eq!(warned.len(), 1, "{warned:?}"); + assert!( + warned[0].contains("'rust-coverage'") + && warned[0].contains("/rustc/0123456789abcdef/library/core/src/ops/arith.rs"), + "{warned:?}" + ); +} + +/// One clippy JSON message: `rule` at `line` of `src/lib.rs`, the primary span. +fn clippy(rule: &str, line: u32) -> String { + serde_json::json!({ + "reason": "compiler-message", + "package_id": "path+file:///project#adder@0.1.0", + "target": {"kind": ["lib"], "name": "adder", "src_path": "src/lib.rs"}, + "message": { + "$message_type": "diagnostic", + "level": "warning", + "message": format!("{rule} fired"), + "code": {"code": rule, "explanation": null}, + "spans": [{ + "file_name": "src/lib.rs", + "is_primary": true, + "line_start": line, + "line_end": line, + "column_start": 5, + "column_end": 9 + }], + "children": [] + } + }) + .to_string() +} + +#[specforge_test_macros::test(requirement = "FEATURE-146")] +fn rust_lint_records_each_clippy_diagnostic() { + let p = fixture(); + let stdout = format!( + "{}\n{}\n{{\"reason\":\"build-finished\",\"success\":true}}\n", + clippy("clippy::unwrap_used", 15), + clippy("unused_variables", 20) + ); + let outcome = collected(&p, "rust-lint", &machine(printing(&stdout))); + let findings = facts(&outcome, "rust-lint", "static_finding"); + let cited: Vec<&serde_json::Value> = findings.iter().map(|f| &f.fields["item"]).collect(); + assert_eq!( + cited, + ["rust:adder::tests::adds", "rust:adder::tests::slow"], + "each finding cites the innermost item holding its line: {:?}", + ids(&findings) + ); + assert!(said(&outcome, "W203").is_empty()); +} + +/// A cargo-cyclonedx BOM of the fixture crate whose one component is `name`. +fn bom(name: &str) -> String { + serde_json::json!({ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "metadata": { + "component": { + "type": "application", + "bom-ref": "path+file:///project#adder@0.1.0", + "name": "adder", + "version": "0.1.0", + "purl": "pkg:cargo/adder@0.1.0?download_url=file://." + } + }, + "components": [{ + "type": "library", + "bom-ref": format!("registry+https://github.com/rust-lang/crates.io-index#{name}@1.0.0"), + "name": name, + "version": "1.0.0", + "scope": "required", + "purl": format!("pkg:cargo/{name}@1.0.0") + }] + }) + .to_string() +} + +/// Write `text` at `path` of `p`, stamped one second before the run starts: a file an earlier run left or the project +/// committed. +fn earlier(p: &TestProject, path: &str, text: &str) { + p.write(path, text); + std::fs::File::options() + .write(true) + .open(p.root().join(path)) + .unwrap() + .set_modified(ScriptedMachine::started() - Duration::from_secs(1)) + .unwrap(); +} + +#[specforge_test_macros::test(requirement = "FEATURE-148")] +fn rust_sbom_reads_only_the_bom_the_run_wrote() { + let p = fixture(); + // A BOM an earlier run left: the report glob reaches it, freshness does not. + earlier(&p, "stale/rust-sbom.cdx.json", &bom("stale")); + // The glob's base is the root: cargo-cyclonedx writes the BOM beside the root manifest. + let run = ScriptedRun { + files: vec![("rust-sbom.cdx.json".into(), bom("serde"))], + ..ScriptedRun::default() + }; + let outcome = collected(&p, "rust-sbom", &machine(run)); + let dependencies = ids(&facts(&outcome, "rust-sbom", "dependency")); + assert_eq!( + dependencies, + ["dep:pkg:cargo/adder/pkg%3Acargo%2Fserde%401.0.0"] + ); +} + +/// cargo-public-api's text of the fixture's library: its one public function, re-exported at the root. +const PUBLIC_API: &str = "pub mod adder\npub fn adder::add(a: i32, b: i32) -> i32\n"; + +#[specforge_test_macros::test(requirement = "FEATURE-150")] +fn rust_api_records_the_public_api() { + let p = fixture(); + let outcome = collected(&p, "rust-api", &machine(printing(PUBLIC_API))); + let api = facts(&outcome, "rust-api", "api_item"); + assert_eq!(ids(&api), ["api:rust:adder", "api:rust:adder::add"]); + assert_eq!(api[1].fields["kind"], "function"); +} + +/// Each fact's id and its `change`, sorted by id. +fn changes(api: &[&Fact]) -> Vec<(String, Option)> { + let mut changes: Vec<_> = api + .iter() + .map(|f| { + let change = f.fields.get("change").and_then(|c| c.as_str()); + (f.id.clone(), change.map(str::to_string)) + }) + .collect(); + changes.sort(); + changes +} + +#[specforge_test_macros::test(requirement = "FEATURE-150")] +fn rust_api_reads_the_committed_accepted_api() { + let p = fixture(); + // Committed before the run: the accepted side is read whatever its age, unlike a report. + let accepted = format!("{PUBLIC_API}pub fn adder::sub(a: i32, b: i32) -> i32\n"); + earlier(&p, "tests/public-api.txt", &accepted); + let outcome = collected(&p, "rust-api", &machine(printing(PUBLIC_API))); + let change = |id: &str, change: &str| (id.to_string(), Some(change.to_string())); + assert_eq!( + changes(&facts(&outcome, "rust-api", "api_item")), + [ + change("api:rust:adder", "unchanged"), + change("api:rust:adder::add", "unchanged"), + change("api:rust:adder::sub", "removed"), + ] + ); + assert_eq!(said(&outcome, "W203"), Vec::::new()); +} + +#[specforge_test_macros::test(requirement = "FEATURE-150")] +fn an_accepted_report_past_64_kib_is_read() { + let p = fixture(); + let mut accepted = PUBLIC_API.to_string(); + for n in 0..2700 { + accepted.push_str(&format!("pub fn adder::generated_{n:04}() -> i32\n")); + } + assert!(accepted.len() > 96 * 1024, "{}", accepted.len()); + earlier(&p, "tests/public-api.txt", &accepted); + let outcome = collected(&p, "rust-api", &machine(printing(PUBLIC_API))); + let changes = changes(&facts(&outcome, "rust-api", "api_item")); + assert!( + changes.contains(&( + "api:rust:adder::add".to_string(), + Some("unchanged".to_string()) + )), + "{:?}", + &changes[..3] + ); + let warned = said(&outcome, "W203"); + assert!( + !warned.iter().any(|w| w.contains("too_large")), + "{warned:?}" + ); +} + +#[specforge_test_macros::test(requirement = "FEATURE-150")] +fn a_hard_linked_accepted_file_is_not_read_in_a_bounded_containment() { + let outside = tempfile::tempdir().unwrap(); + let secret = outside.path().join("public-api.txt"); + std::fs::write( + &secret, + format!("{PUBLIC_API}pub fn adder::sub(a: i32, b: i32) -> i32\n"), + ) + .unwrap(); + let p = fixture(); + std::fs::create_dir_all(p.root().join("tests")).unwrap(); + std::fs::hard_link(&secret, p.root().join("tests/public-api.txt")).unwrap(); + + // MCP bounds the request: the second name of a file outside the project is never read (ADR 0146). + let bounded = Containment::within(p.root()); + let run = machine(printing(PUBLIC_API)); + let outcome = collect_within(&p, "rust-api", &run, &bounded).unwrap(); + let api = facts(&outcome, "rust-api", "api_item"); + assert!( + changes(&api).iter().all(|(_, change)| change.is_none()), + "{:?}", + changes(&api) + ); + let warned = said(&outcome, "W203"); + assert!( + warned + .iter() + .any(|w| w.contains("tests/public-api.txt") && w.contains("(unreadable)")), + "{warned:?}" + ); + + // The CLI runs unbounded (ADR 0092 D6): the same link is read. + let outcome = collected(&p, "rust-api", &machine(printing(PUBLIC_API))); + let changes = changes(&facts(&outcome, "rust-api", "api_item")); + assert!( + changes.contains(&( + "api:rust:adder::sub".to_string(), + Some("removed".to_string()) + )), + "{changes:?}" + ); +} + +/// Kani's regular output: the harness `tests::slow`, which only the fixture's library holds, verified. +const KANI: &str = "Kani Rust Verifier 0.68.0 (cargo plugin)\n\ + Compiling adder v0.1.0 (/project)\n\ +Checking harness tests::slow...\n\ +\n\ +RESULTS:\n\ +Check 1: tests::slow.assertion.1\n\ +\t - Status: SUCCESS\n\ +\t - Description: \"assertion failed\"\n\ +\n\ +SUMMARY:\n\ + ** 0 of 1 failed\n\ +\n\ +VERIFICATION:- SUCCESSFUL\n\ +Verification Time: 0.25s\n\ +\n\ +Manual Harness Summary:\n\ +Complete - 1 successfully verified harnesses, 0 failures, 1 total.\n"; + +#[specforge_test_macros::test(requirement = "FEATURE-154")] +fn rust_proof_records_a_verified_harness_at_its_item() { + let p = fixture(); + let outcome = collected(&p, "rust-proof", &machine(printing(KANI))); + let tests = facts(&outcome, "rust-proof", "test"); + assert_eq!(ids(&tests), ["rust:adder#tests::slow"]); + assert_eq!(tests[0].fields["status"], "passed"); + assert_eq!(tests[0].fields["file"], "src/lib.rs"); + assert!(!tests[0].at.is_empty(), "placed at the harness fn"); +} + +#[specforge_test_macros::test(requirement = "FEATURE-154")] +fn a_kani_output_cut_before_complete_is_the_collectors_error() { + let p = fixture(); + let cut = &KANI[..KANI.find("Manual Harness Summary").unwrap()]; + let refused = collect_or_refused(&p, "rust-proof", &machine(printing(cut))).unwrap_err(); + // The run is refused whole: no proof result is stored, none dropped silently. + assert!(refused.starts_with("E028: "), "{refused}"); + assert!(refused.contains("rust-proof"), "{refused}"); +} diff --git a/crates/kernel/common/tests/titled_list.rs b/crates/kernel/common/tests/titled_list.rs index 1ae0bef642..df73f66a5e 100644 --- a/crates/kernel/common/tests/titled_list.rs +++ b/crates/kernel/common/tests/titled_list.rs @@ -16,6 +16,7 @@ fn a_list_and_a_document_title_a_code_from_the_code_book_they_were_built_with() machine: false, reported_while: None, settled_later: false, + facts: Vec::new(), }], ) .unwrap(); diff --git a/crates/kernel/effects/src/testing.rs b/crates/kernel/effects/src/testing.rs index 8ae9aa485d..81687d5128 100644 --- a/crates/kernel/effects/src/testing.rs +++ b/crates/kernel/effects/src/testing.rs @@ -39,6 +39,7 @@ pub fn ports() -> Ports { #[derive(Default)] pub struct FakeProcess { answers: BTreeMap)>, + paths: BTreeMap, requests: Mutex>, } @@ -60,6 +61,12 @@ impl FakeProcess { self } + /// `which(program)` finds it `at`; every other program stays not found. + pub fn on_path(mut self, program: &str, at: impl Into) -> Self { + self.paths.insert(program.to_string(), at.into()); + self + } + /// The requests run so far, in order. pub fn requests(&self) -> Vec { self.requests.lock().expect("no request panics").clone() @@ -102,6 +109,10 @@ impl Process for FakeProcess { } outcome } + + fn which(&self, program: &str) -> Option { + self.paths.get(program).cloned() + } } /// A file port over files held in memory, by absolute path; a directory is any prefix of a file's path. With a diff --git a/crates/leaf/diagnostics/src/catalog.rs b/crates/leaf/diagnostics/src/catalog.rs index 0513c4b2ca..b266a36e90 100644 --- a/crates/leaf/diagnostics/src/catalog.rs +++ b/crates/leaf/diagnostics/src/catalog.rs @@ -205,7 +205,7 @@ catalog! { "An entity writes a field its kind does not declare, and that field is the other side of a relation a reference field owns, its own kind's included. A relation is written on its owning field only (ADR 0150): the one reference field an extension declares for it. The other side is derived, never written: `query` shows it as the incoming edges and `trace` as the upstream. The field is recognised in two ways: a reference field whose targets hold this kind names it in its `inverse_of`, a self-relation's and a union's included (so a documented reverse such as `behaviors` on a feature, or `superseded_by` on a decision, is refused even when its ids do not resolve), or every id it lists is one other kind's entity and that kind owns a single-kind reference field into this one (`journeys [..]` on a feature). By its values alone a self-relation's or a union's other side is not recognised, and a kind that accepts any field is not checked. The graph still carries the field's untyped edge, and `check` fails. Remove the field and write the owning field on each entity it listed; the suggestion names both."; E080: Error core, "Typed edit would add errors", - "A typed edit (`specforge new`, `set`, `unset`, `link`, `unlink`, `delete`, or MCP `specforge.edit`) was planned, and the project it would leave reports errors the project does not report now (the same error by code, severity, message shape, file and, for an extension's finding, its subject): the edit is refused and nothing is written. The refusal lists each new error (an unresolved reference, a missing required field, a value its field does not take, …). Fix what they name first: create the referenced entity, give the required field, or make both changes in one `specforge.edit` call. `delete --unlink-references` removes the references a delete would leave dangling. A judged rule's finding (no verdict, a stale or a failing verdict) is never one of them: its judge settles it, not the edit (ADR 0297). Nor is an extension's finding whose code waits for an owner state (`reported_while`) and that the edit revealed by moving its entity into that state: the edit is accepted and the finding is reported once it is written (ADR 0363). Nor is an extension's finding whose code a later step of the authoring settles (`settled_later`) on an entity the edit creates, or creates something under, when the edit alters nothing the project held there: the edit is accepted, lists the finding, and `check` reports it until that step is written; an edit that creates neither, one that also sets, unsets, links, unlinks, deletes or moves at or under that entity, and a migration still count it (ADR 0385). A writing collector's plan is compared with the project as its collect left it, and is refused for host errors only: an extension's error refuses no collected fact (ADR 0303)."; + "A typed edit (`specforge new`, `set`, `unset`, `link`, `unlink`, `delete`, or MCP `specforge.edit`) was planned, and the project it would leave reports errors the project does not report now (the same error by code, severity, message shape, file and, for an extension's finding, its subject): the edit is refused and nothing is written. The refusal lists each new error (an unresolved reference, a missing required field, a value its field does not take, …). Fix what they name first: create the referenced entity, give the required field, or make both changes in one `specforge.edit` call. `delete --unlink-references` removes the references a delete would leave dangling. A judged rule's finding (no verdict, a stale or a failing verdict) is never one of them: its judge settles it, not the edit (ADR 0297). Nor is an extension's finding whose code waits for an owner state (`reported_while`) and that the edit revealed by moving its entity into that state: the edit is accepted and the finding is reported once it is written (ADR 0363). Nor is an extension's finding whose code a later step of the authoring settles (`settled_later`) on an entity the edit creates, or creates something under, when the edit alters nothing the project held there: the edit is accepted, lists the finding, and `check` reports it until that step is written; an edit that creates neither, one that also sets, unsets, links, unlinks, deletes or moves at or under that entity, and a migration still count it (ADR 0385). A writing collector's plan is compared with the project as its collect left it, and is refused for host errors only: an extension's error refuses no collected fact (ADR 0303). The plan of a command that declares `imports` writes an extension's rule error about authored entities the imported records carry, and `check` reports it: a code in the extension's namespace that its own catalog lists and whose entry judges no collected fact. It is still refused for any other error: the host's or a `@specforge/*` builtin's (E016 included), and one that judges the records against collected facts, such as `code/E101` (ADR 0392)."; E081: Error core, "Field written twice in one block", "A block writes one field (an entry of a block field, a member of a type) more than once. A field holds one value: the graph keeps the first and every output, check and rule reads it; the message names the first's line. Delete the later line, or give every value in the first: a list field takes all its items in one list (`ports [a, b]`), a block field all its entries in one block. A typed edit that changes the field (`set`, `unset`, `link`, `unlink`) removes the later lines itself. A repeat in a `defaults` block is E078."; @@ -481,7 +481,7 @@ catalog! { "An entity sets a field that isn't declared for its kind by any installed extension, or a typed block or block list item sets a key its field declares no member for. Remove it, fix a typo in its name, or install the extension that declares it."; W021: Warning core, "Undeclared target kind or edge label", - "A field, edge type or validation rule references a `target_kind` or edge label that isn't declared — either in the extension's own manifest when it declares no peer dependencies, or in the compiler's global kind/edge registry once all extensions are loaded. Declare the missing kind or edge label, or add the appropriate peer dependency (a validation rule on another extension's kind that this one works without names that extension as its `target_extension` instead). The same code reports a declaration the registry refuses: a `derived_from` that derives nothing, a `proof_role` other than `bound` or `claim`, a `scoped_by` that is not one of the kind's single reference fields with a target kind, targets a kind no extension loads or the kind itself, or closes a scope cycle (the kind is then unscoped), an `enum` field that declares no values, or a `default_value` an enum field does not take. A field that writes a declared edge type from a kind outside its declared `source_kind`, or to a kind outside its declared `target_kind`, is W021 too, and its edges are of no edge type. So is a typed field the registry refuses and drops the attribute of: `members` on a type other than `block` or `block_list`, a `block_list` with none, a member named twice or not one identifier, a member that declares `derived_from`, `target_kinds` together with `target_kind`, on a type other than `reference` or `reference_list`, or naming one kind, a `minimum` or `maximum` on a type other than `integer` or `number`, a fraction or a value beyond `i64` on an `integer`, more than 15 significant digits on a `number`, or a `minimum` above the `maximum` (ADR 0361); a `scoped_by` field with `target_kinds` scopes nothing. Who writes a field is checked too (ADR 0287): a `writer` other than `computed`, `harness`, `human` or `verdict`, `harness` or `verdict` on a member, a computed or verdict field that is also `required`, `immutable`, `append_only` or `derived_from`, `append_only` on a field that is not a list, a computed field no compute pass lists in `computes`, a `computes` entry that is not a computed field of the extension or that two passes list or whose pass is not in the `compute` phase, and a `baseline` naming a kind no loaded extension declares. Who writes a kind is checked as well (ADR 0289): a kind `writer` other than `human`, a `human` field marked `required` on a kind that is not human-only (an agent could then create no entity of the kind), a `guard` pass that declares `computes`, and a `guard` pass that reports the code of a judged rule of its extension (ADR 0302). A kind's `result` is checked too (ADR 0329): on a kind no collector writes, naming a field the kind does not declare or one that is no `enum`, or an enum whose values are not all test statuses (`passed`, `failed`, `skipped`), it is dropped. So is a kind's `complete_when` (ADR 0329): naming a field the kind does not declare or one that is no `enum`, no value, or a value the enum does not take, it is dropped and the kind's entities follow their scope's owner state. The `settings` category is checked too (ADR 0288): a setting named twice or not a dotted name or a family (`*` segments), of a type the field forms do not have, with a default its type refuses, with `gates` or `gates_when_on` (ADR 0305) on a type other than `bool` or on a family (only a setting named whole gates codes), naming a code the extension does not catalog, or gating one code both ways, or with `keys` that do not match its `*`s; a preset whose source is not an enum or bool setting of the extension or of a loaded peer, that names a value its source does not take, that sets a setting the extension does not declare to a value its type refuses, or that raises a code the extension does not catalog; a secret named twice or whose environment variable is not a name; and an item of a kind the host does not know. The `surfaces` category is checked too (ADR 0291): a prompt whose id is not snake_case or whose export is not `prompt__`, that declares an argument twice or named for something the host owns (`path`, `format`, `help`, `settings`, `secrets`, `host`, `argv`), of a type an argument does not take, a reference argument naming no loaded kind, bounds on an argument that is no integer or a default its type refuses, a gate that is not a code the extension catalogs (a command's gates too), a command that is `human` and does not `writes` (ADR 0301), a `subject` that is not an argument it declares, a `when` that is not a bool setting of the extension, or a step that names a command or prompt neither the extension nor a declared peer declares; the prompt or command is dropped whole, since a gate or an argument the host cannot read must not be ignored, and a step's `agent` (until the host knows agents) or an attribution with an empty field is dropped alone. The item is dropped, the rest of the category is kept. The host contributions are checked too (ADR 0292): an agent, skill, slash command or hook the registry refuses and drops, alone — an agent or skill id that is not kebab-case or is declared twice, a hook id that is not snake_case, a tool class outside the host-neutral vocabulary (`read`, `write`, `edit`, `shell`, `search`, `web_fetch`, `web_search`, `ask_user`, `agent`, `skill`, `todo`, `mcp:/`, or a `specforge:`, `specforge:` or `specforge:.` naming an engine tool, engine group or a command an agent may run (ADR 0334), but never on a hook), `mcp:specforge/` (SpecForge's whole server, which the `specforge:` classes name tool by tool), a `specforge:` class naming a human-attested or refused command, a `model` or `effort` outside its tiers that is not a `setting:` naming a string or enum setting of the extension, variants without a `variant_setting` (or the reverse), a `when` that is not a bool setting of the extension, a slash command that names no single prompt or command the extension declares, `tools` or `paths` on a hook of an event that takes none, a `timeout_ms` of 0 or above the ceiling (30 s, or the sandbox's), `writes` on a `statusline` hook, a hook export that is not `hook__`, an attribution with an empty field, and a prompt step whose `agent` is no agent of the extension or of a declared peer. An input the host would serve empty is W021 too (ADR 0293, ADR 0337), the call being kept: an input its call kind is not served, a collector's included, or a second one of a kind served once (`tests`, `state`, `graph`, `slash_commands`, `git`), a `setting` input naming the call's own extension or no extension and setting, and a `files` input whose name is no word or is repeated, that names neither or both of `field` and `glob`, a `field` that is not `kind.field` or that no loaded extension declares, a `root` on a glob or that is no root's name, and a glob that is empty, absolute, climbs with `..`, or has more than four `**` segments."; + "A field, edge type or validation rule references a `target_kind` or edge label that isn't declared — either in the extension's own manifest when it declares no peer dependencies, or in the compiler's global kind/edge registry once all extensions are loaded. Declare the missing kind or edge label, or add the appropriate peer dependency (a validation rule on another extension's kind that this one works without names that extension as its `target_extension` instead). The same code reports a declaration the registry refuses: a `derived_from` that derives nothing, a `proof_role` other than `bound` or `claim`, a `scoped_by` that is not one of the kind's single reference fields with a target kind, targets a kind no extension loads or the kind itself, or closes a scope cycle (the kind is then unscoped), an `enum` field that declares no values, or a `default_value` an enum field does not take. A field that writes a declared edge type from a kind outside its declared `source_kind`, or to a kind outside its declared `target_kind`, is W021 too, and its edges are of no edge type. So is a typed field the registry refuses and drops the attribute of: `members` on a type other than `block` or `block_list`, a `block_list` with none, a member named twice or not one identifier, a member that declares `derived_from`, `target_kinds` together with `target_kind`, on a type other than `reference` or `reference_list`, or naming one kind, a `minimum` or `maximum` on a type other than `integer` or `number`, a fraction or a value beyond `i64` on an `integer`, more than 15 significant digits on a `number`, or a `minimum` above the `maximum` (ADR 0361); a `scoped_by` field with `target_kinds` scopes nothing. Who writes a field is checked too (ADR 0287): a `writer` other than `computed`, `harness`, `human` or `verdict`, `harness` or `verdict` on a member, a computed or verdict field that is also `required`, `immutable`, `append_only` or `derived_from`, `append_only` on a field that is not a list, a computed field no compute pass lists in `computes`, a `computes` entry that is not a computed field of the extension or that two passes list or whose pass is not in the `compute` phase, and a `baseline` naming a kind no loaded extension declares. Who writes a kind is checked as well (ADR 0289): a kind `writer` other than `human`, a `human` field marked `required` on a kind that is not human-only (an agent could then create no entity of the kind), a `guard` pass that declares `computes`, and a `guard` pass that reports the code of a judged rule of its extension (ADR 0302). A kind's `result` is checked too (ADR 0329): on a kind no collector writes, naming a field the kind does not declare or one that is no `enum`, or an enum whose values are not all test statuses (`passed`, `failed`, `skipped`), it is dropped. So is a kind's `complete_when` (ADR 0329): naming a field the kind does not declare or one that is no `enum`, no value, or a value the enum does not take, it is dropped and the kind's entities follow their scope's owner state. The `settings` category is checked too (ADR 0288): a setting named twice or not a dotted name or a family (`*` segments), of a type the field forms do not have, with a default its type refuses, with `gates` or `gates_when_on` (ADR 0305) on a type other than `bool` or on a family (only a setting named whole gates codes), naming a code the extension does not catalog, or gating one code both ways, or with `keys` that do not match its `*`s; a preset whose source is not an enum or bool setting of the extension or of a loaded peer, that names a value its source does not take, that sets a setting the extension does not declare to a value its type refuses, or that raises a code the extension does not catalog; a secret named twice or whose environment variable is not a name; and an item of a kind the host does not know. The `surfaces` category is checked too (ADR 0291): a prompt whose id is not snake_case or whose export is not `prompt__`, that declares an argument twice or named for something the host owns (`path`, `format`, `help`, `settings`, `secrets`, `host`, `argv`), of a type an argument does not take, a reference argument naming no loaded kind, bounds on an argument that is no integer or a default its type refuses, a gate that is not a code the extension catalogs (a command's gates too), a command that is `human` and does not `writes` (ADR 0301), a `subject` that is not an argument it declares, a `when` that is not a bool setting of the extension, or a step that names a command or prompt neither the extension nor a declared peer declares; the prompt or command is dropped whole, since a gate or an argument the host cannot read must not be ignored, and a step's `agent` (until the host knows agents) or an attribution with an empty field is dropped alone. The item is dropped, the rest of the category is kept. The host contributions are checked too (ADR 0292): an agent, skill, slash command or hook the registry refuses and drops, alone — an agent or skill id that is not kebab-case or is declared twice, a hook id that is not snake_case, a tool class outside the host-neutral vocabulary (`read`, `write`, `edit`, `shell`, `search`, `web_fetch`, `web_search`, `ask_user`, `agent`, `skill`, `todo`, `mcp:/`, or a `specforge:`, `specforge:` or `specforge:.` naming an engine tool, engine group or a command an agent may run (ADR 0334), but never on a hook), `mcp:specforge/` (SpecForge's whole server, which the `specforge:` classes name tool by tool), a `specforge:` class naming a human-attested or refused command, a `model` or `effort` outside its tiers that is not a `setting:` naming a string or enum setting of the extension, variants without a `variant_setting` (or the reverse), a `when` that is not a bool setting of the extension, a slash command that names no single prompt or command the extension declares, `tools` or `paths` on a hook of an event that takes none, a `timeout_ms` of 0 or above the ceiling (30 s, or the sandbox's), `writes` on a `statusline` hook, a hook export that is not `hook__`, an attribution with an empty field, and a prompt step whose `agent` is no agent of the extension or of a declared peer. An input the host would serve empty is W021 too (ADR 0293, ADR 0337), the call being kept: an input its call kind is not served, a collector's included, or a second one of a kind served once (`tests`, `state`, `graph`, `slash_commands`, `git`), a `setting` input naming the call's own extension or no extension and setting, and a `files` input whose name is no word or is repeated, that names neither or both of `field` and `glob`, a `field` that is not `kind.field` or that no loaded extension declares, a `root` on a glob or that is no root's name, a glob that is empty, absolute, climbs with `..`, or has more than four `**` segments, and a `text_max` that is zero, over 4 MiB or set without `text` (ADR 0390)."; W027: Warning core, "Import binding not found", "A selective import, `use { A, B } from \"target\"` or `pub use { A, B } from \"target\"`, names a binding the target file does not export: an entity it neither declares nor re-exports with `pub use`. A binding may be a path (`use { 03/D-01 }`). References resolve without `use`, so the binding changes nothing, but it names nothing either; a rename and a delete keep bindings in step with the entities they name (ADR 0233). Correct the binding's name, or remove it."; @@ -743,4 +743,7 @@ catalog! { W202: Warning core, "Fact store renamed two ways", "The harness ledger holds two `stale:` lines for one name a fact store holds (ADR 0346 D7): ` stale::::` and `...::`, both for the store's bytes. A rename replaces the line of the name it renames again, so one ledger never writes two; two branches that each renamed the name, merged (`specforge-harness` merges as a union of lines), do. The ledger cannot say which name the source holds now, so none of the store's renames is served: its facts read as collected, and its places as the collect read them (a file the renames rewrote is not the text they are in, W198). A rename of a name the store holds is refused (`stale_conflict`). Run `specforge collect`: it replaces the store and drops its stale lines."; + W203: Warning core, + "A collector warned of what it skipped", + "A collector's export read its report and answered facts, and also returned lines about entries it could not use (ADR 0389): a path outside the project, a record of no supported shape. Each line is one W203 naming the collector and its extension, escaped, at most 100 per collector and then one W203 counting the rest. The facts it did answer are kept. Read the lines and fix the report or the tool's configuration."; } diff --git a/crates/leaf/diagnostics/src/codebook.rs b/crates/leaf/diagnostics/src/codebook.rs index 7ffeed9dcd..67379c5e25 100644 --- a/crates/leaf/diagnostics/src/codebook.rs +++ b/crates/leaf/diagnostics/src/codebook.rs @@ -24,6 +24,8 @@ pub struct ExtensionCode { pub reported_while: Option, /// A later step of the authoring settles a finding of it (`CodeDescriptor.settled_later`, ADR 0385). pub settled_later: bool, + /// The collected fact kinds it judges (`CodeDescriptor.facts`, ADR 0389): empty for a code about authored entities. + pub facts: Vec, } /// Two loaded extensions share one code namespace. @@ -196,6 +198,27 @@ impl Codebook { .is_some_and(|entry| entry.settled_later) } + /// Whether `code` (as it prints, `gsd.security/E101`), which `extension` reported, is a rule of `extension`'s own + /// about authored entities (ADR 0392): `code` is in `extension`'s namespace, `extension`'s own catalog lists it, + /// and that entry judges no collected fact kind (`ExtensionCode.facts`, ADR 0389). An importing command's plan + /// writes such an error and refuses every other: a first-party code (bare), a code no catalog of `extension`'s + /// lists, and one that judges a record against the facts collected from the tree, such as `code/E101` (a + /// reference naming no collected fact). + pub fn authored_rule(&self, extension: &str, code: &str) -> bool { + let CodeRef { + namespace: Some(namespace), + local, + } = CodeRef::parse(code) + else { + return false; + }; + code_namespace(extension).is_some_and(|own| own.eq_ignore_ascii_case(namespace)) + && self + .owned_by(extension) + .and_then(|owned| owned.codes.get(&local.to_uppercase())) + .is_some_and(|entry| entry.facts.is_empty()) + } + /// Whether a finding of `code` that `extension` reports speaks on an entity whose owner is `pending` (ADR 0363): /// always, unless the extension's own catalog entry names the owner state its findings wait for, then only in /// that state. A first-party extension's code waits for none. @@ -251,6 +274,30 @@ impl Codebook { .collect() } + /// The qualified codes (`code/W104`) of every namespace whose entry judges one of the collected kinds `lost` and + /// none of the kinds `answered` (`ExtensionCode.facts`, ADR 0389), sorted and unique: the codes no finding can speak + /// for when no collector answers `lost` and a collector still answers each of `answered`. A code that also judges a + /// kind still answered keeps judging it, so it is not one of them. + pub fn switched_off(&self, lost: &[String], answered: &[String]) -> Vec { + let mut off: Vec = self + .namespaces + .iter() + .flat_map(|(namespace, owned)| { + owned + .codes + .iter() + .filter(|(_, entry)| { + entry.facts.iter().any(|kind| lost.contains(kind)) + && !entry.facts.iter().any(|kind| answered.contains(kind)) + }) + .map(move |(local, _)| format!("{namespace}/{local}")) + }) + .collect(); + off.sort(); + off.dedup(); + off + } + /// The level a diagnostic of `code` (as it prints: `gsd/W304`, `E001`) /// is reported at: a static entry's catalogued level (`None` for `A###`, /// whose pass sets it), a namespaced code's letter when its namespace's @@ -304,6 +351,7 @@ mod tests { machine: false, reported_while: None, settled_later: false, + facts: Vec::new(), }) .collect(); book.add(extension, entries).unwrap(); @@ -462,6 +510,7 @@ mod tests { machine: true, reported_while: None, settled_later: false, + facts: Vec::new(), }], ) .unwrap(); @@ -489,6 +538,7 @@ mod tests { machine: false, reported_while: Some(state.into()), settled_later: false, + facts: Vec::new(), }; book.add( "@acme/links", @@ -522,6 +572,7 @@ mod tests { machine: false, reported_while: None, settled_later: true, + facts: Vec::new(), }], ) .unwrap(); @@ -538,6 +589,97 @@ mod tests { ); } + #[test] + fn an_authored_rule_is_the_reporters_own_catalogued_code_judging_no_fact() { + let mut book = book("@gsd/security", &["E101"]); + book.add( + "@code/core", + vec![ExtensionCode { + local: "E101".into(), + title: "t".into(), + explanation: "e".into(), + docs: None, + machine: false, + reported_while: None, + settled_later: false, + facts: vec!["test".into()], + }], + ) + .unwrap(); + assert!(book.authored_rule("@gsd/security", "gsd.security/E101")); + assert!( + !book.authored_rule("@code/core", "code/E101"), + "it judges collected facts" + ); + assert!( + !book.authored_rule("@gsd/security", "gsd.security/E102"), + "not catalogued" + ); + assert!( + !book.authored_rule("@gsd/security", "code/E101"), + "another namespace's code" + ); + assert!( + !book.authored_rule("@gsd/security", "E101"), + "a bare code is first party" + ); + assert!( + !book.authored_rule("@specforge/checks", "E016"), + "a first-party extension's code" + ); + } + + #[test] + fn switched_off_lists_the_qualified_codes_about_a_lost_kind_sorted_and_unique() { + let judging = |local: &str, facts: &[&str]| ExtensionCode { + local: local.into(), + title: "t".into(), + explanation: "e".into(), + docs: None, + machine: false, + reported_while: None, + settled_later: false, + facts: facts.iter().map(|kind| kind.to_string()).collect(), + }; + let mut book = Codebook::default(); + book.add( + "@code/core", + vec![ + judging("W105", &["static_finding"]), + judging("W104", &["coverage", "api_item"]), + judging("E101", &[]), + ], + ) + .unwrap(); + book.add("@acme/cov", vec![judging("W900", &["coverage"])]) + .unwrap(); + let kinds = + |kinds: &[&str]| -> Vec { kinds.iter().map(|k| k.to_string()).collect() }; + assert_eq!( + book.switched_off(&kinds(&["coverage"]), &[]), + ["acme.cov/W900", "code/W104"] + ); + assert_eq!( + book.switched_off(&kinds(&["coverage", "api_item"]), &[]), + ["acme.cov/W900", "code/W104"], + "a code judging two of the kinds comes once" + ); + assert!( + book.switched_off(&kinds(&["vulnerability"]), &[]) + .is_empty() + ); + assert!(book.switched_off(&[], &[]).is_empty()); + // W104 also judges api_item, which a collector still answers: it is still judged. + assert_eq!( + book.switched_off(&kinds(&["coverage"]), &kinds(&["api_item"])), + ["acme.cov/W900"] + ); + assert!( + book.switched_off(&kinds(&["coverage"]), &kinds(&["coverage"])) + .is_empty() + ); + } + #[test] fn a_first_party_extension_owns_only_the_static_catalogs_codes_it_is_owner_of() { let book = Codebook::default(); diff --git a/crates/leaf/diagnostics/src/tests/namespace.rs b/crates/leaf/diagnostics/src/tests/namespace.rs index 6190e0cd13..8ee816a89c 100644 --- a/crates/leaf/diagnostics/src/tests/namespace.rs +++ b/crates/leaf/diagnostics/src/tests/namespace.rs @@ -61,6 +61,7 @@ fn code(local: &str) -> ExtensionCode { machine: false, reported_while: None, settled_later: false, + facts: Vec::new(), } } diff --git a/crates/leaf/protocol-types/src/calls/collect.rs b/crates/leaf/protocol-types/src/calls/collect.rs index 51ed2e5876..73b94437bb 100644 --- a/crates/leaf/protocol-types/src/calls/collect.rs +++ b/crates/leaf/protocol-types/src/calls/collect.rs @@ -80,6 +80,11 @@ pub struct CollectOutput { /// The entities the collector observed (protocol 1.15.0, ADR 0327): stored by the host, served read-only. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub facts: Vec, + /// Lines the collector wants the user to read about what it read but could not use (a file outside the + /// project, a record skipped), each reported as W203 (protocol 2.3.0, ADR 0389). Never an error: an error is + /// the export's `Err`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, } /// A test the report doesn't link to an entity: its name, the name split diff --git a/crates/leaf/protocol-types/src/code_catalog.rs b/crates/leaf/protocol-types/src/code_catalog.rs index 75d14914f8..b4a66007f5 100644 --- a/crates/leaf/protocol-types/src/code_catalog.rs +++ b/crates/leaf/protocol-types/src/code_catalog.rs @@ -6,7 +6,8 @@ use serde::{Deserialize, Serialize}; /// One diagnostic code an extension reports: its local code (`E101`, never /// qualified; the host adds the namespace), a title, what it means and how /// to fix it, an optional absolute `http(s)` documentation URL, whether this machine decides it (2.0.0), the owner -/// state its findings wait for (2.2.0), and whether a later step of the authoring settles its findings (2.3.0). +/// state its findings wait for (2.2.0), whether a later step of the authoring settles its findings, and the collected +/// kinds it judges (both 2.3.0). #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CodeDescriptor { pub code: String, @@ -32,4 +33,9 @@ pub struct CodeDescriptor { /// `check`, `--strict` and every gate read it. Serialized only when set. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub settled_later: bool, + /// The collected fact kinds this code judges (the kinds whose facts its passes read to raise it), so a host can + /// say which codes cannot be judged when no collector answers those kinds (doctor, 2.3.0, ADR 0389). Empty for a + /// code about authored entities; serialized only when not. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub facts: Vec, } diff --git a/crates/leaf/protocol-types/src/inputs.rs b/crates/leaf/protocol-types/src/inputs.rs index e75f930ddf..e58f522ceb 100644 --- a/crates/leaf/protocol-types/src/inputs.rs +++ b/crates/leaf/protocol-types/src/inputs.rs @@ -157,7 +157,10 @@ impl InputKind { /// [`FileRead`]'s fields). const fn wire(self) -> (&'static str, &'static [&'static str]) { match self { - InputKind::Files => ("files", &["name", "field", "glob", "root", "text"]), + InputKind::Files => ( + "files", + &["name", "field", "glob", "root", "text", "text_max"], + ), InputKind::Tests => ("tests", &[]), InputKind::State => ("state", &[]), InputKind::Graph => ("graph", &[]), diff --git a/crates/leaf/protocol-types/src/inputs/tests.rs b/crates/leaf/protocol-types/src/inputs/tests.rs index fc4300ab88..2970d2bb22 100644 --- a/crates/leaf/protocol-types/src/inputs/tests.rs +++ b/crates/leaf/protocol-types/src/inputs/tests.rs @@ -11,6 +11,7 @@ fn each() -> Vec { glob: Some("src/**".into()), root: Some("project".into()), text: true, + text_max: Some(200_000), }), Input::Tests, Input::State, diff --git a/crates/leaf/protocol-types/src/lib.rs b/crates/leaf/protocol-types/src/lib.rs index 73d788e75f..6f2b011f27 100644 --- a/crates/leaf/protocol-types/src/lib.rs +++ b/crates/leaf/protocol-types/src/lib.rs @@ -110,7 +110,9 @@ pub use prompt::{ Attribution, PromptArgDescriptor, PromptDescriptor, PromptInput, PromptMessage, PromptOutput, PromptRole, PromptStep, ServedSlash, }; -pub use reads::{FILE_READ_MAX, FileFact, FileFacts, FileMap, FileRead}; +pub use reads::{ + FILE_READ_MAX, FileFact, FileFacts, FileMap, FileRead, GLOB_VISITS_MAX, TEXT_MAX_CEILING_BYTES, +}; pub use rooted::{PrefixProblem, Root, RootedPath}; pub use route::{ROUTE_START, RouteAnnotationDescriptor, RouteDescriptor, RouteStepDescriptor}; pub use settings::{ @@ -564,10 +566,35 @@ pub struct CollectorDescriptor { /// input names one, and the only kinds whose facts the host admits from it. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub answers: Vec, - /// What to run to install its program, said when the program is not found on PATH (ADR 0348 D4): one printable - /// line of at most [`INSTALL_LINE_MAX`] bytes. + /// What to run to install its programs, said when one is not found on PATH (ADR 0348 D4): one printable line of at + /// most [`INSTALL_LINE_MAX`] bytes. #[serde(default, skip_serializing_if = "Option::is_none")] pub install: Option, + /// The other programs its command runs, beside its argv's first (`cargo-llvm-cov llvm-cov nextest` runs + /// `cargo-nextest`): `specforge doctor` looks each up on PATH as it does the first (protocol 2.3.0, ADR 0389 D3). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub requires: Vec, +} + +/// Whether `program` may be named in a collector's `requires`: a bare program name, non-empty, with no path separator, +/// whitespace or control character, so doctor looks it up on PATH and nowhere else. +pub fn is_program_name(program: &str) -> bool { + !program.is_empty() + && !program + .chars() + .any(|c| matches!(c, '/' | '\\') || c.is_whitespace() || c.is_control()) +} + +/// Whether `report` may be a collector's report (ADR 0389 D6): its last `/`-separated segment is a literal file name, +/// so a glob names the files one tool writes (`**/rust-sbom.cdx.json`) and never every file of a kind (`**/*.pem`). +pub fn is_report_name(report: &str) -> bool { + !is_wild(report.rsplit('/').next().unwrap_or_default()) +} + +/// Whether one `/`-separated segment of a declared glob (a file read's, a report's) is a wildcard: it holds `*` or +/// `?`. The host's walks and the declaration checks read a glob through this one predicate. +pub fn is_wild(segment: &str) -> bool { + segment.contains(['*', '?']) } /// The most bytes a collector's install line holds. diff --git a/crates/leaf/protocol-types/src/reads.rs b/crates/leaf/protocol-types/src/reads.rs index 23766c43b9..7026bd1f96 100644 --- a/crates/leaf/protocol-types/src/reads.rs +++ b/crates/leaf/protocol-types/src/reads.rs @@ -9,7 +9,8 @@ use serde::{Deserialize, Serialize}; /// under `name` in the input's `files`. /// /// Exactly one of `field` and `glob` names the files; a read that names neither or both, a `name` that is no word or -/// repeats, or a `root` on a glob is W021 and served empty. +/// repeats, a `root` on a glob, or a `text_max` that is zero, over [`TEXT_MAX_CEILING_BYTES`] or without `text` is W021 +/// and served empty. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct FileRead { /// The key of this read in the input's `files`: a word `[a-z][a-z0-9_]*`, unique among the owner's reads. @@ -28,21 +29,33 @@ pub struct FileRead { /// root's costs the read, not the declaration. #[serde(default, skip_serializing_if = "Option::is_none")] pub root: Option, - /// Send each file's text (UTF-8, at most 64 KiB) as well as its facts. + /// Send each file's text (UTF-8, at most 64 KiB, or `text_max`) as well as its facts. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub text: bool, + /// The most text of one file this read sends, in bytes, instead of 64 KiB; at most 4 MiB, and only with `text` + /// (protocol 2.3.0). The read's text budget is then the larger of 1 MiB and four times it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text_max: Option, } /// The most files one [`FileRead`] names: past it the host reads that many and says [`FileFacts::truncated`]. pub const FILE_READ_MAX: usize = 2000; +/// The most entries (files and directories, matched or not) the walk of one glob visits: past it the walk stops and +/// the host says [`FileFacts::truncated`], whatever it matched so far. +pub const GLOB_VISITS_MAX: usize = 20_000; + +/// The largest [`FileRead::text_max`] (4 MiB): the registry refuses a larger one (W021) and the host never sends more. +pub const TEXT_MAX_CEILING_BYTES: u32 = 4 * 1024 * 1024; + /// What the host read for one [`FileRead`]. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct FileFacts { /// One per (entity, path), sorted by `(entity, path)`; a glob's by `path`. #[serde(default)] pub facts: Vec, - /// The glob matched more files than the host reads ([`FILE_READ_MAX`]). + /// The read stopped early: it named more files than the host reads ([`FILE_READ_MAX`]), or its glob's walk + /// reached [`GLOB_VISITS_MAX`] entries. The guest cannot tell which. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub truncated: bool, } diff --git a/crates/leaf/protocol-types/src/surface.rs b/crates/leaf/protocol-types/src/surface.rs index a5d4e3ebcb..d465ddee56 100644 --- a/crates/leaf/protocol-types/src/surface.rs +++ b/crates/leaf/protocol-types/src/surface.rs @@ -45,6 +45,11 @@ pub struct CommandDescriptor { /// Records what a person says: the host runs it only for a person at a terminal (protocol 1.12.0, ADR 0301). #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub human: bool, + /// Imports what was recorded outside the spec: the host writes an error its plan adds only when the code is in the + /// reporting extension's own namespace and own catalog and declares no `facts`, and refuses a host, `@specforge/*`, + /// fact-judging or uncatalogued code (protocol 2.3.0, ADR 0392). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub imports: bool, /// Local codes of the extension: the command is refused (`gate_failed`) while one fails in the `subject`'s scope /// (protocol 1.10.0, ADR 0291). #[serde(default, skip_serializing_if = "Vec::is_empty")] diff --git a/crates/leaf/protocol-types/src/version.rs b/crates/leaf/protocol-types/src/version.rs index 9e9cedc24e..0f4c8b4d6b 100644 --- a/crates/leaf/protocol-types/src/version.rs +++ b/crates/leaf/protocol-types/src/version.rs @@ -84,6 +84,14 @@ /// does not change. /// - a pass entity carries `title` ([`PassEntity::title`](crate::PassEntity::title), ADR 0387), the title its header /// writes, as a command's graph node does; absent for a fact written without one. +/// - a collector may declare `requires`, the other programs its command runs beside its argv's first, which +/// `specforge doctor` looks up on PATH (ADR 0389 D3); absent when empty. +/// - a file read may declare `text_max` with `text` ([`FileRead::text_max`](crate::FileRead::text_max), ADR 0390 +/// D3): the most text of one file it is sent, in bytes, instead of 64 KiB, at most 4 MiB; its text budget is then +/// the larger of 1 MiB and four times it. Zero, over 4 MiB or without `text` is W021 and served empty. +/// - a command may declare `imports` ([`CommandDescriptor::imports`](crate::CommandDescriptor::imports), ADR 0392): +/// it imports what was recorded outside the spec, so the host writes a third-party extension's error its plan adds +/// and refuses a first-party one (E016 included); it must `writes`, else W021. /// /// A 2.2.0 guest still loads; a 2.3.0 guest is refused by a 2.2 host (E088, newer). /// diff --git a/crates/leaf/protocol-types/tests/calls_roundtrip.rs b/crates/leaf/protocol-types/tests/calls_roundtrip.rs index eb2831b471..f29f19157b 100644 --- a/crates/leaf/protocol-types/tests/calls_roundtrip.rs +++ b/crates/leaf/protocol-types/tests/calls_roundtrip.rs @@ -309,6 +309,21 @@ fn collect_output_with_facts_round_trips_and_omits_an_empty_list() { assert!(empty.get("facts").is_none(), "{empty}"); } +#[test] +fn collect_output_warnings_round_trip_and_an_empty_list_is_off_the_wire() { + use specforge_protocol_types::CollectOutput; + + let answer = json!({"entity_results": [], "warnings": ["skipped 1 file outside the project: /elsewhere/a.rs"]}); + let output: CollectOutput = round_trips(&answer); + assert_eq!( + output.warnings, + ["skipped 1 file outside the project: /elsewhere/a.rs"] + ); + + let empty = serde_json::to_value(CollectOutput::default()).unwrap(); + assert!(empty.get("warnings").is_none(), "{empty}"); +} + #[test] fn a_pass_entity_carries_pending_and_its_unheld_spans_and_omits_them_when_absent() { use specforge_protocol_types::PassEntity; diff --git a/crates/leaf/protocol-types/tests/declaration.rs b/crates/leaf/protocol-types/tests/declaration.rs index 121402e1ea..ef9d64384f 100644 --- a/crates/leaf/protocol-types/tests/declaration.rs +++ b/crates/leaf/protocol-types/tests/declaration.rs @@ -115,6 +115,7 @@ fn full() -> ExtensionDeclaration { machine: true, reported_while: Some("complete".to_string()), settled_later: true, + facts: vec!["coverage".to_string()], }, CodeDescriptor { code: "R002".to_string(), @@ -502,6 +503,8 @@ fn codes_round_trip_on_the_wire() { assert!(items[1].get("docs").is_none(), "{}", items[1]); assert_eq!(items[0]["settled_later"], true); assert!(items[1].get("settled_later").is_none(), "{}", items[1]); + assert_eq!(items[0]["facts"], serde_json::json!(["coverage"])); + assert!(items[1].get("facts").is_none(), "{}", items[1]); assert!(declared.declares(DeclaredCategory::Codes)); let loaded = ExtensionDeclaration::from_wire( declared.handshake.clone(), diff --git a/crates/pipeline/registry/src/collectors.rs b/crates/pipeline/registry/src/collectors.rs index e6835db730..a82a99951a 100644 --- a/crates/pipeline/registry/src/collectors.rs +++ b/crates/pipeline/registry/src/collectors.rs @@ -116,6 +116,7 @@ mod tests { }, answers: answers.iter().map(ToString::to_string).collect(), install: None, + requires: Vec::new(), } } diff --git a/crates/pipeline/registry/src/compilation/capabilities.rs b/crates/pipeline/registry/src/compilation/capabilities.rs index cb1dd845ca..fb0488cb38 100644 --- a/crates/pipeline/registry/src/compilation/capabilities.rs +++ b/crates/pipeline/registry/src/compilation/capabilities.rs @@ -3,11 +3,12 @@ use specforge_protocol_types::{ ExtensionDeclaration, INSTALL_LINE_MAX, Owner, capability_problems, is_install_line, + is_program_name, }; /// The messages (W021) about the capabilities `declaration` makes, and about its collectors' `capability`: a -/// collector that keeps a `capture` with no command has no output to keep (ADR 0345 D2), and an install line must be -/// one printable line (ADR 0348 D4). +/// collector that keeps a `capture` with no command has no output to keep (ADR 0345 D2), an install line must be +/// one printable line (ADR 0348 D4), and a `requires` program a bare program name (ADR 0389 D3). pub(crate) fn problems(declaration: &ExtensionDeclaration) -> Vec { let name = declaration.name(); let uncaptured = declaration @@ -44,5 +45,19 @@ pub(crate) fn problems(declaration: &ExtensionDeclaration) -> Vec { ) }) })) + .chain(declaration.collectors.iter().flat_map(move |collector| { + collector + .requires + .iter() + .filter(|program| !is_program_name(program)) + .map(move |program| { + format!( + "extension '{name}': collector '{}': its `requires` program '{}' is no bare program name \ + (non-empty, no path separator, whitespace or control character)", + collector.name, + program.escape_debug() + ) + }) + })) .collect() } diff --git a/crates/pipeline/registry/src/compilation/codes.rs b/crates/pipeline/registry/src/compilation/codes.rs index 29472b7764..cdda57aed1 100644 --- a/crates/pipeline/registry/src/compilation/codes.rs +++ b/crates/pipeline/registry/src/compilation/codes.rs @@ -53,6 +53,7 @@ pub fn extension_codes(declaration: &ExtensionDeclaration) -> Vec machine: entry.machine, reported_while: entry.reported_while.clone(), settled_later: entry.settled_later, + facts: entry.facts.clone(), }) .collect() } diff --git a/crates/pipeline/registry/src/compilation/declaration.rs b/crates/pipeline/registry/src/compilation/declaration.rs index 920962282b..aada868c01 100644 --- a/crates/pipeline/registry/src/compilation/declaration.rs +++ b/crates/pipeline/registry/src/compilation/declaration.rs @@ -9,7 +9,8 @@ use std::collections::{HashMap, HashSet, VecDeque}; use specforge_common::{Diagnostic, codes}; use specforge_diagnostics::is_local_code; use specforge_protocol_types::{ - CompilerPassDescriptor, ExtensionDeclaration, FieldDescriptor, FieldType, is_valid_short, + CompilerPassDescriptor, ExtensionDeclaration, FieldDescriptor, FieldType, is_report_name, + is_valid_short, }; use super::populate::keyword; @@ -20,7 +21,8 @@ fn e030(message: String) -> Diagnostic { /// E030: a declaration the host cannot use as declared: an empty name or /// version, an `ext_short` that is not lowercase kebab case (it names a CLI -/// subcommand and an MCP tool prefix), or a malformed `codes` entry. +/// subcommand and an MCP tool prefix), a malformed `codes` entry, or a +/// collector report glob that does not end in a literal file name (ADR 0389 D6). pub(crate) fn shape(declaration: &ExtensionDeclaration) -> Vec { let name = declaration.name(); let mut diagnostics = Vec::new(); @@ -43,6 +45,19 @@ pub(crate) fn shape(declaration: &ExtensionDeclaration) -> Vec { ); } diagnostics.extend(code_entries(declaration)); + for collector in &declaration.collectors { + if let Some(report) = collector + .report + .as_deref() + .filter(|report| !is_report_name(report)) + { + diagnostics.push(e030(format!( + "extension '{name}': collector '{}' declares the report '{report}': a report glob must end in a \ + literal file name, so it names the files one tool writes", + collector.name + ))); + } + } diagnostics } diff --git a/crates/pipeline/registry/src/inputs.rs b/crates/pipeline/registry/src/inputs.rs index c6c54ebc26..e2a7051750 100644 --- a/crates/pipeline/registry/src/inputs.rs +++ b/crates/pipeline/registry/src/inputs.rs @@ -6,7 +6,7 @@ use std::collections::HashSet; use specforge_common::structural::NODE_KINDS; use specforge_protocol_types::{ - ExtensionDeclaration, FieldWriter, FileRead, Input, InputKind, Root, + ExtensionDeclaration, FieldWriter, FileRead, Input, InputKind, Root, TEXT_MAX_CEILING_BYTES, }; use crate::compilation::UnloadedPeers; @@ -43,8 +43,9 @@ pub fn served(kind: CallKind, input: &Input) -> bool { /// Why `read` cannot be served as declared, or `None` when its shape is sound: a name that is no word, neither or both /// of `field` and `glob`, a field that is not `kind.field`, a glob that is absolute, climbs with `..`, has an empty -/// segment or more than [`MAX_DOUBLE_STAR`] `**` segments, `root` on a glob, or a `root` that is no root's name. A name repeated in an owner's reads is -/// [`problems`]'. +/// segment or more than [`MAX_DOUBLE_STAR`] `**` segments, `root` on a glob, a `root` that is no root's name, or a +/// `text_max` that is zero, over [`TEXT_MAX_CEILING_BYTES`] or set without `text`. A name repeated in an owner's +/// reads is [`problems`]'. pub fn read_problem(read: &FileRead) -> Option { if !is_word(&read.name) { return Some(format!( @@ -52,6 +53,18 @@ pub fn read_problem(read: &FileRead) -> Option { read.name )); } + match read.text_max { + Some(0) => return Some("its text_max is zero".to_string()), + Some(max) if max > TEXT_MAX_CEILING_BYTES => { + return Some(format!( + "its text_max {max} is over 4 MiB ({TEXT_MAX_CEILING_BYTES} bytes)" + )); + } + Some(_) if !read.text => { + return Some("it sets `text_max` but asks for no text".to_string()); + } + _ => {} + } match (&read.field, &read.glob) { (None, None) => Some("it names neither a `field` nor a `glob`".to_string()), (Some(_), Some(_)) => Some("it names both a `field` and a `glob`".to_string()), @@ -556,4 +569,31 @@ mod tests { ] ); } + + /// A read's `text_max` is a positive size of at most 4 MiB, and only with `text` (ADR 0390 D3). + #[test] + fn a_text_max_that_is_zero_too_large_or_without_text_is_a_problem() { + let read = |text: bool, text_max: u32| FileRead { + name: "report".into(), + glob: Some("etc/*.api.md".into()), + text, + text_max: Some(text_max), + ..FileRead::default() + }; + assert_eq!( + read_problem(&read(true, 0)).as_deref(), + Some("its text_max is zero") + ); + assert_eq!( + read_problem(&read(true, 5_000_000)).as_deref(), + Some("its text_max 5000000 is over 4 MiB (4194304 bytes)") + ); + assert_eq!( + read_problem(&read(false, 200_000)).as_deref(), + Some("it sets `text_max` but asks for no text") + ); + for fine in [1, 200_000, TEXT_MAX_CEILING_BYTES] { + assert_eq!(read_problem(&read(true, fine)), None, "{fine}"); + } + } } diff --git a/crates/pipeline/registry/src/surface/prompts.rs b/crates/pipeline/registry/src/surface/prompts.rs index dc3c56dc01..6ac8e282a7 100644 --- a/crates/pipeline/registry/src/surface/prompts.rs +++ b/crates/pipeline/registry/src/surface/prompts.rs @@ -148,6 +148,9 @@ impl Ctx<'_> { if command.human && !command.writes { return Err("it is human and does not write".to_string()); } + if command.imports && !command.writes { + return Err("it imports and does not write".to_string()); + } self.gates(&command.gates)?; if let Some(subject) = &command.subject { let takes_entity = command diff --git a/crates/pipeline/registry/tests/build/namespaces.rs b/crates/pipeline/registry/tests/build/namespaces.rs index 5770ff98b3..73e517cf3a 100644 --- a/crates/pipeline/registry/tests/build/namespaces.rs +++ b/crates/pipeline/registry/tests/build/namespaces.rs @@ -114,3 +114,26 @@ fn a_settled_later_code_reaches_the_code_book_and_no_e030() { assert!(book.settled_later("@acme/plans", "E301")); assert!(!book.settled_later("@acme/plans", "E302")); } + +/// A code naming the collected kinds it judges (ADR 0389): the code book lists it by kind, qualified. +#[spec(requirement = "FEATURE-028")] +fn a_code_naming_the_kinds_it_judges_reaches_the_code_book() { + let reports = declare("@acme/reports", |c| { + c.code("W104", |d| { + d.title("Report entry on no item") + .explanation("Serve the item.") + .facts(&["coverage"]); + }); + c.code("W105", |d| { + d.title("Plain").explanation("About authored entities."); + }); + }); + let build = build([reports]); + assert!(coded(&build, "E030").is_empty(), "{:?}", codes(&build)); + let book = build.codes(); + assert_eq!( + book.switched_off(&["coverage".into()], &[]), + ["acme.reports/W104"] + ); + assert!(book.switched_off(&["api_item".into()], &[]).is_empty()); +} diff --git a/crates/pipeline/registry/tests/declarations.rs b/crates/pipeline/registry/tests/declarations.rs index e07f0aba8c..0b842bf39f 100644 --- a/crates/pipeline/registry/tests/declarations.rs +++ b/crates/pipeline/registry/tests/declarations.rs @@ -57,6 +57,35 @@ fn a_malformed_short_name_is_e030() { ); } +#[specforge_test_macros::test(requirement = "FEATURE-028")] +fn a_report_glob_ending_in_a_wildcard_is_e030() { + let mut c = declaration("@acme/reports", "1.0.0"); + for name in ["keys", "secrets", "sbom"] { + c.collector(name, |k| { + k.report("**/sbom.cdx.json") + .collect(|_| Ok(CollectOutput::default())); + }); + } + let mut bad = c.declaration(); + // A raw declaration can carry any report; the SDK refuses one at build. + bad.collectors[0].report = Some("**/*.pem".to_string()); + bad.collectors[1].report = Some("config/.env?".to_string()); + let build = build_registries(vec![bad]); + assert_eq!(codes(&build), ["E030", "E030"]); + let messages: Vec<&str> = diagnostics(&build) + .iter() + .map(|d| d.message.as_str()) + .collect(); + assert!( + messages[0].contains("collector 'keys' declares the report '**/*.pem'"), + "{messages:?}" + ); + assert!( + messages[1].contains("collector 'secrets' declares the report 'config/.env?'"), + "{messages:?}" + ); +} + fn with_peer(name: &str, peer: &str, range: &str, optional: bool) -> ExtensionDeclaration { let mut c = ContributionsBuilder::new(ExtensionMeta::new(name, "1.0.0")); c.meta.peer_dependencies.push(PeerDependency { @@ -604,6 +633,25 @@ fn capabilities_with_a_config_that_is_not_sound_are_w021() { assert_eq!(found.len(), expect.len(), "{found:#?}"); } +#[specforge_test_macros::test(requirement = "FEATURE-028")] +fn a_required_program_that_is_no_bare_name_is_w021() { + let found = capability_problems_of(|c| { + c.collector("cov", |k| { + k.requires(&["cargo-nextest", "", "bin/tool", "two words"]) + .collect(|_| Ok(CollectOutput::default())); + }); + }); + assert_eq!(found.len(), 3, "{found:#?}"); + for named in ["''", "'bin/tool'", "'two words'"] { + assert!( + found + .iter() + .any(|m| m.contains(&format!("`requires` program {named}"))), + "{named} in {found:#?}" + ); + } +} + #[specforge_test_macros::test(requirement = "FEATURE-028")] fn a_collector_capture_without_a_command_is_w021() { let found = capability_problems_of(|c| { diff --git a/crates/pipeline/registry/tests/prompts.rs b/crates/pipeline/registry/tests/prompts.rs index d2175995c5..7e95e54c5b 100644 --- a/crates/pipeline/registry/tests/prompts.rs +++ b/crates/pipeline/registry/tests/prompts.rs @@ -111,21 +111,33 @@ fn a_prompt_declaration_the_registry_refuses_is_w021() { } #[specforge_test(requirement = "FEATURE-131")] -fn a_human_command_that_does_not_write_is_dropped() { +fn a_human_or_importing_command_that_does_not_write_is_dropped() { let mut mute = command("attest"); mute["human"] = json!(true); let mut writing = command("confirm"); writing["human"] = json!(true); writing["writes"] = json!(true); + // An import that does not write is dropped the same way (ADR 0392). + let mut reader = command("read"); + reader["imports"] = json!(true); + let mut importing = command("import"); + importing["imports"] = json!(true); + importing["writes"] = json!(true); let build = build_registries(vec![declaration( "@t/core", "t", - json!({"surfaces": {"commands": [mute, writing]}}), + json!({"surfaces": {"commands": [mute, writing, reader, importing]}}), )]); let w021 = messages(&build, "W021"); - assert_eq!(w021.len(), 1, "{w021:#?}"); + assert_eq!(w021.len(), 2, "{w021:#?}"); + assert!( + w021.iter() + .any(|m| m.contains("'attest'") && m.contains("human and does not write")), + "{w021:#?}" + ); assert!( - w021[0].contains("'attest'") && w021[0].contains("human and does not write"), + w021.iter() + .any(|m| m.contains("'read'") && m.contains("imports and does not write")), "{w021:#?}" ); let routed: Vec<_> = build @@ -134,7 +146,7 @@ fn a_human_command_that_does_not_write_is_dropped() { .iter() .map(|r| r.declaration().id.clone()) .collect(); - assert_eq!(routed, ["confirm"]); + assert_eq!(routed, ["confirm", "import"]); } #[specforge_test(requirement = "FEATURE-125")] diff --git a/crates/pipeline/registry/tests/rules/mod.rs b/crates/pipeline/registry/tests/rules/mod.rs index a7d49e8f96..16279209e1 100644 --- a/crates/pipeline/registry/tests/rules/mod.rs +++ b/crates/pipeline/registry/tests/rules/mod.rs @@ -90,6 +90,7 @@ fn catalog_of(rules: &[ValidationRuleDescriptor]) -> Vec ExtensionD machine: false, reported_while: None, settled_later: false, + facts: Vec::new(), }); } } diff --git a/crates/runtime/component/data/builtin-vocabulary.json b/crates/runtime/component/data/builtin-vocabulary.json index 10bb266efb..385f5e5942 100644 --- a/crates/runtime/component/data/builtin-vocabulary.json +++ b/crates/runtime/component/data/builtin-vocabulary.json @@ -1,6 +1,9 @@ { "$comment": "Generated by `cargo run -p xtask --bin revendor` from the builtins' pinned declarations (ADR 0122, ADR 0369). Do not edit.", "kinds": { + "api_item": [ + "@code/core" + ], "artifact": [ "@gsd/core" ], @@ -34,6 +37,9 @@ "context": [ "@gsd/core" ], + "coverage": [ + "@code/core" + ], "decision": [ "@gsd/core", "@specforge/governance" @@ -45,6 +51,9 @@ "@gsd/core", "@specforge/product" ], + "dependency": [ + "@code/core" + ], "deviation": [ "@gsd/core" ], @@ -208,6 +217,9 @@ "stack_choice": [ "@gsd/core" ], + "static_finding": [ + "@code/core" + ], "summary": [ "@gsd/core" ], @@ -253,6 +265,9 @@ "verify_gap": [ "@gsd/core" ], + "vulnerability": [ + "@code/core" + ], "wave0_item": [ "@gsd/core" ], diff --git a/crates/runtime/component/src/builtins.rs b/crates/runtime/component/src/builtins.rs index 0f2214be03..0db64a85c4 100644 --- a/crates/runtime/component/src/builtins.rs +++ b/crates/runtime/component/src/builtins.rs @@ -6,12 +6,12 @@ use specforge_wasm::{LoadError, Provenance, WasmRuntime}; /// One builtin extension: its package name, its crate, the component `build-blobs` vendors into /// `/wasm/`, and the vendored bytes this host embeds. Name and crate follow one rule: /// `extensions/` is `@specforge/`, and `extensions//` is `@/` -/// (ADR 0328 D3). One crate lives outside `extensions/` and is named in its row: `@gsd/core` at -/// `gsd/core`, in the gsd workspace (ADR 0366 D1). +/// (ADR 0328 D3). Two crates live outside `extensions/` and are named in their rows: `@gsd/core` at +/// `gsd/core` and `@gsd/import` at `gsd/import`, both in the gsd workspace (ADR 0366 D1, ADR 0391 D12). pub struct Builtin { pub name: &'static str, /// Its crate, from the repository root: `extensions/`, `extensions//`, or - /// the path a named row gives (`gsd/core`). + /// the path a named row gives (`gsd/core`, `gsd/import`). pub crate_dir: &'static str, pub artifact: &'static str, pub bytes: &'static [u8], @@ -53,8 +53,21 @@ builtins! { "@rust/cargo" in "rust/cargo" as "specforge_ext_rust_cargo.wasm", "@rust/source" in "rust/source" as "specforge_ext_rust_source.wasm", "@rust/test" in "rust/test" as "specforge_ext_rust_test.wasm", - "@javascript/source" in "javascript/source" as "specforge_ext_javascript_source.wasm"; + "@javascript/source" in "javascript/source" as "specforge_ext_javascript_source.wasm", + "@rust/coverage" in "rust/coverage" as "specforge_ext_rust_coverage.wasm", + "@rust/lint" in "rust/lint" as "specforge_ext_rust_lint.wasm", + "@rust/deps" in "rust/deps" as "specforge_ext_rust_deps.wasm", + "@rust/api" in "rust/api" as "specforge_ext_rust_api.wasm", + "@rust/proof" in "rust/proof" as "specforge_ext_rust_proof.wasm", + "@javascript/coverage" in "javascript/coverage" as "specforge_ext_javascript_coverage.wasm", + "@javascript/lint" in "javascript/lint" as "specforge_ext_javascript_lint.wasm", + "@javascript/deps" in "javascript/deps" as "specforge_ext_javascript_deps.wasm", + "@javascript/api" in "javascript/api" as "specforge_ext_javascript_api.wasm", + "@javascript/vitest" in "javascript/vitest" as "specforge_ext_javascript_vitest.wasm", + "@javascript/jest" in "javascript/jest" as "specforge_ext_javascript_jest.wasm", + "@javascript/playwright" in "javascript/playwright" as "specforge_ext_javascript_playwright.wasm"; "@gsd/core" at "gsd/core" as "gsd_core.wasm", + "@gsd/import" at "gsd/import" as "gsd_import.wasm", } /// (name, bytes) of every builtin, read from [`BUILTINS`]: what the extension load reads @@ -114,7 +127,7 @@ pub fn load_builtins(runtime: &dyn WasmRuntime) -> Result<(), LoadError> { #[cfg(feature = "testing")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Family { - /// The fourteen builtins of the `@specforge/*` starter set and what they load with. + /// The twenty-six builtins of the `@specforge/*` starter set and what they load with. Old, /// `@gsd/core` with its peers and the collectors that need `@code/core`. Gsd, @@ -126,7 +139,8 @@ impl Family { pub const ALL: [Family; 2] = [Family::Old, Family::Gsd]; /// The names of the set, as ADR 0369 D3 lists them. The old set is in [`BUILTINS`] order; the gsd - /// set names `@gsd/core` first, then the seven builtins it shares with the old set. + /// set names `@gsd/core` and `@gsd/import` first, then the nineteen builtins it shares with the old set + /// (`@specforge/vitest` stays in the old set only). pub const fn names(self) -> &'static [&'static str] { match self { Family::Old => &[ @@ -144,9 +158,22 @@ impl Family { "@rust/source", "@rust/test", "@javascript/source", + "@rust/coverage", + "@rust/lint", + "@rust/deps", + "@rust/api", + "@rust/proof", + "@javascript/coverage", + "@javascript/lint", + "@javascript/deps", + "@javascript/api", + "@javascript/vitest", + "@javascript/jest", + "@javascript/playwright", ], Family::Gsd => &[ "@gsd/core", + "@gsd/import", "@code/core", "@javascript/node-test", "@specforge/checks", @@ -154,6 +181,18 @@ impl Family { "@rust/source", "@rust/test", "@javascript/source", + "@rust/coverage", + "@rust/lint", + "@rust/deps", + "@rust/api", + "@rust/proof", + "@javascript/coverage", + "@javascript/lint", + "@javascript/deps", + "@javascript/api", + "@javascript/vitest", + "@javascript/jest", + "@javascript/playwright", ], } } diff --git a/crates/runtime/component/tests/blob_size.rs b/crates/runtime/component/tests/blob_size.rs index bcbbb66c0c..4c4d7adb66 100644 --- a/crates/runtime/component/tests/blob_size.rs +++ b/crates/runtime/component/tests/blob_size.rs @@ -9,13 +9,14 @@ use specforge_component::builtins::BUILTINS; use specforge_component::committed::COMMITTED; -// The fifteen builtins total 18,033,150 B, the sum of the `.wasm` files `revendor` commits (built with -// `--profile blob` on the pinned rustc): the fourteen under `extensions/` 12,304,701 B, the largest of them -// `@specforge/checks` at 2,452,015 B, and `gsd/core/wasm/gsd_core.wasm` 5,728,449 B, the one blob over the gate's cap, -// held to its own allowance (ADR 0366 D3). The budget is that total rounded up to the next 100,000 B, here 18,100,000 -// (66,850 B of headroom): a change that grows the blobs past it re-measures and takes the rule's next step in the same -// commit (ADR 0373 D3). A build without the profile is far larger, so this catches a profile regression. -const TOTAL_BUDGET: usize = 18_100_000; +// The twenty-eight builtins total 27,991,688 B, the sum of the `.wasm` files `revendor` commits (built with +// `--profile blob` on the pinned rustc): the twenty-six under `extensions/` 20,687,816 B, the largest of them +// `@specforge/checks` at 2,454,208 B, `gsd/core/wasm/gsd_core.wasm` 5,759,902 B, the one blob over the gate's cap, +// held to its own allowance (ADR 0366 D3), and `gsd/import/wasm/gsd_import.wasm` 1,543,970 B (ADR 0391 D12). The +// budget is that total rounded up to the next 100,000 B, here 28,000,000 (8,312 B of headroom): a change that grows +// the blobs past it re-measures and takes the rule's next step in the same commit (ADR 0373 D3). A build without the +// profile is far larger, so this catches a profile regression. +const TOTAL_BUDGET: usize = 28_000_000; #[test] fn committed_builtins_stay_under_their_size_budget() { diff --git a/crates/runtime/component/tests/builtin_codes.rs b/crates/runtime/component/tests/builtin_codes.rs index 5652bd58e6..4c95b169fb 100644 --- a/crates/runtime/component/tests/builtin_codes.rs +++ b/crates/runtime/component/tests/builtin_codes.rs @@ -82,6 +82,56 @@ fn builtin_rules_use_their_own_codes() { ); } +/// Every `@gsd/core` error code that an importing command's plan writes rather than refuses (ADR 0392): all of them, +/// as none declares `facts`. `E533` and `E535` read API and package facts but judge a closed milestone's claim, which +/// is history, so they land too (ADR 0392, Limits). +const GSD_CORE_LANDS: &[&str] = &[ + "E101", "E102", "E105", "E106", "E107", "E108", "E201", "E202", "E206", "E301", "E302", "E303", + "E307", "E310", "E312", "E314", "E319", "E320", "E322", "E401", "E402", "E405", "E501", "E502", + "E503", "E505", "E507", "E509", "E511", "E512", "E513", "E515", "E516", "E517", "E518", "E521", + "E523", "E533", "E535", +]; + +#[specforge_test_macros::test(requirement = "FEATURE-131")] +fn the_gsd_core_errors_an_import_lands_are_pinned() { + let name = "@gsd/core"; + let (_, bytes) = BUILTIN_EXTENSIONS + .iter() + .find(|(builtin, _)| *builtin == name) + .expect("@gsd/core is a builtin"); + let runtime = ComponentRuntime::new(); + runtime + .load(name, bytes, specforge_wasm::Provenance::third_party(bytes)) + .expect("builtin loads"); + let declaration = load_declaration(&runtime, name) + .expect("builtin declares itself") + .declaration; + // The vendored blob read as the registry build reads it, so the pin follows what the host judges. + let codes = specforge_registry::extension_codes(&declaration); + let errors: Vec = codes + .iter() + .filter(|code| code.local.starts_with('E')) + .map(|code| code.local.clone()) + .collect(); + let mut book = Codebook::default(); + book.add(name, codes).unwrap(); + let (mut lands, mut refused): (Vec<&str>, Vec<&str>) = errors + .iter() + .map(String::as_str) + .partition(|local| book.authored_rule(name, &format!("gsd/{local}"))); + lands.sort_unstable(); + refused.sort_unstable(); + assert!( + refused.is_empty(), + "these @gsd/core errors now refuse an import (their catalog entry declares `facts`, ADR 0392); \ + if that is meant, amend ADR 0392's Limits and this pin: {refused:?}" + ); + assert_eq!( + lands, GSD_CORE_LANDS, + "the @gsd/core errors an import lands changed: update GSD_CORE_LANDS (ADR 0392)" + ); +} + #[specforge_test_macros::test(requirement = "FEATURE-007")] fn the_checks_switches_gate_codes_the_catalog_gives_checks() { let runtime = ComponentRuntime::new(); diff --git a/crates/runtime/component/tests/builtins_table.rs b/crates/runtime/component/tests/builtins_table.rs index 1b8844122b..12be85c797 100644 --- a/crates/runtime/component/tests/builtins_table.rs +++ b/crates/runtime/component/tests/builtins_table.rs @@ -159,9 +159,11 @@ fn layout(root: &Path) -> Layout { fn the_table_is_the_extensions_directory_by_the_naming_rule() { let on_disk = layout(specforge_repo_root::repo_root()); assert!(on_disk.problems.is_empty(), "{:#?}", on_disk.problems); - // The one builtin outside `extensions/`, named in its row (ADR 0366 D1); every other row is the rule's. + // The two builtins outside `extensions/`, named in their rows (ADR 0366 D1, ADR 0391 D12); every + // other row is the rule's. let mut expected = on_disk.builtins; expected.push(Named::new("gsd/core", "@gsd/core", "gsd_core.wasm")); + expected.push(Named::new("gsd/import", "@gsd/import", "gsd_import.wasm")); expected.sort(); let mut listed: Vec = BUILTINS .iter() @@ -170,7 +172,7 @@ fn the_table_is_the_extensions_directory_by_the_naming_rule() { listed.sort(); assert_eq!( listed, expected, - "BUILTINS lists every builtin crate under extensions/, once, named by the rule, and @gsd/core at gsd/core" + "BUILTINS lists every builtin crate under extensions/, once, named by the rule, @gsd/core at gsd/core and @gsd/import at gsd/import" ); for builtin in BUILTINS { assert!( diff --git a/crates/runtime/component/tests/declarations/code_core/describe_codes.json b/crates/runtime/component/tests/declarations/code_core/describe_codes.json index eaaff64916..522623f2d7 100644 --- a/crates/runtime/component/tests/declarations/code_core/describe_codes.json +++ b/crates/runtime/component/tests/declarations/code_core/describe_codes.json @@ -4,22 +4,69 @@ { "code": "E101", "explanation": "A reference names no collected fact of the kinds its field admits, narrowed to those its id is shaped as (a test id holds `#`, an item id never does), while a fact store the session served holds facts of one of those kinds in its scheme: the test, item or package was renamed, moved or deleted, or the reference is misspelled. A test or run reference is told the closest one of the same file or binary. It is not reported while the citing entity's owner is pending (ADR 0329 D4): a test not written yet is TDD. Fix the reference, or run `specforge collect` if what it names is new. A reference one of its own facts holds (a test run's test) that no fact or entity answers, or that names an entity of another kind, is reported at the place its collector read it, addressed to that collector: its facts disagree, and running `specforge collect` again, or fixing the pack, is the remedy (ADR 0346).", + "facts": [ + "item", + "package", + "test", + "test_run" + ], "title": "A fact reference names no fact" }, { "code": "W102", - "explanation": "A reference names no collected fact, and no fact store the session served holds facts of the kinds its field admits (narrowed to those its id is shaped as) in its scheme: on a fresh clone, or before the pack that writes them ran, there is nothing to check it against. It is reported once per cited reference, and not while the citing entity's owner is pending. Run `specforge collect` with the pack the finding names: `@javascript/node-test` for `js` tests, `@rust/test` for `rust` tests, `@rust/source` for `rust` items, `@javascript/source` for `js` items, `@rust/cargo` for `pkg:cargo` packages, `@javascript/source` for `pkg:npm` packages.", + "explanation": "A reference names no collected fact, and no fact store the session served holds facts of the kinds its field admits (narrowed to those its id is shaped as) in its scheme: on a fresh clone, or before the pack that writes them ran, there is nothing to check it against. It is reported once per cited reference, and not while the citing entity's owner is pending. Run `specforge collect` with the pack the finding names: `@javascript/node-test`, `@javascript/vitest`, `@javascript/jest` or `@javascript/playwright` for `js` tests, `@rust/test` or `@rust/proof` for `rust` tests, `@rust/source` for `rust` items, `@javascript/source` for `js` items, `@rust/cargo` for `pkg:cargo` packages, `@javascript/source` for `pkg:npm` packages.", "title": "No facts of the reference's kinds were collected" }, { "code": "W401", "explanation": "An entity whose owner is complete links a test whose last collected status is `failed`: the proof it cites does not hold. A pending owner's failing test is not reported (TDD). Fix the code or the test, and run `specforge collect` again.", + "facts": [ + "test" + ], "title": "A linked test fails" }, { "code": "I402", "explanation": "A test or item fact's `names` (the entities its source's idiom says it proves or implements) holds a name that is no entity of the project, or the short name of several: the entity was renamed or deleted, or the name is misspelled. Fix the name in the source, then collect again.", + "facts": [ + "item", + "test" + ], "title": "A test or item names an entity that does not exist" + }, + { + "code": "W104", + "explanation": "A fact a report reader minted cites no item, because the report's file or line lies in no collected item (a macro expansion, top-level statements, or a file no source pack collected), or because an API snapshot's entry has a path no collected item has: a re-exported path whose definition path differs, an item a macro generates, or a crate whose library is named apart from its package. A static finding is reported only when no collected package holds its file either, or it has no location. The entry is kept with what the report says of it, so nothing is lost. Collect the source pack for those files (`@rust/source`, `@javascript/source`) and the manifest pack for their packages, then collect the report again.", + "facts": [ + "api_item", + "coverage", + "static_finding" + ], + "title": "A report entry names no item" + }, + { + "code": "W105", + "explanation": "A static finding's SARIF result states no rule (no `ruleId`, no `rule`, and no rule index naming a rule of its tool's driver), or states no level (none on the result, and none in its rule's `defaultConfiguration`): the field reads `unknown`. The finding is kept, never dropped. SARIF's own default level is `warning`; it is not applied, so a level the tool never wrote cannot pass for one it did. Make the tool write its rule ids and levels in its SARIF output, or the rule metadata (`tool.driver.rules` with a `defaultConfiguration.level`), then collect the report again.", + "facts": [ + "static_finding" + ], + "title": "A finding's rule or level is unknown" + }, + { + "code": "W106", + "explanation": "A component of a CycloneDX bill of materials carries no package URL (`purl`), so its dependency is named by name and version only (`dep:/@`). The dependency is kept, never dropped, but no other report can be matched to it: an OSV scan or another BOM names a package by its purl. Generate the BOM with an SBOM tool that writes a purl for every component (cargo-cyclonedx, cyclonedx-npm), then collect it again.", + "facts": [ + "dependency" + ], + "title": "A dependency has no purl" + }, + { + "code": "W107", + "explanation": "An OSV record of a vulnerability scan has no severity label (`database_specific.severity`) and no CVSS v3 vector this reader rates: its only severity entries are CVSS v4 or v2 vectors, or its v3 vector is malformed. The vulnerability is kept with severity `unknown`, never dropped and never given a guessed rating, so a gate on severity cannot pass it by mistake. Read the advisory by its OSV id (osv.dev, or the database its id names) and judge its severity there.", + "facts": [ + "vulnerability" + ], + "title": "A vulnerability's severity is unknown" } ] } \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/code_core/describe_edges.json b/crates/runtime/component/tests/declarations/code_core/describe_edges.json index 60dd099c67..c3ef2fbcea 100644 --- a/crates/runtime/component/tests/declarations/code_core/describe_edges.json +++ b/crates/runtime/component/tests/declarations/code_core/describe_edges.json @@ -45,6 +45,60 @@ "label": "runs_as", "source_kind": "item", "target_kind": "test" + }, + { + "description": "The item a coverage fact reports on", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "covers", + "source_kind": "coverage", + "target_kind": "item" + }, + { + "description": "The item an API snapshot's entry is the API of", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "api_of", + "source_kind": "api_item", + "target_kind": "item" + }, + { + "description": "The item a static finding lies in", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "found_in", + "source_kind": "static_finding", + "target_kind": "item" + }, + { + "description": "The package a static finding lies in, when no item holds it", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "found_in_package", + "source_kind": "static_finding", + "target_kind": "package" + }, + { + "description": "The project package a dependency is a component of the BOM of", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "dependency_of", + "source_kind": "dependency", + "target_kind": "package" + }, + { + "description": "The project package a vulnerability affects", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "affects", + "source_kind": "vulnerability", + "target_kind": "package" } ] } \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/code_core/describe_entities.json b/crates/runtime/component/tests/declarations/code_core/describe_entities.json index 746f34798f..bbebb917d2 100644 --- a/crates/runtime/component/tests/declarations/code_core/describe_entities.json +++ b/crates/runtime/component/tests/declarations/code_core/describe_entities.json @@ -413,6 +413,576 @@ "testable": false, "verify_kinds": [], "writer": "collector" + }, + { + "description": "What a coverage report (LCOV) says of one item, written by a coverage pack's collector (ADR 0388): cov: for the innermost item holding the report's lines, cov:@ for what no item of a file holds (W104)", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "fields": [ + { + "default_value": null, + "description": "The item holding the lines; absent when no collected item does", + "edge": "covers", + "field_type": "reference", + "inverse_of": null, + "name": "item", + "required": false, + "target_kind": "item" + }, + { + "default_value": null, + "description": "The report's file, project-relative, with / separators", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "file", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The functions the report lists in it", + "edge": null, + "field_type": "integer", + "inverse_of": null, + "name": "functions_found", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "Those of its functions that ran", + "edge": null, + "field_type": "integer", + "inverse_of": null, + "name": "functions_hit", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The lines the report measured in it", + "edge": null, + "field_type": "integer", + "inverse_of": null, + "name": "lines_found", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "Those of its lines that ran", + "edge": null, + "field_type": "integer", + "inverse_of": null, + "name": "lines_hit", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The branches the report measured in it", + "edge": null, + "field_type": "integer", + "inverse_of": null, + "name": "branches_found", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "Those of its branches that were taken", + "edge": null, + "field_type": "integer", + "inverse_of": null, + "name": "branches_hit", + "required": false, + "target_kind": null + } + ], + "has_body_parser": false, + "incremental": null, + "inference_guide": null, + "keyword": null, + "lsp_icon": null, + "name": "coverage", + "open_fields": false, + "schemes": [ + "cov" + ], + "semantic_token": null, + "singleton": false, + "supports_verify": false, + "testable": false, + "verify_kinds": [], + "writer": "collector" + }, + { + "description": "One public entry of an API snapshot, written by an api pack's collector (ADR 0388): api:rust::: (cargo public-api, a trait-impl member ...::::m), api:js::: (api-extractor), the id holding no line, order nor source file", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "fields": [ + { + "default_value": null, + "description": "The item the entry is the API of; absent when no collected item has its path (W104 for a kind an item can have)", + "edge": "api_of", + "field_type": "reference", + "inverse_of": null, + "name": "item", + "required": false, + "target_kind": "item" + }, + { + "default_value": null, + "description": "The entry's qualified path as the snapshot wrote it", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "path", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "What the entry is: an item kind, or variant, reexport, extern_crate, other, which no item is", + "edge": null, + "enum_values": [ + "module", + "function", + "method", + "field", + "struct", + "enum", + "union", + "trait", + "type", + "const", + "static", + "macro", + "class", + "interface", + "variable", + "namespace", + "variant", + "reexport", + "extern_crate", + "other" + ], + "field_type": "enum", + "inverse_of": null, + "name": "kind", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "Who may name it, as the snapshot wrote it", + "edge": null, + "enum_values": [ + "public", + "crate", + "restricted", + "private" + ], + "field_type": "enum", + "inverse_of": null, + "name": "visibility", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The entry exactly as the snapshot wrote it, attributes included", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "signature", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The api-extractor release tag (Public, Beta, Alpha, Internal)", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "tag", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The entry against the committed accepted report; absent when no accepted report covers its crate or package", + "edge": null, + "enum_values": [ + "added", + "unchanged", + "changed", + "narrowed", + "removed" + ], + "field_type": "enum", + "inverse_of": null, + "name": "change", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The accepted report's entry as it wrote it, for a changed, narrowed or removed entry", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "accepted_signature", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The accepted report's release tag, for a changed, narrowed or removed entry that has one", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "accepted_tag", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The accepted report's visibility, for a changed or narrowed entry whose visibility differs", + "edge": null, + "enum_values": [ + "public", + "crate", + "restricted", + "private" + ], + "field_type": "enum", + "inverse_of": null, + "name": "accepted_visibility", + "required": false, + "target_kind": null + } + ], + "has_body_parser": false, + "incremental": null, + "inference_guide": null, + "keyword": null, + "lsp_icon": null, + "name": "api_item", + "open_fields": false, + "schemes": [ + "api" + ], + "semantic_token": null, + "singleton": false, + "supports_verify": false, + "testable": false, + "verify_kinds": [], + "writer": "collector" + }, + { + "description": "One result of a SARIF run (a lint or static analysis finding), written by a lint pack's collector (ADR 0388): sarif:/#:, # with no line, neither with no location, ~2 on a repeat in document order", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "fields": [ + { + "default_value": null, + "description": "The run's tool (tool.driver.name)", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "tool", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The rule id the result states; unknown when it states none (W105)", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "rule", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The level the result or its rule's defaultConfiguration states; unknown when neither does (W105), never SARIF's own warning default", + "edge": null, + "enum_values": [ + "error", + "warning", + "note", + "none", + "unknown" + ], + "field_type": "enum", + "inverse_of": null, + "name": "level", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The result's message.text", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "message", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The file of its first location, project-relative, with / separators", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "file", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The 1-based start line of its first location", + "edge": null, + "field_type": "integer", + "inverse_of": null, + "name": "line", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The innermost item holding its line; absent when no collected item does", + "edge": "found_in", + "field_type": "reference", + "inverse_of": null, + "name": "item", + "required": false, + "target_kind": "item" + }, + { + "default_value": null, + "description": "The package holding its file, when no item holds its line; absent with neither (W104)", + "edge": "found_in_package", + "field_type": "reference", + "inverse_of": null, + "name": "package", + "required": false, + "target_kind": "package" + } + ], + "has_body_parser": false, + "incremental": null, + "inference_guide": null, + "keyword": null, + "lsp_icon": null, + "name": "static_finding", + "open_fields": false, + "schemes": [ + "sarif" + ], + "semantic_token": null, + "singleton": false, + "supports_verify": false, + "testable": false, + "verify_kinds": [], + "writer": "collector" + }, + { + "description": "One component of a CycloneDX bill of materials, written by an SBOM pack's collector (ADR 0388): dep:/, or dep:/@<[group/]name[@version]> for a component with no purl (W106); one fact per id, a purl listed twice merged", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "fields": [ + { + "default_value": null, + "description": "The project package the BOM describes (its metadata.component)", + "edge": "dependency_of", + "field_type": "reference", + "inverse_of": null, + "name": "package", + "required": false, + "target_kind": "package" + }, + { + "default_value": null, + "description": "The component's package URL as written; absent when it has none (W106)", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "purl", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The component's name, group/name when it states a group", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "name", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The component's version, when it states one", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "version", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The component's scope, required when the BOM states none (the spec's default); the widest of a purl listed twice", + "edge": null, + "enum_values": [ + "required", + "optional", + "excluded" + ], + "field_type": "enum", + "inverse_of": null, + "name": "scope", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "Whether the project package depends on it directly; present only when the BOM states a dependency graph for its root, never false for a graph it does not state", + "edge": null, + "field_type": "bool", + "inverse_of": null, + "name": "direct", + "required": false, + "target_kind": null + } + ], + "has_body_parser": false, + "incremental": null, + "inference_guide": null, + "keyword": null, + "lsp_icon": null, + "name": "dependency", + "open_fields": false, + "schemes": [ + "dep" + ], + "semantic_token": null, + "singleton": false, + "supports_verify": false, + "testable": false, + "verify_kinds": [], + "writer": "collector" + }, + { + "description": "One OSV record of an osv-scanner report, written by a vulnerability pack's collector (ADR 0388): vuln:/, one fact per project package the scanned lockfile belongs to and OSV id, the versions of one dependency merged; severity critical, high, medium, low, else unknown (W107)", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "fields": [ + { + "default_value": null, + "description": "The project package the scanned lockfile belongs to: the one at its directory, else each one under it", + "edge": "affects", + "field_type": "reference", + "inverse_of": null, + "name": "package", + "required": false, + "target_kind": "package" + }, + { + "default_value": null, + "description": "The OSV record's id (GHSA-…, RUSTSEC-…)", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "osv_id", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The record's aliases (CVE ids and the like), sorted", + "edge": null, + "field_type": "string_list", + "inverse_of": null, + "name": "aliases", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The record's one-line summary; absent when it states none", + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "summary", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The affected dependency's package URL at each affected version", + "edge": null, + "field_type": "string_list", + "inverse_of": null, + "name": "purl", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The affected dependency's versions the lockfile pins", + "edge": null, + "field_type": "string_list", + "inverse_of": null, + "name": "version", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": "The record's own severity label (MODERATE reads medium), else the rating of its highest CVSS v3 base score, else unknown (W107); the highest of the records merged", + "edge": null, + "enum_values": [ + "critical", + "high", + "medium", + "low", + "unknown" + ], + "field_type": "enum", + "inverse_of": null, + "name": "severity", + "required": false, + "target_kind": null + } + ], + "has_body_parser": false, + "incremental": null, + "inference_guide": null, + "keyword": null, + "lsp_icon": null, + "name": "vulnerability", + "open_fields": false, + "schemes": [ + "vuln" + ], + "semantic_token": null, + "singleton": false, + "supports_verify": false, + "testable": false, + "verify_kinds": [], + "writer": "collector" } ] } \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/code_core/describe_passes.json b/crates/runtime/component/tests/declarations/code_core/describe_passes.json index 28868686dd..2c8f10712b 100644 --- a/crates/runtime/component/tests/declarations/code_core/describe_passes.json +++ b/crates/runtime/component/tests/declarations/code_core/describe_passes.json @@ -32,6 +32,24 @@ ], "name": "proof", "phase": "check" + }, + { + "after": null, + "before": null, + "inputs": [ + { + "input": "facts", + "kinds": [ + "coverage", + "api_item", + "static_finding", + "dependency", + "vulnerability" + ] + } + ], + "name": "reports", + "phase": "check" } ] } \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/code_core/handshake.json b/crates/runtime/component/tests/declarations/code_core/handshake.json index bb8ce8ec27..447d65cdc3 100644 --- a/crates/runtime/component/tests/declarations/code_core/handshake.json +++ b/crates/runtime/component/tests/declarations/code_core/handshake.json @@ -1,8 +1,8 @@ { "protocol_version": "2.3.0", "name": "@code/core", - "version": "1.1.0", + "version": "1.4.0", "peer_dependencies": [], "sandbox_policy": null, - "description": "The neutral base of code facts: the test, test_run, item and package kinds the code packs collect, and the checks of the references a spec writes to them" + "description": "The neutral base of code facts: the test, test_run, item and package kinds the code packs collect, the report facts (coverage, api_item, static_finding, dependency, vulnerability) a standard report's reader mints, and the checks of the references a spec writes to them and of what a report leaves unmapped" } \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/gsd_core/describe_codes.json b/crates/runtime/component/tests/declarations/gsd_core/describe_codes.json index d1f46b793c..8ac125bb1a 100644 --- a/crates/runtime/component/tests/declarations/gsd_core/describe_codes.json +++ b/crates/runtime/component/tests/declarations/gsd_core/describe_codes.json @@ -442,6 +442,18 @@ "docs": "https://github.com/leaderiop/SpecForge/blob/main/gsd/core/spec/rules.md#project-and-roadmap", "explanation": "A phase's title does not begin with a phase number: its label reads the number from its id. It is a warning, and an error under gsd-strict and gsd-plus.", "title": "Phase title embeds a number" + }, + { + "code": "E533", + "docs": "https://github.com/leaderiop/SpecForge/blob/main/gsd/core/spec/rules.md#project-and-roadmap", + "explanation": "A milestone whose API facts show a changed, narrowed or removed item is closed while its version is API-compatible with the last shipped milestone of its workstream scope (Cargo's rule: for 0.x the minor counts as major), or while its name is not a version, so no major bump can be shown. It is an error.", + "title": "Breaking API change without a major version bump" + }, + { + "code": "E535", + "docs": "https://github.com/leaderiop/SpecForge/blob/main/gsd/core/spec/rules.md#project-and-roadmap", + "explanation": "A milestone named by its version is closed while a package fact's version is not its version, while its version is not later than the last shipped milestone of its workstream scope, or while the last shipped milestone's tag does not resolve to a commit. It is an error.", + "title": "Release evidence does not match the milestone" } ] } \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/gsd_core/describe_entities.json b/crates/runtime/component/tests/declarations/gsd_core/describe_entities.json index f5c76dd2f6..9fbb1c9b84 100644 --- a/crates/runtime/component/tests/declarations/gsd_core/describe_entities.json +++ b/crates/runtime/component/tests/declarations/gsd_core/describe_entities.json @@ -761,6 +761,125 @@ "required": false, "target_kind": null, "writer": "computed" + }, + { + "default_value": null, + "description": "the API items the last collect found changed, narrowed or removed against the committed accepted report: ` `; absent when no API fact carries a change; gsd/E533 reads it", + "edge": null, + "field_type": "string_list", + "inverse_of": null, + "name": "api_breaks", + "required": false, + "target_kind": null, + "writer": "computed" + }, + { + "default_value": null, + "description": "the release evidence gsd/E535 reads: `tag` and `commit` the recorded tag of a shipped milestone, `packages` the `name` and `version` of each package fact not at an open milestone's version, at most 50, and `more` the count past them; absent when nothing was observed", + "edge": null, + "field_type": "block", + "inverse_of": null, + "members": [ + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "tag", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "commit", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "block_list", + "inverse_of": null, + "members": [ + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "name", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "version", + "required": false, + "target_kind": null + } + ], + "name": "packages", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "integer", + "inverse_of": null, + "name": "more", + "required": false, + "target_kind": null + } + ], + "name": "release", + "required": false, + "target_kind": null, + "writer": "computed" + }, + { + "default_value": null, + "description": "written by gsd-git from `refs/tags/v` for a shipped milestone named by its version: the tag's `name`, and the `commit` it resolves to, absent when it resolves to none", + "edge": null, + "field_type": "block", + "inverse_of": null, + "members": [ + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "name", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "commit", + "required": false, + "target_kind": null + } + ], + "name": "tag", + "required": false, + "target_kind": null, + "writer": "harness" } ], "has_body_parser": false, diff --git a/crates/runtime/component/tests/declarations/gsd_core/describe_passes.json b/crates/runtime/component/tests/declarations/gsd_core/describe_passes.json index 80a5b67f56..91c08d9933 100644 --- a/crates/runtime/component/tests/declarations/gsd_core/describe_passes.json +++ b/crates/runtime/component/tests/declarations/gsd_core/describe_passes.json @@ -111,6 +111,8 @@ "milestone.git_range", "milestone.progress", "milestone.branch", + "milestone.api_breaks", + "milestone.release", "phase.inserted", "phase.backlog", "phase.branch", @@ -171,7 +173,9 @@ { "input": "facts", "kinds": [ - "test" + "test", + "api_item", + "package" ] } ], @@ -387,6 +391,24 @@ "E516" ] }, + { + "after": null, + "before": null, + "name": "gate_e533", + "phase": "guard", + "reports": [ + "E533" + ] + }, + { + "after": null, + "before": null, + "name": "gate_e535", + "phase": "guard", + "reports": [ + "E535" + ] + }, { "after": null, "before": null, diff --git a/crates/runtime/component/tests/declarations/gsd_core/describe_routes.json b/crates/runtime/component/tests/declarations/gsd_core/describe_routes.json index 5fb38b68f1..cfbf7208a3 100644 --- a/crates/runtime/component/tests/declarations/gsd_core/describe_routes.json +++ b/crates/runtime/component/tests/declarations/gsd_core/describe_routes.json @@ -60,6 +60,29 @@ "via": "/dist/index.d.ts\",\n \"apiReport\": { \"enabled\": false },\n \"docModel\": { \"enabled\": true, \"apiJsonFilePath\": \"{report}\" },\n \"dtsRollup\": { \"enabled\": false },\n \"tsdocMetadata\": { \"enabled\": false },\n \"messages\": {\n \"compilerMessageReporting\": { \"default\": { \"logLevel\": \"none\" } },\n \"extractorMessageReporting\": { \"default\": { \"logLevel\": \"none\" } },\n \"tsdocMessageReporting\": { \"default\": { \"logLevel\": \"none\" } }\n }\n}\n" + }, + "env": [ + "NODE_*", + "CI" + ], + "name": "javascript-api", + "port": "process", + "why": "run the command whose report the collector 'javascript-api' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_checkers.json b/crates/runtime/component/tests/declarations/javascript_api/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_codes.json b/crates/runtime/component/tests/declarations/javascript_api/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_collectors.json b/crates/runtime/component/tests/declarations/javascript_api/describe_collectors.json new file mode 100644 index 0000000000..719e904c3a --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_collectors.json @@ -0,0 +1,46 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "api_item" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "tsconfig.json" + ] + }, + "capability": "javascript-api", + "export": "collect__javascript_api", + "input_formats": [ + "api-extractor-json" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "item" + ] + }, + { + "glob": "**/etc/*.api.md", + "input": "files", + "name": "accepted", + "text": true, + "text_max": 4194304 + }, + { + "glob": "common/reviews/api/*.api.md", + "input": "files", + "name": "reviews", + "text": true, + "text_max": 4194304 + } + ], + "install": "npm install --save-dev @microsoft/api-extractor typescript", + "name": "javascript-api", + "report": ".specforge/reports/javascript-api.api.json" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_contexts.json b/crates/runtime/component/tests/declarations/javascript_api/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_edges.json b/crates/runtime/component/tests/declarations/javascript_api/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_enhancements.json b/crates/runtime/component/tests/declarations/javascript_api/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_entities.json b/crates/runtime/component/tests/declarations/javascript_api/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_feature_flags.json b/crates/runtime/component/tests/declarations/javascript_api/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_passes.json b/crates/runtime/component/tests/declarations/javascript_api/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_routes.json b/crates/runtime/component/tests/declarations/javascript_api/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_settings.json b/crates/runtime/component/tests/declarations/javascript_api/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_shared_fields.json b/crates/runtime/component/tests/declarations/javascript_api/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_surfaces.json b/crates/runtime/component/tests/declarations/javascript_api/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/describe_validation_rules.json b/crates/runtime/component/tests/declarations/javascript_api/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_api/handshake.json b/crates/runtime/component/tests/declarations/javascript_api/handshake.json new file mode 100644 index 0000000000..7b49b18b24 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_api/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@javascript/api", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.4", + "optional": false + }, + { + "name": "@javascript/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs api-extractor and records the package's public API as api_item facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_capabilities.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_capabilities.json new file mode 100644 index 0000000000..124c0df37a --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_capabilities.json @@ -0,0 +1,29 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "npx", + "--no", + "--", + "c8", + "--reporter=lcovonly", + "--reports-dir=.specforge/reports/javascript-coverage", + "npm", + "test" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "NODE_*", + "NPM_CONFIG_*", + "npm_config_*", + "CI" + ], + "name": "javascript-coverage", + "port": "process", + "why": "run the command whose report the collector 'javascript-coverage' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_checkers.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_codes.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_collectors.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_collectors.json new file mode 100644 index 0000000000..9aa5fa609b --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_collectors.json @@ -0,0 +1,32 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "coverage" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "package.json" + ] + }, + "capability": "javascript-coverage", + "export": "collect__javascript_coverage", + "input_formats": [ + "lcov" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "item" + ] + } + ], + "install": "npm install --save-dev c8", + "name": "javascript-coverage", + "report": ".specforge/reports/javascript-coverage/lcov.info" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_contexts.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_edges.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_enhancements.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_entities.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_feature_flags.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_passes.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_routes.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_settings.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_shared_fields.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_surfaces.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/describe_validation_rules.json b/crates/runtime/component/tests/declarations/javascript_coverage/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_coverage/handshake.json b/crates/runtime/component/tests/declarations/javascript_coverage/handshake.json new file mode 100644 index 0000000000..b6d8e9ba17 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_coverage/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@javascript/coverage", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.2", + "optional": false + }, + { + "name": "@javascript/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs c8 around npm test and records its LCOV coverage as coverage facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_capabilities.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_capabilities.json new file mode 100644 index 0000000000..298b77ce21 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_capabilities.json @@ -0,0 +1,60 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "npx", + "--no", + "--", + "cyclonedx-npm", + "--output-format", + "JSON", + "--spec-version", + "1.6", + "--package-lock-only", + "--output-file", + "{report}" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "NODE_*", + "NPM_CONFIG_*", + "npm_config_*", + "CI" + ], + "name": "javascript-sbom", + "port": "process", + "why": "run the command whose report the collector 'javascript-sbom' reads" + }, + { + "argv": [ + "osv-scanner", + "scan", + "source", + "--lockfile", + "package-lock.json", + "--format", + "json", + "--output-file", + "{report}" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "HTTPS_PROXY", + "HTTP_PROXY", + "NO_PROXY", + "https_proxy", + "http_proxy", + "no_proxy", + "OSV_*" + ], + "name": "javascript-osv", + "port": "process", + "why": "run the command whose report the collector 'javascript-osv' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_checkers.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_codes.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_collectors.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_collectors.json new file mode 100644 index 0000000000..02895ddd78 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_collectors.json @@ -0,0 +1,59 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "dependency" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "package-lock.json" + ] + }, + "capability": "javascript-sbom", + "export": "collect__javascript_sbom", + "input_formats": [ + "cyclonedx-json" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "package" + ] + } + ], + "install": "npm install --save-dev @cyclonedx/cyclonedx-npm", + "name": "javascript-sbom", + "report": ".specforge/reports/javascript-sbom.cdx.json" + }, + { + "answers": [ + "vulnerability" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "package-lock.json" + ] + }, + "capability": "javascript-osv", + "export": "collect__javascript_osv", + "input_formats": [ + "osv-json" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "package" + ] + } + ], + "install": "go install github.com/google/osv-scanner/v2/cmd/osv-scanner@latest (or: brew install osv-scanner)", + "name": "javascript-osv", + "report": ".specforge/reports/javascript-osv.json" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_contexts.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_edges.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_enhancements.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_entities.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_feature_flags.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_passes.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_routes.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_settings.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_shared_fields.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_surfaces.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/describe_validation_rules.json b/crates/runtime/component/tests/declarations/javascript_deps/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_deps/handshake.json b/crates/runtime/component/tests/declarations/javascript_deps/handshake.json new file mode 100644 index 0000000000..edbe6f0fe0 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_deps/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@javascript/deps", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.2", + "optional": false + }, + { + "name": "@javascript/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs cyclonedx-npm and osv-scanner and records dependencies and vulnerabilities as facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_capabilities.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_capabilities.json new file mode 100644 index 0000000000..4aaf1b02e3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_capabilities.json @@ -0,0 +1,32 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "node", + "--env-file={config}", + "node_modules/jest/bin/jest.js", + "--reporters=default", + "--reporters=jest-junit" + ], + "call_kinds": [ + "collect" + ], + "config": { + "name": "jest-junit.env.toml", + "template": "JEST_JUNIT_OUTPUT_FILE = \"{report}\"\nJEST_JUNIT_ADD_FILE_ATTRIBUTE = \"true\"\nJEST_JUNIT_ANCESTOR_SEPARATOR = \" > \"\nJEST_JUNIT_SUITE_NAME = \"{filepath}\"\nJEST_JUNIT_CLASSNAME = \"{classname}\"\nJEST_JUNIT_TITLE = \"{title}\"\n" + }, + "env": [ + "NODE_*", + "CI" + ], + "filter": [ + "-t", + "{filter}" + ], + "name": "javascript-jest", + "port": "process", + "why": "run the command whose report the collector 'javascript-jest' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_checkers.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_codes.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_collectors.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_collectors.json new file mode 100644 index 0000000000..2674150061 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_collectors.json @@ -0,0 +1,33 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "test", + "test_run" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "jest.config.*" + ] + }, + "capability": "javascript-jest", + "export": "collect__javascript_jest", + "input_formats": [ + "junit-xml" + ], + "inputs": [ + { + "glob": "**/package.json", + "input": "files", + "name": "packages", + "text": true + } + ], + "install": "npm install --save-dev jest jest-junit", + "name": "javascript-jest", + "report": ".specforge/reports/javascript-jest.xml" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_contexts.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_edges.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_enhancements.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_entities.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_feature_flags.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_passes.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_routes.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_settings.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_shared_fields.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_surfaces.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/describe_validation_rules.json b/crates/runtime/component/tests/declarations/javascript_jest/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_jest/handshake.json b/crates/runtime/component/tests/declarations/javascript_jest/handshake.json new file mode 100644 index 0000000000..5b9aec681c --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_jest/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@javascript/jest", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.2", + "optional": false + }, + { + "name": "@javascript/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs jest with jest-junit and records its tests as test facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_capabilities.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_capabilities.json new file mode 100644 index 0000000000..602c4f72e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_capabilities.json @@ -0,0 +1,29 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "npx", + "--no", + "--", + "eslint", + "--format", + "@microsoft/eslint-formatter-sarif", + "--output-file", + "{report}", + "." + ], + "call_kinds": [ + "collect" + ], + "env": [ + "NODE_*", + "ESLINT_*", + "CI" + ], + "name": "javascript-lint", + "port": "process", + "why": "run the command whose report the collector 'javascript-lint' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_checkers.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_codes.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_collectors.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_collectors.json new file mode 100644 index 0000000000..16166d413e --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_collectors.json @@ -0,0 +1,33 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "static_finding" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "eslint.config.*" + ] + }, + "capability": "javascript-lint", + "export": "collect__javascript_lint", + "input_formats": [ + "sarif" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "item", + "package" + ] + } + ], + "install": "npm install --save-dev eslint @microsoft/eslint-formatter-sarif", + "name": "javascript-lint", + "report": ".specforge/reports/javascript-lint.sarif" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_contexts.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_edges.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_enhancements.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_entities.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_feature_flags.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_passes.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_routes.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_settings.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_shared_fields.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_surfaces.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/describe_validation_rules.json b/crates/runtime/component/tests/declarations/javascript_lint/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_lint/handshake.json b/crates/runtime/component/tests/declarations/javascript_lint/handshake.json new file mode 100644 index 0000000000..81082446c6 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_lint/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@javascript/lint", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.2", + "optional": false + }, + { + "name": "@javascript/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs ESLint with its SARIF formatter and records its findings as static_finding facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_capabilities.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_capabilities.json new file mode 100644 index 0000000000..86bf7a9e07 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_capabilities.json @@ -0,0 +1,31 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "npx", + "--no", + "--", + "playwright", + "test", + "--reporter=junit", + "--output=.specforge/reports/javascript-playwright-results" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "NODE_*", + "PLAYWRIGHT_BROWSERS_PATH", + "CI" + ], + "filter": [ + "--grep", + "{filter}" + ], + "name": "javascript-playwright", + "port": "process", + "why": "run the command whose report the collector 'javascript-playwright' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_checkers.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_codes.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_collectors.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_collectors.json new file mode 100644 index 0000000000..4cded500ce --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_collectors.json @@ -0,0 +1,34 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "test", + "test_run" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "playwright.config.*" + ] + }, + "capability": "javascript-playwright", + "capture": "stdout", + "export": "collect__javascript_playwright", + "input_formats": [ + "junit-xml" + ], + "inputs": [ + { + "glob": "**/package.json", + "input": "files", + "name": "packages", + "text": true + } + ], + "install": "npm install --save-dev @playwright/test", + "name": "javascript-playwright", + "report": ".specforge/reports/javascript-playwright" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_contexts.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_edges.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_enhancements.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_entities.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_feature_flags.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_passes.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_routes.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_settings.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_shared_fields.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_surfaces.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/describe_validation_rules.json b/crates/runtime/component/tests/declarations/javascript_playwright/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_playwright/handshake.json b/crates/runtime/component/tests/declarations/javascript_playwright/handshake.json new file mode 100644 index 0000000000..5fec38b7cd --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_playwright/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@javascript/playwright", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.2", + "optional": false + }, + { + "name": "@javascript/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs Playwright and records its tests as test facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_capabilities.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_capabilities.json new file mode 100644 index 0000000000..9f5c941bb1 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_capabilities.json @@ -0,0 +1,32 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "npx", + "--no", + "--", + "vitest", + "run", + "--reporter=default", + "--reporter=junit", + "--outputFile.junit={report}" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "NODE_*", + "VITEST_*", + "CI" + ], + "filter": [ + "-t", + "{filter}" + ], + "name": "javascript-vitest", + "port": "process", + "why": "run the command whose report the collector 'javascript-vitest' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_checkers.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_codes.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_collectors.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_collectors.json new file mode 100644 index 0000000000..c4f94d4037 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_collectors.json @@ -0,0 +1,34 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "test", + "test_run" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "vitest.config.*", + "vitest.workspace.*" + ] + }, + "capability": "javascript-vitest", + "export": "collect__javascript_vitest", + "input_formats": [ + "junit-xml" + ], + "inputs": [ + { + "glob": "**/package.json", + "input": "files", + "name": "packages", + "text": true + } + ], + "install": "npm install --save-dev vitest", + "name": "javascript-vitest", + "report": ".specforge/reports/javascript-vitest.xml" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_contexts.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_edges.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_enhancements.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_entities.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_feature_flags.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_passes.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_routes.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_settings.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_shared_fields.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_surfaces.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/describe_validation_rules.json b/crates/runtime/component/tests/declarations/javascript_vitest/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/javascript_vitest/handshake.json b/crates/runtime/component/tests/declarations/javascript_vitest/handshake.json new file mode 100644 index 0000000000..50fa0544c1 --- /dev/null +++ b/crates/runtime/component/tests/declarations/javascript_vitest/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@javascript/vitest", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.2", + "optional": false + }, + { + "name": "@javascript/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs vitest and records its tests as test facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_capabilities.json b/crates/runtime/component/tests/declarations/rust_api/describe_capabilities.json new file mode 100644 index 0000000000..2151cf59ac --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_capabilities.json @@ -0,0 +1,32 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "cargo-public-api", + "--color", + "never", + "-ss" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "RUSTDOCFLAGS", + "RUST_LOG" + ], + "filter": [ + "--package", + "{filter}" + ], + "name": "rust-api", + "port": "process", + "why": "run the command whose report the collector 'rust-api' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_checkers.json b/crates/runtime/component/tests/declarations/rust_api/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_codes.json b/crates/runtime/component/tests/declarations/rust_api/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_collectors.json b/crates/runtime/component/tests/declarations/rust_api/describe_collectors.json new file mode 100644 index 0000000000..26955d557b --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_collectors.json @@ -0,0 +1,41 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "api_item" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "Cargo.toml" + ] + }, + "capability": "rust-api", + "capture": "stdout", + "export": "collect__rust_api", + "input_formats": [ + "public-api-text" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "item", + "package" + ] + }, + { + "glob": "**/public-api.txt", + "input": "files", + "name": "accepted", + "text": true, + "text_max": 4194304 + } + ], + "install": "cargo install cargo-public-api --locked (and: rustup toolchain install nightly --profile minimal)", + "name": "rust-api", + "report": ".specforge/reports/rust-api" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_contexts.json b/crates/runtime/component/tests/declarations/rust_api/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_edges.json b/crates/runtime/component/tests/declarations/rust_api/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_enhancements.json b/crates/runtime/component/tests/declarations/rust_api/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_entities.json b/crates/runtime/component/tests/declarations/rust_api/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_feature_flags.json b/crates/runtime/component/tests/declarations/rust_api/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_passes.json b/crates/runtime/component/tests/declarations/rust_api/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_routes.json b/crates/runtime/component/tests/declarations/rust_api/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_settings.json b/crates/runtime/component/tests/declarations/rust_api/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_shared_fields.json b/crates/runtime/component/tests/declarations/rust_api/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_surfaces.json b/crates/runtime/component/tests/declarations/rust_api/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/describe_validation_rules.json b/crates/runtime/component/tests/declarations/rust_api/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_api/handshake.json b/crates/runtime/component/tests/declarations/rust_api/handshake.json new file mode 100644 index 0000000000..6dcad0a6d9 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_api/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@rust/api", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.4", + "optional": false + }, + { + "name": "@rust/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs cargo public-api and records the crate's public API as api_item facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_cargo/describe_settings.json b/crates/runtime/component/tests/declarations/rust_cargo/describe_settings.json index 25d73ebee3..f2031fa58c 100644 --- a/crates/runtime/component/tests/declarations/rust_cargo/describe_settings.json +++ b/crates/runtime/component/tests/declarations/rust_cargo/describe_settings.json @@ -1,4 +1,12 @@ { "category": "settings", - "items": [] + "items": [ + { + "default": [], + "description": "Project-relative directories whose manifests are no packages of this project (a fixture's or an example's crate): @rust/cargo answers no package for a manifest in or under one, so @rust/source reads no item there; the tool-running packs still run over the whole cargo workspace", + "field_type": "string_list", + "kind": "setting", + "name": "exclude" + } + ] } \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_capabilities.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_capabilities.json new file mode 100644 index 0000000000..6553faa138 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_capabilities.json @@ -0,0 +1,32 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "cargo-llvm-cov", + "llvm-cov", + "nextest", + "--workspace", + "--ignore-run-fail", + "--lcov", + "--output-path", + "{report}" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "RUSTDOCFLAGS", + "LLVM_*" + ], + "name": "rust-coverage", + "port": "process", + "why": "run the command whose report the collector 'rust-coverage' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_checkers.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_codes.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_collectors.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_collectors.json new file mode 100644 index 0000000000..600a2d5cc9 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_collectors.json @@ -0,0 +1,35 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "coverage" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "Cargo.toml" + ] + }, + "capability": "rust-coverage", + "export": "collect__rust_coverage", + "input_formats": [ + "lcov" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "item" + ] + } + ], + "install": "cargo install cargo-llvm-cov cargo-nextest --locked", + "name": "rust-coverage", + "report": ".specforge/reports/rust-coverage.lcov", + "requires": [ + "cargo-nextest" + ] + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_contexts.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_edges.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_enhancements.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_entities.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_feature_flags.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_passes.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_routes.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_settings.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_shared_fields.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_surfaces.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/describe_validation_rules.json b/crates/runtime/component/tests/declarations/rust_coverage/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_coverage/handshake.json b/crates/runtime/component/tests/declarations/rust_coverage/handshake.json new file mode 100644 index 0000000000..22a39f0c62 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_coverage/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@rust/coverage", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.2", + "optional": false + }, + { + "name": "@rust/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs cargo llvm-cov and records its LCOV coverage as coverage facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_capabilities.json b/crates/runtime/component/tests/declarations/rust_deps/describe_capabilities.json new file mode 100644 index 0000000000..d5895c338a --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_capabilities.json @@ -0,0 +1,59 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "cargo-cyclonedx", + "cyclonedx", + "--format", + "json", + "--spec-version", + "1.5", + "--all-features", + "--override-filename", + "rust-sbom.cdx" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "SOURCE_DATE_EPOCH" + ], + "name": "rust-sbom", + "port": "process", + "why": "run the command whose report the collector 'rust-sbom' reads" + }, + { + "argv": [ + "osv-scanner", + "scan", + "source", + "--lockfile", + "Cargo.lock", + "--format", + "json", + "--output-file", + "{report}" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "HTTPS_PROXY", + "HTTP_PROXY", + "NO_PROXY", + "https_proxy", + "http_proxy", + "no_proxy", + "OSV_*" + ], + "name": "rust-osv", + "port": "process", + "why": "run the command whose report the collector 'rust-osv' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_checkers.json b/crates/runtime/component/tests/declarations/rust_deps/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_codes.json b/crates/runtime/component/tests/declarations/rust_deps/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_collectors.json b/crates/runtime/component/tests/declarations/rust_deps/describe_collectors.json new file mode 100644 index 0000000000..75b5b50f9d --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_collectors.json @@ -0,0 +1,59 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "dependency" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "Cargo.toml" + ] + }, + "capability": "rust-sbom", + "export": "collect__rust_sbom", + "input_formats": [ + "cyclonedx-json" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "package" + ] + } + ], + "install": "cargo install cargo-cyclonedx --locked", + "name": "rust-sbom", + "report": "**/rust-sbom.cdx.json" + }, + { + "answers": [ + "vulnerability" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "Cargo.lock" + ] + }, + "capability": "rust-osv", + "export": "collect__rust_osv", + "input_formats": [ + "osv-json" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "package" + ] + } + ], + "install": "go install github.com/google/osv-scanner/v2/cmd/osv-scanner@latest (or: brew install osv-scanner)", + "name": "rust-osv", + "report": ".specforge/reports/rust-osv.json" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_contexts.json b/crates/runtime/component/tests/declarations/rust_deps/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_edges.json b/crates/runtime/component/tests/declarations/rust_deps/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_enhancements.json b/crates/runtime/component/tests/declarations/rust_deps/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_entities.json b/crates/runtime/component/tests/declarations/rust_deps/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_feature_flags.json b/crates/runtime/component/tests/declarations/rust_deps/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_passes.json b/crates/runtime/component/tests/declarations/rust_deps/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_routes.json b/crates/runtime/component/tests/declarations/rust_deps/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_settings.json b/crates/runtime/component/tests/declarations/rust_deps/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_shared_fields.json b/crates/runtime/component/tests/declarations/rust_deps/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_surfaces.json b/crates/runtime/component/tests/declarations/rust_deps/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/describe_validation_rules.json b/crates/runtime/component/tests/declarations/rust_deps/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_deps/handshake.json b/crates/runtime/component/tests/declarations/rust_deps/handshake.json new file mode 100644 index 0000000000..54cc8d5d05 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_deps/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@rust/deps", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.2", + "optional": false + }, + { + "name": "@rust/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs cargo-cyclonedx and osv-scanner and records dependencies and vulnerabilities as facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_capabilities.json b/crates/runtime/component/tests/declarations/rust_lint/describe_capabilities.json new file mode 100644 index 0000000000..5882bcf8a9 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_capabilities.json @@ -0,0 +1,29 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "cargo-clippy", + "clippy", + "--workspace", + "--all-targets", + "--message-format=json" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "RUSTDOCFLAGS", + "CLIPPY_*" + ], + "name": "rust-lint", + "port": "process", + "why": "run the command whose report the collector 'rust-lint' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_checkers.json b/crates/runtime/component/tests/declarations/rust_lint/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_codes.json b/crates/runtime/component/tests/declarations/rust_lint/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_collectors.json b/crates/runtime/component/tests/declarations/rust_lint/describe_collectors.json new file mode 100644 index 0000000000..430fce273b --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_collectors.json @@ -0,0 +1,34 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "static_finding" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "Cargo.toml" + ] + }, + "capability": "rust-lint", + "capture": "stdout", + "export": "collect__rust_lint", + "input_formats": [ + "cargo-json" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "item", + "package" + ] + } + ], + "install": "rustup component add clippy", + "name": "rust-lint", + "report": ".specforge/reports/rust-lint" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_contexts.json b/crates/runtime/component/tests/declarations/rust_lint/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_edges.json b/crates/runtime/component/tests/declarations/rust_lint/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_enhancements.json b/crates/runtime/component/tests/declarations/rust_lint/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_entities.json b/crates/runtime/component/tests/declarations/rust_lint/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_feature_flags.json b/crates/runtime/component/tests/declarations/rust_lint/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_passes.json b/crates/runtime/component/tests/declarations/rust_lint/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_routes.json b/crates/runtime/component/tests/declarations/rust_lint/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_settings.json b/crates/runtime/component/tests/declarations/rust_lint/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_shared_fields.json b/crates/runtime/component/tests/declarations/rust_lint/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_surfaces.json b/crates/runtime/component/tests/declarations/rust_lint/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/describe_validation_rules.json b/crates/runtime/component/tests/declarations/rust_lint/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_lint/handshake.json b/crates/runtime/component/tests/declarations/rust_lint/handshake.json new file mode 100644 index 0000000000..0d4f64c853 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_lint/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@rust/lint", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.2", + "optional": false + }, + { + "name": "@rust/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs cargo clippy and records its diagnostics as static_finding facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_capabilities.json b/crates/runtime/component/tests/declarations/rust_proof/describe_capabilities.json new file mode 100644 index 0000000000..52c0e8e0f1 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_capabilities.json @@ -0,0 +1,31 @@ +{ + "category": "capabilities", + "items": [ + { + "argv": [ + "cargo-kani", + "--workspace", + "--output-format", + "regular" + ], + "call_kinds": [ + "collect" + ], + "env": [ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "KANI_*" + ], + "filter": [ + "--harness", + "{filter}" + ], + "name": "rust-proof", + "port": "process", + "why": "run the command whose report the collector 'rust-proof' reads" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_checkers.json b/crates/runtime/component/tests/declarations/rust_proof/describe_checkers.json new file mode 100644 index 0000000000..2c0d93db04 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_checkers.json @@ -0,0 +1,4 @@ +{ + "category": "checkers", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_codes.json b/crates/runtime/component/tests/declarations/rust_proof/describe_codes.json new file mode 100644 index 0000000000..476fe856cc --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_codes.json @@ -0,0 +1,4 @@ +{ + "category": "codes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_collectors.json b/crates/runtime/component/tests/declarations/rust_proof/describe_collectors.json new file mode 100644 index 0000000000..0610576a55 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_collectors.json @@ -0,0 +1,35 @@ +{ + "category": "collectors", + "items": [ + { + "answers": [ + "test", + "test_run" + ], + "auto_detect": { + "env_vars": [], + "file_patterns": [ + "Cargo.toml" + ] + }, + "capability": "rust-proof", + "capture": "stdout", + "export": "collect__rust_proof", + "input_formats": [ + "kani-regular" + ], + "inputs": [ + { + "input": "facts", + "kinds": [ + "item", + "package" + ] + } + ], + "install": "cargo install --locked kani-verifier && cargo kani setup", + "name": "rust-proof", + "report": ".specforge/reports/rust-proof" + } + ] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_contexts.json b/crates/runtime/component/tests/declarations/rust_proof/describe_contexts.json new file mode 100644 index 0000000000..afd6be3149 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_contexts.json @@ -0,0 +1,4 @@ +{ + "category": "contexts", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_edges.json b/crates/runtime/component/tests/declarations/rust_proof/describe_edges.json new file mode 100644 index 0000000000..bb4c7452e4 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_edges.json @@ -0,0 +1,4 @@ +{ + "category": "edges", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_enhancements.json b/crates/runtime/component/tests/declarations/rust_proof/describe_enhancements.json new file mode 100644 index 0000000000..e79b88a896 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_enhancements.json @@ -0,0 +1,4 @@ +{ + "category": "enhancements", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_entities.json b/crates/runtime/component/tests/declarations/rust_proof/describe_entities.json new file mode 100644 index 0000000000..ade72d8d90 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_entities.json @@ -0,0 +1,4 @@ +{ + "category": "entities", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_feature_flags.json b/crates/runtime/component/tests/declarations/rust_proof/describe_feature_flags.json new file mode 100644 index 0000000000..355b7dc9d2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_feature_flags.json @@ -0,0 +1,4 @@ +{ + "category": "feature_flags", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_passes.json b/crates/runtime/component/tests/declarations/rust_proof/describe_passes.json new file mode 100644 index 0000000000..c5e67bce72 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_passes.json @@ -0,0 +1,4 @@ +{ + "category": "passes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_routes.json b/crates/runtime/component/tests/declarations/rust_proof/describe_routes.json new file mode 100644 index 0000000000..425fbe7ef2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_routes.json @@ -0,0 +1,4 @@ +{ + "category": "routes", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_settings.json b/crates/runtime/component/tests/declarations/rust_proof/describe_settings.json new file mode 100644 index 0000000000..25d73ebee3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_settings.json @@ -0,0 +1,4 @@ +{ + "category": "settings", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_shared_fields.json b/crates/runtime/component/tests/declarations/rust_proof/describe_shared_fields.json new file mode 100644 index 0000000000..6677481472 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_shared_fields.json @@ -0,0 +1,4 @@ +{ + "category": "shared_fields", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_surfaces.json b/crates/runtime/component/tests/declarations/rust_proof/describe_surfaces.json new file mode 100644 index 0000000000..11f01236f3 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_surfaces.json @@ -0,0 +1,4 @@ +{ + "category": "surfaces", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/describe_validation_rules.json b/crates/runtime/component/tests/declarations/rust_proof/describe_validation_rules.json new file mode 100644 index 0000000000..00357eaaf2 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/describe_validation_rules.json @@ -0,0 +1,4 @@ +{ + "category": "validation_rules", + "items": [] +} \ No newline at end of file diff --git a/crates/runtime/component/tests/declarations/rust_proof/handshake.json b/crates/runtime/component/tests/declarations/rust_proof/handshake.json new file mode 100644 index 0000000000..7c5a6e7a89 --- /dev/null +++ b/crates/runtime/component/tests/declarations/rust_proof/handshake.json @@ -0,0 +1,19 @@ +{ + "protocol_version": "2.3.0", + "name": "@rust/proof", + "version": "1.0.0", + "peer_dependencies": [ + { + "name": "@code/core", + "version": "^1.2", + "optional": false + }, + { + "name": "@rust/source", + "version": "^1.0", + "optional": false + } + ], + "sandbox_policy": null, + "description": "Runs Kani and records each proof harness as test facts (@code/core)" +} \ No newline at end of file diff --git a/crates/runtime/component/tests/families.rs b/crates/runtime/component/tests/families.rs index 631b1a3d15..cc3cba64ed 100644 --- a/crates/runtime/component/tests/families.rs +++ b/crates/runtime/component/tests/families.rs @@ -54,12 +54,24 @@ fn the_two_sets_are_adr_0369s_and_every_builtin_is_in_one() { "@rust/test", "@javascript/source", "@javascript/node-test", + "@rust/coverage", + "@rust/lint", + "@rust/deps", + "@rust/api", + "@rust/proof", + "@javascript/coverage", + "@javascript/lint", + "@javascript/deps", + "@javascript/api", + "@javascript/vitest", + "@javascript/jest", + "@javascript/playwright", ]), "both sets" ); assert_eq!( names(&gsd.difference(&old).copied().collect()), - ["@gsd/core"], + ["@gsd/core", "@gsd/import"], "the gsd set only" ); @@ -114,6 +126,57 @@ fn each_set_builds_one_registry_with_no_e026_and_no_missing_peer() { } } +/// The legacy `@specforge/vitest` and `@javascript/vitest`, each with the peers it requires +/// (`@specforge/testing`; `@code/core` and `@javascript/source`), build one registry with no E026 and no +/// missing peer, and each keeps its own collector (owner decision D4: the old pack stays in the old set, +/// so a project may load both while it moves). +#[test] +fn the_old_vitest_loads_beside_javascript_vitest() { + let names = [ + "@specforge/testing", + "@code/core", + "@javascript/source", + "@specforge/vitest", + "@javascript/vitest", + ]; + for name in names { + assert!( + BUILTINS.iter().any(|builtin| builtin.name == name), + "'{name}' is a BUILTINS row" + ); + } + let declarations: Vec<_> = pinned_builtin_declarations() + .unwrap() + .into_iter() + .filter(|declaration| names.contains(&declaration.name())) + .collect(); + assert_eq!(declarations.len(), names.len()); + let collectors: BTreeSet<(String, String)> = declarations + .iter() + .flat_map(|declaration| { + declaration + .collectors + .iter() + .map(|collector| (declaration.name().to_string(), collector.name.clone())) + }) + .collect(); + for (owner, collector) in [ + ("@specforge/vitest", "vitest"), + ("@javascript/vitest", "javascript-vitest"), + ] { + assert!( + collectors.contains(&(owner.to_string(), collector.to_string())), + "{owner} declares the collector '{collector}': {collectors:?}" + ); + } + + let build = build_registries(declarations); + for code in ["E026", "E027"] { + let found: Vec<_> = build.diagnostics().filter(|d| d.code == code).collect(); + assert!(found.is_empty(), "{code}: {found:?}"); + } +} + /// The kinds `@gsd/core` declares, as a declaration named `@gsd/core` with nothing else in it. They are /// read from `gsd/core/tests/golden/kinds.json`, which the gsd suite's own golden test keeps equal to /// the extension's declaration, so this follows every later change to those kinds with no edit here. diff --git a/crates/runtime/extension-sdk/src/builders.rs b/crates/runtime/extension-sdk/src/builders.rs index 866b2b06c0..0f12c1da86 100644 --- a/crates/runtime/extension-sdk/src/builders.rs +++ b/crates/runtime/extension-sdk/src/builders.rs @@ -439,6 +439,13 @@ impl CodeBuilder { self.0.settled_later = true; self } + /// The collected fact kinds this code judges (the kinds whose facts its passes read to raise it), so a host can + /// say which codes cannot be judged when no collector answers them (`specforge doctor`, ADR 0389). Leave it out + /// for a code about authored entities. + pub fn facts(&mut self, kinds: &[&str]) -> &mut Self { + self.0.facts = kinds.iter().map(|kind| kind.to_string()).collect(); + self + } } /// Builder for [`ValidationRuleDescriptor`], with a `custom` rule's @@ -659,6 +666,7 @@ impl CollectorBuilder { inputs: Vec::new(), answers: Vec::new(), install: None, + requires: Vec::new(), }, collect: None, run: None, @@ -745,11 +753,16 @@ impl CollectorBuilder { self.env = names.iter().map(|n| n.to_string()).collect(); self } - /// What to run to install the command's program, said when it is not found on PATH (ADR 0348 D4). + /// What to run to install the command's programs, said when one is not found on PATH (ADR 0348 D4). pub fn install(&mut self, line: &str) -> &mut Self { self.descriptor.install = Some(line.to_string()); self } + /// The other programs the command runs beside its first, which `specforge doctor` looks up (ADR 0389 D3). + pub fn requires(&mut self, programs: &[&str]) -> &mut Self { + self.descriptor.requires = programs.iter().map(ToString::to_string).collect(); + self + } /// The `process` capability (one the extension declares with /// [`ContributionsBuilder::capability`](crate::ContributionsBuilder::capability)) whose command the host runs. pub fn capability(&mut self, name: &str) -> &mut Self { @@ -757,9 +770,16 @@ impl CollectorBuilder { self.descriptor.capability = Some(name.to_string()); self } - /// Report file or directory the runner writes, relative to the project - /// root. A directory is read as every `*.json` file directly inside it. + /// The report the runner writes, relative to the project root: a file, a directory (read as every `*.json` file + /// directly inside it), or a glob over project files the tool writes itself (`**/name.json`), every match read + /// fresh after each run by the walk `Input::files` globs take (ADR 0389). A glob's command is told no path: it + /// takes no `{report}` and no `capture_stdout()`. Its last segment is a literal file name: a wildcard there panics. pub fn report(&mut self, path: &str) -> &mut Self { + assert!( + specforge_protocol_types::is_report_name(path), + "collector '{}' declares the report '{path}': a report glob must end in a literal file name", + self.descriptor.name + ); self.descriptor.report = Some(path.to_string()); self } diff --git a/crates/runtime/extension-sdk/src/lib.rs b/crates/runtime/extension-sdk/src/lib.rs index 0cc4004465..e353841b76 100644 --- a/crates/runtime/extension-sdk/src/lib.rs +++ b/crates/runtime/extension-sdk/src/lib.rs @@ -38,9 +38,9 @@ pub use specforge_protocol_types::{ pub use specforge_protocol_types::{ ByteRange, CapabilityDescriptor, CheckFinding, CheckItem, CheckOutcome, CheckPhase, CheckPlan, - CheckRef, CheckStatus, CheckValuesInput, CheckerDescriptor, FILE_READ_MAX, FsAccess, GitOp, - HttpMethod, MAX_PROBE_ROUNDS, Operation, OutcomeClass, OutcomeData, PlannedItem, PortScope, - Probe, ProbeOutcome, StatEntry, ValueForm, + CheckRef, CheckStatus, CheckValuesInput, CheckerDescriptor, FILE_READ_MAX, FsAccess, + GLOB_VISITS_MAX, GitOp, HttpMethod, MAX_PROBE_ROUNDS, Operation, OutcomeClass, OutcomeData, + PlannedItem, PortScope, Probe, ProbeOutcome, StatEntry, TEXT_MAX_CEILING_BYTES, ValueForm, }; pub use specforge_protocol_types::{ @@ -655,7 +655,7 @@ pub mod prelude { pub use crate::{ CollectEntityResult, CollectInput, CollectOutput, CollectReportFile, CollectUnlinkedTest, CollectorBuilder, DanglingReason, DanglingReference, FILE_READ_MAX, Fact, FactLocation, - PlanBuilder, + GLOB_VISITS_MAX, PlanBuilder, TEXT_MAX_CEILING_BYTES, }; pub use crate::{DeltaAspect, DeltaBase, DeltaChange, DeltaEdge, DeltaNode, DeltaPayload}; pub use specforge_extension_sdk_macros::extension; diff --git a/crates/runtime/extension-sdk/src/reads.rs b/crates/runtime/extension-sdk/src/reads.rs index 764360b053..b1f46d16f2 100644 --- a/crates/runtime/extension-sdk/src/reads.rs +++ b/crates/runtime/extension-sdk/src/reads.rs @@ -44,6 +44,14 @@ impl FileReadSpec { self.0.text = true; self } + + /// Send each file's text up to `bytes` (at most 4 MiB) instead of 64 KiB, as well as its facts; the read's text + /// budget is the larger of 1 MiB and four times `bytes` (protocol 2.3.0). + pub fn text_up_to(mut self, bytes: u32) -> Self { + self.0.text = true; + self.0.text_max = Some(bytes); + self + } } impl From for FileRead { diff --git a/crates/runtime/extension-sdk/src/surface.rs b/crates/runtime/extension-sdk/src/surface.rs index b63b97deb9..0ecf6baa8c 100644 --- a/crates/runtime/extension-sdk/src/surface.rs +++ b/crates/runtime/extension-sdk/src/surface.rs @@ -412,6 +412,15 @@ impl CommandBuilder { self.writes() } + /// The command imports what was recorded outside the spec (a legacy project's history), so the host judges its + /// plan for host errors only: an error lands, and `check` reports it, only when its code is in the reporting + /// extension's own namespace and own catalog and declares no `facts`; a host or `@specforge/*` code (E016), a + /// fact-judging one (`code/E101`) and an uncatalogued one still refuse (ADR 0392). It `writes`. + pub fn imports(&mut self) -> &mut Self { + self.descriptor.imports = true; + self.writes() + } + /// The command answers an edit plan ([`CommandOutput::with_plan`]) the host applies (ADR 0289). It receives /// the `revisions` of the project's sources, and the host gives it `--dry-run`, so no arg may take that name. pub fn writes(&mut self) -> &mut Self { diff --git a/crates/runtime/extension-sdk/tests/declaration.rs b/crates/runtime/extension-sdk/tests/declaration.rs index 03a24630dc..a11b561c5c 100644 --- a/crates/runtime/extension-sdk/tests/declaration.rs +++ b/crates/runtime/extension-sdk/tests/declaration.rs @@ -344,6 +344,22 @@ fn a_code_entry_may_be_settled_later() { assert!(!declared.codes[1].settled_later); } +#[specforge_test_macros::test(requirement = "FEATURE-028")] +fn a_code_entry_may_name_the_collected_kinds_it_judges() { + let mut b = ContributionsBuilder::new(ExtensionMeta::new("@acme/reports", "0.1.0")); + b.code("W104", |d| { + d.title("Report entry on no item") + .explanation("Serve the item.") + .facts(&["coverage", "api_item"]); + }); + b.code("W105", |d| { + d.title("Plain").explanation("About authored entities."); + }); + let declared = b.declaration(); + assert_eq!(declared.codes[0].facts, ["coverage", "api_item"]); + assert!(declared.codes[1].facts.is_empty()); +} + #[specforge_test_macros::test(requirement = "FEATURE-028")] fn settings_presets_secrets_and_flags_are_declared() { let mut b = ContributionsBuilder::new(ExtensionMeta::new("@acme/gsd", "0.1.0")); diff --git a/crates/runtime/extension-sdk/tests/golden.rs b/crates/runtime/extension-sdk/tests/golden.rs index 3a29ec483c..c56551b193 100644 --- a/crates/runtime/extension-sdk/tests/golden.rs +++ b/crates/runtime/extension-sdk/tests/golden.rs @@ -158,8 +158,9 @@ fn mock_host_pins_wire_output() { /// No builtin of the old set contributes to a host (ADR 0292): its pinned `surfaces` holds none of the four /// kinds, and a guest that declares none is byte-equal to what it was before they existed. `@gsd/core` -/// (`gsd_core`) contributes agents, skills, slash commands and hooks by design (ADR 0373 D7), so its -/// directory is not read. +/// (`gsd_core`) contributes agents, skills, slash commands and hooks by design (ADR 0373 D7), and +/// `@gsd/import` (`gsd_import`) declares its command's file inputs (ADR 0391), so their directories, +/// the gsd set's own, are not read. #[specforge_test_macros::test(requirement = "FEATURE-013")] fn the_builtins_declare_no_host_contribution() { let root = specforge_repo_root::repo_root().join("crates/runtime/component/tests/declarations"); @@ -167,7 +168,10 @@ fn the_builtins_declare_no_host_contribution() { for dir in std::fs::read_dir(&root).unwrap() { let dir = dir.unwrap().path(); // The old set and the pinned examples only (ADR 0373 D7). - if dir.file_name().is_some_and(|name| name == "gsd_core") { + if dir + .file_name() + .is_some_and(|name| name == "gsd_core" || name == "gsd_import") + { continue; } let surfaces = dir.join("describe_surfaces.json"); diff --git a/crates/runtime/extension-sdk/tests/operations.rs b/crates/runtime/extension-sdk/tests/operations.rs index 459ccbe442..fee9312019 100644 --- a/crates/runtime/extension-sdk/tests/operations.rs +++ b/crates/runtime/extension-sdk/tests/operations.rs @@ -53,6 +53,7 @@ fn extension() -> ContributionsBuilder { unlinked: Vec::new(), plan: None, facts: Vec::new(), + warnings: Vec::new(), }) }); }); @@ -179,6 +180,16 @@ fn a_collector_without_its_handler_is_refused() { }); } +#[test] +#[should_panic(expected = "collector 'k' declares the report '**/*.pem'")] +fn a_report_glob_ending_in_a_wildcard_is_refused() { + let mut c = ContributionsBuilder::new(ExtensionMeta::new("@acme/x", "1.0.0")); + c.collector("k", |k| { + k.report("**/*.pem") + .collect(|_| Ok(CollectOutput::default())); + }); +} + #[test] #[should_panic(expected = "custom rule 'E1' declares no handler")] fn a_custom_rule_without_its_handler_is_refused() { diff --git a/crates/runtime/extension-sdk/tests/plan.rs b/crates/runtime/extension-sdk/tests/plan.rs index 70cbee1b8f..d7fe8c4b9d 100644 --- a/crates/runtime/extension-sdk/tests/plan.rs +++ b/crates/runtime/extension-sdk/tests/plan.rs @@ -189,3 +189,25 @@ fn human_sets_writes() { let plain = serde_json::to_value(&writer().declaration().surfaces.commands[0]).unwrap(); assert!(plain.get("human").is_none()); } + +#[specforge_test(requirement = "FEATURE-131")] +fn imports_sets_writes() { + let mut b = ContributionsBuilder::new(ExtensionMeta::new("@acme/i", "1.0.0")); + b.command("import", |c| { + c.title("Import") + .description("Import what a legacy project recorded") + .imports() + .handler(|_| CommandOutput::ok("ok\n")); + }); + let declaration = b.declaration(); + let command = &declaration.surfaces.commands[0]; + assert!(command.imports && command.writes && !command.human); + let wire = serde_json::to_value(command).unwrap(); + assert_eq!( + (wire["imports"].clone(), wire["writes"].clone()), + (json!(true), json!(true)) + ); + // An ordinary command does not carry the key. + let plain = serde_json::to_value(&writer().declaration().surfaces.commands[0]).unwrap(); + assert!(plain.get("imports").is_none()); +} diff --git a/crates/runtime/wasm/tests/calls.rs b/crates/runtime/wasm/tests/calls.rs index 39fafd658f..70933ad678 100644 --- a/crates/runtime/wasm/tests/calls.rs +++ b/crates/runtime/wasm/tests/calls.rs @@ -115,6 +115,7 @@ fn collect_answer() -> CollectOutput { }], plan: None, facts: Vec::new(), + warnings: Vec::new(), } } diff --git a/crates/runtime/wasm/tests/protocol_types.rs b/crates/runtime/wasm/tests/protocol_types.rs index 7fbfbf5d75..43aec512ae 100644 --- a/crates/runtime/wasm/tests/protocol_types.rs +++ b/crates/runtime/wasm/tests/protocol_types.rs @@ -546,6 +546,7 @@ fn collector_descriptor_with_auto_detect() { inputs: vec![], answers: vec!["test".to_string()], install: None, + requires: vec![], }; let json = serde_json::to_string(&collector).unwrap(); let decoded: CollectorDescriptor = serde_json::from_str(&json).unwrap(); diff --git a/crates/session/project/src/file_reads.rs b/crates/session/project/src/file_reads.rs index b6c314d1c3..bddfc44d46 100644 --- a/crates/session/project/src/file_reads.rs +++ b/crates/session/project/src/file_reads.rs @@ -17,17 +17,18 @@ use specforge_effects::contained::{Contained, Resolved}; use specforge_effects::fs::SKIPPED; use specforge_effects::{Root, Roots}; -use specforge_protocol_types::{FILE_READ_MAX, FileFact, FileFacts, FileRead}; +use specforge_protocol_types::{ + FILE_READ_MAX, FileFact, FileFacts, FileRead, GLOB_VISITS_MAX, is_wild, +}; use specforge_registry::{Disk, DiskLookup, EntitySnapshot, paths_named, read_problem}; use crate::judged::file_digest; -/// The most text of one file a read sends. +/// The most text of one file a read sends, unless it declares `text_max`. pub const TEXT_CAP: usize = 64 * 1024; -/// The most text one read sends in all. +/// The most text one read sends in all, unless four times its per-file cap is more: at most 16 MiB, as a read whose +/// `text_max` is over [`specforge_protocol_types::TEXT_MAX_CEILING_BYTES`] is never read (`read_problem`, W021). pub const TEXT_BUDGET: usize = 1024 * 1024; -/// The most entries (files and directories) one glob visits, matched or not. -pub const MAX_VISITS: usize = 20_000; /// Where the files are read from. #[derive(Clone)] @@ -100,7 +101,7 @@ pub fn read( if read_problem(read).is_some() || files.contains_key(&read.name) { continue; } - let mut budget = TEXT_BUDGET; + let mut budget = text_cap(read).map_or(TEXT_BUDGET, |cap| TEXT_BUDGET.max(4 * cap)); let facts = match (&read.field, &read.glob) { (Some(field), _) => field_facts(read, field, entities, &ctx, &mut budget), (_, Some(glob)) => glob_facts(read, glob, &ctx, &mut budget), @@ -111,6 +112,13 @@ pub fn read( files } +/// The most text of one file `read` sends: `None` when it asks for no text. `read` passed `read_problem`, the one +/// check of `text_max` against the ceiling. +fn text_cap(read: &FileRead) -> Option { + read.text + .then(|| read.text_max.map_or(TEXT_CAP, |max| max as usize)) +} + fn field_facts( read: &FileRead, field: &str, @@ -144,13 +152,40 @@ fn field_facts( let facts = named .into_iter() .take(FILE_READ_MAX) - .map(|((entity, path), at)| fact(ctx, path, Some(entity), at.as_ref(), read.text, budget)) + .map(|((entity, path), at)| { + fact(ctx, path, Some(entity), at.as_ref(), text_cap(read), budget) + }) .collect(); FileFacts { facts, truncated } } fn glob_facts(read: &FileRead, glob: &str, ctx: &Ctx<'_>, budget: &mut usize) -> FileFacts { - let source = ctx.source; + let GlobPaths { files, truncated } = glob_paths(ctx.source, glob); + let facts = files + .into_iter() + .map(|path| { + let at = ctx.contained.resolve(&path, Root::Project).ok(); + fact(ctx, path, None, at.as_ref(), text_cap(read), budget) + }) + .collect(); + FileFacts { facts, truncated } +} + +/// The project files a glob matches: project-relative, `/` separated, sorted and unique. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct GlobPaths { + pub files: Vec, + /// The walk stopped early: past [`GLOB_VISITS_MAX`] entries, or past [`FILE_READ_MAX`] matches. + pub truncated: bool, +} + +/// The project files under `source` that `glob` matches, by the one walk every glob read takes (ADR 0293 D4): a +/// directory in [`SKIPPED`] is entered only when the glob names it, a directory reached through a link is not entered +/// (nor a literal prefix that links out of the project), and the walk stops after [`GLOB_VISITS_MAX`] entries. A file +/// collector's report glob reads through it too (ADR 0389). +pub fn glob_paths(source: &FileSource<'_>, glob: &str) -> GlobPaths { + let lookup = DiskLookup(source.disk); + let contained = Contained::new(&source.roots, &lookup); let segments: Vec<&str> = glob.split('/').filter(|s| *s != ".").collect(); let named_here: Vec<&str> = segments.iter().copied().filter(|s| !is_wild(s)).collect(); // Directories above the first wildcard are walked to directly: only the rest of the pattern decides. @@ -167,9 +202,9 @@ fn glob_facts(read: &FileRead, glob: &str, ctx: &Ctx<'_>, budget: &mut usize) -> let mut found = Found::default(); let first = source.project_root.join(&start); // A literal prefix that is itself a link out of the project is not entered. - if start.is_empty() || ctx.contained.resolve(&start, Root::Project).is_ok() { + if start.is_empty() || contained.resolve(&start, Root::Project).is_ok() { let real = source.disk.canonical(&first); - walk(ctx, &start, real.as_deref(), &plan, &mut found); + walk(source, &start, real.as_deref(), &plan, &mut found); } let Found { mut files, @@ -178,14 +213,7 @@ fn glob_facts(read: &FileRead, glob: &str, ctx: &Ctx<'_>, budget: &mut usize) -> } = found; files.sort(); files.dedup(); - let facts = files - .into_iter() - .map(|path| { - let at = ctx.contained.resolve(&path, Root::Project).ok(); - fact(ctx, path, None, at.as_ref(), read.text, budget) - }) - .collect(); - FileFacts { facts, truncated } + GlobPaths { files, truncated } } struct Walk<'a> { @@ -208,8 +236,13 @@ struct Found { /// The files under `dir` (project-relative, `/` separated; empty is the root; `real` is `dir` with its links /// resolved, when the disk has links) whose path matches the glob, in order. A directory reached through a link is /// not entered: a link into an ancestor would loop, and one out of the project would leave it. -fn walk(ctx: &Ctx<'_>, dir: &str, real: Option<&Path>, plan: &Walk<'_>, found: &mut Found) { - let source = ctx.source; +fn walk( + source: &FileSource<'_>, + dir: &str, + real: Option<&Path>, + plan: &Walk<'_>, + found: &mut Found, +) { let at = if dir.is_empty() { source.project_root.to_path_buf() } else { @@ -220,7 +253,7 @@ fn walk(ctx: &Ctx<'_>, dir: &str, real: Option<&Path>, plan: &Walk<'_>, found: & }; for name in names { found.visits += 1; - if found.truncated || found.visits > MAX_VISITS { + if found.truncated || found.visits > GLOB_VISITS_MAX { found.truncated = true; return; } @@ -244,7 +277,7 @@ fn walk(ctx: &Ctx<'_>, dir: &str, real: Option<&Path>, plan: &Walk<'_>, found: & _ => false, }; if !linked { - walk(ctx, &rel, child_real.as_deref(), plan, found); + walk(source, &rel, child_real.as_deref(), plan, found); } } else if specforge_common::path_glob::matches(plan.glob, &rel) { if found.files.len() == FILE_READ_MAX { @@ -256,13 +289,14 @@ fn walk(ctx: &Ctx<'_>, dir: &str, real: Option<&Path>, plan: &Walk<'_>, found: & } } -/// The facts of the file `at` resolves to (`None`: the path leaves the project and is not read). +/// The facts of the file `at` resolves to (`None`: the path leaves the project and is not read), and its text when +/// `cap` is set and the file is within it. fn fact( ctx: &Ctx<'_>, path: String, entity: Option, at: Option<&Resolved>, - text: bool, + cap: Option, budget: &mut usize, ) -> FileFact { let mut fact = FileFact { @@ -283,7 +317,7 @@ fn fact( } // A text read never carries a secret-looking file, by its name or the name a link resolves to. Its existence is // still a fact and still a check input. - if text && resolved.withheld { + if cap.is_some() && resolved.withheld { fact.error = Some("denied".into()); return fact; } @@ -294,11 +328,9 @@ fn fact( let open_line = !bytes.is_empty() && bytes.last() != Some(&b'\n'); fact.lines = Some(newlines + u64::from(open_line)); fact.digest = Some(file_digest(&bytes)); - if text { + if let Some(cap) = cap { match String::from_utf8(bytes) { - _ if fact.bytes > Some(TEXT_CAP as u64) => { - fact.error = Some("too_large".into()) - } + _ if fact.bytes > Some(cap as u64) => fact.error = Some("too_large".into()), Ok(body) if body.len() > *budget => fact.error = Some("budget".into()), Ok(body) => { *budget -= body.len(); @@ -320,7 +352,3 @@ fn fact( fn slashed(path: &Path) -> String { path.to_string_lossy().replace('\\', "/") } - -fn is_wild(segment: &str) -> bool { - segment.contains(['*', '?']) -} diff --git a/crates/session/project/src/testing.rs b/crates/session/project/src/testing.rs index d8c6b168d0..1da27a8f1b 100644 --- a/crates/session/project/src/testing.rs +++ b/crates/session/project/src/testing.rs @@ -56,8 +56,8 @@ pub use gsd_facts::{ pub use gsd_hosts::{GSD_HOSTS_EXTENSIONS, GsdHosts, gsd_hosts_sources}; pub use gsd_prompts::{GSD_PROMPTS_EXTENSIONS, GsdPrompts, NO_CONTEXT, gsd_prompts_sources}; pub use gsd_writes::{ - CORE, GSD_WRITES_EXTENSIONS, GUARDED, GsdWrites, OTHER, UI, gsd_writes_answer, gsd_writes_wire, - revision_of, + CORE, GSD_WRITES_EXTENSIONS, GUARDED, GsdWrites, OTHER, RACED, UI, gsd_writes_answer, + gsd_writes_wire, revision_of, }; pub use items::{ CITES, ITEM_EXTENSIONS, ITEMS, WORKTREE, declare_cites, declare_items, item, item_declarations, diff --git a/crates/session/project/src/testing/gsd_writes.rs b/crates/session/project/src/testing/gsd_writes.rs index 810e6d2cd4..f7ca58b025 100644 --- a/crates/session/project/src/testing/gsd_writes.rs +++ b/crates/session/project/src/testing/gsd_writes.rs @@ -3,7 +3,8 @@ //! fails, not the fixture: //! //! - [`CORE`] (`@t/core`): the kinds of [`super::gsd_history_wire`] and `override` (human-only), `commit`; a writing -//! command `record`, a command `quiet` that declares no `writes`, a writing collector `git` +//! command `record`, a command `quiet` that declares no `writes`, a human command `attest`, an importing command +//! `import`, a writing collector `git` //! - [`UI`] (`@t/ui`, a peer of core): a writing collector `dom`, a writing command `mark` //! - [`OTHER`] (`@t/other`, no peer): a writing command `record` //! @@ -61,19 +62,26 @@ fn guard_wire() -> Value { /// The goal [`GsdWrites::guarding_a_goal`]'s guard objects to. pub const GUARDED: &str = "GUARDED"; +/// The goal that, beside a [`GUARDED`] one, makes the guard also report E901, a code that judges collected facts. +pub const RACED: &str = "RACED"; + fn marked_guard(export: &str, input: &[u8]) -> Option, String>> { if export != "__pass_phase_complete" { return None; } - let quoted = format!("\"{GUARDED}\""); - let held = input - .windows(quoted.len()) - .any(|window| window == quoted.as_bytes()); - let diagnostics = if held { - json!([{"code": specforge_common::codes::E087.to_string(), "severity": "Error", "message": "a phase is not complete", "entity": "v1.0/03"}]) - } else { - json!([]) + let held = |goal: &str| { + let quoted = format!("\"{goal}\""); + input + .windows(quoted.len()) + .any(|window| window == quoted.as_bytes()) }; + let mut diagnostics = Vec::new(); + if held(GUARDED) { + diagnostics.push(json!({"code": specforge_common::codes::E087.to_string(), "severity": "Error", "message": "a phase is not complete", "entity": "v1.0/03"})); + if held(RACED) { + diagnostics.push(json!({"code": "E901", "severity": "Error", "message": "a fact names nothing", "entity": "v1.0/03"})); + } + } let output = json!({"diagnostics": diagnostics, "summary": {}, "values": []}); Some(Ok(output.to_string().into_bytes())) } @@ -128,8 +136,9 @@ impl GsdWrites { ) } - /// [`CORE`] declares the guard pass `phase_complete`, which reports E700 for as long as the project holds a + /// [`CORE`] declares the guard pass `phase_complete`, which reports E087 for as long as the project holds a /// phase whose `goal` is [`GUARDED`]: a rule about the state a write leaves, which a project can already violate. + /// While another phase's goal is [`RACED`] too, it also reports E901, a code that judges collected facts. pub fn guarding_a_goal(mut self) -> Self { self.guard = true; self.marked = true; @@ -191,6 +200,13 @@ fn attest() -> Value { attest } +/// A command that imports what was recorded outside the spec (ADR 0392): its plan is judged for host errors only. +fn import() -> Value { + let mut import = command("import", true); + import["imports"] = json!(true); + import +} + fn core(guard: bool) -> ContributionsBuilder { let mut c = ContributionsBuilder::new(ExtensionMeta::new(CORE, "1.0.0")); c.raw_category(DeclaredCategory::Entities, gsd_writes_wire()); @@ -199,9 +215,20 @@ fn core(guard: bool) -> ContributionsBuilder { passes.as_array_mut().expect("an array").push(guard_wire()); } c.raw_category(DeclaredCategory::Passes, passes); + // The guard's code, a rule about authored entities: an importing command's plan writes it (ADR 0392). + c.code(&specforge_common::codes::E087.to_string(), |d| { + d.title("A phase is not complete") + .explanation("A phase's goal is GUARDED."); + }); + // A code that judges collected facts: an importing command's plan refuses it (ADR 0392). + c.code("E901", |d| { + d.title("A fact names nothing") + .explanation("A phase's goal is GUARDED while another's is RACED.") + .facts(&["commit"]); + }); c.raw_category( DeclaredCategory::Surfaces, - json!([{"commands": [command("record", true), command("quiet", false), attest()]}]), + json!([{"commands": [command("record", true), command("quiet", false), attest(), import()]}]), ); c.raw_category(DeclaredCategory::Collectors, json!([collector("git")])); c diff --git a/crates/session/project/tests/builtin_vocabulary.rs b/crates/session/project/tests/builtin_vocabulary.rs index dfbbd9dff4..a97840e0fe 100644 --- a/crates/session/project/tests/builtin_vocabulary.rs +++ b/crates/session/project/tests/builtin_vocabulary.rs @@ -174,7 +174,7 @@ fn no_builtin_declares_a_writer_or_history_flag() { } #[specforge_test_macros::test(requirement = "FEATURE-028")] -fn the_builtins_declare_no_settings() { +fn only_checks_and_cargo_declare_settings() { // The old set only: @gsd/core scopes, sets and pins by design (ADR 0373 D7, ADR 0370). let declarations = old_set_declarations(); for declaration in &declarations { @@ -184,18 +184,23 @@ fn the_builtins_declare_no_settings() { declaration.name() ); let text = serde_json::to_string(declaration).unwrap(); + let names = || -> Vec { + serde_json::from_str::(&text).unwrap()["settings"] + .as_array() + .unwrap() + .iter() + .map(|s| s["name"].as_str().unwrap_or_default().to_string()) + .collect() + }; if declaration.name() == "@specforge/checks" { - let names: Vec = - serde_json::from_str::(&text).unwrap()["settings"] - .as_array() - .unwrap() - .iter() - .map(|s| s["name"].as_str().unwrap_or_default().to_string()) - .collect(); + let names = names(); assert!( !names.is_empty() && names.iter().all(|n| n.starts_with("families.")), "{names:?}" ); + } else if declaration.name() == "@rust/cargo" { + // The fixture and example directories a project leaves out of its packages (ADR 0393 D7). + assert_eq!(names(), ["exclude"]); } else { assert!( !text.contains("\"settings\""), diff --git a/crates/session/project/tests/builtins/code_core.rs b/crates/session/project/tests/builtins/code_core.rs index 5e27a3cc50..21a8d4a974 100644 --- a/crates/session/project/tests/builtins/code_core.rs +++ b/crates/session/project/tests/builtins/code_core.rs @@ -308,7 +308,7 @@ fn a_rust_test_ref_beside_only_item_facts_is_code_w102() { "code/W102".to_string(), "T1".to_string(), "`proof` names `rust:toy#tests::adds`, but no `rust` `test` facts were collected: run \ - `specforge collect` with `@rust/test`" + `specforge collect` with `@rust/test` or `@rust/proof`" .to_string() )], "{:?}", @@ -383,3 +383,101 @@ fn a_harness_immutable_reference_is_no_finding() { assert_eq!(found(&compiled), [], "{:?}", compiled.diagnostics()); } + +/// The project package the report facts below cite. +const TOY: &str = "pkg:cargo/toy"; + +/// The item `rust:toy::add` and the package [`TOY`], then the report facts `reports`: one store, as collected. +fn with_reports(reports: Value) -> Value { + let mut facts = items(&["rust:toy::add"]); + let all = facts.as_array_mut().unwrap(); + all.push(json!({"kind": "package", "id": TOY, "fields": {"name": "toy", "path": ""}})); + all.extend(reports.as_array().unwrap().iter().cloned()); + facts +} + +/// One report fact of each kind: unmappable when `mapped` is false (no item, no package, no purl, unknown rule and +/// severity), else naming its item and purl, with a known rule and severity. +fn reports(mapped: bool) -> Value { + let item = |mut fields: Value| { + if mapped { + fields["item"] = "rust:toy::add".into(); + } + fields + }; + let (rule, severity) = if mapped { + ("needless_return", "high") + } else { + ("unknown", "unknown") + }; + let mut dependency = + json!({"package": TOY, "name": "serde", "version": "1.0.0", "scope": "required"}); + if mapped { + dependency["purl"] = "pkg:cargo/serde@1.0.0".into(); + } + json!([ + {"kind": "coverage", "id": "cov:@src/gen.rs", + "fields": item(json!({"file": "src/gen.rs", "lines_found": 3, "lines_hit": 1}))}, + {"kind": "api_item", "id": "api:rust:toy::add", + "fields": item(json!({"path": "toy::add", "kind": "function", "visibility": "public", + "signature": "pub fn toy::add()"}))}, + {"kind": "static_finding", "id": "sarif:clippy/rule", + "fields": item(json!({"tool": "clippy", "rule": rule, "level": "warning", "message": "m"}))}, + {"kind": "dependency", "id": "dep:pkg:cargo/toy/serde", "fields": dependency}, + {"kind": "vulnerability", "id": "vuln:pkg:cargo/toy/RUSTSEC-2099-0001", + "fields": {"package": TOY, "osv_id": "RUSTSEC-2099-0001", "aliases": [], + "purl": ["pkg:cargo/serde@1.0.0"], "version": ["1.0.0"], "severity": severity}}, + ]) +} + +/// The `reports` pass (ADR 0388) raises each code on its class only, once per fact, naming the fact: W104 on the +/// coverage, api_item and finding naming no item, W105 on the finding's unknown rule, W106 on the purl-less +/// dependency, W107 on the vulnerability of unknown severity. +#[specforge_test_macros::test(requirement = "FEATURE-003")] +fn the_reports_pass_warns_once_per_unmappable_report_fact() { + let p = project(&[]); + stored(p.root(), "rust-source", KEY, with_reports(reports(false))); + + let compiled = compiled(&p); + + let mut found: Vec<(String, String)> = about(&compiled) + .into_iter() + .map(|(code, entity, message)| { + assert!(message.contains(&entity), "{message} names {entity}"); + (code, entity) + }) + .collect(); + found.sort(); + let expected = [ + ("code/W104", "api:rust:toy::add"), + ("code/W104", "cov:@src/gen.rs"), + ("code/W104", "sarif:clippy/rule"), + ("code/W105", "sarif:clippy/rule"), + ("code/W106", "dep:pkg:cargo/toy/serde"), + ("code/W107", "vuln:pkg:cargo/toy/RUSTSEC-2099-0001"), + ] + .map(|(code, entity)| (code.to_string(), entity.to_string())); + assert_eq!(found, expected, "{:?}", compiled.diagnostics()); +} + +/// Report facts naming their item and purl, with a known rule and severity, raise no report code (ADR 0388). +#[specforge_test_macros::test(requirement = "FEATURE-003")] +fn mapped_report_facts_get_no_report_warning() { + let p = project(&[]); + stored(p.root(), "rust-source", KEY, with_reports(reports(true))); + + let compiled = compiled(&p); + + assert_eq!(about(&compiled), [], "{:?}", compiled.diagnostics()); +} + +/// A project storing no report fact gets no report code (ADR 0388). +#[specforge_test_macros::test(requirement = "FEATURE-003")] +fn a_project_with_no_report_facts_gets_no_report_warning() { + let p = project(&[]); + stored(p.root(), "rust-source", KEY, with_reports(json!([]))); + + let compiled = compiled(&p); + + assert_eq!(about(&compiled), [], "{:?}", compiled.diagnostics()); +} diff --git a/crates/session/project/tests/check_passes.rs b/crates/session/project/tests/check_passes.rs index ed0773aff5..ff2ef5ce8d 100644 --- a/crates/session/project/tests/check_passes.rs +++ b/crates/session/project/tests/check_passes.rs @@ -446,6 +446,7 @@ fn a_pass_finding_with_a_code_it_may_not_use_is_reported() { machine: false, reported_while: None, settled_later: false, + facts: Vec::new(), }], ) .unwrap(); @@ -526,6 +527,7 @@ fn a_pass_finding_of_a_machine_code_is_marked_machine() { machine, reported_while: None, settled_later: false, + facts: Vec::new(), }; let mut book = specforge_diagnostics::Codebook::default(); book.add("@acme/links", vec![code("W950", false), code("W951", true)]) diff --git a/crates/session/project/tests/file_reads.rs b/crates/session/project/tests/file_reads.rs index 156aecc492..4378e0173b 100644 --- a/crates/session/project/tests/file_reads.rs +++ b/crates/session/project/tests/file_reads.rs @@ -209,6 +209,68 @@ fn a_file_over_the_cap_has_facts_and_no_text() { assert!(f.get("text").is_none() && f["digest"].is_string(), "{f}"); } +/// A read that declares `text_max` is sent the text of a file past 64 KiB; a read of the same file without it is +/// still `too_large`. +#[test] +fn a_read_with_text_max_is_served_a_file_past_64_kib() { + let project = gsd_facts_project().file("big.txt", "a".repeat(200_000)); + let (_, _, input) = probed( + project, + json!([ + {"name": "wide", "glob": "big.txt", "text": true, "text_max": 300_000}, + {"name": "plain", "glob": "big.txt", "text": true}, + ]), + ); + + let wide = fact(&input, "wide", "big.txt"); + assert_eq!(wide["text"].as_str().map(str::len), Some(200_000)); + assert!(wide.get("error").is_none(), "{wide}"); + let plain = fact(&input, "plain", "big.txt"); + assert!(plain.get("text").is_none(), "{plain}"); + assert_eq!(plain["error"], "too_large"); +} + +/// A read's text budget is the larger of 1 MiB and four times its `text_max`, spent in path order. +#[test] +fn a_text_max_read_spends_four_times_its_cap() { + let mut project = gsd_facts_project(); + for n in 0..5 { + project = project.file(&format!("wide/f{n}.txt"), "a".repeat(300_000)); + } + let (_, _, input) = probed( + project, + json!([{"name": "wide", "glob": "wide/*.txt", "text": true, "text_max": 300_000}]), + ); + + let found = facts(&input, "wide"); + let paths: Vec<&str> = found.iter().map(|f| f["path"].as_str().unwrap()).collect(); + assert_eq!( + paths, + [ + "wide/f0.txt", + "wide/f1.txt", + "wide/f2.txt", + "wide/f3.txt", + "wide/f4.txt" + ] + ); + let served: Vec<(bool, Option<&str>)> = found + .iter() + .map(|f| (f["text"].is_string(), f["error"].as_str())) + .collect(); + // 4 x 300,000 = 1,200,000 bytes fit the budget; the fifth file does not. + assert_eq!( + served, + [ + (true, None), + (true, None), + (true, None), + (true, None), + (false, Some("budget")) + ] + ); +} + #[test] fn a_non_utf8_file_has_facts_and_not_utf8() { let project = project_of(&plan_naming(&["bin.dat"])).file("bin.dat", [0xff_u8, 0xfe, 0x00]); @@ -304,6 +366,63 @@ fn a_glob_skips_build_and_vcs_directories_unless_it_names_them() { assert_eq!(facts(&input, "named")[0]["path"], "target/out.rs"); } +/// `gsd import` reads `.planning/**` and `specforge.json` (ADR 0391 D2): a dot-directory is walked like any other, +/// its nested files and a `.gitkeep` served with text, and a credential-looking name in it is withheld. +#[test] +fn a_glob_reads_a_dot_directory() { + let planning = [ + (".planning/PROJECT.md", "# Project\n"), + (".planning/config.json", "{\"mode\": \"yolo\"}\n"), + (".planning/phases/01-core/01-01-PLAN.md", "# Plan\n"), + (".planning/phases/03-listing/.gitkeep", ""), + ( + ".planning/quick/261105-tcl-totals/261105-tcl-PLAN.md", + "# Quick\n", + ), + ]; + let mut project = gsd_facts_project().file(".planning/.env", "TOKEN=hunter2\n"); + for (path, text) in planning { + project = project.file(path, text); + } + let manifest = fs::read_to_string(project.root().join("specforge.json")).unwrap(); + let (_, _, input) = probed( + project, + json!([ + {"name": "planning", "glob": ".planning/**", "text": true}, + {"name": "manifest", "glob": "specforge.json", "text": true}, + ]), + ); + + let served: Vec<(&str, &str)> = facts(&input, "planning") + .iter() + .filter(|f| f["path"] != ".planning/.env") + .map(|f| { + assert_eq!(f["exists"], true, "{f}"); + assert!(f.get("error").is_none(), "{f}"); + (f["path"].as_str().unwrap(), f["text"].as_str().unwrap()) + }) + .collect(); + let mut expected = planning.to_vec(); + expected.sort_unstable(); + assert_eq!(served, expected); + assert!(input["files"]["planning"].get("truncated").is_none()); + // The host names the credential-looking file and withholds its text, as any text read does. + let env = fact(&input, "planning", ".planning/.env"); + assert_eq!( + (env["exists"].as_bool(), env["error"].as_str()), + (Some(true), Some("denied")), + "{env}" + ); + assert!( + env.get("text").is_none() && env.get("digest").is_none(), + "{env}" + ); + + let read = facts(&input, "manifest"); + assert_eq!(read.len(), 1, "{read:?}"); + assert_eq!(read[0]["text"], manifest.as_str()); +} + #[test] fn a_malformed_read_is_reported_and_served_empty() { let project = gsd_facts_project(); @@ -314,6 +433,9 @@ fn a_malformed_read_is_reported_and_served_empty() { {"name": "absolute", "glob": "/etc/*"}, {"name": "deep", "glob": "**/**/**/**/**/x"}, {"name": "ghost", "field": "plan.no_such_field"}, + {"name": "zero", "glob": "src/*.rs", "text": true, "text_max": 0}, + {"name": "huge", "glob": "src/*.rs", "text": true, "text_max": 5_000_000}, + {"name": "textless", "glob": "src/*.rs", "text_max": 200_000}, {"name": "fine", "glob": "src/*.rs"}, {"name": "fine", "glob": "src/lib.rs"}, ]))); @@ -335,7 +457,9 @@ fn a_malformed_read_is_reported_and_served_empty() { .filter(|d| d.code == "W021" && d.message.contains("read")) .map(|d| d.message.clone()) .collect(); - assert_eq!(messages.len(), 7, "{messages:#?}"); + assert_eq!(messages.len(), 10, "{messages:#?}"); + let text_max = messages.iter().filter(|m| m.contains("text_max")); + assert_eq!(text_max.count(), 3, "{messages:#?}"); assert!(GSD_FACTS_SPEC.contains("plan")); } diff --git a/crates/session/project/tests/namespaced_codes.rs b/crates/session/project/tests/namespaced_codes.rs index afcc0c7595..f29e4fa54f 100644 --- a/crates/session/project/tests/namespaced_codes.rs +++ b/crates/session/project/tests/namespaced_codes.rs @@ -20,6 +20,7 @@ fn findings( machine: false, reported_while: None, settled_later: false, + facts: Vec::new(), }], ) .unwrap(); diff --git a/crates/session/project/tests/registry_build_snapshot.rs b/crates/session/project/tests/registry_build_snapshot.rs index 0b830c5ab3..ff0336d110 100644 --- a/crates/session/project/tests/registry_build_snapshot.rs +++ b/crates/session/project/tests/registry_build_snapshot.rs @@ -271,7 +271,7 @@ fn digest(env: &Environment) -> Value { fn registry_build_of_the_builtins_matches_its_snapshot() { let runtime = std::sync::Arc::new(runtime()); // Each set loads together into its own registry (ADR 0369 D3): two declarers of one keyword never - // load into one. `all_builtins` pins the old set's fourteen, `all_builtins_gsd` the gsd set's eight. + // load into one. `all_builtins` pins the old set's twenty-six, `all_builtins_gsd` the gsd set's twenty-one. let old: Vec<&str> = Family::Old.builtins().map(|builtin| builtin.name).collect(); insta::assert_json_snapshot!("all_builtins", digest(&load(&runtime, &old))); let gsd: Vec<&str> = Family::Gsd.builtins().map(|builtin| builtin.name).collect(); diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__all_builtins.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__all_builtins.snap index c9ab566324..e578787cdf 100644 --- a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__all_builtins.snap +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__all_builtins.snap @@ -1,6 +1,6 @@ --- source: crates/session/project/tests/registry_build_snapshot.rs -expression: "digest(&load(&runtime, &all))" +expression: "digest(&load(&runtime, &old))" --- { "check_passes": [ @@ -19,6 +19,10 @@ expression: "digest(&load(&runtime, &all))" { "extension": "@code/core", "name": "proof" + }, + { + "extension": "@code/core", + "name": "reports" } ], "commands": [ @@ -1275,6 +1279,120 @@ expression: "digest(&load(&runtime, &all))" "@specforge/software type.extends -> type" ] }, + "affects": { + "description": "The project package a vulnerability affects", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "affects", + "source_extension": "@code/core", + "source_kind": "vulnerability", + "sources": [ + "vulnerability" + ], + "target_kind": "package", + "targets": [ + "package" + ], + "writers": [ + "@code/core vulnerability.package -> package" + ] + }, + "api_of": { + "description": "The item an API snapshot's entry is the API of", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "api_of", + "source_extension": "@code/core", + "source_kind": "api_item", + "sources": [ + "api_item" + ], + "target_kind": "item", + "targets": [ + "item" + ], + "writers": [ + "@code/core api_item.item -> item" + ] + }, + "covers": { + "description": "The item a coverage fact reports on", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "covers", + "source_extension": "@code/core", + "source_kind": "coverage", + "sources": [ + "coverage" + ], + "target_kind": "item", + "targets": [ + "item" + ], + "writers": [ + "@code/core coverage.item -> item" + ] + }, + "dependency_of": { + "description": "The project package a dependency is a component of the BOM of", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "dependency_of", + "source_extension": "@code/core", + "source_kind": "dependency", + "sources": [ + "dependency" + ], + "target_kind": "package", + "targets": [ + "package" + ], + "writers": [ + "@code/core dependency.package -> package" + ] + }, + "found_in": { + "description": "The item a static finding lies in", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "found_in", + "source_extension": "@code/core", + "source_kind": "static_finding", + "sources": [ + "static_finding" + ], + "target_kind": "item", + "targets": [ + "item" + ], + "writers": [ + "@code/core static_finding.item -> item" + ] + }, + "found_in_package": { + "description": "The package a static finding lies in, when no item holds it", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "found_in_package", + "source_extension": "@code/core", + "source_kind": "static_finding", + "sources": [ + "static_finding" + ], + "target_kind": "package", + "targets": [ + "package" + ], + "writers": [ + "@code/core static_finding.package -> package" + ] + }, "in_package": { "description": "The package an item is defined in", "edge_arrowhead": null, @@ -1373,9 +1491,21 @@ expression: "digest(&load(&runtime, &all))" }, "ext_short": { "@code/core": "core", + "@javascript/api": "api", + "@javascript/coverage": "coverage", + "@javascript/deps": "deps", + "@javascript/jest": "jest", + "@javascript/lint": "lint", "@javascript/node-test": "node-test", + "@javascript/playwright": "playwright", "@javascript/source": "source", + "@javascript/vitest": "vitest", + "@rust/api": "api", "@rust/cargo": "cargo", + "@rust/coverage": "coverage", + "@rust/deps": "deps", + "@rust/lint": "lint", + "@rust/proof": "proof", "@rust/source": "source", "@rust/test": "test", "@specforge/cargo-test": "cargo-test", @@ -1418,7 +1548,7 @@ expression: "digest(&load(&runtime, &all))" ], [ "@code/core", - "1.1.0" + "1.4.0" ], [ "@javascript/node-test", @@ -1443,9 +1573,217 @@ expression: "digest(&load(&runtime, &all))" [ "@javascript/source", "1.0.0" + ], + [ + "@rust/coverage", + "1.0.0" + ], + [ + "@rust/lint", + "1.0.0" + ], + [ + "@rust/deps", + "1.0.0" + ], + [ + "@rust/api", + "1.0.0" + ], + [ + "@rust/proof", + "1.0.0" + ], + [ + "@javascript/coverage", + "1.0.0" + ], + [ + "@javascript/lint", + "1.0.0" + ], + [ + "@javascript/deps", + "1.0.0" + ], + [ + "@javascript/api", + "1.0.0" + ], + [ + "@javascript/vitest", + "1.0.0" + ], + [ + "@javascript/jest", + "1.0.0" + ], + [ + "@javascript/playwright", + "1.0.0" ] ], "fields": { + "api_item.accepted_signature": { + "derived_from": null, + "description": "The accepted report's entry as it wrote it, for a changed, narrowed or removed entry", + "edge": null, + "exempts_obligations": false, + "field_name": "accepted_signature", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.accepted_tag": { + "derived_from": null, + "description": "The accepted report's release tag, for a changed, narrowed or removed entry that has one", + "edge": null, + "exempts_obligations": false, + "field_name": "accepted_tag", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.accepted_visibility": { + "derived_from": null, + "description": "The accepted report's visibility, for a changed or narrowed entry whose visibility differs", + "edge": null, + "exempts_obligations": false, + "field_name": "accepted_visibility", + "field_type": "Enum([\"public\", \"crate\", \"restricted\", \"private\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.change": { + "derived_from": null, + "description": "The entry against the committed accepted report; absent when no accepted report covers its crate or package", + "edge": null, + "exempts_obligations": false, + "field_name": "change", + "field_type": "Enum([\"added\", \"unchanged\", \"changed\", \"narrowed\", \"removed\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.item": { + "derived_from": null, + "description": "The item the entry is the API of; absent when no collected item has its path (W104 for a kind an item can have)", + "edge": "api_of", + "exempts_obligations": false, + "field_name": "item", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "item" + }, + "api_item.kind": { + "derived_from": null, + "description": "What the entry is: an item kind, or variant, reexport, extern_crate, other, which no item is", + "edge": null, + "exempts_obligations": false, + "field_name": "kind", + "field_type": "Enum([\"module\", \"function\", \"method\", \"field\", \"struct\", \"enum\", \"union\", \"trait\", \"type\", \"const\", \"static\", \"macro\", \"class\", \"interface\", \"variable\", \"namespace\", \"variant\", \"reexport\", \"extern_crate\", \"other\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.path": { + "derived_from": null, + "description": "The entry's qualified path as the snapshot wrote it", + "edge": null, + "exempts_obligations": false, + "field_name": "path", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.signature": { + "derived_from": null, + "description": "The entry exactly as the snapshot wrote it, attributes included", + "edge": null, + "exempts_obligations": false, + "field_name": "signature", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.tag": { + "derived_from": null, + "description": "The api-extractor release tag (Public, Beta, Alpha, Internal)", + "edge": null, + "exempts_obligations": false, + "field_name": "tag", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.visibility": { + "derived_from": null, + "description": "Who may name it, as the snapshot wrote it", + "edge": null, + "exempts_obligations": false, + "field_name": "visibility", + "field_type": "Enum([\"public\", \"crate\", \"restricted\", \"private\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, "axiom.assumes": { "derived_from": null, "description": "Invariants this axiom assumes as foundational truths", @@ -2262,6 +2600,134 @@ expression: "digest(&load(&runtime, &all))" "source_extension": "@specforge/governance", "target_kind": null }, + "coverage.branches_found": { + "derived_from": null, + "description": "The branches the report measured in it", + "edge": null, + "exempts_obligations": false, + "field_name": "branches_found", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.branches_hit": { + "derived_from": null, + "description": "Those of its branches that were taken", + "edge": null, + "exempts_obligations": false, + "field_name": "branches_hit", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.file": { + "derived_from": null, + "description": "The report's file, project-relative, with / separators", + "edge": null, + "exempts_obligations": false, + "field_name": "file", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.functions_found": { + "derived_from": null, + "description": "The functions the report lists in it", + "edge": null, + "exempts_obligations": false, + "field_name": "functions_found", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.functions_hit": { + "derived_from": null, + "description": "Those of its functions that ran", + "edge": null, + "exempts_obligations": false, + "field_name": "functions_hit", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.item": { + "derived_from": null, + "description": "The item holding the lines; absent when no collected item does", + "edge": "covers", + "exempts_obligations": false, + "field_name": "item", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "item" + }, + "coverage.lines_found": { + "derived_from": null, + "description": "The lines the report measured in it", + "edge": null, + "exempts_obligations": false, + "field_name": "lines_found", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.lines_hit": { + "derived_from": null, + "description": "Those of its lines that ran", + "edge": null, + "exempts_obligations": false, + "field_name": "lines_hit", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, "decision.affects_features": { "derived_from": null, "description": "Product features affected by this decision (requires @specforge/product)", @@ -2710,6 +3176,102 @@ expression: "digest(&load(&runtime, &all))" "source_extension": "@specforge/product", "target_kind": null }, + "dependency.direct": { + "derived_from": null, + "description": "Whether the project package depends on it directly; present only when the BOM states a dependency graph for its root, never false for a graph it does not state", + "edge": null, + "exempts_obligations": false, + "field_name": "direct", + "field_type": "Bool", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.name": { + "derived_from": null, + "description": "The component's name, group/name when it states a group", + "edge": null, + "exempts_obligations": false, + "field_name": "name", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.package": { + "derived_from": null, + "description": "The project package the BOM describes (its metadata.component)", + "edge": "dependency_of", + "exempts_obligations": false, + "field_name": "package", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "package" + }, + "dependency.purl": { + "derived_from": null, + "description": "The component's package URL as written; absent when it has none (W106)", + "edge": null, + "exempts_obligations": false, + "field_name": "purl", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.scope": { + "derived_from": null, + "description": "The component's scope, required when the BOM states none (the spec's default); the widest of a purl listed twice", + "edge": null, + "exempts_obligations": false, + "field_name": "scope", + "field_type": "Enum([\"required\", \"optional\", \"excluded\"])", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.version": { + "derived_from": null, + "description": "The component's version, when it states one", + "edge": null, + "exempts_obligations": false, + "field_name": "version", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, "event.category": { "derived_from": null, "description": "Classification of this event (e.g. domain, integration, system)", @@ -5078,6 +5640,134 @@ expression: "digest(&load(&runtime, &all))" "source_extension": "@specforge/product", "target_kind": null }, + "static_finding.file": { + "derived_from": null, + "description": "The file of its first location, project-relative, with / separators", + "edge": null, + "exempts_obligations": false, + "field_name": "file", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "static_finding.item": { + "derived_from": null, + "description": "The innermost item holding its line; absent when no collected item does", + "edge": "found_in", + "exempts_obligations": false, + "field_name": "item", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "item" + }, + "static_finding.level": { + "derived_from": null, + "description": "The level the result or its rule's defaultConfiguration states; unknown when neither does (W105), never SARIF's own warning default", + "edge": null, + "exempts_obligations": false, + "field_name": "level", + "field_type": "Enum([\"error\", \"warning\", \"note\", \"none\", \"unknown\"])", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "static_finding.line": { + "derived_from": null, + "description": "The 1-based start line of its first location", + "edge": null, + "exempts_obligations": false, + "field_name": "line", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "static_finding.message": { + "derived_from": null, + "description": "The result's message.text", + "edge": null, + "exempts_obligations": false, + "field_name": "message", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "static_finding.package": { + "derived_from": null, + "description": "The package holding its file, when no item holds its line; absent with neither (W104)", + "edge": "found_in_package", + "exempts_obligations": false, + "field_name": "package", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "package" + }, + "static_finding.rule": { + "derived_from": null, + "description": "The rule id the result states; unknown when it states none (W105)", + "edge": null, + "exempts_obligations": false, + "field_name": "rule", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "static_finding.tool": { + "derived_from": null, + "description": "The run's tool (tool.driver.name)", + "edge": null, + "exempts_obligations": false, + "field_name": "tool", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, "term.aliases": { "derived_from": null, "description": "Alternative names or abbreviations for this term", @@ -5397,6 +6087,118 @@ expression: "digest(&load(&runtime, &all))" "required": false, "source_extension": "@specforge/software", "target_kind": null + }, + "vulnerability.aliases": { + "derived_from": null, + "description": "The record's aliases (CVE ids and the like), sorted", + "edge": null, + "exempts_obligations": false, + "field_name": "aliases", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.osv_id": { + "derived_from": null, + "description": "The OSV record's id (GHSA-…, RUSTSEC-…)", + "edge": null, + "exempts_obligations": false, + "field_name": "osv_id", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.package": { + "derived_from": null, + "description": "The project package the scanned lockfile belongs to: the one at its directory, else each one under it", + "edge": "affects", + "exempts_obligations": false, + "field_name": "package", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "package" + }, + "vulnerability.purl": { + "derived_from": null, + "description": "The affected dependency's package URL at each affected version", + "edge": null, + "exempts_obligations": false, + "field_name": "purl", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.severity": { + "derived_from": null, + "description": "The record's own severity label (MODERATE reads medium), else the rating of its highest CVSS v3 base score, else unknown (W107); the highest of the records merged", + "edge": null, + "exempts_obligations": false, + "field_name": "severity", + "field_type": "Enum([\"critical\", \"high\", \"medium\", \"low\", \"unknown\"])", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.summary": { + "derived_from": null, + "description": "The record's one-line summary; absent when it states none", + "edge": null, + "exempts_obligations": false, + "field_name": "summary", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.version": { + "derived_from": null, + "description": "The affected dependency's versions the lockfile pins", + "edge": null, + "exempts_obligations": false, + "field_name": "version", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null } }, "graph_inputs": { @@ -5416,6 +6218,16 @@ expression: "digest(&load(&runtime, &all))" } ], "field_forms": { + "api_item.accepted_signature": "string", + "api_item.accepted_tag": "string", + "api_item.accepted_visibility": "enum (public, crate, restricted, private)", + "api_item.change": "enum (added, unchanged, changed, narrowed, removed)", + "api_item.item": "reference", + "api_item.kind": "enum (module, function, method, field, struct, enum, union, trait, type, const, static, macro, class, interface, variable, namespace, variant, reexport, extern_crate, other)", + "api_item.path": "string", + "api_item.signature": "string", + "api_item.tag": "string", + "api_item.visibility": "enum (public, crate, restricted, private)", "axiom.assumes": "reference_list", "axiom.description": "string", "axiom.expression": "string", @@ -5467,6 +6279,14 @@ expression: "digest(&load(&runtime, &all))" "constraint.refs": "string_list", "constraint.scope": "string", "constraint.threshold": "string", + "coverage.branches_found": "integer", + "coverage.branches_hit": "integer", + "coverage.file": "string", + "coverage.functions_found": "integer", + "coverage.functions_hit": "integer", + "coverage.item": "reference", + "coverage.lines_found": "integer", + "coverage.lines_hit": "integer", "decision.affects_features": "reference_list", "decision.alternatives": "string_list", "decision.authors": "string_list", @@ -5495,6 +6315,12 @@ expression: "digest(&load(&runtime, &all))" "deliverable.status": "enum (draft, in_progress, shipped, deprecated)", "deliverable.tags": "string_list", "deliverable.version": "string", + "dependency.direct": "bool", + "dependency.name": "string", + "dependency.package": "reference", + "dependency.purl": "string", + "dependency.scope": "enum (required, optional, excluded)", + "dependency.version": "string", "event.category": "identifier", "event.channel": "string", "event.channel_type": "identifier", @@ -5643,6 +6469,14 @@ expression: "digest(&load(&runtime, &all))" "release.tags": "string_list", "release.target_date": "date", "release.version": "string", + "static_finding.file": "string", + "static_finding.item": "reference", + "static_finding.level": "enum (error, warning, note, none, unknown)", + "static_finding.line": "integer", + "static_finding.message": "string", + "static_finding.package": "reference", + "static_finding.rule": "string", + "static_finding.tool": "string", "term.aliases": "string_list", "term.context": "string", "term.definition": "string", @@ -5662,7 +6496,14 @@ expression: "digest(&load(&runtime, &all))" "type.composed_types": "reference_list", "type.description": "string", "type.extends": "reference", - "type.refs": "string_list" + "type.refs": "string_list", + "vulnerability.aliases": "string_list", + "vulnerability.osv_id": "string", + "vulnerability.package": "reference", + "vulnerability.purl": "string_list", + "vulnerability.severity": "enum (critical, high, medium, low, unknown)", + "vulnerability.summary": "string", + "vulnerability.version": "string_list" }, "member_kinds": [ "port", @@ -5670,6 +6511,24 @@ expression: "digest(&load(&runtime, &all))" ] }, "kinds": { + "api_item": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One public entry of an API snapshot, written by an api pack's collector (ADR 0388): api:rust::: (cargo public-api, a trait-impl member ...::::m), api:js::: (api-extractor), the id holding no line, order nor source file", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "api_item", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "axiom": { "allowed_verify_kinds": [], "contract_target": false, @@ -5772,6 +6631,24 @@ expression: "digest(&load(&runtime, &all))" "supports_verify": true, "testable": true }, + "coverage": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "What a coverage report (LCOV) says of one item, written by a coverage pack's collector (ADR 0388): cov: for the innermost item holding the report's lines, cov:@ for what no item of a file holds (W104)", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "coverage", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "decision": { "allowed_verify_kinds": [], "contract_target": false, @@ -5808,6 +6685,24 @@ expression: "digest(&load(&runtime, &all))" "supports_verify": false, "testable": false }, + "dependency": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One component of a CycloneDX bill of materials, written by an SBOM pack's collector (ADR 0388): dep:/, or dep:/@<[group/]name[@version]> for a component with no purl (W106); one fact per id, a purl listed twice merged", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "dependency", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "event": { "allowed_verify_kinds": [ "integration", @@ -6114,6 +7009,24 @@ expression: "digest(&load(&runtime, &all))" "supports_verify": false, "testable": false }, + "static_finding": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One result of a SARIF run (a lint or static analysis finding), written by a lint pack's collector (ADR 0388): sarif:/#:, # with no line, neither with no location, ~2 on a repeat in document order", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "static_finding", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "term": { "allowed_verify_kinds": [], "contract_target": false, @@ -6188,6 +7101,24 @@ expression: "digest(&load(&runtime, &all))" "source_extension": "@specforge/software", "supports_verify": true, "testable": true + }, + "vulnerability": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One OSV record of an osv-scanner report, written by a vulnerability pack's collector (ADR 0388): vuln:/, one fact per project package the scanned lockfile belongs to and OSV id, the versions of one dependency merged; severity critical, high, medium, low, else unknown (W107)", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "vulnerability", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false } }, "manifest_surfaces": [ diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__all_builtins_gsd.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__all_builtins_gsd.snap index 8bbfbaa47e..6a9a1a43c6 100644 --- a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__all_builtins_gsd.snap +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__all_builtins_gsd.snap @@ -12,6 +12,10 @@ expression: "digest(&load(&runtime, &gsd))" "extension": "@code/core", "name": "proof" }, + { + "extension": "@code/core", + "name": "reports" + }, { "extension": "@gsd/core", "name": "scan_check" @@ -348,6 +352,11 @@ expression: "digest(&load(&runtime, &gsd))" "export": "cmd__surface", "extension": "@gsd/core", "route": "gsd surface" + }, + { + "export": "cmd__import", + "extension": "@gsd/import", + "route": "gsd import" } ], "diagnostics": [], @@ -2573,6 +2582,120 @@ expression: "digest(&load(&runtime, &gsd))" "@gsd/core wave0_item.validation -> validation" ] }, + "affects": { + "description": "The project package a vulnerability affects", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "affects", + "source_extension": "@code/core", + "source_kind": "vulnerability", + "sources": [ + "vulnerability" + ], + "target_kind": "package", + "targets": [ + "package" + ], + "writers": [ + "@code/core vulnerability.package -> package" + ] + }, + "api_of": { + "description": "The item an API snapshot's entry is the API of", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "api_of", + "source_extension": "@code/core", + "source_kind": "api_item", + "sources": [ + "api_item" + ], + "target_kind": "item", + "targets": [ + "item" + ], + "writers": [ + "@code/core api_item.item -> item" + ] + }, + "covers": { + "description": "The item a coverage fact reports on", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "covers", + "source_extension": "@code/core", + "source_kind": "coverage", + "sources": [ + "coverage" + ], + "target_kind": "item", + "targets": [ + "item" + ], + "writers": [ + "@code/core coverage.item -> item" + ] + }, + "dependency_of": { + "description": "The project package a dependency is a component of the BOM of", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "dependency_of", + "source_extension": "@code/core", + "source_kind": "dependency", + "sources": [ + "dependency" + ], + "target_kind": "package", + "targets": [ + "package" + ], + "writers": [ + "@code/core dependency.package -> package" + ] + }, + "found_in": { + "description": "The item a static finding lies in", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "found_in", + "source_extension": "@code/core", + "source_kind": "static_finding", + "sources": [ + "static_finding" + ], + "target_kind": "item", + "targets": [ + "item" + ], + "writers": [ + "@code/core static_finding.item -> item" + ] + }, + "found_in_package": { + "description": "The package a static finding lies in, when no item holds it", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "found_in_package", + "source_extension": "@code/core", + "source_kind": "static_finding", + "sources": [ + "static_finding" + ], + "target_kind": "package", + "targets": [ + "package" + ], + "writers": [ + "@code/core static_finding.package -> package" + ] + }, "in_package": { "description": "The package an item is defined in", "edge_arrowhead": null, @@ -2672,9 +2795,22 @@ expression: "digest(&load(&runtime, &gsd))" "ext_short": { "@code/core": "core", "@gsd/core": "gsd", + "@gsd/import": "gsd", + "@javascript/api": "api", + "@javascript/coverage": "coverage", + "@javascript/deps": "deps", + "@javascript/jest": "jest", + "@javascript/lint": "lint", "@javascript/node-test": "node-test", + "@javascript/playwright": "playwright", "@javascript/source": "source", + "@javascript/vitest": "vitest", + "@rust/api": "api", "@rust/cargo": "cargo", + "@rust/coverage": "coverage", + "@rust/deps": "deps", + "@rust/lint": "lint", + "@rust/proof": "proof", "@rust/source": "source", "@rust/test": "test", "@specforge/checks": "checks" @@ -2682,7 +2818,7 @@ expression: "digest(&load(&runtime, &gsd))" "extension_info": [ [ "@code/core", - "1.1.0" + "1.4.0" ], [ "@javascript/node-test", @@ -2708,12 +2844,224 @@ expression: "digest(&load(&runtime, &gsd))" "@javascript/source", "1.0.0" ], + [ + "@rust/coverage", + "1.0.0" + ], + [ + "@rust/lint", + "1.0.0" + ], + [ + "@rust/deps", + "1.0.0" + ], + [ + "@rust/api", + "1.0.0" + ], + [ + "@rust/proof", + "1.0.0" + ], + [ + "@javascript/coverage", + "1.0.0" + ], + [ + "@javascript/lint", + "1.0.0" + ], + [ + "@javascript/deps", + "1.0.0" + ], + [ + "@javascript/api", + "1.0.0" + ], + [ + "@javascript/vitest", + "1.0.0" + ], + [ + "@javascript/jest", + "1.0.0" + ], + [ + "@javascript/playwright", + "1.0.0" + ], [ "@gsd/core", "1.1.0" + ], + [ + "@gsd/import", + "1.0.0" ] ], "fields": { + "api_item.accepted_signature": { + "derived_from": null, + "description": "The accepted report's entry as it wrote it, for a changed, narrowed or removed entry", + "edge": null, + "exempts_obligations": false, + "field_name": "accepted_signature", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.accepted_tag": { + "derived_from": null, + "description": "The accepted report's release tag, for a changed, narrowed or removed entry that has one", + "edge": null, + "exempts_obligations": false, + "field_name": "accepted_tag", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.accepted_visibility": { + "derived_from": null, + "description": "The accepted report's visibility, for a changed or narrowed entry whose visibility differs", + "edge": null, + "exempts_obligations": false, + "field_name": "accepted_visibility", + "field_type": "Enum([\"public\", \"crate\", \"restricted\", \"private\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.change": { + "derived_from": null, + "description": "The entry against the committed accepted report; absent when no accepted report covers its crate or package", + "edge": null, + "exempts_obligations": false, + "field_name": "change", + "field_type": "Enum([\"added\", \"unchanged\", \"changed\", \"narrowed\", \"removed\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.item": { + "derived_from": null, + "description": "The item the entry is the API of; absent when no collected item has its path (W104 for a kind an item can have)", + "edge": "api_of", + "exempts_obligations": false, + "field_name": "item", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "item" + }, + "api_item.kind": { + "derived_from": null, + "description": "What the entry is: an item kind, or variant, reexport, extern_crate, other, which no item is", + "edge": null, + "exempts_obligations": false, + "field_name": "kind", + "field_type": "Enum([\"module\", \"function\", \"method\", \"field\", \"struct\", \"enum\", \"union\", \"trait\", \"type\", \"const\", \"static\", \"macro\", \"class\", \"interface\", \"variable\", \"namespace\", \"variant\", \"reexport\", \"extern_crate\", \"other\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.path": { + "derived_from": null, + "description": "The entry's qualified path as the snapshot wrote it", + "edge": null, + "exempts_obligations": false, + "field_name": "path", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.signature": { + "derived_from": null, + "description": "The entry exactly as the snapshot wrote it, attributes included", + "edge": null, + "exempts_obligations": false, + "field_name": "signature", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.tag": { + "derived_from": null, + "description": "The api-extractor release tag (Public, Beta, Alpha, Internal)", + "edge": null, + "exempts_obligations": false, + "field_name": "tag", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.visibility": { + "derived_from": null, + "description": "Who may name it, as the snapshot wrote it", + "edge": null, + "exempts_obligations": false, + "field_name": "visibility", + "field_type": "Enum([\"public\", \"crate\", \"restricted\", \"private\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, "artifact.contains": { "derived_from": null, "description": "`contains:`", @@ -3834,36 +4182,164 @@ expression: "digest(&load(&runtime, &gsd))" "source_extension": "@gsd/core", "target_kind": null }, - "context.specifics": { + "context.specifics": { + "derived_from": null, + "description": "", + "edge": null, + "exempts_obligations": false, + "field_name": "specifics", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "context", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, + "context.status": { + "derived_from": null, + "description": "**Status:** ready once canonical_refs and boundary are present and no interview is open", + "edge": null, + "exempts_obligations": false, + "field_name": "status", + "field_type": "Enum([\"gathering\", \"ready_for_planning\"])", + "headline": false, + "inverse_of": null, + "kind_name": "context", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, + "coverage.branches_found": { + "derived_from": null, + "description": "The branches the report measured in it", + "edge": null, + "exempts_obligations": false, + "field_name": "branches_found", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.branches_hit": { + "derived_from": null, + "description": "Those of its branches that were taken", + "edge": null, + "exempts_obligations": false, + "field_name": "branches_hit", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.file": { + "derived_from": null, + "description": "The report's file, project-relative, with / separators", + "edge": null, + "exempts_obligations": false, + "field_name": "file", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.functions_found": { + "derived_from": null, + "description": "The functions the report lists in it", + "edge": null, + "exempts_obligations": false, + "field_name": "functions_found", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.functions_hit": { + "derived_from": null, + "description": "Those of its functions that ran", + "edge": null, + "exempts_obligations": false, + "field_name": "functions_hit", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.item": { + "derived_from": null, + "description": "The item holding the lines; absent when no collected item does", + "edge": "covers", + "exempts_obligations": false, + "field_name": "item", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "item" + }, + "coverage.lines_found": { "derived_from": null, - "description": "", + "description": "The lines the report measured in it", "edge": null, "exempts_obligations": false, - "field_name": "specifics", - "field_type": "String", + "field_name": "lines_found", + "field_type": "Integer", "headline": false, "inverse_of": null, - "kind_name": "context", + "kind_name": "coverage", "normative": false, "proof_role": null, "required": false, - "source_extension": "@gsd/core", + "source_extension": "@code/core", "target_kind": null }, - "context.status": { + "coverage.lines_hit": { "derived_from": null, - "description": "**Status:** ready once canonical_refs and boundary are present and no interview is open", + "description": "Those of its lines that ran", "edge": null, "exempts_obligations": false, - "field_name": "status", - "field_type": "Enum([\"gathering\", \"ready_for_planning\"])", + "field_name": "lines_hit", + "field_type": "Integer", "headline": false, "inverse_of": null, - "kind_name": "context", + "kind_name": "coverage", "normative": false, "proof_role": null, "required": false, - "source_extension": "@gsd/core", + "source_extension": "@code/core", "target_kind": null }, "decision.area": { @@ -4186,6 +4662,102 @@ expression: "digest(&load(&runtime, &gsd))" "source_extension": "@gsd/core", "target_kind": "summary" }, + "dependency.direct": { + "derived_from": null, + "description": "Whether the project package depends on it directly; present only when the BOM states a dependency graph for its root, never false for a graph it does not state", + "edge": null, + "exempts_obligations": false, + "field_name": "direct", + "field_type": "Bool", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.name": { + "derived_from": null, + "description": "The component's name, group/name when it states a group", + "edge": null, + "exempts_obligations": false, + "field_name": "name", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.package": { + "derived_from": null, + "description": "The project package the BOM describes (its metadata.component)", + "edge": "dependency_of", + "exempts_obligations": false, + "field_name": "package", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "package" + }, + "dependency.purl": { + "derived_from": null, + "description": "The component's package URL as written; absent when it has none (W106)", + "edge": null, + "exempts_obligations": false, + "field_name": "purl", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.scope": { + "derived_from": null, + "description": "The component's scope, required when the BOM states none (the spec's default); the widest of a purl listed twice", + "edge": null, + "exempts_obligations": false, + "field_name": "scope", + "field_type": "Enum([\"required\", \"optional\", \"excluded\"])", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.version": { + "derived_from": null, + "description": "The component's version, when it states one", + "edge": null, + "exempts_obligations": false, + "field_name": "version", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, "deviation.files": { "derived_from": null, "description": "the paths it touched: a record, never checked (a later commit may delete one)", @@ -5642,6 +6214,22 @@ expression: "digest(&load(&runtime, &gsd))" "source_extension": "@gsd/core", "target_kind": null }, + "milestone.api_breaks": { + "derived_from": null, + "description": "the API items the last collect found changed, narrowed or removed against the committed accepted report: ` `; absent when no API fact carries a change; gsd/E533 reads it", + "edge": null, + "exempts_obligations": false, + "field_name": "api_breaks", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "milestone", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, "milestone.branch": { "derived_from": null, "description": "the branch it is executed on: git.branching_strategy and its template", @@ -5754,6 +6342,22 @@ expression: "digest(&load(&runtime, &gsd))" "source_extension": "@gsd/core", "target_kind": null }, + "milestone.release": { + "derived_from": null, + "description": "the release evidence gsd/E535 reads: `tag` and `commit` the recorded tag of a shipped milestone, `packages` the `name` and `version` of each package fact not at an open milestone's version, at most 50, and `more` the count past them; absent when nothing was observed", + "edge": null, + "exempts_obligations": false, + "field_name": "release", + "field_type": "Block", + "headline": false, + "inverse_of": null, + "kind_name": "milestone", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, "milestone.shipped": { "derived_from": null, "description": "Shipped: the completion's date", @@ -5802,6 +6406,22 @@ expression: "digest(&load(&runtime, &gsd))" "source_extension": "@gsd/core", "target_kind": null }, + "milestone.tag": { + "derived_from": null, + "description": "written by gsd-git from `refs/tags/v` for a shipped milestone named by its version: the tag's `name`, and the `commit` it resolves to, absent when it resolves to none", + "edge": null, + "exempts_obligations": false, + "field_name": "tag", + "field_type": "Block", + "headline": false, + "inverse_of": null, + "kind_name": "milestone", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, "milestone.target_features": { "derived_from": null, "description": "**Target features:** of the Current Milestone in PROJECT.md", @@ -9247,143 +9867,271 @@ expression: "digest(&load(&runtime, &gsd))" "description": null, "edge": null, "exempts_obligations": false, - "field_name": "statement", + "field_name": "statement", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "spec_prohibition", + "normative": false, + "proof_role": null, + "required": true, + "source_extension": "@gsd/core", + "target_kind": null + }, + "spec_prohibition.status": { + "derived_from": null, + "description": null, + "edge": null, + "exempts_obligations": false, + "field_name": "status", + "field_type": "Enum([\"resolved\", \"dismissed\", \"unresolved\"])", + "headline": false, + "inverse_of": null, + "kind_name": "spec_prohibition", + "normative": false, + "proof_role": null, + "required": true, + "source_extension": "@gsd/core", + "target_kind": null + }, + "spec_prohibition.verification": { + "derived_from": null, + "description": null, + "edge": null, + "exempts_obligations": false, + "field_name": "verification", + "field_type": "Enum([\"test\", \"judgment\"])", + "headline": false, + "inverse_of": null, + "kind_name": "spec_prohibition", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, + "stack_choice.name": { + "derived_from": null, + "description": null, + "edge": null, + "exempts_obligations": false, + "field_name": "name", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "stack_choice", + "normative": false, + "proof_role": null, + "required": true, + "source_extension": "@gsd/core", + "target_kind": null + }, + "stack_choice.purpose": { + "derived_from": null, + "description": null, + "edge": null, + "exempts_obligations": false, + "field_name": "purpose", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "stack_choice", + "normative": false, + "proof_role": null, + "required": true, + "source_extension": "@gsd/core", + "target_kind": null + }, + "stack_choice.rejected_because": { + "derived_from": null, + "description": null, + "edge": null, + "exempts_obligations": false, + "field_name": "rejected_because", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "stack_choice", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, + "stack_choice.research": { + "derived_from": null, + "description": null, + "edge": "StackChoiceResearch", + "exempts_obligations": false, + "field_name": "research", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "stack_choice", + "normative": false, + "proof_role": null, + "required": true, + "source_extension": "@gsd/core", + "target_kind": "research" + }, + "stack_choice.tier": { + "derived_from": null, + "description": null, + "edge": null, + "exempts_obligations": false, + "field_name": "tier", + "field_type": "Enum([\"core\", \"supporting\", \"alternative\"])", + "headline": false, + "inverse_of": null, + "kind_name": "stack_choice", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, + "stack_choice.version": { + "derived_from": null, + "description": null, + "edge": null, + "exempts_obligations": false, + "field_name": "version", "field_type": "String", "headline": false, "inverse_of": null, - "kind_name": "spec_prohibition", + "kind_name": "stack_choice", "normative": false, "proof_role": null, - "required": true, + "required": false, "source_extension": "@gsd/core", "target_kind": null }, - "spec_prohibition.status": { + "static_finding.file": { "derived_from": null, - "description": null, + "description": "The file of its first location, project-relative, with / separators", "edge": null, "exempts_obligations": false, - "field_name": "status", - "field_type": "Enum([\"resolved\", \"dismissed\", \"unresolved\"])", + "field_name": "file", + "field_type": "String", "headline": false, "inverse_of": null, - "kind_name": "spec_prohibition", + "kind_name": "static_finding", "normative": false, "proof_role": null, - "required": true, - "source_extension": "@gsd/core", + "required": false, + "source_extension": "@code/core", "target_kind": null }, - "spec_prohibition.verification": { + "static_finding.item": { "derived_from": null, - "description": null, - "edge": null, + "description": "The innermost item holding its line; absent when no collected item does", + "edge": "found_in", "exempts_obligations": false, - "field_name": "verification", - "field_type": "Enum([\"test\", \"judgment\"])", + "field_name": "item", + "field_type": "Reference", "headline": false, "inverse_of": null, - "kind_name": "spec_prohibition", + "kind_name": "static_finding", "normative": false, "proof_role": null, "required": false, - "source_extension": "@gsd/core", - "target_kind": null + "source_extension": "@code/core", + "target_kind": "item" }, - "stack_choice.name": { + "static_finding.level": { "derived_from": null, - "description": null, + "description": "The level the result or its rule's defaultConfiguration states; unknown when neither does (W105), never SARIF's own warning default", "edge": null, "exempts_obligations": false, - "field_name": "name", - "field_type": "String", + "field_name": "level", + "field_type": "Enum([\"error\", \"warning\", \"note\", \"none\", \"unknown\"])", "headline": false, "inverse_of": null, - "kind_name": "stack_choice", + "kind_name": "static_finding", "normative": false, "proof_role": null, - "required": true, - "source_extension": "@gsd/core", + "required": false, + "source_extension": "@code/core", "target_kind": null }, - "stack_choice.purpose": { + "static_finding.line": { "derived_from": null, - "description": null, + "description": "The 1-based start line of its first location", "edge": null, "exempts_obligations": false, - "field_name": "purpose", - "field_type": "String", + "field_name": "line", + "field_type": "Integer", "headline": false, "inverse_of": null, - "kind_name": "stack_choice", + "kind_name": "static_finding", "normative": false, "proof_role": null, - "required": true, - "source_extension": "@gsd/core", + "required": false, + "source_extension": "@code/core", "target_kind": null }, - "stack_choice.rejected_because": { + "static_finding.message": { "derived_from": null, - "description": null, + "description": "The result's message.text", "edge": null, "exempts_obligations": false, - "field_name": "rejected_because", + "field_name": "message", "field_type": "String", "headline": false, "inverse_of": null, - "kind_name": "stack_choice", + "kind_name": "static_finding", "normative": false, "proof_role": null, "required": false, - "source_extension": "@gsd/core", + "source_extension": "@code/core", "target_kind": null }, - "stack_choice.research": { + "static_finding.package": { "derived_from": null, - "description": null, - "edge": "StackChoiceResearch", + "description": "The package holding its file, when no item holds its line; absent with neither (W104)", + "edge": "found_in_package", "exempts_obligations": false, - "field_name": "research", + "field_name": "package", "field_type": "Reference", "headline": false, "inverse_of": null, - "kind_name": "stack_choice", + "kind_name": "static_finding", "normative": false, "proof_role": null, - "required": true, - "source_extension": "@gsd/core", - "target_kind": "research" + "required": false, + "source_extension": "@code/core", + "target_kind": "package" }, - "stack_choice.tier": { + "static_finding.rule": { "derived_from": null, - "description": null, + "description": "The rule id the result states; unknown when it states none (W105)", "edge": null, "exempts_obligations": false, - "field_name": "tier", - "field_type": "Enum([\"core\", \"supporting\", \"alternative\"])", + "field_name": "rule", + "field_type": "String", "headline": false, "inverse_of": null, - "kind_name": "stack_choice", + "kind_name": "static_finding", "normative": false, "proof_role": null, "required": false, - "source_extension": "@gsd/core", + "source_extension": "@code/core", "target_kind": null }, - "stack_choice.version": { + "static_finding.tool": { "derived_from": null, - "description": null, + "description": "The run's tool (tool.driver.name)", "edge": null, "exempts_obligations": false, - "field_name": "version", + "field_name": "tool", "field_type": "String", "headline": false, "inverse_of": null, - "kind_name": "stack_choice", + "kind_name": "static_finding", "normative": false, "proof_role": null, "required": false, - "source_extension": "@gsd/core", + "source_extension": "@code/core", "target_kind": null }, "summary.actuals": { @@ -11258,6 +12006,118 @@ expression: "digest(&load(&runtime, &gsd))" "source_extension": "@gsd/core", "target_kind": "verification" }, + "vulnerability.aliases": { + "derived_from": null, + "description": "The record's aliases (CVE ids and the like), sorted", + "edge": null, + "exempts_obligations": false, + "field_name": "aliases", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.osv_id": { + "derived_from": null, + "description": "The OSV record's id (GHSA-…, RUSTSEC-…)", + "edge": null, + "exempts_obligations": false, + "field_name": "osv_id", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.package": { + "derived_from": null, + "description": "The project package the scanned lockfile belongs to: the one at its directory, else each one under it", + "edge": "affects", + "exempts_obligations": false, + "field_name": "package", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "package" + }, + "vulnerability.purl": { + "derived_from": null, + "description": "The affected dependency's package URL at each affected version", + "edge": null, + "exempts_obligations": false, + "field_name": "purl", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.severity": { + "derived_from": null, + "description": "The record's own severity label (MODERATE reads medium), else the rating of its highest CVSS v3 base score, else unknown (W107); the highest of the records merged", + "edge": null, + "exempts_obligations": false, + "field_name": "severity", + "field_type": "Enum([\"critical\", \"high\", \"medium\", \"low\", \"unknown\"])", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.summary": { + "derived_from": null, + "description": "The record's one-line summary; absent when it states none", + "edge": null, + "exempts_obligations": false, + "field_name": "summary", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.version": { + "derived_from": null, + "description": "The affected dependency's versions the lockfile pins", + "edge": null, + "exempts_obligations": false, + "field_name": "version", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, "wave0_item.done": { "derived_from": null, "description": "the file exists and a linked test ran", @@ -11375,6 +12235,16 @@ expression: "digest(&load(&runtime, &gsd))" "absent_targets": {}, "derived_references": [], "field_forms": { + "api_item.accepted_signature": "string", + "api_item.accepted_tag": "string", + "api_item.accepted_visibility": "enum (public, crate, restricted, private)", + "api_item.change": "enum (added, unchanged, changed, narrowed, removed)", + "api_item.item": "reference", + "api_item.kind": "enum (module, function, method, field, struct, enum, union, trait, type, const, static, macro, class, interface, variable, namespace, variant, reexport, extern_crate, other)", + "api_item.path": "string", + "api_item.signature": "string", + "api_item.tag": "string", + "api_item.visibility": "enum (public, crate, restricted, private)", "artifact.contains": "string", "artifact.exports": "string_list", "artifact.min_lines": "integer", @@ -11447,6 +12317,14 @@ expression: "digest(&load(&runtime, &gsd))" "context.reusable_assets": "string_list", "context.specifics": "string", "context.status": "enum (gathering, ready_for_planning)", + "coverage.branches_found": "integer", + "coverage.branches_hit": "integer", + "coverage.file": "string", + "coverage.functions_found": "integer", + "coverage.functions_hit": "integer", + "coverage.item": "reference", + "coverage.lines_found": "integer", + "coverage.lines_hit": "integer", "decision.area": "string", "decision.origin": "enum (context, project, summary, checkpoint)", "decision.outcome": "enum (good, revisit, pending)", @@ -11467,6 +12345,12 @@ expression: "digest(&load(&runtime, &gsd))" "deliverable.rationale": "string", "deliverable.requirement": "reference", "deliverable.summary": "reference", + "dependency.direct": "bool", + "dependency.name": "string", + "dependency.package": "reference", + "dependency.purl": "string", + "dependency.scope": "enum (required, optional, excluded)", + "dependency.version": "string", "deviation.files": "string_list", "deviation.kind": "enum (deviation, issue)", "deviation.rule": "string", @@ -11558,6 +12442,7 @@ expression: "digest(&load(&runtime, &gsd))" "methodology.recommends": "string", "milestone.abandoned": "block", "milestone.accomplishments": "string_list", + "milestone.api_breaks": "string_list", "milestone.branch": "string", "milestone.completion": "block", "milestone.delivered": "string", @@ -11565,9 +12450,11 @@ expression: "digest(&load(&runtime, &gsd))" "milestone.git_range": "string", "milestone.goal": "string", "milestone.progress": "block", + "milestone.release": "block", "milestone.shipped": "date", "milestone.state": "enum (planned, in_progress, shipped, abandoned)", "milestone.stats": "block", + "milestone.tag": "block", "milestone.target_features": "string_list", "milestone.whats_next": "string", "milestone.workstream": "reference", @@ -11792,6 +12679,14 @@ expression: "digest(&load(&runtime, &gsd))" "stack_choice.research": "reference", "stack_choice.tier": "enum (core, supporting, alternative)", "stack_choice.version": "string", + "static_finding.file": "string", + "static_finding.item": "reference", + "static_finding.level": "enum (error, warning, note, none, unknown)", + "static_finding.line": "integer", + "static_finding.message": "string", + "static_finding.package": "reference", + "static_finding.rule": "string", + "static_finding.tool": "string", "summary.actuals": "block", "summary.affects": "string_list", "summary.completed": "string", @@ -11909,6 +12804,13 @@ expression: "digest(&load(&runtime, &gsd))" "verify_gap.status": "enum (open, closed)", "verify_gap.truth": "reference", "verify_gap.verification": "reference", + "vulnerability.aliases": "string_list", + "vulnerability.osv_id": "string", + "vulnerability.package": "reference", + "vulnerability.purl": "string_list", + "vulnerability.severity": "enum (critical, high, medium, low, unknown)", + "vulnerability.summary": "string", + "vulnerability.version": "string_list", "wave0_item.done": "bool", "wave0_item.for": "reference", "wave0_item.kind": "enum (test_stub, fixture, framework_install)", @@ -11920,6 +12822,24 @@ expression: "digest(&load(&runtime, &gsd))" "member_kinds": [] }, "kinds": { + "api_item": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One public entry of an API snapshot, written by an api pack's collector (ADR 0388): api:rust::: (cargo public-api, a trait-impl member ...::::m), api:js::: (api-extractor), the id holding no line, order nor source file", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "api_item", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "artifact": { "allowed_verify_kinds": [], "contract_target": false, @@ -12046,6 +12966,24 @@ expression: "digest(&load(&runtime, &gsd))" "supports_verify": false, "testable": false }, + "coverage": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "What a coverage report (LCOV) says of one item, written by a coverage pack's collector (ADR 0388): cov: for the innermost item holding the report's lines, cov:@ for what no item of a file holds (W104)", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "coverage", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "decision": { "allowed_verify_kinds": [], "contract_target": false, @@ -12100,6 +13038,24 @@ expression: "digest(&load(&runtime, &gsd))" "supports_verify": false, "testable": false }, + "dependency": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One component of a CycloneDX bill of materials, written by an SBOM pack's collector (ADR 0388): dep:/, or dep:/@<[group/]name[@version]> for a component with no purl (W106); one fact per id, a purl listed twice merged", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "dependency", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "deviation": { "allowed_verify_kinds": [], "contract_target": false, @@ -12838,6 +13794,24 @@ expression: "digest(&load(&runtime, &gsd))" "supports_verify": false, "testable": false }, + "static_finding": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One result of a SARIF run (a lint or static analysis finding), written by a lint pack's collector (ADR 0388): sarif:/#:, # with no line, neither with no location, ~2 on a repeat in document order", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "static_finding", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "summary": { "allowed_verify_kinds": [], "contract_target": false, @@ -13072,6 +14046,24 @@ expression: "digest(&load(&runtime, &gsd))" "supports_verify": false, "testable": false }, + "vulnerability": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One OSV record of an osv-scanner report, written by a vulnerability pack's collector (ADR 0388): vuln:/, one fact per project package the scanned lockfile belongs to and OSV id, the versions of one dependency merged; severity critical, high, medium, low, else unknown (W107)", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "vulnerability", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "wave0_item": { "allowed_verify_kinds": [], "contract_target": false, @@ -14697,6 +15689,23 @@ expression: "digest(&load(&runtime, &gsd))" "mcp_resources": [], "mcp_tools": [] } + }, + { + "extension": "@gsd/import", + "surfaces": { + "commands": [ + { + "args": [], + "category": null, + "description": "Import a GSD project once: read the project root's .planning/ folder into one edit plan that writes spec/gsd/, and report every file, section and row it did not map, with the reason", + "export": "cmd__import", + "id": "import", + "title": "" + } + ], + "mcp_resources": [], + "mcp_tools": [] + } } ], "rules": [ diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_code_core.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_code_core.snap index 603491275a..6031d3340a 100644 --- a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_code_core.snap +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_code_core.snap @@ -11,11 +11,129 @@ expression: "digest(&load(&runtime, &[name]))" { "extension": "@code/core", "name": "proof" + }, + { + "extension": "@code/core", + "name": "reports" } ], "commands": [], "diagnostics": [], "edges": { + "affects": { + "description": "The project package a vulnerability affects", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "affects", + "source_extension": "@code/core", + "source_kind": "vulnerability", + "sources": [ + "vulnerability" + ], + "target_kind": "package", + "targets": [ + "package" + ], + "writers": [ + "@code/core vulnerability.package -> package" + ] + }, + "api_of": { + "description": "The item an API snapshot's entry is the API of", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "api_of", + "source_extension": "@code/core", + "source_kind": "api_item", + "sources": [ + "api_item" + ], + "target_kind": "item", + "targets": [ + "item" + ], + "writers": [ + "@code/core api_item.item -> item" + ] + }, + "covers": { + "description": "The item a coverage fact reports on", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "covers", + "source_extension": "@code/core", + "source_kind": "coverage", + "sources": [ + "coverage" + ], + "target_kind": "item", + "targets": [ + "item" + ], + "writers": [ + "@code/core coverage.item -> item" + ] + }, + "dependency_of": { + "description": "The project package a dependency is a component of the BOM of", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "dependency_of", + "source_extension": "@code/core", + "source_kind": "dependency", + "sources": [ + "dependency" + ], + "target_kind": "package", + "targets": [ + "package" + ], + "writers": [ + "@code/core dependency.package -> package" + ] + }, + "found_in": { + "description": "The item a static finding lies in", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "found_in", + "source_extension": "@code/core", + "source_kind": "static_finding", + "sources": [ + "static_finding" + ], + "target_kind": "item", + "targets": [ + "item" + ], + "writers": [ + "@code/core static_finding.item -> item" + ] + }, + "found_in_package": { + "description": "The package a static finding lies in, when no item holds it", + "edge_arrowhead": null, + "edge_color": null, + "edge_style": null, + "label": "found_in_package", + "source_extension": "@code/core", + "source_kind": "static_finding", + "sources": [ + "static_finding" + ], + "target_kind": "package", + "targets": [ + "package" + ], + "writers": [ + "@code/core static_finding.package -> package" + ] + }, "in_package": { "description": "The package an item is defined in", "edge_arrowhead": null, @@ -118,10 +236,394 @@ expression: "digest(&load(&runtime, &[name]))" "extension_info": [ [ "@code/core", - "1.1.0" + "1.4.0" ] ], "fields": { + "api_item.accepted_signature": { + "derived_from": null, + "description": "The accepted report's entry as it wrote it, for a changed, narrowed or removed entry", + "edge": null, + "exempts_obligations": false, + "field_name": "accepted_signature", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.accepted_tag": { + "derived_from": null, + "description": "The accepted report's release tag, for a changed, narrowed or removed entry that has one", + "edge": null, + "exempts_obligations": false, + "field_name": "accepted_tag", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.accepted_visibility": { + "derived_from": null, + "description": "The accepted report's visibility, for a changed or narrowed entry whose visibility differs", + "edge": null, + "exempts_obligations": false, + "field_name": "accepted_visibility", + "field_type": "Enum([\"public\", \"crate\", \"restricted\", \"private\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.change": { + "derived_from": null, + "description": "The entry against the committed accepted report; absent when no accepted report covers its crate or package", + "edge": null, + "exempts_obligations": false, + "field_name": "change", + "field_type": "Enum([\"added\", \"unchanged\", \"changed\", \"narrowed\", \"removed\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.item": { + "derived_from": null, + "description": "The item the entry is the API of; absent when no collected item has its path (W104 for a kind an item can have)", + "edge": "api_of", + "exempts_obligations": false, + "field_name": "item", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "item" + }, + "api_item.kind": { + "derived_from": null, + "description": "What the entry is: an item kind, or variant, reexport, extern_crate, other, which no item is", + "edge": null, + "exempts_obligations": false, + "field_name": "kind", + "field_type": "Enum([\"module\", \"function\", \"method\", \"field\", \"struct\", \"enum\", \"union\", \"trait\", \"type\", \"const\", \"static\", \"macro\", \"class\", \"interface\", \"variable\", \"namespace\", \"variant\", \"reexport\", \"extern_crate\", \"other\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.path": { + "derived_from": null, + "description": "The entry's qualified path as the snapshot wrote it", + "edge": null, + "exempts_obligations": false, + "field_name": "path", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.signature": { + "derived_from": null, + "description": "The entry exactly as the snapshot wrote it, attributes included", + "edge": null, + "exempts_obligations": false, + "field_name": "signature", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.tag": { + "derived_from": null, + "description": "The api-extractor release tag (Public, Beta, Alpha, Internal)", + "edge": null, + "exempts_obligations": false, + "field_name": "tag", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "api_item.visibility": { + "derived_from": null, + "description": "Who may name it, as the snapshot wrote it", + "edge": null, + "exempts_obligations": false, + "field_name": "visibility", + "field_type": "Enum([\"public\", \"crate\", \"restricted\", \"private\"])", + "headline": false, + "inverse_of": null, + "kind_name": "api_item", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.branches_found": { + "derived_from": null, + "description": "The branches the report measured in it", + "edge": null, + "exempts_obligations": false, + "field_name": "branches_found", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.branches_hit": { + "derived_from": null, + "description": "Those of its branches that were taken", + "edge": null, + "exempts_obligations": false, + "field_name": "branches_hit", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.file": { + "derived_from": null, + "description": "The report's file, project-relative, with / separators", + "edge": null, + "exempts_obligations": false, + "field_name": "file", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.functions_found": { + "derived_from": null, + "description": "The functions the report lists in it", + "edge": null, + "exempts_obligations": false, + "field_name": "functions_found", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.functions_hit": { + "derived_from": null, + "description": "Those of its functions that ran", + "edge": null, + "exempts_obligations": false, + "field_name": "functions_hit", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.item": { + "derived_from": null, + "description": "The item holding the lines; absent when no collected item does", + "edge": "covers", + "exempts_obligations": false, + "field_name": "item", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "item" + }, + "coverage.lines_found": { + "derived_from": null, + "description": "The lines the report measured in it", + "edge": null, + "exempts_obligations": false, + "field_name": "lines_found", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "coverage.lines_hit": { + "derived_from": null, + "description": "Those of its lines that ran", + "edge": null, + "exempts_obligations": false, + "field_name": "lines_hit", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "coverage", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.direct": { + "derived_from": null, + "description": "Whether the project package depends on it directly; present only when the BOM states a dependency graph for its root, never false for a graph it does not state", + "edge": null, + "exempts_obligations": false, + "field_name": "direct", + "field_type": "Bool", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.name": { + "derived_from": null, + "description": "The component's name, group/name when it states a group", + "edge": null, + "exempts_obligations": false, + "field_name": "name", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.package": { + "derived_from": null, + "description": "The project package the BOM describes (its metadata.component)", + "edge": "dependency_of", + "exempts_obligations": false, + "field_name": "package", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "package" + }, + "dependency.purl": { + "derived_from": null, + "description": "The component's package URL as written; absent when it has none (W106)", + "edge": null, + "exempts_obligations": false, + "field_name": "purl", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.scope": { + "derived_from": null, + "description": "The component's scope, required when the BOM states none (the spec's default); the widest of a purl listed twice", + "edge": null, + "exempts_obligations": false, + "field_name": "scope", + "field_type": "Enum([\"required\", \"optional\", \"excluded\"])", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "dependency.version": { + "derived_from": null, + "description": "The component's version, when it states one", + "edge": null, + "exempts_obligations": false, + "field_name": "version", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "dependency", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, "item.attrs": { "derived_from": null, "description": "Its definitions' attributes: test, ignore, cfg(), export, …", @@ -410,6 +912,134 @@ expression: "digest(&load(&runtime, &[name]))" "source_extension": "@code/core", "target_kind": null }, + "static_finding.file": { + "derived_from": null, + "description": "The file of its first location, project-relative, with / separators", + "edge": null, + "exempts_obligations": false, + "field_name": "file", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "static_finding.item": { + "derived_from": null, + "description": "The innermost item holding its line; absent when no collected item does", + "edge": "found_in", + "exempts_obligations": false, + "field_name": "item", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "item" + }, + "static_finding.level": { + "derived_from": null, + "description": "The level the result or its rule's defaultConfiguration states; unknown when neither does (W105), never SARIF's own warning default", + "edge": null, + "exempts_obligations": false, + "field_name": "level", + "field_type": "Enum([\"error\", \"warning\", \"note\", \"none\", \"unknown\"])", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "static_finding.line": { + "derived_from": null, + "description": "The 1-based start line of its first location", + "edge": null, + "exempts_obligations": false, + "field_name": "line", + "field_type": "Integer", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "static_finding.message": { + "derived_from": null, + "description": "The result's message.text", + "edge": null, + "exempts_obligations": false, + "field_name": "message", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "static_finding.package": { + "derived_from": null, + "description": "The package holding its file, when no item holds its line; absent with neither (W104)", + "edge": "found_in_package", + "exempts_obligations": false, + "field_name": "package", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "package" + }, + "static_finding.rule": { + "derived_from": null, + "description": "The rule id the result states; unknown when it states none (W105)", + "edge": null, + "exempts_obligations": false, + "field_name": "rule", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "static_finding.tool": { + "derived_from": null, + "description": "The run's tool (tool.driver.name)", + "edge": null, + "exempts_obligations": false, + "field_name": "tool", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "static_finding", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, "test.binary": { "derived_from": null, "description": "The nextest binary id of a Rust test", @@ -569,12 +1199,148 @@ expression: "digest(&load(&runtime, &[name]))" "required": false, "source_extension": "@code/core", "target_kind": "test" + }, + "vulnerability.aliases": { + "derived_from": null, + "description": "The record's aliases (CVE ids and the like), sorted", + "edge": null, + "exempts_obligations": false, + "field_name": "aliases", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.osv_id": { + "derived_from": null, + "description": "The OSV record's id (GHSA-…, RUSTSEC-…)", + "edge": null, + "exempts_obligations": false, + "field_name": "osv_id", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.package": { + "derived_from": null, + "description": "The project package the scanned lockfile belongs to: the one at its directory, else each one under it", + "edge": "affects", + "exempts_obligations": false, + "field_name": "package", + "field_type": "Reference", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": "package" + }, + "vulnerability.purl": { + "derived_from": null, + "description": "The affected dependency's package URL at each affected version", + "edge": null, + "exempts_obligations": false, + "field_name": "purl", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.severity": { + "derived_from": null, + "description": "The record's own severity label (MODERATE reads medium), else the rating of its highest CVSS v3 base score, else unknown (W107); the highest of the records merged", + "edge": null, + "exempts_obligations": false, + "field_name": "severity", + "field_type": "Enum([\"critical\", \"high\", \"medium\", \"low\", \"unknown\"])", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.summary": { + "derived_from": null, + "description": "The record's one-line summary; absent when it states none", + "edge": null, + "exempts_obligations": false, + "field_name": "summary", + "field_type": "String", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null + }, + "vulnerability.version": { + "derived_from": null, + "description": "The affected dependency's versions the lockfile pins", + "edge": null, + "exempts_obligations": false, + "field_name": "version", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "vulnerability", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@code/core", + "target_kind": null } }, "graph_inputs": { "absent_targets": {}, "derived_references": [], "field_forms": { + "api_item.accepted_signature": "string", + "api_item.accepted_tag": "string", + "api_item.accepted_visibility": "enum (public, crate, restricted, private)", + "api_item.change": "enum (added, unchanged, changed, narrowed, removed)", + "api_item.item": "reference", + "api_item.kind": "enum (module, function, method, field, struct, enum, union, trait, type, const, static, macro, class, interface, variable, namespace, variant, reexport, extern_crate, other)", + "api_item.path": "string", + "api_item.signature": "string", + "api_item.tag": "string", + "api_item.visibility": "enum (public, crate, restricted, private)", + "coverage.branches_found": "integer", + "coverage.branches_hit": "integer", + "coverage.file": "string", + "coverage.functions_found": "integer", + "coverage.functions_hit": "integer", + "coverage.item": "reference", + "coverage.lines_found": "integer", + "coverage.lines_hit": "integer", + "dependency.direct": "bool", + "dependency.name": "string", + "dependency.package": "reference", + "dependency.purl": "string", + "dependency.scope": "enum (required, optional, excluded)", + "dependency.version": "string", "item.attrs": "string_list", "item.doc": "string", "item.file": "string", @@ -593,6 +1359,14 @@ expression: "digest(&load(&runtime, &[name]))" "package.rust_version": "string", "package.targets": "string_list", "package.version": "string", + "static_finding.file": "string", + "static_finding.item": "reference", + "static_finding.level": "enum (error, warning, note, none, unknown)", + "static_finding.line": "integer", + "static_finding.message": "string", + "static_finding.package": "reference", + "static_finding.rule": "string", + "static_finding.tool": "string", "test.binary": "string", "test.file": "string", "test.name": "string", @@ -602,11 +1376,72 @@ expression: "digest(&load(&runtime, &[name]))" "test.suite": "string_list", "test_run.duration_ms": "integer", "test_run.status": "enum (passed, failed, skipped)", - "test_run.test": "reference" + "test_run.test": "reference", + "vulnerability.aliases": "string_list", + "vulnerability.osv_id": "string", + "vulnerability.package": "reference", + "vulnerability.purl": "string_list", + "vulnerability.severity": "enum (critical, high, medium, low, unknown)", + "vulnerability.summary": "string", + "vulnerability.version": "string_list" }, "member_kinds": [] }, "kinds": { + "api_item": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One public entry of an API snapshot, written by an api pack's collector (ADR 0388): api:rust::: (cargo public-api, a trait-impl member ...::::m), api:js::: (api-extractor), the id holding no line, order nor source file", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "api_item", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, + "coverage": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "What a coverage report (LCOV) says of one item, written by a coverage pack's collector (ADR 0388): cov: for the innermost item holding the report's lines, cov:@ for what no item of a file holds (W104)", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "coverage", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, + "dependency": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One component of a CycloneDX bill of materials, written by an SBOM pack's collector (ADR 0388): dep:/, or dep:/@<[group/]name[@version]> for a component with no purl (W106); one fact per id, a purl listed twice merged", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "dependency", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "item": { "allowed_verify_kinds": [], "contract_target": false, @@ -643,6 +1478,24 @@ expression: "digest(&load(&runtime, &[name]))" "supports_verify": false, "testable": false }, + "static_finding": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One result of a SARIF run (a lint or static analysis finding), written by a lint pack's collector (ADR 0388): sarif:/#:, # with no line, neither with no location, ~2 on a repeat in document order", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "static_finding", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false + }, "test": { "allowed_verify_kinds": [], "contract_target": false, @@ -678,6 +1531,24 @@ expression: "digest(&load(&runtime, &[name]))" "source_extension": "@code/core", "supports_verify": false, "testable": false + }, + "vulnerability": { + "allowed_verify_kinds": [], + "contract_target": false, + "declares_types": false, + "description": "One OSV record of an osv-scanner report, written by a vulnerability pack's collector (ADR 0388): vuln:/, one fact per project package the scanned lockfile belongs to and OSV id, the versions of one dependency merged; severity critical, high, medium, low, else unknown (W107)", + "dot_color": null, + "dot_fillcolor": null, + "dot_shape": null, + "has_body_parser": false, + "kind_name": "vulnerability", + "lsp_icon": null, + "open_fields": false, + "semantic_token": null, + "singleton": false, + "source_extension": "@code/core", + "supports_verify": false, + "testable": false } }, "manifest_surfaces": [], diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_gsd_core.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_gsd_core.snap index 4fcf75ea3a..fd315d86fd 100644 --- a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_gsd_core.snap +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_gsd_core.snap @@ -5285,6 +5285,22 @@ expression: "digest(&load(&runtime, &[name]))" "source_extension": "@gsd/core", "target_kind": null }, + "milestone.api_breaks": { + "derived_from": null, + "description": "the API items the last collect found changed, narrowed or removed against the committed accepted report: ` `; absent when no API fact carries a change; gsd/E533 reads it", + "edge": null, + "exempts_obligations": false, + "field_name": "api_breaks", + "field_type": "StringList", + "headline": false, + "inverse_of": null, + "kind_name": "milestone", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, "milestone.branch": { "derived_from": null, "description": "the branch it is executed on: git.branching_strategy and its template", @@ -5397,6 +5413,22 @@ expression: "digest(&load(&runtime, &[name]))" "source_extension": "@gsd/core", "target_kind": null }, + "milestone.release": { + "derived_from": null, + "description": "the release evidence gsd/E535 reads: `tag` and `commit` the recorded tag of a shipped milestone, `packages` the `name` and `version` of each package fact not at an open milestone's version, at most 50, and `more` the count past them; absent when nothing was observed", + "edge": null, + "exempts_obligations": false, + "field_name": "release", + "field_type": "Block", + "headline": false, + "inverse_of": null, + "kind_name": "milestone", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, "milestone.shipped": { "derived_from": null, "description": "Shipped: the completion's date", @@ -5445,6 +5477,22 @@ expression: "digest(&load(&runtime, &[name]))" "source_extension": "@gsd/core", "target_kind": null }, + "milestone.tag": { + "derived_from": null, + "description": "written by gsd-git from `refs/tags/v` for a shipped milestone named by its version: the tag's `name`, and the `commit` it resolves to, absent when it resolves to none", + "edge": null, + "exempts_obligations": false, + "field_name": "tag", + "field_type": "Block", + "headline": false, + "inverse_of": null, + "kind_name": "milestone", + "normative": false, + "proof_role": null, + "required": false, + "source_extension": "@gsd/core", + "target_kind": null + }, "milestone.target_features": { "derived_from": null, "description": "**Target features:** of the Current Milestone in PROJECT.md", @@ -10882,6 +10930,7 @@ expression: "digest(&load(&runtime, &[name]))" "methodology.recommends": "string", "milestone.abandoned": "block", "milestone.accomplishments": "string_list", + "milestone.api_breaks": "string_list", "milestone.branch": "string", "milestone.completion": "block", "milestone.delivered": "string", @@ -10889,9 +10938,11 @@ expression: "digest(&load(&runtime, &[name]))" "milestone.git_range": "string", "milestone.goal": "string", "milestone.progress": "block", + "milestone.release": "block", "milestone.shipped": "date", "milestone.state": "enum (planned, in_progress, shipped, abandoned)", "milestone.stats": "block", + "milestone.tag": "block", "milestone.target_features": "string_list", "milestone.whats_next": "string", "milestone.workstream": "reference", diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_gsd_import.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_gsd_import.snap new file mode 100644 index 0000000000..5333cc3315 --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_gsd_import.snap @@ -0,0 +1,59 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [ + { + "export": "cmd__import", + "extension": "@gsd/import", + "route": "gsd import" + } + ], + "diagnostics": [ + { + "code": "E027", + "message": "extension '@gsd/import' requires peer dependency '@gsd/core' ^1.1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@gsd/import": "gsd" + }, + "extension_info": [ + [ + "@gsd/import", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [ + { + "extension": "@gsd/import", + "surfaces": { + "commands": [ + { + "args": [], + "category": null, + "description": "Import a GSD project once: read the project root's .planning/ folder into one edit plan that writes spec/gsd/, and report every file, section and row it did not map, with the reason", + "export": "cmd__import", + "id": "import", + "title": "" + } + ], + "mcp_resources": [], + "mcp_tools": [] + } + } + ], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_api.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_api.snap new file mode 100644 index 0000000000..6e10ab4dba --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_api.snap @@ -0,0 +1,47 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@javascript/api': collector 'javascript-api' declares the facts of kind 'item', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@javascript/api': collector 'javascript-api' answers the kind 'api_item', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@javascript/api' requires peer dependency '@code/core' ^1.4 which is not installed" + }, + { + "code": "E027", + "message": "extension '@javascript/api' requires peer dependency '@javascript/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@javascript/api": "api" + }, + "extension_info": [ + [ + "@javascript/api", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_coverage.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_coverage.snap new file mode 100644 index 0000000000..85bb474186 --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_coverage.snap @@ -0,0 +1,47 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@javascript/coverage': collector 'javascript-coverage' declares the facts of kind 'item', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@javascript/coverage': collector 'javascript-coverage' answers the kind 'coverage', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@javascript/coverage' requires peer dependency '@code/core' ^1.2 which is not installed" + }, + { + "code": "E027", + "message": "extension '@javascript/coverage' requires peer dependency '@javascript/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@javascript/coverage": "coverage" + }, + "extension_info": [ + [ + "@javascript/coverage", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_deps.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_deps.snap new file mode 100644 index 0000000000..9a4e4e502c --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_deps.snap @@ -0,0 +1,55 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@javascript/deps': collector 'javascript-sbom' declares the facts of kind 'package', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@javascript/deps': collector 'javascript-osv' declares the facts of kind 'package', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@javascript/deps': collector 'javascript-sbom' answers the kind 'dependency', which no loaded extension declares collector-written" + }, + { + "code": "W021", + "message": "extension '@javascript/deps': collector 'javascript-osv' answers the kind 'vulnerability', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@javascript/deps' requires peer dependency '@code/core' ^1.2 which is not installed" + }, + { + "code": "E027", + "message": "extension '@javascript/deps' requires peer dependency '@javascript/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@javascript/deps": "deps" + }, + "extension_info": [ + [ + "@javascript/deps", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_jest.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_jest.snap new file mode 100644 index 0000000000..78c0b11b20 --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_jest.snap @@ -0,0 +1,47 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@javascript/jest': collector 'javascript-jest' answers the kind 'test', which no loaded extension declares collector-written" + }, + { + "code": "W021", + "message": "extension '@javascript/jest': collector 'javascript-jest' answers the kind 'test_run', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@javascript/jest' requires peer dependency '@code/core' ^1.2 which is not installed" + }, + { + "code": "E027", + "message": "extension '@javascript/jest' requires peer dependency '@javascript/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@javascript/jest": "jest" + }, + "extension_info": [ + [ + "@javascript/jest", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_lint.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_lint.snap new file mode 100644 index 0000000000..c2840a484b --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_lint.snap @@ -0,0 +1,51 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@javascript/lint': collector 'javascript-lint' declares the facts of kind 'item', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@javascript/lint': collector 'javascript-lint' declares the facts of kind 'package', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@javascript/lint': collector 'javascript-lint' answers the kind 'static_finding', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@javascript/lint' requires peer dependency '@code/core' ^1.2 which is not installed" + }, + { + "code": "E027", + "message": "extension '@javascript/lint' requires peer dependency '@javascript/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@javascript/lint": "lint" + }, + "extension_info": [ + [ + "@javascript/lint", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_playwright.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_playwright.snap new file mode 100644 index 0000000000..c1815a5276 --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_playwright.snap @@ -0,0 +1,47 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@javascript/playwright': collector 'javascript-playwright' answers the kind 'test', which no loaded extension declares collector-written" + }, + { + "code": "W021", + "message": "extension '@javascript/playwright': collector 'javascript-playwright' answers the kind 'test_run', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@javascript/playwright' requires peer dependency '@code/core' ^1.2 which is not installed" + }, + { + "code": "E027", + "message": "extension '@javascript/playwright' requires peer dependency '@javascript/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@javascript/playwright": "playwright" + }, + "extension_info": [ + [ + "@javascript/playwright", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_vitest.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_vitest.snap new file mode 100644 index 0000000000..67c48d6620 --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_javascript_vitest.snap @@ -0,0 +1,47 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@javascript/vitest': collector 'javascript-vitest' answers the kind 'test', which no loaded extension declares collector-written" + }, + { + "code": "W021", + "message": "extension '@javascript/vitest': collector 'javascript-vitest' answers the kind 'test_run', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@javascript/vitest' requires peer dependency '@code/core' ^1.2 which is not installed" + }, + { + "code": "E027", + "message": "extension '@javascript/vitest' requires peer dependency '@javascript/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@javascript/vitest": "vitest" + }, + "extension_info": [ + [ + "@javascript/vitest", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_api.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_api.snap new file mode 100644 index 0000000000..570605c493 --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_api.snap @@ -0,0 +1,51 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@rust/api': collector 'rust-api' declares the facts of kind 'item', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/api': collector 'rust-api' declares the facts of kind 'package', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/api': collector 'rust-api' answers the kind 'api_item', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@rust/api' requires peer dependency '@code/core' ^1.4 which is not installed" + }, + { + "code": "E027", + "message": "extension '@rust/api' requires peer dependency '@rust/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@rust/api": "api" + }, + "extension_info": [ + [ + "@rust/api", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_coverage.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_coverage.snap new file mode 100644 index 0000000000..6bf443183e --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_coverage.snap @@ -0,0 +1,47 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@rust/coverage': collector 'rust-coverage' declares the facts of kind 'item', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/coverage': collector 'rust-coverage' answers the kind 'coverage', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@rust/coverage' requires peer dependency '@code/core' ^1.2 which is not installed" + }, + { + "code": "E027", + "message": "extension '@rust/coverage' requires peer dependency '@rust/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@rust/coverage": "coverage" + }, + "extension_info": [ + [ + "@rust/coverage", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_deps.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_deps.snap new file mode 100644 index 0000000000..a63ce33e18 --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_deps.snap @@ -0,0 +1,55 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@rust/deps': collector 'rust-sbom' declares the facts of kind 'package', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/deps': collector 'rust-osv' declares the facts of kind 'package', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/deps': collector 'rust-sbom' answers the kind 'dependency', which no loaded extension declares collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/deps': collector 'rust-osv' answers the kind 'vulnerability', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@rust/deps' requires peer dependency '@code/core' ^1.2 which is not installed" + }, + { + "code": "E027", + "message": "extension '@rust/deps' requires peer dependency '@rust/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@rust/deps": "deps" + }, + "extension_info": [ + [ + "@rust/deps", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_lint.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_lint.snap new file mode 100644 index 0000000000..01875f8f9e --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_lint.snap @@ -0,0 +1,51 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@rust/lint': collector 'rust-lint' declares the facts of kind 'item', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/lint': collector 'rust-lint' declares the facts of kind 'package', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/lint': collector 'rust-lint' answers the kind 'static_finding', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@rust/lint' requires peer dependency '@code/core' ^1.2 which is not installed" + }, + { + "code": "E027", + "message": "extension '@rust/lint' requires peer dependency '@rust/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@rust/lint": "lint" + }, + "extension_info": [ + [ + "@rust/lint", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_proof.snap b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_proof.snap new file mode 100644 index 0000000000..909b5eadc8 --- /dev/null +++ b/crates/session/project/tests/snapshots/tests__registry_build_snapshot__alone_rust_proof.snap @@ -0,0 +1,55 @@ +--- +source: crates/session/project/tests/registry_build_snapshot.rs +expression: "digest(&load(&runtime, &[name]))" +--- +{ + "check_passes": [], + "commands": [], + "diagnostics": [ + { + "code": "W021", + "message": "extension '@rust/proof': collector 'rust-proof' declares the facts of kind 'item', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/proof': collector 'rust-proof' declares the facts of kind 'package', which is not served: no loaded extension declares it collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/proof': collector 'rust-proof' answers the kind 'test', which no loaded extension declares collector-written" + }, + { + "code": "W021", + "message": "extension '@rust/proof': collector 'rust-proof' answers the kind 'test_run', which no loaded extension declares collector-written" + }, + { + "code": "E027", + "message": "extension '@rust/proof' requires peer dependency '@code/core' ^1.2 which is not installed" + }, + { + "code": "E027", + "message": "extension '@rust/proof' requires peer dependency '@rust/source' ^1.0 which is not installed" + } + ], + "edges": {}, + "ext_short": { + "@rust/proof": "proof" + }, + "extension_info": [ + [ + "@rust/proof", + "1.0.0" + ] + ], + "fields": {}, + "graph_inputs": { + "absent_targets": {}, + "derived_references": [], + "field_forms": {}, + "member_kinds": [] + }, + "kinds": {}, + "manifest_surfaces": [], + "rules": [], + "shadowed": 0 +} diff --git a/crates/surfaces/cli/src/doctor.rs b/crates/surfaces/cli/src/doctor.rs index dcfe47757b..ce0d6c29de 100644 --- a/crates/surfaces/cli/src/doctor.rs +++ b/crates/surfaces/cli/src/doctor.rs @@ -60,7 +60,8 @@ impl Args { .with_hosts(specforge_ops::host::diagnose::findings( &view, &renderers, caller, )) - .with_grants(&view, &consent); + .with_grants(&view, &consent) + .with_tools(&view, &*process); let credentials = User::current(std::sync::Arc::clone(&ports.git)).credential_health(); let found = OnPath::find(std::env::var_os("PATH").as_deref(), &*process); let path_binary = on_path::finding(found.as_ref(), &view); @@ -259,6 +260,7 @@ fn render_human( ("Rules", Part::Rule), ("Surfaces", Part::Surface), ("Toolchain", Part::Toolchain), + ("Tools", Part::Tools), ("Grants", Part::Grants), ("Hosts", Part::Host), ] { diff --git a/crates/surfaces/cli/tests/doctor_tools.rs b/crates/surfaces/cli/tests/doctor_tools.rs new file mode 100644 index 0000000000..d722cc4d0b --- /dev/null +++ b/crates/surfaces/cli/tests/doctor_tools.rs @@ -0,0 +1,156 @@ +// `specforge doctor` names the programs a detected collector runs that this machine lacks (ADR 0389 D3), through the +// real binary and its vendored builtins, with a PATH the test chooses. Unix only: the fake tool is a shell script. + +#[cfg(unix)] +use std::path::PathBuf; + +#[cfg(unix)] +use crate::support::{Cli, TestProject}; +#[cfg(unix)] +use serde_json::Value; + +/// A Rust crate that is also a TypeScript package, enabling packs whose collectors run cargo-nextest, +/// cargo-llvm-cov, Kani and api-extractor. +#[cfg(unix)] +fn project() -> TestProject { + TestProject::new() + .raw_config( + r#"{"extensions": ["@code/core", "@rust/cargo", "@rust/source", "@rust/test", "@rust/coverage", + "@rust/proof", "@javascript/source", "@javascript/api"]}"#, + ) + .file( + "Cargo.toml", + "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n", + ) + .file("src/lib.rs", "pub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n") + .file("package.json", r#"{"name": "demo", "version": "0.1.0"}"#) + .file("tsconfig.json", "{}\n") +} + +/// `/doctor-tools//`, holding `cargo-llvm-cov` when `with_llvm_cov`. The fake writes a marker file +/// beside itself if anything runs it. Parallel tests race safely: the script is written to a temporary name, made +/// executable, then renamed into place. +#[cfg(unix)] +fn path(name: &str, with_llvm_cov: bool) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")) + .join("doctor-tools") + .join(name); + std::fs::create_dir_all(&dir).unwrap(); + let tool = dir.join("cargo-llvm-cov"); + if with_llvm_cov && !tool.exists() { + let script = format!("#!/bin/sh\ntouch '{}'\n", marker(&dir).display()); + let tmp = dir.join(format!("cargo-llvm-cov.tmp.{}", std::process::id())); + std::fs::write(&tmp, script).unwrap(); + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::rename(&tmp, &tool).unwrap(); + } + dir +} + +#[cfg(unix)] +fn marker(dir: &std::path::Path) -> PathBuf { + dir.join("ran") +} + +/// Doctor's `about: tools` findings with `path` as PATH, and its exit code. +#[cfg(unix)] +fn tools(p: &TestProject, path: &std::path::Path) -> (Vec, Option) { + let out = Cli::on(p) + .command(&["doctor", "--format", "json"]) + .env("PATH", path) + .output() + .unwrap(); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + let found = report["findings"] + .as_array() + .unwrap() + .iter() + .filter(|f| f["about"] == "tools") + .cloned() + .collect(); + (found, out.status.code()) +} + +#[cfg(unix)] +fn programs(found: &[Value]) -> Vec<&str> { + found + .iter() + .map(|f| f["program"].as_str().unwrap()) + .collect() +} + +#[cfg(unix)] +#[specforge_test_macros::test(requirement = "FEATURE-021")] +fn doctor_names_each_missing_tool_as_a_note_and_still_exits_0() { + let p = project(); + let (found, code) = tools(&p, &path("absent", false)); + assert_eq!(code, Some(0)); + assert_eq!( + programs(&found), + [ + "api-extractor", + "cargo-kani", + "cargo-llvm-cov", + "cargo-nextest" + ] + ); + let installs = [ + ( + "api-extractor", + "npm install --save-dev @microsoft/api-extractor typescript", + ), + ( + "cargo-kani", + "cargo install --locked kani-verifier && cargo kani setup", + ), + ( + "cargo-llvm-cov", + "cargo install cargo-llvm-cov cargo-nextest --locked", + ), + ("cargo-nextest", "cargo install cargo-nextest --locked"), + ]; + for (finding, (program, install)) in found.iter().zip(installs) { + assert_eq!(finding["status"], "info", "{finding}"); + assert_eq!(finding["code"], "tool_missing", "{finding}"); + assert!( + finding["remediation"].as_str().unwrap().contains(install), + "{program}: {finding}" + ); + let codes: Vec<&str> = finding["codes"] + .as_array() + .unwrap() + .iter() + .map(|c| c.as_str().unwrap()) + .collect(); + assert!(!codes.is_empty(), "{finding}"); + assert!(codes.iter().all(|c| c.starts_with("code/")), "{finding}"); + if matches!(program, "cargo-llvm-cov" | "api-extractor") { + assert!(codes.contains(&"code/W104"), "{finding}"); + } + } +} + +#[cfg(unix)] +#[specforge_test_macros::test(requirement = "FEATURE-021")] +fn doctor_finds_a_tool_on_path_without_running_it() { + let p = project(); + let dir = path("llvm-cov", true); + let (found, code) = tools(&p, &dir); + assert_eq!(code, Some(0)); + assert_eq!( + programs(&found), + ["api-extractor", "cargo-kani", "cargo-nextest"] + ); + assert!(!marker(&dir).exists(), "doctor ran cargo-llvm-cov"); + + let human = Cli::on(&p) + .command(&["doctor"]) + .env("PATH", &dir) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&human.stdout); + assert!(text.contains("Tools:\n"), "{text}"); + assert!(text.contains("`cargo-kani` is not found here"), "{text}"); + assert!(!marker(&dir).exists(), "doctor ran cargo-llvm-cov"); +} diff --git a/crates/surfaces/cli/tests/explain_declared.rs b/crates/surfaces/cli/tests/explain_declared.rs index fddbf765d1..8443013392 100644 --- a/crates/surfaces/cli/tests/explain_declared.rs +++ b/crates/surfaces/cli/tests/explain_declared.rs @@ -45,6 +45,36 @@ fn explain_explains_a_code_the_projects_extension_catalogs() { ); } +/// The embedded `@code/core` catalogs the `reports` pass's codes (ADR 0388): each is explained with its owner, level +/// and title. +#[specforge_test(requirement = "FEATURE-017")] +fn explain_explains_the_report_warnings_of_code_core() { + let project = TestProject::new().without_config(); + project.write( + "specforge.json", + json!({"name": "p", "version": "0.1.0", "spec_root": "spec", "extensions": ["@code/core"]}) + .to_string(), + ); + let cli = Cli::on(&project); + let mut texts = Vec::new(); + for code in ["code/W104", "code/W105", "code/W106", "code/W107"] { + let entry = cli + .run(&["explain", code, "--format", "json"]) + .exits(0) + .json(); + assert_eq!(entry["code"], code, "{entry}"); + assert_eq!(entry["owner"], "@code/core", "{entry}"); + assert_eq!(entry["level"], "warning", "{entry}"); + assert_eq!(entry["retired"], false, "{entry}"); + assert!( + entry["title"].as_str().is_some_and(|t| !t.is_empty()), + "{entry}" + ); + texts.push(cli.run(&["explain", code]).exits(0).stdout); + } + insta::assert_snapshot!(texts.join("\n")); +} + #[specforge_test(requirement = "FEATURE-017")] fn outside_its_project_a_catalogued_code_is_unknown() { let loose = TestProject::new().without_config(); diff --git a/crates/surfaces/cli/tests/main.rs b/crates/surfaces/cli/tests/main.rs index 4d74935581..7bba6735df 100644 --- a/crates/surfaces/cli/tests/main.rs +++ b/crates/surfaces/cli/tests/main.rs @@ -25,6 +25,7 @@ mod determinism; mod diff; mod docs_relations; mod docs_truth; +mod doctor_tools; mod edit; mod edit_obligations; mod examples; diff --git a/crates/surfaces/cli/tests/snapshots/tests__explain_declared__explain_explains_the_report_warnings_of_code_core.snap b/crates/surfaces/cli/tests/snapshots/tests__explain_declared__explain_explains_the_report_warnings_of_code_core.snap new file mode 100644 index 0000000000..094c502c0b --- /dev/null +++ b/crates/surfaces/cli/tests/snapshots/tests__explain_declared__explain_explains_the_report_warnings_of_code_core.snap @@ -0,0 +1,58 @@ +--- +source: crates/surfaces/cli/tests/explain_declared.rs +expression: "texts.join(\"\\n\")" +--- +code/W104: A report entry names no item + +A fact a report reader minted cites no item, because the report's file or line +lies in no collected item (a macro expansion, top-level statements, or a file no +source pack collected), or because an API snapshot's entry has a path no +collected item has: a re-exported path whose definition path differs, an item a +macro generates, or a crate whose library is named apart from its package. A +static finding is reported only when no collected package holds its file either, +or it has no location. The entry is kept with what the report says of it, so +nothing is lost. Collect the source pack for those files (`@rust/source`, +`@javascript/source`) and the manifest pack for their packages, then collect the +report again. + +Owner: @code/core +Level: warning + +code/W105: A finding's rule or level is unknown + +A static finding's SARIF result states no rule (no `ruleId`, no `rule`, and no +rule index naming a rule of its tool's driver), or states no level (none on the +result, and none in its rule's `defaultConfiguration`): the field reads +`unknown`. The finding is kept, never dropped. SARIF's own default level is +`warning`; it is not applied, so a level the tool never wrote cannot pass for +one it did. Make the tool write its rule ids and levels in its SARIF output, or +the rule metadata (`tool.driver.rules` with a `defaultConfiguration.level`), +then collect the report again. + +Owner: @code/core +Level: warning + +code/W106: A dependency has no purl + +A component of a CycloneDX bill of materials carries no package URL (`purl`), so +its dependency is named by name and version only +(`dep:/@`). The dependency is kept, never dropped, but no +other report can be matched to it: an OSV scan or another BOM names a package by +its purl. Generate the BOM with an SBOM tool that writes a purl for every +component (cargo-cyclonedx, cyclonedx-npm), then collect it again. + +Owner: @code/core +Level: warning + +code/W107: A vulnerability's severity is unknown + +An OSV record of a vulnerability scan has no severity label +(`database_specific.severity`) and no CVSS v3 vector this reader rates: its only +severity entries are CVSS v4 or v2 vectors, or its v3 vector is malformed. The +vulnerability is kept with severity `unknown`, never dropped and never given a +guessed rating, so a gate on severity cannot pass it by mistake. Read the +advisory by its OSV id (osv.dev, or the database its id names) and judge its +severity there. + +Owner: @code/core +Level: warning diff --git a/crates/surfaces/lsp/tests/hover_declared.rs b/crates/surfaces/lsp/tests/hover_declared.rs index f6bea42bc1..0ad2becea7 100644 --- a/crates/surfaces/lsp/tests/hover_declared.rs +++ b/crates/surfaces/lsp/tests/hover_declared.rs @@ -19,6 +19,7 @@ fn hover_explains_a_third_party_code() { machine: false, reported_while: None, settled_later: false, + facts: Vec::new(), }], ) .unwrap(); diff --git a/crates/surfaces/mcp/src/tool/tests.rs b/crates/surfaces/mcp/src/tool/tests.rs index e5bea36a10..956f2e904c 100644 --- a/crates/surfaces/mcp/src/tool/tests.rs +++ b/crates/surfaces/mcp/src/tool/tests.rs @@ -216,6 +216,7 @@ fn a_result_meta_titles_a_code_from_the_project_code_book() { machine: false, reported_while: None, settled_later: false, + facts: Vec::new(), }], ) .unwrap(); diff --git a/crates/surfaces/mcp/src/tools/doctor.rs b/crates/surfaces/mcp/src/tools/doctor.rs index 22ecb14e9e..beb23c2926 100644 --- a/crates/surfaces/mcp/src/tools/doctor.rs +++ b/crates/surfaces/mcp/src/tools/doctor.rs @@ -33,7 +33,8 @@ impl CoreTool for Tool { let mut user = None; let consent = project.consent_or_users(&mut user); let report = specforge_ops::analysis::doctor::diagnose(&view, project.solver) - .with_grants(&view, consent); + .with_grants(&view, consent) + .with_tools(&view, &*project.ports.process); Ok(report.document().into()) } } diff --git a/crates/surfaces/mcp/tests/snapshots/tests__output_schemas__core_output_schema_sizes.snap b/crates/surfaces/mcp/tests/snapshots/tests__output_schemas__core_output_schema_sizes.snap index 61a35ac6bf..0193a0928b 100644 --- a/crates/surfaces/mcp/tests/snapshots/tests__output_schemas__core_output_schema_sizes.snap +++ b/crates/surfaces/mcp/tests/snapshots/tests__output_schemas__core_output_schema_sizes.snap @@ -28,7 +28,7 @@ specforge.providers 2978 specforge.settings 3694 specforge.settings_set 2850 specforge.verdict_inputs 1354 -specforge.doctor 7849 +specforge.doctor 8320 specforge.collect 3994 specforge.render 262 specforge.infer_progress 864 @@ -38,4 +38,4 @@ specforge.find_implementation 581 specforge.find_spec_for_source 735 specforge.prompt 283 specforge.diff 1905 -total 80344 +total 80815 diff --git a/crates/surfaces/mcp/tests/snapshots/tests__tool_arguments__core_tool_listing_today.snap b/crates/surfaces/mcp/tests/snapshots/tests__tool_arguments__core_tool_listing_today.snap index b266007a74..71ee00022f 100644 --- a/crates/surfaces/mcp/tests/snapshots/tests__tool_arguments__core_tool_listing_today.snap +++ b/crates/surfaces/mcp/tests/snapshots/tests__tool_arguments__core_tool_listing_today.snap @@ -8913,6 +8913,60 @@ expression: listing ], "type": "object" }, + { + "additionalProperties": false, + "properties": { + "about": { + "enum": [ + "tools" + ], + "type": "string" + }, + "check": { + "type": "string" + }, + "code": { + "type": "string" + }, + "codes": { + "items": { + "type": "string" + }, + "type": "array" + }, + "collectors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "program": { + "type": "string" + }, + "remediation": { + "type": "string" + }, + "status": { + "enum": [ + "error", + "warn", + "info" + ], + "type": "string" + } + }, + "required": [ + "check", + "status", + "code", + "remediation", + "about", + "program", + "collectors", + "codes" + ], + "type": "object" + }, { "additionalProperties": false, "properties": { diff --git a/docs/README.md b/docs/README.md index 1a796587bd..e262d987e5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -33,7 +33,7 @@ New here? Start with the [root README](../README.md), then [what SpecForge is fo | [Troubleshooting](guides/spec-troubleshooting.md) | Diagnostic codes and their fixes | | [Product getting started](guides/product-getting-started.md) | `@specforge/product`: personas, channels, journeys, features, milestones, releases | | [Formal verification](guides/formal-verification.md) | Machine-checkable bounds and claims proved with z3 | -| [Rust test tracing](guides/rust-test-tracing.md), [vitest test tracing](guides/vitest-test-tracing.md), [node --test facts](guides/node-test-facts.md), [Rust facts](guides/rust-facts.md), [JavaScript facts](guides/javascript-facts.md) | Link tests to the obligations they prove: `specforge collect`, `analyze coverage` | +| [Rust test tracing](guides/rust-test-tracing.md), [vitest test tracing](guides/vitest-test-tracing.md), [node --test facts](guides/node-test-facts.md), [Rust facts](guides/rust-facts.md), [JavaScript facts](guides/javascript-facts.md), [report facts](guides/code-report-facts.md) | Link tests to the obligations they prove: `specforge collect`, `analyze coverage` | | [Demo script](demo.md) | A walkthrough on `examples/shop`, then the same engine on a product plan | ## Examples diff --git a/docs/adr/0374-the-root-spec-runs-on-gsd-core-and-its-tests-name-requirements.md b/docs/adr/0374-the-root-spec-runs-on-gsd-core-and-its-tests-name-requirements.md index fd19cacff7..1bb055c74b 100644 --- a/docs/adr/0374-the-root-spec-runs-on-gsd-core-and-its-tests-name-requirements.md +++ b/docs/adr/0374-the-root-spec-runs-on-gsd-core-and-its-tests-name-requirements.md @@ -16,6 +16,12 @@ converter and its id map) and [ADR 0373](0373-gsd-core-is-vendored-on-a-pinned-r (the vendored blob the root now loads). No protocol, SDK, host-rule or attribute-grammar change comes with this decision. +D5 amended by [ADR 0388](0388-x2-is-the-share-of-test-ids-a-standard-report-saw.md): the dogfood check also prints +X2 for SpecForge, taskboard and ledger. + +D5 amended by [ADR 0393](0393-x2-is-a-floor-every-real-test-reaches-and-only-tests-count.md): guests and the @gsd +workspace write JUnit the step merges, and the guests-only count retires. + ## Context **What the swap moves.** This repository's own spec, `spec/` and `specforge.json`, was written in the old diff --git a/docs/adr/0388-x2-is-the-share-of-test-ids-a-standard-report-saw.md b/docs/adr/0388-x2-is-the-share-of-test-ids-a-standard-report-saw.md new file mode 100644 index 0000000000..9e6d570387 --- /dev/null +++ b/docs/adr/0388-x2-is-the-share-of-test-ids-a-standard-report-saw.md @@ -0,0 +1,126 @@ +# X2 is the share of items with a test id that a standard report saw + +**Status:** accepted (2026-11-22, round r6-breadth, Phase 10). **Amends** +[ADR 0374](0374-the-root-spec-runs-on-gsd-core-and-its-tests-name-requirements.md) D5 (the dogfood check also prints +X2). + +D2, D3 and the Consequences amended by +[ADR 0393](0393-x2-is-a-floor-every-real-test-reaches-and-only-tests-count.md): X2 is a floor on SpecForge, +taskboard, ledger and vault. + +## Context + +- Build-plan R6 exits on "X2 = 100% on taskboard and on SpecForge", and owner decision D3 of the round says what X2 + counts: the items that have a test id, and of those the ones a standard test report saw. Nothing defined the number + or computed it, so it could not be driven anywhere. +- Guests' tests run under `cargo test` and write no JUnit until Phase 14 moves them under nextest, so on SpecForge the + value is far from 100% today, and it need not be more: this round defines and prints it, Phase 14 drives it up. +- JavaScript items carry no `test_id`: `@javascript/source` mints every item with `test_id: None` + (`extensions/javascript/source/src/items.rs`), and only a Rust test function's item names its test's id. Taskboard + is a JavaScript project, so its X2 is `0/0` by construction whatever its JUnit holds (research finding F3). +- `@code/core` holds the code facts and their ids ([ADR 0329](0329-code-core-holds-test-facts-and-their-ids.md), + [ADR 0347](0347-item-and-package-facts-and-ids-a-scip-symbol-maps-into.md)); a library with no wasm is an rlib a + builtin links ([ADR 0328](0328-a-builtin-is-embedded-and-a-non-specforge-builtin-catalogues-its-codes.md) D3). + +### The readers this round adds + +Phase 10 also gives `@code/core` five report readers. Their decisions are recorded here, not in an ADR of their own, +so plans 10-02 to 10-07 implement a written design: + +- **Five kinds**, collector-written like the four before them: `coverage`, `static_finding`, `dependency`, + `vulnerability` and `api_item`. The SARIF kind is `static_finding`, not `finding` (F1): `@gsd/core` declares a + research `finding`, and a project loading both would get E026, the first registration winning + ([ADR 0369](0369-the-builtin-vocabulary-maps-a-kind-keyword-to-every-builtin-that-declares-it.md); the root + project loads both). `@code/core` goes to 1.2.0. +- **One rlib per format** under `extensions/code/`, named `specforge-code-` (`lcov`, `sarif`, `cyclonedx`, + `osv`, `api`). Each depends on `specforge-code-facts`, never the reverse, so a reader edit re-vendors only the packs + that link it (F2). The neutral models (`CoverageFile`, `SarifResult`, `Component`, `OsvRecord`, `ApiEntry`) and the + minters live in `specforge-code-facts`, beside `test_facts` and `item_facts`. +- **Ids and schemes.** `cov:`, and `cov:@` for the lines and functions no item holds; + `sarif:/#:`; `dep:/`; `vuln:/`; `api:rust:...` and + `api:js:...`. Report text that enters an id is percent-encoded, so a rule named `x#y` cannot forge a delimiter. + Every minter merges or suffixes a repeated id (`~2`, `~3`, in document order): the host refuses a collect that + answers one id twice (E116), so one repeat in a real report would drop all of it (F4). +- **SARIF level as the file states it**: the result's `level`, else its rule's `defaultConfiguration.level`, else + `unknown`. SARIF's own default `warning` is not applied, so `unknown` means "stated nowhere" (F5). +- **Severity of a vulnerability**: the record's `database_specific.severity` (GHSA's `MODERATE` read as medium), else + the highest CVSS v3 base score, computed by the v3.1 formula with the integer Roundup of its Appendix A (a score of + 0.0 reads low, the vocabulary having no `none`), else `unknown`. A record with only a v4 or a v2 vector is + `unknown`; nothing guesses. +- **What is the collector's error**, so nothing is minted: a report path outside the project, a malformed report, an + unsupported version (named in the error), a BOM whose root component matches no collected package, and an + osv-scanner lockfile no collected package holds. A vulnerability affects the packages at the lockfile's directory, + else those under it. +- **API snapshots** are `cargo public-api` text for Rust and api-extractor `.api.json` for JavaScript. An entry maps by + its qualified path against item ids; a re-exported path that differs from the definition's path maps to no item. +- **Unmappable entries are kept.** An entry that cannot be mapped is still minted, with `unknown` or no reference, and + the new check pass `reports`, sent only the five kinds + ([ADR 0353](0353-a-pass-reads-the-facts-it-declares.md)), raises one warning per class: `code/W104` an entry names + no item (a finding: no item and no package), `code/W105` a finding's rule or level is unknown, `code/W106` a + dependency has no purl, `code/W107` a vulnerability's severity is unknown. + +## D1. The definition + +Over one project's collected facts: + +- `m` is the number of `item` facts that carry a `test_id`; +- `n` is the number of those whose `test_id` is the id of a `test` fact; +- X2 is `n/m`, with the percent rounded down to one decimal, so `100.0%` is printed only when no item is missing: + `X2 : n/m (p%)`. When `m = 0` it prints + `X2 : 0/0 (no item has a test_id)` and no percent. +- A test of any status counts, a skipped one too: whether it passed is W401's to say, not X2's. +- The items it misses are the item ids with a `test_id` and no `test` fact, sorted, each on its own line under the + ratio, indented two spaces. + +The reason: X2 measures whether a standard report sees the tests the code declares, not whether they pass. Reading it +from the collected facts, not from a test list of its own, keeps it the same number every consumer would compute. + +## D2. A pure function the gate prints + +`gate/src/x2.rs` holds the computation, a pure function over the items' test ids and the test ids, tested on literal +input like `judge::requirement_verdict`. The `dogfood` check calls it and writes its lines to +`/gate/dogfood.log`. It is print only: no floor fails the check until Phase 14 asserts 100% with a negative +control. A failed collect or export of an X2 project is an error of the check, since then no number was computed; the +number itself never is. So is an export of another shape (no `nodes` array, a node with no `id` or `kind`), which would +otherwise read as `0/0`; and when the requirement verdict already fails the check, an X2 error is still logged. `doctor` may call the same function later (Phase 11 owns `doctor`). + +The reason: guests are not under nextest yet, so any floor now would be either meaningless or red; the gate already +collects the root for `dogfood`, so X2 costs no second collect of it. + +## D3. The projects + +Three projects print, in this order: + +- **SpecForge**: the collected dogfood tree `dogfood` already builds. +- **taskboard**: a scratch copy of `gsd/parity/fixtures/taskboard` collected by `javascript-source` and by `node-test` + over its recorded node-test JUnit (`gsd/parity/goldens/taskboard/junit.xml`, `--no-run`). It prints `0/0` (F3). +- **ledger**: a scratch copy of `gsd/parity/fixtures/ledger` collected by `rust-cargo`, `rust-source` and `rust-test` + over its recorded nextest report (`gsd/parity/goldens/ledger/rust-test.xml`): a non-zero denominator, so the ratio + is shown on a project where it means something. + +The scratch copies live under `/gate/x2/`, emptied first; the tracked fixtures are never written. + +The reason: D3 of the round names taskboard and SpecForge. Taskboard's denominator is empty by construction, so ledger +is added to show the computation on real test ids; a further fixture is one more row. + +## Rejected + +- **Computing X2 in `doctor` now.** Phase 11 owns `doctor`; the gate already collects what X2 reads. +- **A failing floor now.** Guests run under `cargo test` until Phase 14; a floor would be red or set to the current + value and mean nothing. +- **Counting JavaScript test files instead of test ids.** It would give taskboard a number, but a different number from + a different definition. A later round may change the definition for JavaScript; this one records it as it is. +- **A second ADR for the readers.** Their decisions are small and belong to the same phase; they are this ADR's + context. + +## Consequences + +- Phase 14 moves the guests' tests under nextest and asserts X2 at 100% on SpecForge and ledger, with a negative + control. +- Phase 11's packs mint the five kinds with the ids above, and run the tools whose reports the readers take. +- Plans 10-03 to 10-07 declare `code/W104` to `code/W107` in `@code/core`, each with the kind it judges. +- Taskboard reads `0/0` until JavaScript items carry a test id or the definition changes. +- Once `@code/core` 1.2.0 is loaded, `coverage`, `api_item`, `static_finding`, `dependency` and `vulnerability` are + kind names, and a project entity with one of them is error E013. The frozen `fixtures/old-spec` has `term coverage`, + so the migrate test that loads it expects exactly that one E013 (ADR 0374 D8 forbids editing the corpus). The owner + accepted the names on 2026-11-22; renaming them would re-vendor every blob that links `code-facts`. diff --git a/docs/adr/0389-report-packs-run-standard-tools-and-doctor-names-a-missing-one.md b/docs/adr/0389-report-packs-run-standard-tools-and-doctor-names-a-missing-one.md new file mode 100644 index 0000000000..085aebcb79 --- /dev/null +++ b/docs/adr/0389-report-packs-run-standard-tools-and-doctor-names-a-missing-one.md @@ -0,0 +1,190 @@ +# Report packs run standard tools, and doctor names a missing one + +**Status:** accepted (2026-11-23, round r6-breadth, Phase 11). Amended by +[ADR 0390](0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md) (D9: every +accepted risk listed). **Amends** +[ADR 0348](0348-a-collector-declares-a-config-file-and-the-rust-packs.md) (a report may be a glob; the host reports a +collector's warnings). **Follows** [ADR 0388](0388-x2-is-the-share-of-test-ids-a-standard-report-saw.md) (the readers +and kinds), [ADR 0329](0329-code-core-holds-test-facts-and-their-ids.md) and +[ADR 0347](0347-item-and-package-facts-and-ids-a-scip-symbol-maps-into.md) (test, item and package ids), +[ADR 0345](0345-the-syntax-import-and-collectors-that-read-answer-and-are-served-facts.md) (collectors served facts), +[ADR 0369](0369-the-builtin-vocabulary-maps-a-kind-keyword-to-every-builtin-that-declares-it.md) (builtin +vocabulary), [ADR 0328](0328-a-builtin-is-embedded-and-a-non-specforge-builtin-catalogues-its-codes.md) (extension +libraries), [ADR 0293](0293-a-pass-or-command-declares-the-project-files-it-reads.md) D4 (the walk rules) and +[ADR 0373](0373-gsd-core-is-vendored-on-a-pinned-rustc-with-its-load-and-size-measured.md) D3 (the size budget rule). + +## Context + +- Phase 10 gave `@code/core` five report readers (`specforge-code-{lcov,sarif,cyclonedx,osv,api}`) and five kinds + (`coverage`, `static_finding`, `dependency`, `vulnerability`, `api_item`), but no pack runs a tool whose report they + read. Requirements PACK-01 to PACK-07 ask for those packs, Rust and JavaScript, and for `specforge doctor` to name a + tool the machine lacks with the codes that then cannot be judged. +- The guest never runs anything: the host runs the declared argv with consent, reads one report (a file, or the + `*.json` files directly in a directory) or the captured standard output, and hands it to the pure export. It cannot + pipe, and it sets no variable but `SPECFORGE_REPORT`. +- A protocol-types or SDK change makes every builtin blob stale, and blobs rebuild on linux/amd64 only. So every + protocol and host change the packs need lands first (plan 11-01) and the series re-vendors once (plan 11-09). +- Two reader outcomes had no way to reach the user: `Vulnerabilities::skipped` (records that minted nothing) and a + report path outside the project, which made the LCOV and SARIF readers fail the whole report. + +## D1. Twelve packs, one crate and one blob each + +Rust: `@rust/coverage`, `@rust/lint`, `@rust/deps`, `@rust/api`, `@rust/proof`. JavaScript: `@javascript/coverage`, +`@javascript/lint`, `@javascript/deps`, `@javascript/api`, `@javascript/vitest`, `@javascript/jest`, +`@javascript/playwright`. Each peers `@code/core` and its source pack (`@rust/source` or `@javascript/source`). The two +`deps` packs hold two collectors each (CycloneDX and OSV), because a collector runs one command: fourteen collectors. +Every pack joins both builtin families (`Family::Old` and `Family::Gsd`); the legacy `@specforge/vitest` stays in +`Family::Old` beside `@javascript/vitest` (owner decision D4). vitest, jest and Playwright report JUnit XML, read by +`specforge-code-junit`; their test ids and places follow `@javascript/node-test`. + +## D2. Kani for Rust only: no JavaScript proof pack + +`@rust/proof` runs Kani. There is no JavaScript proof pack, because no JavaScript tool proves a property of all inputs +and reports per-harness verdicts the way Kani does: property-based testing such as fast-check samples inputs and +already reports as tests through the runner packs, and TypeScript's checker proves types, not behaviour. A JS proof +pack would be a test runner under another name. Owner decision D2. + +## D3. Doctor's tool notes + +- The program is the collector argv's first item, probed through the process port's `which`. Existence checks only: + nothing is run. +- A collector whose command runs another program declares it in `requires` (`CollectorDescriptor.requires`, protocol + 2.3.0; the SDK's `.requires(&[..])`): `rust-coverage`'s `cargo-llvm-cov llvm-cov nextest` requires `cargo-nextest`. + Doctor looks each up on PATH as it does the first, and a missing one is its own note naming the collector and its + install line (which installs all its programs). A name that is no bare program name is W021 and never looked up. +- For `npx --no -- ` the program is ``, present when `node_modules/.bin/` (or `.cmd`) is under the + project root, or under an npm workspace package directory the root `package.json` names (`workspaces`: a literal + directory or `dir/*`), or `which` finds it. Every file check is held by the project's containment, so nothing above + the root is read: a binary hoisted to a parent directory is not seen, and the note says it is missing. For + `node … node_modules//…` it is `node` and the script, the note naming ``. +- Only collectors detected in this project are probed. +- One Info note per missing program, grouped (two collectors on one program give one note), with the union of their + codes and the collector's install line (ADR 0348 D4). +- The codes are every loaded code whose `facts` (D4) meet the missing collectors' `answers` and meet no kind a + runnable detected collector answers (its program found, or no program at all, like a source reader), derived + through `Codebook::switched_off`, never hand-written per pack: a code that judges a kind another collector still + answers is still judged, so it is not named. +- A missing tool never fails doctor: `ok()` does not change. + +## D4. `CodeDescriptor.facts`, declared once by `@code/core` + +A code entry may name the collected fact kinds it judges (`facts`, protocol 2.3.0; the SDK's `.facts(&[..])`), so a +host can say which codes no finding can speak for when no collector answers those kinds. `@code/core` declares it on +its own codes once. It is absent from the wire when empty, so a code about authored entities keeps today's bytes. The +registry keeps it on the code book and does not validate the kind names: a kind no extension declares is simply never +matched (T-11-06 accepted). + +## D5. `CollectOutput.warnings` and W203 + +A collector's output may carry `warnings` (protocol 2.3.0): lines about entries it read but could not use. The host +reports each as one core W203 naming the collector and its extension, escaped through `printable`, at most 100 per +collector and then one W203 counting the rest. The facts it did answer are kept. A warning is never an error: an error +is the export's `Err`, and fails the collect as before. + +## D6. A report may be a glob + +cargo-cyclonedx writes `.cdx.json` beside each member manifest and has no output path, so `report(...)` accepts +a project-relative glob (`**/rust-sbom.cdx.json`). Its last segment is a literal file name, so a glob names the files +one tool writes and never every file of a kind (`**/*`, `**/*.pem`, `**/.env*`): the SDK's `report` panics on a +wildcard there, the registry refuses a raw declaration of one (E030), and the host's collect refuses it too (E058). +After a run the host reads every match modified since the run started; with `--no-run`, every match. A report's files +hold at most 64 MiB together (`REPORT_BYTES_MAX`, a captured output's cap), past which the collect is E045. The walk is `Input::files`' own (`glob_paths`, ADR 0293 D4): directories in +`SKIPPED` (`target`, `node_modules`, …) are not entered unless the glob names them, a directory reached through a link +is not entered, and the walk stops at 20,000 entries, which is E045 naming the cap. Each match is held by containment: +one whose link lands outside the project is never read, and one W203 per collector names such matches (the E045 +"produced no report" names them too when no other match was read). Nothing is removed before the run, and the command is told no +path: `{report}` in the argv or config, or `capture_stdout()`, beside a glob is E058, and `SPECFORGE_REPORT` is not +set. No match is the usual E045 ("produced no report"). + +## D7. The LCOV and SARIF readers skip a path outside the project + +A file record whose path lies outside the project is skipped and counted, and the count is surfaced as a W203 line, +instead of failing the whole report. The readers still touch no file system, so ADR 0388's threat holds. A SARIF +artifact with a non-`file` URI scheme still fails the report. A path naming no file is not "outside": one that +resolves to the project root itself (`.`, `a/..`, the root's absolute path) or a compiler's pseudo name in angle +brackets (rustc's ``, ``) is `Place::NoFile`. SARIF and clippy skip and count such a result in a +warning line of its own, never minting a finding at a file no one can open; an LCOV `SF` naming no file fails the +report, as an empty `SF` does. + +## D8. The commands per pack + +| Collector | argv (first items) | Report | Filter | Install line | +|-----------|--------------------|--------|--------|--------------| +| `rust-coverage` | `cargo-llvm-cov llvm-cov nextest --workspace --ignore-run-fail --lcov --output-path {report}` | `.specforge/reports/rust-coverage.lcov` | none | `cargo install cargo-llvm-cov --locked` | +| `rust-lint` | `cargo-clippy clippy --workspace --all-targets --message-format=json` | captured stdout under `.specforge/reports/rust-lint` | none | `rustup component add clippy` | +| `rust-sbom` | `cargo-cyclonedx cyclonedx --format json --override-filename rust-sbom.cdx …` (the tool appends `.json`) | glob `**/rust-sbom.cdx.json` | none | `cargo install cargo-cyclonedx --locked` | +| `rust-osv` | `osv-scanner scan source --lockfile Cargo.lock --format json --output {report}` | `.specforge/reports/rust-osv.json` | none | `brew install osv-scanner` (or the release binary) | +| `rust-api` | `cargo-public-api --color never -ss` | captured stdout under `.specforge/reports/rust-api` | `--package {filter}` | `cargo install cargo-public-api --locked` | +| `rust-proof` | `cargo-kani --workspace --output-format regular` | captured stdout under `.specforge/reports/rust-proof` | `--harness {filter}` | `cargo install --locked kani-verifier && cargo kani setup` | +| `javascript-coverage` | `npx --no -- c8 --reporter=lcovonly --reports-dir=.specforge/reports/javascript-coverage …` | `.specforge/reports/javascript-coverage` | none | `npm install --save-dev c8` | +| `javascript-lint` | `npx --no -- eslint --format @microsoft/eslint-formatter-sarif --output-file {report}` | `.specforge/reports/javascript-lint.sarif` | none | `npm install --save-dev eslint @microsoft/eslint-formatter-sarif` | +| `javascript-sbom` | `npx --no -- cyclonedx-npm --output-format JSON --spec-version 1.6 --package-lock-only …` | `.specforge/reports/javascript-sbom.cdx.json` | none | `npm install --save-dev @cyclonedx/cyclonedx-npm` | +| `javascript-osv` | `osv-scanner scan source --lockfile package-lock.json --format json --output {report}` | `.specforge/reports/javascript-osv.json` | none | `brew install osv-scanner` (or the release binary) | +| `javascript-api` | `npx --no -- api-extractor run --local --config {config}` | `.specforge/reports/javascript-api.api.json` | none | `npm install --save-dev @microsoft/api-extractor typescript` | +| `javascript-vitest` | `npx --no -- vitest run --reporter=default --reporter=junit --outputFile.junit={report}` | `.specforge/reports/javascript-vitest.xml` | `-t {filter}` | `npm install --save-dev vitest` | +| `javascript-jest` | `node --env-file={config} node_modules/jest/bin/jest.js --reporters=default --reporters=jest-junit` | `.specforge/reports/javascript-jest.xml` | `-t {filter}` | `npm install --save-dev jest jest-junit` | +| `javascript-playwright` | `npx --no -- playwright test --reporter=junit …` | captured stdout under `.specforge/reports/javascript-playwright` | `--grep {filter}` | `npm install --save-dev @playwright/test` | + +The plan that builds each pack fixes its exact argv and names; this table is the design they implement. + +A captured output that cannot be told from a clean run is never read as one. clippy's capture without cargo's last +`build-finished` record is a run cut off (killed between two lines), and is the collector's error. Kani's and +cargo-public-api's captures with nothing read are a warning (W203) saying nothing was checked or recorded, not an +error: "no harness" and "no public item" are real outcomes the text cannot tell from a tool that stopped at the build, +a wholly empty capture is already the host's E045, and an export's error would fail the whole collect. + +## D9. Tool limits, accepted and documented + +- vitest's and jest's `-t` filters match test names, not ids. +- jest needs `jest-junit` installed in the project and runs through `node --env-file`, because the report path reaches + jest-junit only through a variable. +- Playwright reports paths relative to its `testDir`. +- `cargo public-api` reads one package per run (the root package; the filter names another) and needs a nightly + toolchain. +- api-extractor reads built declarations: the pack's config names `/dist/index.d.ts` as its entry, so + the project builds them there first; the pack runs no build. +- Each risk below is accepted, and each runs only after the collector's command is approved; the consent prompt shows + the command. + - The coverage packs and the runner packs (vitest, jest, Playwright) run the project's own tests. + - osv-scanner sends the project's package names and versions to the OSV API. + - ESLint loads the project's own plugins and configuration code. + - Kani builds and model-checks the project's code. + - cargo-cyclonedx, cargo public-api and clippy run the project's build scripts. +- osv-scanner exits 1 when it finds vulnerabilities, which the host does not judge: it reads the report whatever the + exit code. + +## D10. Kani ids + +`@rust/proof` mints `rust:#` (`TestId::rust`), the crate found as the one whose served items hold +every harness of a `Complete` block. `@rust/source` is unchanged. + +## D11. Enablement and size + +`specforge init` enables none of the packs. `TOTAL_BUDGET` is measured once the blobs exist and raised by ADR 0373 +D3's rule. + +## D12. Windows + +Kani is unsupported on Windows (documented). The `npx` and `node --env-file` routes are unverified on Windows, and +said so. + +## D13. The five report kind names stay + +A project loading `@code/core` cannot name an entity `coverage`, `api_item`, `static_finding`, `dependency` or +`vulnerability` (E013), as ADR 0388 records. Renaming them would re-vendor every blob that links `code-facts` for no +gain the owner asked for. + +## Rejected + +- **A collector `switches_off` field.** Twelve packs would restate one table, and drift from the codes' own passes. + The code says what it judges once (D4). +- **A shared pack library.** It would be an input of every pack blob, so a change to it would re-vendor all twelve. +- **Running `npx --no -- --version` in doctor.** It executes project code; existence checks run nothing. + +## Consequences + +- One re-vendor for the whole series (plan 11-09); the `builtins` gate check is red until then. +- The readers' out-of-project tests change from "fails the report" to "skips and counts". +- W102 names every runner pack. +- `CollectOutput.warnings`, `CodeDescriptor.facts` and report globs join the 2.3.0 protocol row; a host that does not + know them ignores them. diff --git a/docs/adr/0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md b/docs/adr/0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md new file mode 100644 index 0000000000..84cd41b8a8 --- /dev/null +++ b/docs/adr/0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md @@ -0,0 +1,197 @@ +# A milestone computes its API breaks and release evidence, and two guards read them + +**Status:** accepted (2026-11-23, round r6-breadth, Phase 12). **Builds on** +[ADR 0370](0370-gsd-core-holds-exactly-gsd-cores-kinds-and-fields.md) D1 (`@gsd/core` holds gsd-core's kinds, and +SpecForge adds computed values, collected facts and guards), [ADR 0364](0364-the-software-kinds-are-dropped-and-a-census-gives-every-old-kind-its-fate.md) +D3 (a release is a version milestone), [ADR 0353](0353-a-pass-reads-the-facts-it-declares.md) (a pass reads the facts +it declares; a guard reads the graph and its computed values), [ADR 0335](0335-the-host-owns-every-effect-through-one-effect-plane.md) +D2.2 and D4 (which call kinds reach a port), [ADR 0287](0287-who-writes-a-field-is-declared.md) (who writes a field), +[ADR 0366](0366-gsd-core-is-vendored-as-a-builtin-with-a-size-allowance-of-its-own.md) D3 and +[ADR 0373](0373-gsd-core-is-vendored-on-a-pinned-rustc-with-its-load-and-size-measured.md) D3 (the size rule), +[ADR 0389](0389-report-packs-run-standard-tools-and-doctor-names-a-missing-one.md) (the API packs, the report read) and +[ADR 0360](0360-the-self-spec-moves-to-gsd-core-by-a-one-time-converter.md) D13 (a host-run command's environment). +**Amends** ADR 0389 D9 (every accepted tool risk listed). + +## Context + +- The round asks `specforge check` to tell a user about a breaking change to a public API (`gsd/E533`) and about a + release problem (`gsd/E535`), on the kinds `@gsd/core` already has. The owner decided so on 2026-11-23: no new kind, + computed fields and guards only. +- Phase 11's API packs (`@rust/api`, `@javascript/api`) collect `api_item` facts of the current code, and `@code/core` + collects `package` facts with a `version`. Nothing says what the API was when it was last accepted, nothing reads + `api_item` or `package` in `@gsd/core`, and no rule looks at a tag. +- A milestone's id is its version (`v1.7`, ADR 0364 D3, ADR 0372 D4). GSD tags a milestone after + `close-milestone`. + +## D1. No `interface` and no `release` kind + +ADR 0370 D1 and ADR 0364 D3 stand. `@gsd/core` declares the same 61 kinds. `milestone` gains two computed fields, +`api_breaks` (D4) and `release` (D6), and one harness field, `tag` (D6), written by `@gsd/core`'s own `gsd-git` +collector. An API item and a package are `@code/core` facts; a release is a version milestone. + +## D2. E533 and E535 are used for the first time, with new meanings + +The round's README says ADR 0370 lists E533 and E535 as historically used. It does not: ADR 0370 removed `gsd/W530`, +`gsd/E531`, `gsd/W532`, `gsd/W534`, `gsd/I536`, `gsd/W538` and `gsd/E537` only. E533 and E535 were proposed in an +earlier round for the never-built `interface` and `release` kinds, and no code ever declared them. This ADR gives them +their first, and new, meanings: E533 a breaking API change the milestone's version does not allow (D5), E535 a release +whose tag, package versions or order is wrong (D6). `@gsd/core`'s codes go from 73 to 75. + +## D3. The accepted API side is a committed, accepted report + +The owner chose the tools' own baseline: a report the project commits and accepts. + +- **Files.** JavaScript: api-extractor's `etc/.api.md`, and rush's `common/reviews/api/*.api.md`. Never + `**/*.api.md`, which matches api-extractor's `temp/` copy, and never the `*.alpha.api.md`, `*.beta.api.md` or + `*.public.api.md` variants. Rust: cargo-public-api's `**/public-api.txt`, written with the pack's own flags + (`cargo public-api --color never -ss > public-api.txt`). +- **The read.** The packs read the accepted file through `Input::files(..).text_up_to(..)` (containment, link refusal, + credential withholding), not through the report machinery: a report is read only when it is fresh since the run, and + a committed file is not. `FileRead.text_max` is a protocol 2.3.0 addition with no bump: a per-read text ceiling of + at most 4 MiB, the read's budget the larger of 1 MiB and four times it. +- **One fact per item.** The packs classify each item and set `change` (`added`, `unchanged`, `changed`, `narrowed`, + `removed`) and `accepted_signature`, `accepted_tag`, `accepted_visibility` on the same `api_item` fact, under the + same id. An item that is gone is a fact with `change` `removed`. `@code/core` 1.4.0 declares the fields, and W104 + skips a removed item (it names no item of the current code). +- **Pairing.** Only a crate or package present on both sides is judged. Accepted `@internal` entries are skipped. The + tag order is Public, Beta, Alpha, Internal; a member without its own tag inherits its container's, so narrowing a + class narrows each member. Items pair by base id, then by comparable signature, never by an `~N` overload suffix. +- **Breaking** is `changed`, `narrowed` or `removed`. An added item is not breaking. +- **Limits, stated.** A required method added to a trait cannot be seen in the text. A Rust visibility narrowing reads + as `removed`, because cargo public-api prints public items only. An attribute change (`#[non_exhaustive]`, + `#[must_use]`) reads as `changed`. A tool upgrade can change every line, so the accepted file is regenerated with the + version CI runs. +- **Outcomes.** No accepted file: silence (the committed report is the opt-in). An unparseable one of the run's own + crate or package (by its `pub mod ` line or its report title), or two of one crate or package: the + collector's Err naming the files. An unusable one (`too_large`, `budget`, `not_utf8`, no report or snapshot at all, + or naming no crate or package the run read, parseable or not): one W203 naming it, and the collect goes on, so a + stray `etc/notes.api.md` or a conflicted sibling package stops no collector. +- **Accepting a break.** api-extractor's `apiReport` stays disabled in the pack's config (T-11-26), so the pack writes + no accepted file. A user accepts a break by committing the updated report from their own + `api-extractor run --local` or `cargo public-api --color never -ss > public-api.txt`. + +## D4. `milestone.api_breaks` is a selection, computed in derive + +`derive` selects; it holds no format knowledge and diffs nothing. `api_breaks` is one ` ` line +per fact whose `change` is `changed`, `narrowed` or `removed`, sorted by id, at most 50 lines and then one +`more ` line. It is written on each milestone that is neither shipped nor abandoned, and only when some `api_item` +fact carries `change`: absent means never observed, empty means clean. It reflects the last `specforge collect`. + +## D5. What E533 judges + +At the milestone gate, a subject milestone with a non-empty `api_breaks` is refused unless its version is not +API-compatible with the last shipped milestone of the same workstream scope. Compatibility is Cargo's rule: two +versions are compatible when they agree up to and including the first non-zero component of the older one, so for +`0.x` a minor bump counts as major. + +- **Last shipped:** the other shipped milestones of the scope whose name is a version, the latest by their `shipped` + date, ties broken by the higher version, the subject excluded. A shipped milestone whose name is not a version (an + `mvp`, a release candidate `v1.7-rc1`) is no release to compare with: E533 and E535 both skip it. No such + milestone: allowed (a first release). +- **Not a version:** a subject name that is not a version (`v1.7`, `1.7`, `v1.7.2`: one to three numeric parts) + makes E533 fire, saying no major bump can be shown. +- **Findings:** one error per broken item, at most 25, then one summary error. Each echoed id is escaped (`quoted`). + +## D6. What E535 judges, and where git is read + +- **The tag, by the owner's route.** The `gsd-git` collector, a Collect call that may use the git port, looks up + `refs/tags/v` with the port's existing `commit` verb (no new verb; no log walk is needed, and an annotated + tag resolves to its commit) for each shipped milestone whose name is a version, when `git.create_tag` is not false + and the clone is not shallow. It writes the harness field `milestone.tag {name, commit}`, `commit` absent when the + tag does not resolve. The derive pass copies it into `milestone.release {tag, commit}`. +- **Why not derive.** The research's route, the derive pass calling `git::commit` itself, cannot run: a pass is a pure + call kind. `Operation::is_effectful` is true only for a command, an MCP tool or resource and a collector; ADR 0335 D4 + answers a pure kind `denied(call-kind)` and nothing runs; and a pass's cache key is its payload (ADR 0353 D4), which + a git answer read mid-call would not be part of. The test + `a_pure_call_that_calls_a_port_is_denied_its_call_kind` holds the rule. +- **Packages.** For an unshipped subject, `release.packages` holds the `name` and `version` of every `package` fact + with a `version` that does not equal the milestone's, less the names in `specforge.release_exempt`. Equal compares + the first max(2, the milestone's parts) numeric components; a `+build` suffix is ignored; a pre-release is not + equal. At most 50 packages, and `release.more` counts the rest: a separate member, so no package name reads as the + count. A package with no version is not judged. +- **Backwards.** An unshipped subject whose version is not later than the last shipped one of its scope (D5's rule for + "last shipped"). +- **Order.** GSD tags after `close-milestone`, so the milestone being closed has no tag yet. The tag part judges the + last shipped milestone of the subject's scope (the release before this one must be tagged before the next one + closes), or the subject itself when it is already shipped. The package and backwards parts judge the milestone being + closed. +- **Not judged.** A subject whose name is not a version (there is no version to release; E533 already fails closed on + it). No observation is silence: no repository, a shallow clone, `git.create_tag` false, no `package` fact with a + version, no `tag` written. +- **Limits.** A tag that resolves locally is not proof that it was pushed. A backport (`v1.6.1` after `v1.7`) reads as + backwards. `package` facts carry no publish marker, so a workspace of internal crates lists them in + `specforge.release_exempt`. + +## D7. The gate + +E533 and E535 are gate codes of the `complete_milestone` prompt and the `close_milestone` command only. A guard answers +only at a gate, so `specforge check` shows the computed fields, and the refusal comes at `/gsd-complete-milestone` or +`specforge gsd close-milestone`, as E515's does. Both are silent on a write and at a phase or a plan gate. + +## D8. Settings and profiles + +`specforge.interface_gate` (E533) and `specforge.release_gate` (E535) are bool gates (ADR 0305), preset `false`, +`true`, `true` for `gsd-compat`, `gsd-strict` and `gsd-plus`: gsd-core has no such rule, so compat stays silent. +`specforge.release_exempt` is a string list, empty by default. + +## D9. The twins + +Success criterion 5 is measured as the harness's `codes()` empty for the taskboard and ledger twins under the three +profiles, the vault twin's `codes()` equal to the set it carried before this decision (W019, gsd/W103, two +gsd.security/E101 for the duplicate threat it exists to carry, W302 and W303 for its judged security verdicts), and no +W407, E533 or E535 for any twin at its close gate. A raw `specforge check` keeps owed judged warnings in every +profile, so it is not the measure. W407 is silenced by each twin's own setting `specforge.task_commits: false` (the +twins record no commits), held in a committed `specforge.json` of the fixture that the test harness merges under a +test's own settings. The ledger's crate is `0.1.0` under milestone `v1.0`; bumping the fixture or exempting it moves no +golden either way, so the twin keeps its real crate version and lists `ledger` in its own +`specforge.release_exempt`. + +## D10. Absorb and route + +No absorb row is added: no old field carries a tag, a package version or an API break. An old `release` converts to a +version milestone (ADR 0372 D4), and `release_date` stays dropped, since `shipped` is computed. A `milestone-release` +trace route shows `api_breaks`, `release` and `tag`. + +## D11. Size + +The `gsd_core` allowance (5,800,000 B) and the builtins' `TOTAL_BUDGET` are re-measured at the phase's single +re-vendor, by ADR 0366 D3 and ADR 0373 D3's rule. + +## D12. Carried security items + +- **O-1.** The jest and Playwright pack docs said the run inherits no `JEST_*` or `PLAYWRIGHT_*`. A host-run collector + command keeps the caller's environment less credentials (ADR 0360 D13, ADR 0335 D4), so the docs are corrected and + no `inherit` is passed: Node's `--env-file` does not override a variable already set, and the residual is accepted. +- **O-2.** The report read (`read_held` in collect's dispatch) reads through `Containment::read_held`, which refuses a + file with more than one name when the containment is bounded (ADR 0146), so a hard link to a file outside the + project is E045 there. The CLI is unbounded by design (ADR 0092 D6) and still reads it. Test: + `a_hard_linked_report_is_refused_in_a_bounded_containment`. The accepted file is a declared file read, not a report: + a call's and an analyze pass's `Input::files` read each file through the same containment + (`Containment::file_reads_disk`, walked as the plain disk), so a bounded one gives a hard-linked file + `error: "unreadable"` and the pack's W203. Test: `a_hard_linked_accepted_file_is_not_read_in_a_bounded_containment`. +- **O-3.** ADR 0389 D9 now lists every risk the packs' approvals accept. + +## Rejected + +- **New `interface` or `release` kinds.** ADR 0370 D1 and ADR 0364 D3 stand (D1). +- **The derive pass calling git** (D6): a pass is a pure call kind and its cache key is its payload. +- **A collector fact kind for the tag.** A harness field on the milestone it names says the same, and `derive` reads + the graph it is handed. +- **The `semver` crate.** It refuses `1.7`, and grows the blob; the comparison is a few lines over numeric parts. +- **E533 at a phase gate.** A break is allowed or refused by the release it ships in. +- **Reading `**/*.api.md`.** It matches api-extractor's `temp/` copy (D3). +- **The report machinery for the accepted file.** Its freshness rule skips a committed file (D3). +- **A second fact per item, or an accepted id scheme.** One fact per item, same id, keeps W104 and the anchors as they + are (D3). +- **`inherit` for the packs' env lists** (D12, O-1). +- **The doc model `.api.json` as the committed baseline.** api-extractor's own reviewed file is the `.api.md` report. + +## Consequences + +- E533's rules are proved by a failing and a passing case each in `@gsd/core`'s unit tests (the version functions, + `api_breaks`, the guard) and end to end at the close gate; E535's likewise (`release`, the `gsd-git` tag lookup, the + guard). The twins stay at zero codes under the three profiles. +- `@gsd/core` declares 75 codes; every pin of the code count follows (the parity evidence, the codebook golden, the + guard list, the README and the acceptance file). +- `@code/core` goes to 1.4.0 and the API packs peer `^1.4`. +- The phase re-vendors once; the `gsd_core` allowance and `TOTAL_BUDGET` are re-measured then (D11). diff --git a/docs/adr/0391-gsd-import-reads-a-planning-folder-once-into-one-edit-plan.md b/docs/adr/0391-gsd-import-reads-a-planning-folder-once-into-one-edit-plan.md new file mode 100644 index 0000000000..d33e063fb6 --- /dev/null +++ b/docs/adr/0391-gsd-import-reads-a-planning-folder-once-into-one-edit-plan.md @@ -0,0 +1,228 @@ +# `specforge gsd import` reads a `.planning/` folder once into one edit plan + +**Status:** accepted (2026-11-24, round r6-breadth, Phase 13). **Builds on** +[ADR 0289](0289-an-extension-writes-through-an-edit-plan-the-host-applies.md) (an extension writes through one edit +plan, applied all or nothing), [ADR 0293](0293-a-pass-or-command-declares-the-project-files-it-reads.md) (a command +declares the project files it reads, by static globs), [ADR 0287](0287-who-writes-a-field-is-declared.md) (who writes a +field), [ADR 0290](0290-a-judged-rule-holds-while-a-fresh-verdict-says-so.md) and +[ADR 0377](0377-a-verdict-is-fresh-over-what-it-cites-and-owed-by-its-owner-state.md) (verdicts, their origin, what +owes one), [ADR 0301](0301-a-human-attested-command-runs-only-for-a-person-at-a-terminal.md) (human commands), +[ADR 0366](0366-gsd-core-is-vendored-as-a-builtin-with-a-size-allowance-of-its-own.md) and +[ADR 0373](0373-gsd-core-is-vendored-on-a-pinned-rustc-with-its-load-and-size-measured.md) D3 (vendored builtins, the +size rule), [ADR 0370](0370-gsd-core-holds-exactly-gsd-cores-kinds-and-fields.md) (`@gsd/core` holds exactly +gsd-core's kinds), [ADR 0372](0372-the-converter-gives-every-old-kind-one-fate-and-writes-gsds-ids.md) (the fate +table, the ledger, GSD's ids) and +[ADR 0390](0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md) D9 (the twins +are measured by the harness's `codes()`). + +## Context + +- A project that ran upstream GSD holds its state in Markdown under `.planning/`: `PROJECT.md`, `REQUIREMENTS.md`, + `ROADMAP.md`, `STATE.md`, and per phase its context, research, plans, summaries, verification, UAT and security + files. `@gsd/core` holds the same state as `.spec` entities. Requirement IMP-01 asks for one command that moves a + `.planning/` folder into `spec/gsd/` and names everything it could not move; IMP-02 measures it on the three parity + fixtures (taskboard, ledger, vault) against their hand-written twins; IMP-03 makes it its own crate and blob. +- The owner settled the shape on 2026-11-24 (Phase 13's context): one command, no positional, the project root's + `.planning/**`, one all-or-nothing edit plan plus a report, no mirror, verdicts never imported, re-import refused, + the fixtures not edited. +- The host already enforces most of what an importer could get wrong: who writes a field (computed, context, harness, + human, verdict), a verdict's origin, the revision of a new file, and the errors a plan may add (E080). The importer + mirrors those refusals and reports them instead of meeting them as a refused plan. + +This ADR is recorded before any `@gsd/import` code. Every later plan of the phase cites its D-numbers. + +## D1. One way, once + +`specforge gsd import` reads the project root's `.planning/**` once and answers ONE edit plan that writes `spec/gsd/`, +plus a report. There is no Markdown mirror and no later Markdown read: after the import, `.spec` is the only state, and +`.planning/` is the user's to keep or delete. The command never writes under `.planning/`. + +## D2. The command + +- **Name.** `specforge gsd import`, with no positional and no `--dir`. A file glob is declared at contribution time + (ADR 0293), so a directory chosen at run time cannot become a read, and the SDK offers no optional positional (a + non-required argument is a `--name` flag). The host's `--path` picks the project; `--format json` and `--dry-run` are + the host's own. +- **Inputs.** Two static globs: `.planning/**` (text, up to the 4 MiB `TEXT_MAX_CEILING_BYTES` ceiling) and + `specforge.json` (text). +- **Contribution.** `@gsd/import` contributes this one command and no kind. Its peers are `@gsd/core` (required) and + `@gsd/security` (optional). + +## D3. The fate table + +ADR 0372's pattern, applied to files instead of old kinds. Every name of `gsd_kit::files::PLANNING_FILES`, plus +`config.json`, `state.json` and `.gitkeep`, and every known section, key and table row of the Tier 1 formats has +exactly one outcome among `mapped`, `computed`, `redundant`, `runtime`, `ignored`, `unmapped`, `needs-extension`, +`setting`, `authored-after-import` and `filled`. A ledger test counts it: a name or a section with no row, or with two, +fails the test. + +- **Tier 1 (mapped).** `PROJECT.md`, `REQUIREMENTS.md`, `ROADMAP.md` (the flat form and the milestone-grouped one), + `NN-CONTEXT.md`, `NN-DISCUSSION-LOG.md`, `NN-RESEARCH.md`, `NN-MM-PLAN.md`, `NN-MM-SUMMARY.md`, + `NN-VERIFICATION.md`, `NN-UAT.md`, `NN-SECURITY.md` and the plans' threat models (both with `@gsd/security`, D11), + and the `quick/*` plans and summaries. +- **Every other name** is `unmapped`, with the kit's own kinds or reason text, so the importer and the kit cannot + disagree about a file. +- **Tier 2 sections inside Tier 1 files** (`key-decisions`, `next_readiness`, deviations, checkpoints, `prohibitions`, + `user_setup`) are reported, not mapped, in this phase. +- **A section whose kit kind was removed** in R4 (persona, journey, term, risk) is reported "no target (ADR 0370)". +- `.gitkeep` is `ignored`; `state.json` is `runtime` (gsd-tools' derived state, which `STATE.md` and the graph compute). + +## D4. Ids and files + +- **Ids** are GSD's, as ADR 0372 D3 writes them: a requirement keeps the bold id written (`TASK-01`); an out-of-scope + row, which carries none, is `OOS-` in row order; a project decision is `D-` in its table's row order; a phase + is its integer part on two digits with a decimal kept (`02.1`); a plan is `-` from its file name; a quick + plan is its `quick_id`; tasks, truths, artifacts and key links are `T`, `TR`, `AR`, `KL` in document + order; summaries, contexts, discussions, research, verifications, UAT sessions and security audits are their file + stems; threats keep their Threat ID cell. The milestone is `v1.0` when the roadmap names none, recorded `filled`. +- **Validation.** Every id is validated against the identifier grammar the host's create accepts before it is used. A + source value that fails it is reported at its `file:line` and the entity is not created. +- **Files.** Every target file path is built only from validated ids, under `spec/gsd/`. A spec root other than `spec` + (read from `specforge.json`) is refused with a message: the twins and the fixtures use `spec`, and the spec root is + no input a command is given. An absent spec root and `.` are accepted: both mean the project root to the host, + which holds `spec/gsd/`. + +## D5. Verdicts are never imported + +- **The host's rule.** The host accepts a `set_verdict` only from a command of the rule's own extension, and only on + an entity already in the compiled graph (`only a command of {extension} writes a verdict for the rule '{rule}'`, + `crates/app/ops/src/authoring/apply/verdict.rs`). `@gsd/import` is not `@gsd/core`, and the entities it creates are + not in the graph its plan is checked against. No plan `@gsd/import` answers holds a verdict operation. +- **What follows.** Executed plans owe `gsd/E501` on each truth, artifact and key link after an import, so + `specforge check` exits 1 until the verifier runs. That is the expected result, not a failure of the import. E516 + fires at a gate only, never in `check`. +- **The report.** It lists each verdict a `.planning` file recorded (a `passed` verification, a score) as owed, and + prints, per phase, `/gsd-verify-work `, and per owed entity the runnable + `specforge query '' --inputs gsd/E501 --format json` whose `basis` `specforge gsd record-verdict` takes, as + the verifier records it (`gsd/core/assets/agents/gsd-verifier.md`). No basis can be printed ahead: a basis is a + digest of today's cited files, and a legacy `passed` is no judgement of today's code. + +## D6. Settings + +- `config.json` is never written: the plan writes no `specforge.json`. +- The report prints one `specforge settings set ` line per mappable key, each value POSIX single-quoted + (`'` written `'\''`), because the line is meant to be pasted into a shell and the input is untrusted. +- A value holding a control character is reported, not printed. +- A secret string (the search providers' API keys) is reported with its environment variable's name only. +- A key of an extension the project does not load is `needs-extension`. +- `worktree.baseRef`, which GSD keeps outside `.planning/`, is reported, not read. + +## D7. Harness fields + +- **What is written.** `@gsd/import` writes the harness fields it has a `.planning` source for: `uat_test.result`, + `threat.status`, `security_audit.asvs_level` and `created`, `accepted_risk.at`, and an `audit_run`'s counts and + `at`. It writes them as a declared peer of their extension: the host lets a command of an extension whose handshake + names the declaring extension a peer set its harness fields (`may_write_harness` in + `crates/app/ops/src/authoring/apply/flags.rs`, which reads every peer, required or optional), and the host writes + each `specforge-harness` ledger line. +- **Filled and reported.** A date-only `audit_run.at` is filled as `T00:00:00Z` and reported `filled`. + `summary.started` and `summary.completed` are reported only. +- **Never written.** Computed, context, human and verdict fields. A plan that sets one is refused whole by the host. +- **Not `.human()`.** `@gsd/core`'s `set_uat_result` is `.human()` (ADR 0301): it records a person's answer as they + give it. The import command is not: it copies what a person already recorded in `.planning/`, and an agent may run an + adoption. A UAT result the import writes is the earlier answer, carried, not a new one. +- **The premise.** D7 rests on the host accepting a peer's harness write. Phase 13's spike tests it before any importer + code depends on it. Were it refused, D7 is amended before any importer code writes a harness field: the values would + then be reported like verdicts, each with the command that records it. + +## D8. The report + +- File- and section-level: one entry per line, with `file:line`, the section, the outcome and the reason. +- Every echoed string is escaped: C0, C1, DEL and the Unicode bidi and format controls are written `\u{..}`. Each + echoed value is capped. +- Deterministic: sorted, no clock, no absolute path. +- No content of an `unmapped` file is echoed: its name and reason only. +- `--format json` gives the same entries as JSON, beside the plan, in the host's `{output, plan, files_written}`. + +## D9. The guest validates first, and caps + +- **Mirror the host.** The guest refuses what the host would refuse (two entities with one id, an id the grammar + refuses, a reference to nothing, a write the writer flags forbid) and reports it before answering, because a host + E080 refusal drops the JSON report and leaves only the diagnostic. +- **Caps.** Plan operations and report entries are capped. A cap reached, or a host read that stopped early or failed + on a mapped file, refuses the plan with "truncated at N" rather than write a partial project. +- **Dropped, never stubbed.** A record missing a required field that no `filled` rule fills is dropped and reported; + its children are reported "parent not imported", never created with a dangling reference (ADR 0372 D4). +- **What the guest cannot see is the host's.** The host refuses a plan that adds any unjudged error (E080, `added` in + `crates/app/ops/src/authoring/edit/validate.rs`). A path field naming a file that no longer exists (E016 on a complete + plan's `files_modified`, a done task's `files`, any `context_refs`) therefore refuses the whole import, naming each + path; the user corrects that path in `.planning/` and runs the import again. A static glob cannot list the project + tree, so the guest does not guess which paths exist. + +## D10. Re-import is refused + +The command reads its graph and refuses when any `@gsd/core` entity exists, naming one (its kind, path and file). There +is no `--force`: to start over the user deletes those entities (by default `spec/gsd/`). Two imports run at once +cannot both land: the second plan's new files carry revision "absent", and the host's revision check refuses it. + +## D11. `@gsd/security` + +Threats, trust boundaries, the security audit, accepted risks and audit runs map only when `specforge.json` lists +`@gsd/security`. That is a text check of the file, not a registry query, and the report says so. Otherwise each such +file and each plan's threat model is `needs-extension`. + +## D12. Packaging (IMP-03) + +- Crate `gsd/import`, a named `BUILTINS` row in `Family::Gsd`, and its own blob under the 2,500,000 B per-blob cap. +- No `gsd-core` dependency: it would export a second component's handlers and link `@gsd/core`'s kinds, passes and + prompts into the blob. `gsd-kit` is the shared crate, as it is for `@gsd/security`. +- `@gsd/core` re-vendors in the same single re-vendor, because the shared `gsd/Cargo.lock` is hashed into its record, + and stays under its 5,800,000 B allowance (ADR 0366 D3). +- `TOTAL_BUDGET` (`crates/runtime/component/tests/blob_size.rs`) is re-measured in the blob's commit, by ADR 0373 D3. + +## D13. The measure (IMP-02) + +- **Codes.** Each of taskboard, ledger and vault imports to a project whose harness `codes()` equal a set pinned per + fixture under `gsd-compat`, `gsd-strict` and `gsd-plus`: the twin's set (ADR 0390 D9), adjusted only by listed, + reasoned differences. The one known today: the vault yields 2 `gsd.security/W302`, not the twin's 5, because the + twin's closed `01-01/T-01-02` and both `T-01-SC` rows have no `.planning` source, and the importer does not invent a + status. +- **Entities.** The imported entity set equals the twin's with computed fields, `context_pack` and verdicts excluded, + and a two-way list of reasoned differences (a field with no `.planning` source, such as a vault threat's `files`, is + "authored after import" on one side; a twin's invented title or id on the other). The list fails both ways: a + difference not listed, and a listed one that no longer differs. +- **Check.** `specforge check` on an imported fixture exits 1 with exactly the owed judged codes (D5). +- The fixtures under `gsd/parity/fixtures/` are not edited: their gsd-ab pins and goldens stay. + +## How this differs from ADR 0360's rejected `@gsd/import` + +[ADR 0360](0360-the-self-spec-moves-to-gsd-core-by-a-one-time-converter.md) rejected an `@gsd/import` as the way to +move this repository's own `spec/` from the old builtins to `@gsd/core`: that spec is not `.planning/` Markdown, an +importer cannot compile its old kinds, and a `gsd/` crate may not name the repository's `spec/`. That decision stands; +the one-time converter (`xtask/src/absorb/`, ADR 0372) did the move. The `@gsd/import` this ADR records is a different +thing: a user-facing, one-way reader of a user's `.planning/` folder, run in the user's project. It never reads or +writes the repository's own `spec/`, and it reads no old kind. + +## Rejected + +- **A `[]` positional, or `--dir`.** A glob is declared at contribution time, and the SDK has no optional + positional (D2). +- **A YAML crate.** The frontmatter GSD writes is a small subset; a crate adds supply-chain surface, blob size and + anchor, alias and tag handling the reader would have to refuse anyway. A bounded hand-written reader over + `gsd_kit::markdown` reports an unsupported construct at its `file:line`. +- **A `@gsd/core` command that applies imported verdicts.** A legacy `passed` is no judgement of today's code, and the + owner chose report-only (D5). +- **Depending on `gsd-core`.** Blob size and a double component export (D12). +- **Inventing the vault's missing threat statuses** to match the twin's five W302. The importer writes what + `.planning/` holds (D13). +- **Writing `specforge.json`.** The report prints the settings lines instead (D6). +- **A `--force` re-import** (D10). + +## Out of scope + +- A reverse export to Markdown, and any mirror (D1). +- Re-reading `.planning/` after the import (D1). +- New `@gsd/core` kinds (ADR 0370). +- Reading a `.planning/` other than the project root's (D2). +- Upstream's `/gsd-import` slash command, which the roster gives `@gsd/import` later. + +## Consequences + +- A user adopts SpecForge on a GSD project with one command and a report that names every file, section and row it did + not map, with a reason; nothing is dropped silently, and a test counts it (D3). +- An imported project with executed plans fails `specforge check` with owed `gsd/E501` until `/gsd-verify-work` runs, + and the report prints the commands that clear it (D5). +- The builtins gain one blob, `gsd_import.wasm`; `TOTAL_BUDGET` and the `gsd_core` record move once, at the phase's + single re-vendor (D12). +- The acceptance test pins each fixture's codes and entity differences, so a later change to `@gsd/core` that moves an + imported project's codes is seen (D13). diff --git a/docs/adr/0392-an-import-commands-plan-is-judged-for-host-errors-only.md b/docs/adr/0392-an-import-commands-plan-is-judged-for-host-errors-only.md new file mode 100644 index 0000000000..2629ae33b0 --- /dev/null +++ b/docs/adr/0392-an-import-commands-plan-is-judged-for-host-errors-only.md @@ -0,0 +1,110 @@ +# An import command's plan is judged for host errors only + +**Status:** accepted (2026-11-24, round r6-breadth, Phase 13). Amends +[ADR 0391](0391-gsd-import-reads-a-planning-folder-once-into-one-edit-plan.md) D9 and D13 (what refuses an import, what +`check` reports after it). Extends [ADR 0303](0303-a-collectors-plan-is-judged-for-host-errors-only.md) (a collector's +plan is judged for host errors only) from collected facts to imported history, under the same rule. Builds on +[ADR 0289](0289-an-extension-writes-through-an-edit-plan-the-host-applies.md) (E080) and +[ADR 0297](0297-a-judged-rules-finding-is-not-an-error-a-write-adds.md) (judged findings). No WIT change and no +protocol version change: one key added to the current minor, 2.3.0. + +## Context + +- `specforge gsd import` copies a legacy `.planning/` folder into `spec/gsd/` as one edit plan (ADR 0391). Like any + command's plan, it was refused (E080) for any error it would add, an extension's included. +- 13-09 ran it through the binary. The vault fixture's `.planning/` claims threat `T-01-02` in plans 01-01 and 01-02, + so `@gsd/security` reports `gsd.security/E101` twice, and the host refused the whole import. This repository's own + `.planning/` was refused for `gsd/E201` (a context with no canonical refs) and `gsd/E312` (a task action saying + "placeholder"). Both are rules about how a project should be written, and a project that ran upstream GSD broke them + before SpecForge existed in it. +- Refusing the import leaves the project unimported and fixes nothing: the user would have to edit legacy Markdown to + satisfy rules of a system they have not adopted yet, then import again. That is ADR 0303's case: a collected fact is + history, and refusing it for an extension's error starves every later fact. +- The host names no extension (the dependency rule), so it cannot know `@gsd/import` is an import unless the command + says so. + +## Decision + +- **The command declares it.** A command may declare `imports: true` (the SDK's `CommandBuilder::imports()`, which + also declares `writes`): it imports what was recorded outside the spec. A command that declares `imports` and not + `writes` is W021 and dropped, as a `human` one is. `@gsd/import`'s `import` declares it. +- **Its plan is judged for host errors only.** The host applies the plan with + `Origin::Command { extension, imports: true }`, and E080 writes, rather than refuses, an extension's rule error + about authored entities (`gsd.security/E101`, `gsd/E312`), in the plan's check and in the re-judgement under the + write lock. What is a rule error is read from the code's meaning, not from which extension reported it + (`Codebook::authored_rule`): the code is in the reporting extension's namespace, that extension's own catalog lists + it, and the catalog entry judges no collected fact kind (`CodeDescriptor.facts`, ADR 0389, which the SDK says to + leave out "for a code about authored entities"). `validate::Lands`, threaded through `plan_steps`, `validate::check` and + `refuse_new_errors` in place of ADR 0303's `host_only` flag, names the three cases: `Nothing` (a typed edit, a + command's or a hook's plan), `Extensions` (a collector's plan, ADR 0303, unchanged: any extension's error, whatever + its code) and `ThirdParty` (an importing command's plan). +- **What still refuses.** Every error whose code is first party, the host's own or a `@specforge/*` builtin's, which + the host's catalog describes (ADR 0286): a path field naming no file (E016, which `@specforge/checks` reports for a + path value check, so its origin is an extension's), an unresolved reference (E003), an id the grammar refuses, two + entities with one id, a file the parser refuses. An extension's error that judges the records against the facts + collected from the tree, whatever the extension: `@code/core`'s `code/E101` (a reference naming no collected fact) + is a reference to nothing, like E003, and a builtin outside `@specforge/` is namespaced like a third party + (ADR 0328 D1), so the namespace alone cannot tell it from a rule. An extension's error whose code its own catalog + does not list (W150's case). And everything checked before E080, unchanged: a malformed plan, + the field flags (computed, context, human, a harness field of an extension that is not the command's or a peer's), a + verdict from any extension but the rule's own (ADR 0391 D5), a stale revision, a collected entity. +- **What lands.** An extension's rule error about authored entities the imported records carry is written, a builtin's + (`@gsd/core`, `@gsd/security`) as much as a third party's. `specforge check` + reports it beside the owed verdicts and exits 1, and the user fixes it in `spec/gsd/` with SpecForge's own tools. +- **Who may declare it.** Any extension. The declaration is in the extension's contributions, so its declaration + golden shows it, and a review of the extension sees it once rather than per call. + +## Amends ADR 0391 + +- **D9.** "What the guest cannot see is the host's" now reads: the host refuses a plan that adds any unjudged *host* + error, a first-party code (E016 included), or a reference to a collected fact that names nothing (`code/E101`). An + extension's rule error about authored entities lands (this ADR). The guest still + mirrors the host's own refusals (D9 "Mirror the host") and the E016 paragraph stands: a path that no longer exists + refuses the whole import. +- **D13, Check.** `specforge check` on an imported fixture exits 1. Its codes are the owed judged codes (D5) and the + rule errors the fixture's `.planning/` carries: none for taskboard and ledger, the vault's two `gsd.security/E101`. + +## Rejected + +- **Naming `@gsd/import` in the host.** The host names no extension, and the next importer (another tool's planning + folder) would need its own exception. +- **Exempting only the importing extension's own rules.** The vault's errors are `@gsd/security`'s, a peer's + (ADR 0303 rejected the same for collectors). +- **The guest drops or refuses a record that breaks a rule** (13-09's options a and b). Dropping loses history the user + wrote; refusing blocks the import until legacy Markdown is edited; and the guest would have to run every rule of + every extension, which only the host does. +- **A flag on the edit plan.** A command could then opt out per call; the declaration is fixed and reviewable. +- **A new `Origin::Import`.** Every place that reads a command's origin (a peer's harness write, a verdict's origin) + would have to name both; an import is still a command. +- **An import judged exactly as a collector's, any extension's error landing.** `@specforge/checks` reports a path + that names no file (E016) as an extension's finding, so a stale path would land, which ADR 0391 D9 refuses: the user + corrects that path in `.planning/`. A collector keeps ADR 0303's rule; its facts name files it just read. +- **Every command judged host-only.** A command that authors (a new plan, a quick task) must stay held by the + project's rules (ADR 0297). +- **First party read from the code's namespace** (the first version of this ADR: any namespaced code landed). + `@code/core` reports `code/E101` namespaced, so an import that wrote a stale test or item reference landed it. +- **Every builtin first party** (read from the host's builtin registry). It refuses `code/E101`, but also + `gsd.security/E101`, `gsd/E201` and `gsd/E312`, `@gsd/*` builtins' rule errors: the very errors this ADR exists to + land. + +## Limits + +- An import that adds a host error is still refused whole, as ADR 0391 D9 says for E016. +- An agent may run an importing command. It can add no host error and pass no field flag; what it can add is an + extension's rule error, which `check` reports. +- A host that predates the key ignores it and refuses such a plan for an extension's error, as before. +- The meaning is what the catalog declares. A code that reads facts without declaring them lands: `gsd/E533` and + `gsd/E535` read API and package facts, but judge a closed milestone's claim, which is history. A pinned test + (`validate.rs`, `an_import_lands_an_authored_rule_error_and_keeps_every_other`, and `Codebook`'s own) holds which + codes land. + +## Consequences + +- The vault imports: its two `gsd.security/E101` land, and `check` reports them with the owed verdicts. +- A real project's legacy `.planning/` is no longer refused for `gsd/E201` or `gsd/E312`; paths it names that no + longer exist still refuse it. +- `protocol-types` and the SDK are inputs of every committed blob, so the phase's single re-vendor (13-11) rebuilds + every builtin, and each grows by the serializer of one more key: 286 B for `@specforge/governance` and for + `@specforge/software`, measured on a macOS build with the blob profile's settings, so about 7.7 kB over the 27 + builtins, more than the 356 B `TOTAL_BUDGET` had left. 13-11 re-measures `TOTAL_BUDGET` in its blob commit + (ADR 0373 D3) and names this growth there. diff --git a/docs/adr/0393-x2-is-a-floor-every-real-test-reaches-and-only-tests-count.md b/docs/adr/0393-x2-is-a-floor-every-real-test-reaches-and-only-tests-count.md new file mode 100644 index 0000000000..fafa49fb81 --- /dev/null +++ b/docs/adr/0393-x2-is-a-floor-every-real-test-reaches-and-only-tests-count.md @@ -0,0 +1,189 @@ +# X2 is a floor every real test reaches, and only tests count + +**Status:** accepted (2026-11-25, round r6-breadth, Phase 14). **Amends** +[ADR 0388](0388-x2-is-the-share-of-test-ids-a-standard-report-saw.md) D2 (X2 is no longer print only: D8), D3 (the +projects and how the fixtures collect: D8, D9) and its Consequences (taskboard and vault read 100%: D4), and +[ADR 0374](0374-the-root-spec-runs-on-gsd-core-and-its-tests-name-requirements.md) D5 (guests and the `@gsd` workspace +write JUnit the step merges, and the guests-only count retires: D1 to D3). **Keeps** +[ADR 0366](0366-gsd-core-is-vendored-as-a-builtin-with-a-size-allowance-of-its-own.md) D2 (one lockfile per blob, so +one test run per guest manifest) and +[ADR 0373](0373-gsd-core-is-vendored-on-a-pinned-rustc-with-its-load-and-size-measured.md) D3 (a blob that grows +re-measures the size budget in the same commit). + +## Context + +- ADR 0388 defined X2 (the share of items carrying a `test_id` whose id a standard test report saw) and printed it, + leaving the floor to this phase. The last full gate before it (2026-11-25, `dogfood.log`) read + `X2 SpecForge: 9772/13660 (71.5%)`, `X2 taskboard: 0/0 (no item has a test_id)` and `X2 ledger: 6/6 (100.0%)`. +- SpecForge's missing ids fall in five groups: the extension guests' tests (935), which run under `cargo test` and + write no JUnit; the `@gsd` workspace's tests (2,923), whose nextest run wrote no JUnit either; tests of fixture and + example crates (22), which are other projects' and never run as SpecForge's; `#[cfg(windows)]` tests (3), compiled + out on the unix hosts that run the gate; and `__guard_only` helpers (5), which carry a test attribute but are not + tests. Moving the guests under nextest alone reaches about 78%. +- Taskboard and vault are JavaScript projects. `@javascript/source` mints no `test_id`, so their X2 is `0/0` whatever + their reports hold (ADR 0388, research finding F3). +- The owner settled the phase on 2026-11-25: the A/B fixtures taskboard, ledger and vault are X2's fixtures beside + SpecForge; JavaScript test calls carry the id node-test mints; SpecForge reaches 100% by reporting every real test + and counting only tests; X2 becomes a hard floor; the fixtures collect with the Phase 11 packs from recorded reports. + +## D1. Guests run under nextest, one run per guest manifest + +The `guests` check runs `cargo nextest run --no-fail-fast --no-tests=pass --profile

--config-file +--manifest-path ` once per guest manifest (`extensions/*/Cargo.toml` and `extensions/*/*/Cargo.toml`), with +`CARGO_TARGET_DIR` the shared guest target as before; `

` is `ci` under `cargo gate ci`, else `gate`. There is no +shared `extensions/` workspace: each blob keeps its own lockfile (ADR 0366 D2). + +The config file is generated per guest under `/gate/nextest-guests/.toml`: a `[store]` whose `dir` is +the repository root's `target/nextest`, written as a TOML literal string (a Windows path's backslashes need no escape; +a path holding `'` or a line break is refused), then the committed `.config/nextest-guests.toml` (the `default`, `ci` +and `gate` profile bodies), then `[profile.

.junit]` with `path = "junit-guests//junit.xml"`. The slug is the +manifest's directory under `extensions/`, each `/` a `-` (`extensions/rust/test` is `rust-test`), and only ASCII +lowercase letters, digits and `-` are accepted. So each run writes +`target/nextest/

/junit-guests//junit.xml`. The check empties `target/nextest/

/junit-guests` before its +loop, so a report from an earlier run is never read as current. `--no-tests=pass` keeps a future guest with no test +from failing the check (nextest's default for no tests is to fail). + +The root `.config/nextest.toml` cannot be passed: for a manifest outside the root workspace nextest finds no config +of its own, and the root file's package overrides (`package(specforge-ops)`, `binary_id(xtask::absorb_e2e)`) match +nothing in a guest, which nextest refuses as a parse error. Without a `[store]` the report would land in the guest's +own `target/`, where the gate never looks. + +The reason: nextest writes the JUnit report X2 and the requirement verdict read, and one run per manifest is what +the guests already were under `cargo test`. + +## D2. The `@gsd` workspace writes its report beside them, and CI keeps both + +`gsd/.config/nextest.toml` sets `[store] dir = "../target/nextest"` (relative to `gsd/`, so the repository root's +`target/nextest`) and `[profile.gate.junit]` and `[profile.ci.junit]` with `path = "junit-gsd/junit.xml"`; the `gsd` +check passes `--profile

` and empties `target/nextest/

/junit-gsd` first. The custom profiles inherit `default` +and its override, so the suite runs as before; a plain `cargo nextest run` in `gsd/` now stores under the root's +`target/nextest/default`. + +CI keeps `target/nextest/ci/junit-guests` from the specs shard (which runs `guests`) and +`target/nextest/ci/junit-gsd` from the gsd shard, as artifacts named `junit-guests` and `junit-gsd`, each failing +when no file is there. Each artifact is named as its directory, so a download lands where a local run writes; the +dogfood job downloads every `junit-*` artifact. + +The reason: the gate reads every `junit*.xml` under the report directory already (ADR 0374 D5); naming the +directories as the artifacts keeps one reader for a local run and CI. + +## D3. `dogfood` runs after the three test checks, and the guests-only exception retires + +`dogfood` runs after `tests`, `guests` and `gsd`, and refuses, naming those checks, when any of the three report sets +is absent (a missing set would otherwise read as thousands of missing ids and hide the cause). The requirement +verdict no longer reads `specforge anchors --file extensions`, and the "named only by guests' tests" count goes: the +guests' tests are in the merged report like every other test. + +The reason: ADR 0374 D5 carved that exception out because the guests wrote no JUnit; once they do, it only hides a +requirement a guest test fails to prove. + +## D4. A JavaScript test call is an item, and a leaf test carries node-test's id + +`@javascript/source` reads test files for their test calls only: the files `node --test` runs by default (its +patterns `**/*.test.*`, `**/*-test.*`, `**/*_test.*`, `**/test-*.*`, `**/test.*` and `**/test/**`, over `.js .cjs +.mjs .ts .mts .cts`), since node-test is the runner whose ids they carry, and only when the package the pack names a +file after is the one node-test names it after (a test file of a fixture package under `test/` gives no item). A +`.spec.*` file or one under `tests/`, `__tests__/` or `__mocks__/` stays no source item and gives no test item. A +test file the host's reader could not parse gives no item and a warning (W203) naming it, never the collector's +error: test directories hold odd fixtures, and a test call never minted is never missing. A call whose callee is `test`, `it`, `describe` or `suite`, or one of those with `.skip`, `.todo` or `.only`, or a +subtest `.test(...)` inside a test, whose first argument is a string or a template with no substitution and not +empty, becomes a `function` item with the attribute `test`; its path is the enclosing suite and test names, then its +own. A plain call needs a function argument. + +node's JUnit reporter writes a test or a suite as a `` exactly when at least one test, suite or subtest +ran inside it, and as a `` otherwise (checked against node v26.13.0): an empty `describe`, a `describe` +with no function and any `.skip` call are test cases. So a call carries `test_id = TestId::js(package, file, path)`, +the id node-test mints, when it is called with `.skip`, or when no test, suite or subtest call sits inside it, minted +or not: a subtest with a dynamic name, a function reference or only options still makes its parent a ``. +node never runs a skipped call's function, so nothing inside a `.skip` call or a call with a `skip` option is an +item; a call with a `skip` option that holds calls carries no id either, since whether it is skipped is decided when +it runs. A `.todo` call runs its function, so what it holds is read. A dynamic name (an identifier, a concatenation, a +substitution, `.each`, `.concurrent`) or an empty one (node names it `` or after its function) mints +nothing and raises nothing. Shortcut: a subtest a helper registers out of the call's span (`await check(t)`) is not +seen, so that test keeps an id node reports as a suite; X2 names it missing, and the test is rewritten to call +`t.test` in its own body. Helpers in test files stay no item. No new item kind is added. + +The reason: the definition stays ADR 0388 D1's, so taskboard and vault read their number from the same computation +as every other project; a new kind would re-vendor every code-facts linker and `@code/core`. + +## D5. A test compiled out on this platform is reported skipped + +`@rust/test` reports a test item that the report lacks and whose `cfg(...)` attribute is false on the host as +`skipped`, as it already does for `#[ignore]`. `@rust/source` records in an item's `attrs` every `cfg(...)` that +compiles it out, outermost first: those on the `mod` declarations that reach its file, the file's inner `#![cfg]`, +those of every module around it (outer, and inner in its body) and its own; the test is excluded when any of them is +false. The guest reads the host's family from its input: the canonical +project root the host passes as `cwd` is a unix path (`/…`) or a Windows one (`C:\…`, `\\?\C:\…`); with neither, +nothing is decided. The predicate is three-valued: `unix`, `windows` and `target_family = "…"` (any value: a native +host has one family) are decided, and so is `target_os = "…"` on a Windows host; on a unix host only +`target_os = "windows"` is (false), since nothing in the input tells Linux from macOS, so a test gated on another +unix's `target_os` stays missing there. `feature`, `test` and anything else are unknown, so not excluded. The gate's +`dogfood` runs only on a unix host (Linux locally and in CI, macOS locally), whose X2 numbers these rules fix. + +The reason: a `#[cfg(windows)]` test is a real test that cannot run here; reading it as missing would make the floor +unreachable, and an unknown predicate must never hide a test a forgotten feature compiled out. + +## D6. `__guard_only` marks no test + +An attribute whose arguments name the identifier `__guard_only` (an identifier token, never a string's text) marks no +test. `@rust/source` follows the macro when attributes stack: a runner attribute (`#[test]`, `#[tokio::test]`) +registers the test itself; otherwise each spec-link attribute leaves registering to the next one below it, so the +function is a test exactly when the lowest spec-link attribute is not `__guard_only`. A helper no test is registered +for gets no `test_id`. + +The reason: those helpers exist to type-check a guard, never run, and are not tests. + +## D7. `@rust/cargo` excludes directories by a setting + +`@rust/cargo` declares the setting `exclude`, a list of project-relative directories: a manifest in or under one is +no package of the project. `@rust/cargo` still reads it (workspace inheritance needs every manifest) and answers no +package for it, so `@rust/source` reads no item there; the packs that run a tool (`@rust/test`, `@rust/coverage`, +`@rust/lint`, `@rust/deps`) do not consult the setting and run over the cargo workspace as before. SpecForge's root +`specforge.json` lists its fixture and example directories. + +The reason: every consumer computes the same number from the same facts (ADR 0388 D1), so the census leaves those +crates out where the facts are made, not in a gate-side filter. + +## D8. X2 is a floor + +`dogfood` fails when X2 is below 100%, or `0/0`, on SpecForge, taskboard, ledger or vault. It logs every project's +line first, then fails naming at most 10 missing ids and the count of the rest. The negative control is `x2::floor` +unit tests on literals plus one end-to-end gate test over a ledger copy whose report lacks one case; that test is +`#[ignore]`d in the workspace run, because it needs the built `specforge` (`SPECFORGE_BIN`, which the root workspace's +test partitions do not build), and the dogfood check, which sets it, runs it first. Ignored, `@rust/test` reports it +skipped, so X2 still counts it. This closes ADR 0388 D2's "print only until Phase 14". + +The reason: a ratio nothing enforces drifts; a floor with a control that fails end to end proves the floor can fail. + +## D9. The fixtures collect with their packs from recorded reports + +Taskboard, ledger and vault collect with the packs each detects: taskboard and vault with `@javascript/coverage`; +ledger with `@rust/coverage`, `@rust/lint`, `@rust/deps` (sbom and osv) and `@rust/api`, not `@rust/proof` (it has no +Kani harness). Their reports are recorded once on linux/amd64 by `gsd/parity/record-reports.sh` into +`gsd/parity/goldens//reports/`, the LCOV `SF:` prefix rewritten to a relative path, and each row collects +with `--no-run --report ` into a scratch copy, with no Warning and no Error (an Info note is allowed). The +vault row loads no non-builtin extension. The fixtures stay untouched. + +The reason: live tool runs in the gate would need seven tools and drift (an OSV database is a snapshot), so "no +diagnostics" would not reproduce; recorded output keeps the A/B trees and their pins as they are. + +## Rejected + +- **A shared `extensions/` workspace** to run every guest at once: one lockfile per blob (ADR 0366 D2). +- **Passing the root nextest config** to a guest: its overrides fail the parse (D1). +- **A gate-side exclude** of fixture and example crates: the gate would compute another number than a user's + `specforge` (ADR 0388 D1). +- **A test id on every `describe`, or on none**: node reports a suite as a test case exactly when nothing ran inside + it (D4), so the id follows what the suite holds. +- **A new item kind** for JavaScript tests: it re-vendors every code-facts linker and `@code/core`. +- **Live tool runs in the gate** for the fixtures' packs: too many tools, and their output drifts. +- **Editing the fixtures** so every pack applies: it re-pins three A/B trees and re-records their baselines. +- **`dogfood` on pull requests**: deferred; the owner keeps it push only, so a missed test turns main red after merge. + +## Consequences + +- X2 reads 100% on SpecForge, taskboard, ledger and vault, and a regression fails `dogfood`. +- JavaScript test items appear in every JavaScript project's graph and in the A/B B arm (costly, owner-accepted); the + A/B tasks, trees and pins are not changed. +- The guests' and the `@gsd` workspace's reports are CI artifacts; the CI time budgets are re-measured on the first + push (ADR 0375 D3). diff --git a/docs/agents/revendor.md b/docs/agents/revendor.md index 7322fa1876..35ef5aedea 100644 --- a/docs/agents/revendor.md +++ b/docs/agents/revendor.md @@ -55,18 +55,23 @@ ignored tests), and prints the `git add` line that stages exactly those paths. A new committed blob is listed in `crates/runtime/component/src/committed.rs` first; a new builtin is a row of `BUILTINS` (`crates/runtime/component/src/builtins.rs`), which `COMMITTED` lists first. A builtin's crate is -`extensions/

` (`@specforge/`) or, in a family, `extensions//` (`@/`), with one -exception: `@gsd/core`'s crate is `gsd/core`, a named row of `BUILTINS` (ADR 0366 D1). Its lock is the gsd workspace's -`gsd/Cargo.lock`, shared with `gsd-kit` and `gsd-security` and hashed whole, so a dependency change that only touches -`gsd-security` still re-vendors it; its SDK patch comes from `gsd/.cargo/config.toml`, which the stager replays -re-rooted at the repository (ADR 0366 D2, `gate/src/blob_inputs.rs`). The printed `git add` line then holds -`gsd/core/wasm` and `gsd/Cargo.lock`. A crate under `extensions/` +`extensions/` (`@specforge/`) or, in a family, `extensions//` (`@/`), with two +exceptions, named rows of `BUILTINS` outside `extensions/`: `@gsd/core` at `gsd/core` (ADR 0366 D1) and `@gsd/import` +at `gsd/import` (ADR 0391 D12). Both are in the gsd workspace, whose `gsd/Cargo.lock`, shared with `gsd-kit` and +`gsd-security`, is hashed whole into both records, so a dependency change to either crate (or only to `gsd-security`) +re-vendors both; their SDK patch comes from `gsd/.cargo/config.toml`, which the stager replays re-rooted at the +repository (ADR 0366 D2, `gate/src/blob_inputs.rs`). The printed `git add` line then holds `gsd/core/wasm`, +`gsd/import/wasm` and `gsd/Cargo.lock`. A crate under `extensions/` without `wasm/` is an extension library (`extensions/code/junit`, `extensions/code/facts`, `extensions/rust/manifest`, `extensions/javascript/workspace`), an rlib no blob of its own. A library is an input of every builtin that links it, directly or through another library, so editing one re-vendors those builtins: code-facts, and code-junit, which it links, feed `@code/core`, -`@javascript/node-test`, `@javascript/source`, `@rust/cargo`, `@rust/source` and `@rust/test`; `specforge-rust-manifest` -feeds `@rust/cargo`; `specforge-javascript-workspace` feeds `@javascript/node-test` and `@javascript/source`. +`@javascript/node-test`, `@javascript/source`, `@rust/cargo`, `@rust/source`, `@rust/test` and the twelve report packs +(`@rust/{coverage,lint,deps,api,proof}`, `@javascript/{coverage,lint,deps,api,vitest,jest,playwright}`); +`specforge-rust-manifest` feeds `@rust/cargo`; `specforge-javascript-workspace` feeds `@javascript/node-test`, +`@javascript/source`, `@javascript/vitest`, `@javascript/jest` and `@javascript/playwright`. +The report readers `extensions/code/{lcov,api,sarif,cyclonedx,osv}` and `extensions/code/kani` each feed the packs that +link them (`a_change_to_a_report_reader_feeds_the_packs_that_link_it`, ADR 0389). `every_committed_wasm_is_listed` (xtask) fails for a `.wasm` file git tracks that the list does not name. ## Only the vocabulary diff --git a/docs/diagnostics.md b/docs/diagnostics.md index 4af542669e..7693b6a116 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -1134,7 +1134,13 @@ is written; an edit that creates neither, one that also sets, unsets, links, unlinks, deletes or moves at or under that entity, and a migration still count it (ADR 0385). A writing collector's plan is compared with the project as its collect left it, and is refused for host errors only: an extension's error -refuses no collected fact (ADR 0303). +refuses no collected fact (ADR 0303). The plan of a command that declares +`imports` writes an extension's rule error about authored entities the imported +records carry, and `check` reports it: a code in the extension's namespace that +its own catalog lists and whose entry judges no collected fact. It is still +refused for any other error: the host's or a `@specforge/*` builtin's (E016 +included), and one that judges the records against collected facts, such as +`code/E101` (ADR 0392). Owner: core Level: error @@ -3359,8 +3365,9 @@ second one of a kind served once (`tests`, `state`, `graph`, `slash_commands`, setting, and a `files` input whose name is no word or is repeated, that names neither or both of `field` and `glob`, a `field` that is not `kind.field` or that no loaded extension declares, a `root` on a glob or that is no root's name, -and a glob that is empty, absolute, climbs with `..`, or has more than four `**` -segments. +a glob that is empty, absolute, climbs with `..`, or has more than four `**` +segments, and a `text_max` that is zero, over 4 MiB or set without `text` (ADR +0390). Owner: core Level: warning @@ -4874,6 +4881,22 @@ Owner: core Level: warning ``` +## W203 + +``` +W203: A collector warned of what it skipped + +A collector's export read its report and answered facts, and also returned lines +about entries it could not use (ADR 0389): a path outside the project, a record +of no supported shape. Each line is one W203 naming the collector and its +extension, escaped, at most 100 per collector and then one W203 counting the +rest. The facts it did answer are kept. Read the lines and fix the report or the +tool's configuration. + +Owner: core +Level: warning +``` + ## Retired codes These codes are no longer emitted, and are never reused for another meaning. diff --git a/docs/extension-inventory.md b/docs/extension-inventory.md index 14a8f65e8b..b807cf3cbb 100644 --- a/docs/extension-inventory.md +++ b/docs/extension-inventory.md @@ -34,12 +34,24 @@ The counts and lists on this page are read from the builtins' pinned declaration | `@specforge/testing` | 0 | 0 | `verify` kinds on 7 kinds | software, governance (both optional) | | `@specforge/cargo-test` | 0 | 0 | -- | testing (required) | | `@specforge/vitest` | 0 | 0 | -- | testing (required) | -| `@code/core` | 4 (collector-written) | 5 | -- | none | +| `@code/core` | 9 (collector-written) | 11 | -- | none | | `@javascript/node-test` | 0 | 0 | -- | code/core (required) | | `@rust/cargo` | 0 | 0 | -- | code/core (required) | | `@rust/source` | 0 | 0 | -- | code/core, rust/cargo (required) | | `@rust/test` | 0 | 0 | -- | code/core, rust/source (required) | | `@javascript/source` | 0 | 0 | -- | code/core (required) | +| `@rust/coverage` | 0 | 0 | -- | code/core, rust/source (required) | +| `@rust/lint` | 0 | 0 | -- | code/core, rust/source (required) | +| `@rust/deps` | 0 | 0 | -- | code/core, rust/source (required) | +| `@rust/api` | 0 | 0 | -- | code/core, rust/source (required) | +| `@rust/proof` | 0 | 0 | -- | code/core, rust/source (required) | +| `@javascript/coverage` | 0 | 0 | -- | code/core, javascript/source (required) | +| `@javascript/lint` | 0 | 0 | -- | code/core, javascript/source (required) | +| `@javascript/deps` | 0 | 0 | -- | code/core, javascript/source (required) | +| `@javascript/api` | 0 | 0 | -- | code/core, javascript/source (required) | +| `@javascript/vitest` | 0 | 0 | -- | code/core, javascript/source (required) | +| `@javascript/jest` | 0 | 0 | -- | code/core, javascript/source (required) | +| `@javascript/playwright` | 0 | 0 | -- | code/core, javascript/source (required) | | `@specforge/checks` | 1 (collector-written) | 0 | -- | none | Extensions load after the peers they declare; extensions with no peer between them keep the order @@ -50,7 +62,7 @@ must be in the declared version range. | Family | State | |--------|-------| -| `@gsd/*` (the GSD spec framework modelled as extensions) | `@gsd/core` is a vendored builtin and `@gsd/security` is built from `gsd/`; the rest are not started ([gsd/README.md](../gsd/README.md)) | +| `@gsd/*` (the GSD spec framework modelled as extensions) | `@gsd/core` and `@gsd/import` are vendored builtins and `@gsd/security` is built from `gsd/`; the rest are not started ([gsd/README.md](../gsd/README.md)) | | BMAD, OpenSpec, SpecKit | Not started | ## @specforge/product @@ -301,7 +313,16 @@ collector, never by hand: a spec cites a fact by its id, and `specforge collect` It declares no collector. A runner pack (tests), a source pack (items) or a manifest pack (packages) peers it and mints the facts with the linked `specforge-code-facts` library (`extensions/code/facts`, an extension library, ADR 0328 D3), so every pack names a fact the same way. The library reads a JUnit report through -`specforge-code-junit` (`extensions/code/junit`), the second extension library. +`specforge-code-junit` (`extensions/code/junit`), the second extension library. Five more extension libraries read +a standard report into the five report kinds ([ADR 0388](adr/0388-x2-is-the-share-of-test-ids-a-standard-report-saw.md), +[guide](guides/code-report-facts.md)): `specforge-code-lcov` (LCOV coverage), `specforge-code-api` (cargo public-api +and api-extractor snapshots), `specforge-code-sarif` (SARIF 2.1.0), `specforge-code-cyclonedx` (CycloneDX BOMs) and +`specforge-code-osv` (osv-scanner reports). Each is an rlib that links code-facts, linked by the report packs +([ADR 0389](adr/0389-report-packs-run-standard-tools-and-doctor-names-a-missing-one.md)): lcov by `@rust/coverage` +and `@javascript/coverage`, sarif by `@javascript/lint` (`@rust/lint` turns clippy's JSON into findings itself), +cyclonedx and osv by `@rust/deps` and `@javascript/deps`, api by `@rust/api` and `@javascript/api`. A sixth reader, `specforge-code-kani` +(`extensions/code/kani`, Kani's regular output), links nothing and is linked by `@rust/proof` only. Editing a reader +re-vendors the packs that link it. | Kind | Schemes | Fields | |------|---------|--------| @@ -309,6 +330,11 @@ ADR 0328 D3), so every pack names a fact the same way. The library reads a JUnit | `test_run` | `run` | `test` (edge `run_of` to the `test`), `status`, `duration_ms` | | `item` | `rust`, `js` | `package` (edge `in_package` to the `package`), `file`, `kind` (a list: `function`, `method`, `struct`, …), `visibility` (`public`, `crate`, `restricted`, `private`), `signature` (a digest), `doc`, `attrs`, `names` (edge `names`), `test_id` (edge `runs_as` to the `test` a test function is) | | `package` | `pkg` | `name`, `version`, `edition`, `rust_version`, `engines`, `features`, `targets`, `path`, `depends_on` (edge `uses_package` to each `package`) | +| `coverage` | `cov` | `item` (edge `covers` to the `item` holding the lines), `file`, `functions_found`, `functions_hit`, `lines_found`, `lines_hit`, `branches_found`, `branches_hit` | +| `api_item` | `api` | `item` (edge `api_of` to the `item`), `path`, `kind` (an item kind, or `variant`, `reexport`, `extern_crate`, `other`), `visibility`, `signature` (verbatim), `tag` (api-extractor's release tag), `change` (`added`, `unchanged`, `changed`, `narrowed`, `removed`; against the committed accepted report), `accepted_signature`, `accepted_tag`, `accepted_visibility` (the accepted entry's, on a changed, narrowed or removed one) | +| `static_finding` | `sarif` | `tool`, `rule`, `level` (`error`, `warning`, `note`, `none`, `unknown`), `message`, `file`, `line`, `item` (edge `found_in` to the innermost `item`), `package` (edge `found_in_package` to the `package`, when no item holds it) | +| `dependency` | `dep` | `package` (edge `dependency_of` to the project `package` the BOM describes), `purl`, `name`, `version`, `scope` (`required`, `optional`, `excluded`), `direct` | +| `vulnerability` | `vuln` | `package` (edge `affects` to the project `package`), `osv_id`, `aliases`, `summary`, `purl`, `version`, `severity` (`critical`, `high`, `medium`, `low`, `unknown`) | The ids: @@ -320,6 +346,18 @@ The ids: | a JavaScript item | `js:/::`, a member joined by `.` | | a test run | `run:` | | a package | `pkg:cargo/`, `pkg:cargo/#` (two of one name), `pkg:npm/` (`@` written `%40`) | +| coverage | `cov:` for the innermost item holding the lines, `cov:@` for what no item of the file holds | +| an API entry | `api:rust:::::…::` (a member `…::::m` or `…::::m`, a crate root `api:rust:`), `api:js:::[.]` | +| a static finding | `sarif:/#:`, `#` with no line, neither with no location; `~2`, `~3` on a repeat in document order | +| a dependency | `dep:/`, `dep:/@<[group/]name[@version]>` with no purl | +| a vulnerability | `vuln:/` | + +`@code/core` 1.4.0 added `change` and the three `accepted_*` fields to `api_item` +([ADR 0390](adr/0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md) D3). The API +packs read the project's committed accepted report beside the run, never as a report: `@rust/api` cargo-public-api's +`**/public-api.txt`, `@javascript/api` api-extractor's `**/etc/*.api.md` or rush's `common/reviews/api/*.api.md`, each +file up to 4 MiB ([guide](guides/code-report-facts.md#the-accepted-api-side)). With no accepted file a fact carries no +`change`; an entry gone from the code is a fact with `change` `removed`. An item id never holds `#` and a test id always does, so one scheme carries both; every id parses back to itself, and a symbol of rust-analyzer's or scip-typescript's SCIP index maps into exactly one. No kind is scoped: a reference @@ -332,6 +370,13 @@ sends them with each unheld reference): | `code/W102` | A reference names no fact, and no served store holds facts of a kind its field admits in its scheme (a fresh clone, before a collect, or the pack that writes it not run); it names the kind and the pack: `@javascript/node-test` or `@rust/test` for tests, `@rust/source` or `@javascript/source` for items, `@rust/cargo` or `@javascript/source` for packages | | `code/W401` | An entity that is not pending links a test whose last run failed | | `code/I402` | A test's or an item's `names` holds a name that is no entity, or the short name of several | +| `code/W104` | A report fact names no item: a `coverage`, an `api_item` of a kind an item can have (not a crate root), or a `static_finding` that names no `package` either | +| `code/W105` | A `static_finding`'s rule or level reads `unknown` | +| `code/W106` | A `dependency` has no `purl` | +| `code/W107` | A `vulnerability`'s severity is `unknown` | + +A report id's parts are percent-encoded (`%`, `/`, `#`, `:`, `~`, `@`, `?`, whitespace), so each id parses back to its +parts. The `reports` pass raises `code/W104` to `code/W107` and is sent only the five report kinds, never a pending fact. An entity is pending while its owner is (its kind's `complete_when`, or its nearest scope ancestor's): its references are not checked and its failing tests are not reported, so a test not written yet is TDD, not an error. @@ -342,18 +387,24 @@ and names each test after the nearest `package.json` with a `name` ([guide](guid The Rust packs write all four kinds ([ADR 0348](adr/0348-a-collector-declares-a-config-file-and-the-rust-packs.md), [guide](guides/rust-facts.md)), each detected by a `Cargo.toml` and run in fact order: `rust-cargo` (`@rust/cargo`) -reads every `Cargo.toml` with `cargo_toml` into `package` facts and runs nothing; `rust-source` (`@rust/source`) walks +reads every `Cargo.toml` with `cargo_toml` into `package` facts and runs nothing, leaving out the manifests under +the project-relative directories its `exclude` setting lists (fixture crates that are no package of the project, +[ADR 0393](adr/0393-x2-is-a-floor-every-real-test-reaches-and-only-tests-count.md)); `rust-source` (`@rust/source`) walks each target's module tree by rustc's rules and has the host's parser read it into `item` facts, a test function -carrying the id nextest gives it and the entity its `#[specforge_test]` names; `rust-test` (`@rust/test`) runs -`cargo-nextest` with a config file the host writes and reads its JUnit report into `test` and `test_run` facts, an -`#[ignore]`d test nextest leaves out recorded `skipped`. It needs `cargo install cargo-nextest --locked`. +carrying the id nextest gives it and the entity its `#[specforge_test]` names (a `__guard_only` helper carries none); +`rust-test` (`@rust/test`) runs `cargo-nextest` with a config file the host writes and reads its JUnit report into +`test` and `test_run` facts, an `#[ignore]`d test nextest leaves out, or one a `cfg(...)` false on the host compiles +out, recorded `skipped`. It needs `cargo install cargo-nextest --locked`. `@javascript/source` writes `item` and `package` facts ([guide](guides/javascript-facts.md)): its collector `javascript-source`, detected by a `package.json`, runs nothing. It reads every `package.json` into one `package` fact per named package (`pkg:npm/`, its dependencies on the project's own packages), and has the host's reader parse -each `.ts .mts .cts .tsx .js .jsx .mjs .cjs` file a named package owns, test files and generated output left out, into +each `.ts .mts .cts .tsx .js .jsx .mjs .cjs` file a named package owns, generated output left out, into `item` facts `js:/::[.]`: what the file or a namespace declares, and the members of its -classes and interfaces, `public` when an importer reaches it. +classes and interfaces, `public` when an importer reaches it. A test file is read for its statically named test calls +only: each is a `function` item with the attribute `test`, and a call node reports as a test case (a skipped one, or +one holding no test call) carries `test_id`, the id `@javascript/node-test` gives it +([ADR 0393](adr/0393-x2-is-a-floor-every-real-test-reaches-and-only-tests-count.md)). ## @specforge/checks diff --git a/docs/extension-model.md b/docs/extension-model.md index fb5110c388..51ea43c368 100644 --- a/docs/extension-model.md +++ b/docs/extension-model.md @@ -95,8 +95,9 @@ Extensions load in peer order: an extension loads after the peers it declares. ## The builtins are examples -SpecForge ships fifteen builtin extensions. Fourteen are a starter set, aimed at software and product work, and -`@gsd/core` is the GSD spec framework; all are written with the same SDK any extension uses: +SpecForge ships twenty-eight builtin extensions. Twenty-six are a starter set, aimed at software and product work, +`@gsd/core` is the GSD spec framework and `@gsd/import` moves a GSD `.planning/` folder into it; all are written with +the same SDK any extension uses: | Builtin | Shows how to | |---------|--------------| @@ -109,13 +110,41 @@ SpecForge ships fifteen builtin extensions. Fourteen are a starter set, aimed at | `@code/core` | Declare collector-written kinds, a family builtin's own codes, and check passes over facts | | `@specforge/checks` | Declare value checkers with scopes and family switches, on a kit a domain pack can link too | | `@javascript/node-test` | Declare a collector that reads project files and answers facts, with an extension library (`specforge-code-junit`) | -| `@rust/cargo`, `@rust/source`, `@rust/test` | Collectors served each other's facts: a manifest library (`cargo_toml`), the host's parser, and a config file the host writes for a command | -| `@javascript/source` | Read the project's source with the host's reader through a query it ships, and share a library (`specforge-javascript-workspace`) with another pack | +| `@rust/cargo`, `@rust/source`, `@rust/test` | Collectors served each other's facts: a manifest library (`cargo_toml`), the host's parser, a config file the host writes for a command, and a project setting (`exclude`) a collector reads | +| `@javascript/source` | Read the project's source with the host's reader through a query it ships, read test files through a second query for their test calls only, and share a library (`specforge-javascript-workspace`) with another pack | +| `@rust/coverage` | Run cargo-llvm-cov after approval and record its LCOV as `coverage` facts through a reader library (`specforge-code-lcov`); `specforge add` also enables `@rust/source` | +| `@rust/lint` | Run clippy after approval, capture its JSON on standard output and record `static_finding` facts; `specforge add` also enables `@rust/source` | +| `@rust/deps` | Hold two collectors: cargo-cyclonedx, whose BOMs a report glob reads fresh, for `dependency` facts, and osv-scanner for `vulnerability` facts; `specforge add` also enables `@rust/source` | +| `@rust/api` | Run cargo public-api after approval, capture its text and record `api_item` facts; `specforge add` also enables `@rust/source` | +| `@rust/proof` | Run Kani after approval, capture its output and record each proof harness as a placed `test` fact through a reader library (`specforge-code-kani`); `specforge add` also enables `@rust/source` | +| `@javascript/coverage` | Run c8 around the project's `npm test` after approval and record `coverage` facts; `specforge add` also enables `@javascript/source` | +| `@javascript/lint` | Run ESLint with its SARIF formatter after approval and record `static_finding` facts; `specforge add` also enables `@javascript/source` | +| `@javascript/deps` | Hold two collectors: cyclonedx-npm for `dependency` facts and osv-scanner for `vulnerability` facts, a skipped entry shown as W203; `specforge add` also enables `@javascript/source` | +| `@javascript/api` | Run api-extractor after approval on a config file the host writes, and record `api_item` facts; `specforge add` also enables `@javascript/source` | +| `@javascript/vitest`, `@javascript/jest`, `@javascript/playwright` | Run a test runner after approval and record its JUnit as `test`/`test_run` facts (jest through an env file the host writes, Playwright's report captured); `specforge add` also enables `@javascript/source` | | `@gsd/core` | Ship a whole spec framework as one extension: scoped kinds, judged rules, settings, and the prompts, agents, skills, slash commands and hooks a coding agent's host installs | +| `@gsd/import` | Declare no kind, only a command that imports history: its plan lands an extension's rule error and refuses a host one or a fact reference naming nothing (`CommandBuilder::imports()`, ADR 0392) | The [extension inventory](extension-inventory.md) lists exactly what each declares; the [entity pages](entities/) document each builtin kind. +A new check rarely needs a new kind. `@gsd/core` judges a release's breaking API changes and its release evidence with +computed fields of its existing `milestone` kind and two guards at the milestone close, and declares no `interface` or +`release` kind ([ADR 0390](adr/0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md)): + +- `milestone.api_breaks` lists each `api_item` fact whose `change` is `changed`, `narrowed` or `removed`: the API + packs judge each entry against the project's committed API report ([guide](guides/code-report-facts.md)). + `gsd/E533` refuses to close a milestone with breaks unless its version is not API-compatible with the last shipped + one (Cargo's rule: for `0.x` a minor bump counts as major). +- `milestone.release` holds the release tag `@gsd/core`'s own `gsd-git` collector found for a shipped milestone + (`refs/tags/v`, the harness field `milestone.tag`) and the `package` facts whose `version` is not the + milestone's. `gsd/E535` refuses the close when the last shipped milestone has no tag, a package's version differs + (the names in `specforge.release_exempt` aside) or the version goes backwards. + +Both are gate codes of `/gsd-complete-milestone` and `specforge gsd close-milestone` only, switched by +`specforge.interface_gate` and `specforge.release_gate` (off under `gsd-compat`, on under `gsd-strict` and `gsd-plus`). +`specforge check` shows the computed fields; the refusal comes at the close. + ## Any domain Because the core has no domain, the same mechanism fits very different work. These are examples of what an @@ -128,7 +157,8 @@ extension would declare, not extensions that ship: | Operations | `site`, `process`, `kpi`, `owner` | Every KPI has a target and an owner; no process without a site | | Software spec frameworks | the artefacts of GSD, BMAD, OpenSpec or SpecKit | Each framework's own rules, checked on every edit | -A GSD extension family (`@gsd/*`) is being designed; nothing is built yet. BMAD, +The GSD extension family (`@gsd/*`) has `@gsd/core` and `@gsd/import` built as builtins and `@gsd/security` built +from `gsd/`; the rest are being designed ([gsd/README.md](../gsd/README.md)). BMAD, OpenSpec and SpecKit extensions are not started. ## Writing your own diff --git a/docs/extension-protocol.md b/docs/extension-protocol.md index c5f6c8b9ce..89d37d13c7 100644 --- a/docs/extension-protocol.md +++ b/docs/extension-protocol.md @@ -142,7 +142,7 @@ nothing else: | `input` | Keys | Served to | The call's input carries | |---|---|---|---| -| `files` | `name`, `field` or `glob`, `root`?, `text`? | pass, command, collector | `files`, the facts (and capped text) under `name` (see "File reads" under [Category: passes](#category-passes)) | +| `files` | `name`, `field` or `glob`, `root`?, `text`?, `text_max`? | pass, command, collector | `files`, the facts (and capped text) under `name` (see "File reads" under [Category: passes](#category-passes)) | | `tests` | | pass | `test_results`, the recorded test report | | `state` | | command, prompt, hook | `state`, the extension's state | | `graph` | | prompt, hook | `graph` | @@ -518,6 +518,13 @@ that does not know the field ignores it). The host reads the declaration by one dropped): it records what a person says, so the host runs it only for a person at a terminal. An MCP call, and the command line without a terminal, are refused `human_only` before the export runs, `--dry-run` included. A 1.11 host ignores the key. +- **Importing (2.3.0, ADR 0392).** A command may declare `imports: true` (it must `writes`, else W021 and it is + dropped): it imports what was recorded outside the spec, so the host judges its plan for host errors only. An + extension's rule error about authored entities that the plan adds (`gsd.security/E101`: a code in the extension's + namespace, listed in its own `codes`, whose entry declares no `facts`) is written and `check` reports it. Every other + error still refuses the plan (E080): a first-party code, the host's or a `@specforge/*` builtin's (E016 of a path's + value check), and one that judges the records against collected facts (`code/E101`). A host that does not know the + key ignores it. - **Inputs and the clock (ADR 0293, ADR 0294, ADR 0337).** A command may declare `files` and `state` inputs (see [Inputs](#inputs-200-adr-0337)); its input then carries `files`, and it always carries `now`, the host's clock. - **Gates (1.10.0, ADR 0291).** A command may declare `gates`, local codes of its extension, and `subject`, the @@ -711,7 +718,9 @@ The host calls the export with a `CollectInput`, `{"reports": [{"path", its `files` inputs name, by read name, read after the run from the plain disk and absent when it declares none), and reads a `CollectOutput`, `{"entity_results": [{"entity_id", "test_results": [{"name", "status", "verify"?, "duration_ms"?}]}], "unlinked"?: [{"name", -"path", "status"}]}` (each test a `TestResult`), with `status` a `TestStatus`: +"path", "status"}], "warnings"?: [""]}` (each test a `TestResult`; each `warnings` line, about an entry the +collector read but could not use, is one W203 naming the collector, escaped, at most 100 per collector and then one +counting the rest, protocol 2.3.0, ADR 0389), with `status` a `TestStatus`: `passed`, `failed` or `skipped`, the one vocabulary of the collect wire, the recorded test report and a pass's test results. `entity_results`, each test's `name` and its `status` are required, and a status outside the three is not a @@ -839,26 +848,29 @@ sent". Facts are graph nodes, so a fact of a named collected kind changes like a delta once per check, only when a loaded pass declares it, and restricts it per pass to the kinds that pass names. **File reads (1.11.0, ADR 0293).** A pass, a command or a collector may declare `files` inputs, each -`{"input": "files", "name", "field"?, "glob"?, "root"?, "text"?}`: the project files it wants the host to read, because +`{"input": "files", "name", "field"?, "glob"?, "root"?, "text"?, "text_max"?}`: the project files it wants the host to read, because a guest has no file system. Exactly one of `field` (`kind.field` or `kind.field.member`: the paths the entities of that kind write there, each scalar's text or each item of a list) or `glob` (project-relative, `/`-separated; `*`, `?` and a `**` segment, at most four of them; never `..` or an absolute path). `name` is a word, unique among the owner's reads. `root` (a root's name, default `project`) says where a field's -bare paths start and is for a field read only. `text: true` asks for the file's text as well as its facts. A +bare paths start and is for a field read only. `text: true` asks for the file's text as well as its facts. +`text_max` (2.3.0, ADR 0390 D3; only with `text`) is the most text of one file the read sends, in bytes, instead of +64 KiB, at most 4 MiB (4194304); the read's text budget is then the larger of 1 MiB and four times it. A malformed read (neither or both of `field` and `glob`, a repeated name, a field no loaded extension declares, a glob -that is absolute, climbs with `..`, has an empty segment or has more than four `**` segments, `root` on a glob) is W021 from the registry build, and that read is served empty: the pass is kept. +that is absolute, climbs with `..`, has an empty segment or has more than four `**` segments, `root` on a glob, a +`text_max` that is zero, over 4 MiB or without `text`) is W021 from the registry build, and that read is served empty: the pass is kept. The input then carries `files`, `{"": {"facts": [FileFact], "truncated"?: true}}`. A `FileFact` is `{"path", "entity"?, "exists", "bytes"?, "lines"?, "digest"?, "text"?, "error"?}`, one per (entity, path) sorted by `(entity, path)` (a glob: by `path`): `path` is project-relative and normalised, `entity` is the entity whose field named it, `exists` follows links, `bytes`, `lines` and `digest` (`sha256:` over the CRLF-normalised bytes, the digest judged rules use) are present for a regular file that was read, and `text` is the UTF-8 file when the read asks for it. `error` says why text -or facts are missing: `too_large` (text over 64 KiB), `not_utf8`, `unreadable`, `outside_project`, `denied` (a text read of +or facts are missing: `too_large` (text over 64 KiB, or over the read's `text_max`), `not_utf8`, `unreadable`, `outside_project`, `denied` (a text read of a file that looks like a credential: `.env`, `.env.*`, `.envrc`, `*.pem`, `*.key`, `id_rsa*`, `id_ed25519*`, `id_ecdsa*`, `id_dsa*`, everything under `.ssh/` but `*.pub`, `known_hosts` and `config`, `.npmrc`, `.netrc`, `.pgpass`, `.pypirc`, `.dockercfg`, `.docker/config.json`, `.kube/config`, `.git-credentials`, `credentials*`, `.git/config`; the fact has `exists` and no text, digest or bytes, and the file is still a check input), `budget` (a read sends -at most 1 MiB of text in all); a path that does not exist is `exists: false`, not an error. `truncated` is set when a glob +at most 1 MiB of text in all, or four times its `text_max` when that is more, in path order); a path that does not exist is `exists: false`, not an error. `truncated` is set when a glob matched more than 2000 files or walked more than 20,000 entries. A glob never enters `.git`, `.specforge`, `.svn`, `.next`, `.venv`, `dist`, `node_modules`, `target` or `vendor` unless a literal segment names it, and does not descend into a directory reached through a symlink. A file whose real path (every symlink resolved) leaves the project is @@ -935,7 +947,7 @@ A name is dotted, or a family with `*` segments. `field_type` is a field type of ### Category: codes -Returns the extension's diagnostic code catalog (protocol 1.7.0, ADR 0286): one entry per code the extension's rules and passes report. `code` is the extension's own code, `[EWI]` and three digits, never qualified (the host adds the extension's namespace). `title` and `explanation` are required; `docs` (optional) is an absolute `http(s)` URL. `machine` (optional, protocol 2.0.0, ADR 0337 D7) is `true` when this machine decides the code's finding (its approvals, its network or its effects journal), not the project: the diagnostic carries `machine`, `--strict` never promotes it and the gate's warning baseline never counts it. `reported_while` (optional, protocol 2.2.0, ADR 0363) is `complete` or `pending`, an owner state (ADR 0329 D4): a finding of the code on an entity speaks only while the entity's owner is in that state, read after the compute passes, and the host drops it otherwise; a typed edit that moves the entity into that state reveals the finding, which is no error the edit adds (E080). Another word is E030. `settled_later` (optional, protocol 2.3.0, ADR 0385) is `true` when a later step of the authoring settles the code's finding (an open question a later answer resolves, a phase's requirement the rest of its plans hold): a typed edit whose plan creates the finding's subject, or an entity under it, and alters nothing the project held there (sets, unsets, links, unlinks, deletes or moves nothing at or under the subject) adds no error by it (E080); an edit that creates neither, one that also alters what the subject held, and a migration still do. Its severity does not change: `check`, `--strict` and every gate read it, and the edit lists it among the findings it reports. +Returns the extension's diagnostic code catalog (protocol 1.7.0, ADR 0286): one entry per code the extension's rules and passes report. `code` is the extension's own code, `[EWI]` and three digits, never qualified (the host adds the extension's namespace). `title` and `explanation` are required; `docs` (optional) is an absolute `http(s)` URL. `machine` (optional, protocol 2.0.0, ADR 0337 D7) is `true` when this machine decides the code's finding (its approvals, its network or its effects journal), not the project: the diagnostic carries `machine`, `--strict` never promotes it and the gate's warning baseline never counts it. `reported_while` (optional, protocol 2.2.0, ADR 0363) is `complete` or `pending`, an owner state (ADR 0329 D4): a finding of the code on an entity speaks only while the entity's owner is in that state, read after the compute passes, and the host drops it otherwise; a typed edit that moves the entity into that state reveals the finding, which is no error the edit adds (E080). Another word is E030. `settled_later` (optional, protocol 2.3.0, ADR 0385) is `true` when a later step of the authoring settles the code's finding (an open question a later answer resolves, a phase's requirement the rest of its plans hold): a typed edit whose plan creates the finding's subject, or an entity under it, and alters nothing the project held there (sets, unsets, links, unlinks, deletes or moves nothing at or under the subject) adds no error by it (E080); an edit that creates neither, one that also alters what the subject held, and a migration still do. Its severity does not change: `check`, `--strict` and every gate read it, and the edit lists it among the findings it reports. `facts` (optional, protocol 2.3.0, ADR 0389) lists the collected fact kinds the code judges (the kinds whose facts its passes read to raise it): `specforge doctor` names the codes no finding can speak for when no collector answers those kinds. Absent for a code about authored entities; a kind no extension declares is never matched. ```json { @@ -951,7 +963,7 @@ Returns the extension's diagnostic code catalog (protocol 1.7.0, ADR 0286): one } ``` -SDK: `c.code("E901", |d| { d.title(..).explanation(..).docs(..); })`; `.machine()` marks a machine code; `.once_complete()` and `.while_open()` write `reported_while`; `.settled_later()` writes `settled_later`. +SDK: `c.code("E901", |d| { d.title(..).explanation(..).docs(..); })`; `.machine()` marks a machine code; `.once_complete()` and `.while_open()` write `reported_while`; `.settled_later()` writes `settled_later`; `.facts(&["coverage"])` writes `facts`. ### Category: routes @@ -1053,8 +1065,9 @@ name or template is not sound, whose `call_kinds` are not exactly `collect` or w once, `{config}` without a `config`, an argv element holding two placeholders, `{filter}` in the argv, or a `filter` whose arguments do not hold `{filter}` exactly once, name `{report}` or `{config}`, or whose `call_kinds` are not exactly `collect`; so is a collector whose -`capability` names no `process` capability the extension declares, and one whose `install` line is empty, over 200 -bytes or not printable. An unknown `port` fails the +`capability` names no `process` capability the extension declares, one whose `install` line is empty, over 200 +bytes or not printable, and one whose `requires` (the other programs its command runs, which doctor looks up on +PATH) names something that is no bare program name. An unknown `port` fails the category (E028). SDK: `c.capability(Capability::http("links").hosts(&["*.example.com"]).why("check links"))`; a collector's @@ -1242,7 +1255,7 @@ Every call but the handshake and describe also carries the extension's own `sett | MCP tool | the tool's `export` (`mcp__`) | the JSON its `input_schema` describes | the JSON its `output_schema` describes | | MCP resource | the resource's `export` (`mcp__`) | `McpResourceRequest` `{"uri"}` | `McpResourceContent` `{"content", "mime_type"}` | | Compiler pass | `__pass_` | `PassInput` | `PassAnswer`: `[PassDiagnostic]` or `{"diagnostics", "summary"?}` | -| Collector | the collector's `export` (`collect__`) | `CollectInput` (a writing collector: `{"reports", "stdout"?, "cwd", "today", "now"?, "graph", "revisions"}`; `graph` carries computed values and judgements, ADR 0299) | `CollectOutput` (`{"entity_results", "unlinked"?, "plan"?}`) | +| Collector | the collector's `export` (`collect__`) | `CollectInput` (a writing collector: `{"reports", "stdout"?, "cwd", "today", "now"?, "graph", "revisions"}`; `graph` carries computed values and judgements, ADR 0299) | `CollectOutput` (`{"entity_results", "unlinked"?, "plan"?, "facts"?, "warnings"?}`) | | Value checks | `__check_values` | `CheckValuesInput` `{"phase", "items"}` (see [Category: checkers](#category-checkers)) | `CheckPlan` `{"items"}` | | Custom validator | the rule's `wasm_function` (`validate__`) | `ValidatorContext` `{"entity", "referenced", "declared_types", "primitives"}` | `ValidatorVerdict` `{"verdict": "pass"}` or `{"verdict": "fail", "field"?, "value"?}` | | Migration hook | the handshake's `migration_hook` | `MigrationInput` `{"from", "to", "files"}` | not read | @@ -1460,7 +1473,7 @@ or answered. | `2.0.0` | ADR 0337 (the ports round). A command, MCP tool or resource and a collector may call the five `specforge:host@0.1.0` ports (see [Host ports](#host-ports)), `syntax` parsing source with a tags query (ADR 0344, ADR 0345 D1). A pass, command, prompt, hook or collector declares what the host serves it as one tagged list, `inputs`: `files` (a `FileRead`), `tests`, `state`, `graph`, `slash_commands`, `git` (`status`, `when`) and `setting` (`extension`, `name`), replacing `reads`, `reads_tests`, `reads_state`, `reads_graph`, `reads_slash_commands`, `reads_git`, `reads_git_status`, `git_when` and `reads_settings` (see [Inputs](#inputs-200-adr-0337)); an input its call kind is not served, or a second one of a kind served once, is W021 and served empty. A hook's `git.status` is a typed `GitStatus` (`branch` with `oid`, `head`, `upstream`, `ahead`, `behind`; `entries` with `kind`, `path`, `orig_path`, `index`, `worktree`), not porcelain text. A `codes` entry may declare `machine` (`CodeDescriptor.machine`, see [codes](#category-codes)): its finding is this machine's, never promoted by `--strict` nor counted by the gate's warning baseline. A 1.x guest is E088 (older): its keys would be W138 and its inputs unserved. An extension declares `capabilities` (a describe category, see [capabilities](#category-capabilities)): what it may make the host do, each on one port under a scope name (ADR 0335 D2), and a collector names the process `capability` it runs instead of carrying `run`. An extension declares `checkers` (a describe category, see [checkers](#category-checkers)), a field its `checks`, and the host calls `__check_values` in a values phase that runs first (ADR 0336); `CollectInput` gains `check_outcomes`, for a collector declaring that input, and `facts`, for a collector declaring a `facts` input (`kinds`); a collector declares `answers`, the collected kinds whose facts it answers, which order the collect (E119 for a cycle) and admit its facts (E116 otherwise); a collector with no `capability` and no `report` reads through its ports (ADR 0345). A `Fact` carries `at` (a list of `FactLocation`: where it is written, a project-relative file, 1-based lines, 1-based byte columns, end exclusive) and `named_at` (field → id → places: where each name it holds is written); a `PassEntity` carries `dangling` (`DanglingReference`: `field`, `id`, `span`, `reason` `unresolved` \| `ambiguous` \| `mistyped`, `actual`, `did_you_mean`, `candidates`), a fact's references that name no entity, the wrong kind or several: sent to every pass, judged by the extension declaring the holder's kind (ADR 0346). An `UnheldReference` carries `kinds`, the collected kinds of its scheme its field admits, and a `FactStore` carries `held` (scheme → the kinds of its facts), replacing `schemes` (ADR 0347 D9). `CommandInput` gains `nonce`, 32 lowercase hex digits of the host's entropy, fresh per call (ADR 0341); a pass, prompt, hook or collector is not told one. A field may declare `checks_while`, `complete` or `pending` (ADR 0350), and a check row's status (`CheckOutcome.status`) may be `planned` or `closed`. The source scanners' describe category and their operation (and its request and response types) are gone: source code reaches the graph as the `item` facts a source pack collects (ADR 0199). A `process` capability may declare one `config` (`ProcessConfig`: `name`, `template`): the host writes it to `.specforge/reports/.` before the run, `{report}` expanded and escaped for a quoted string, and `{config}` in the argv names it; a `CollectorDescriptor` may declare `install`, the line said when its program is not found (ADR 0348). The git port answers `log` (a `log-query` of commit ids and paths from the repository's top: typed commits, their trailers and each signature's `name` and `seconds` (never an email address nor the signer's offset), as many as the answer holds, `truncated` past it or past the host's counted walk, which leaves no `count`; a pickaxe never reads a withheld file and is refused a withheld path) and `diff` (a `diff-query` from a commit or the empty tree to a commit, the index or the worktree, with `hunks`, a file's changed line ranges, and `renames`, searched by the host's rules: a file past the bytes the host reads for one diff says `truncated` and counts no lines; each `file-change` says `withheld` and then carries no `patch` nor `hunks`: a withheld name, or, against the worktree, a file the call's fs grant does not read) (ADR 0352). A collector's `auto_detect` may declare `repository`: it is detected when the git port locates the project root in a repository, git's ceilings kept, so a project in a subdirectory of its repository is (ADR 0352 D4). An `UnheldReference` carries `history` when its field is one the harness writes once (`writer: "harness"` and `immutable`): a pass reads it as what held then, never a missing fact (ADR 0352 D2). | | `2.1.0` | A contribution's `tools` may name the engine's tools (ADR 0334): `specforge:` (`specforge:trace`), `specforge:` (`specforge:reads`, `navigation`, `edits`, `output`, `setup`) and `specforge:.`, an extension command run as `specforge `. An unknown one, a human-attested or refused command, `mcp:specforge/…` and any `specforge:` class on a hook are W021. `specforge_protocol_types::engine_tools` is the catalogue they name. An extension declares `contexts`, the fifteenth describe category, read last: for one entity of a subject kind, the ordered sections a role reads, each a named selector, core or enrich (ADR 0356). A selector kind may carry a field filter, `kind[field=value|…]` (ADR 0356 D13). A context route may record its pack in a `context` field (`records`) and name the code a stale record raises (`stale`, ADR 0356 D10); an edit plan's `record_context` asks the host to record it (D11). A 2.0.0 guest still loads. | | `2.2.0` | A kind field or a block member may be `number` (ADR 0361): an exact decimal of at most 15 significant digits, written as one decimal word (`0.75`, `-0.25`, `1.5e3`), carried as a JSON number (an integer when whole and within `u64`) in the graph and a `FieldJson`; a pass entity carries a top-level number field as its canonical text in `fields` (`PassEntity::number` reads it) and a number member of a typed block as a JSON number in `values`; E061 refuses a word that is no decimal, has more digits or lies outside its bounds. A `number` field's `minimum` and `maximum` are decimals, compared exactly; a bound its type cannot read is W021 and dropped. `Decimal`, `GraphNode::number` and `PassEntity::number` read one. A judged target may declare `judged_while`, `complete` or `pending` (ADR 0362): an entity in the other owner state owes no verdict, decided on the merged snapshot after the compute passes; the SDK writes it with `once_complete()` and `while_open()`. A `codes` entry may declare `reported_while`, `complete` or `pending` (ADR 0363): its findings speak only on an entity in that owner state, and a typed edit that moves the entity into it reveals one rather than adding it (E080); the SDK's `CodeBuilder` writes it with `once_complete()` and `while_open()`. A `process` capability may declare `filter` (`ProcessScope.filter`): the arguments the host appends after `argv` only when a caller passes a filter (`specforge collect --filter`), `{filter}` in exactly one of them, approved with the command; no guest request is admitted on such a scope (ADR 0360). A declared `env` name may end in `*` after a namespace prefix (a letter, at least 4 characters, ending in `_`): the program inherits every variable with that prefix, and no guest sets a variable through it (ADR 0360). A program a guest runs and a collector's command the host runs go through one credential filter: a secret's name (now also `_AUTHTOKEN`, `_AUTH`, `PASSWORD` without its `_`, `_PASSWD`, `_PWD`, `_PAT`) and a cargo credential provider are withheld, and a URL's user and password, or a scheme-less proxy's, are removed (ADR 0360). A collector's command told its report path through `{report}` in its argv or config runs with `SPECFORGE_REPORT` removed from its environment, a value the caller exported included; one told it no other way gets it set to its report path over the caller's (ADR 0360). A 2.1.0 guest still loads; a 2.2.0 guest is refused by a 2.1 host (E088, newer). | -| `2.3.0` | A pass may declare the `delta` input (`kinds`, ADR 0376 D6; the SDK's `Input::delta(&["item"])`): its `PassInput` then carries `delta` (`DeltaPayload`), what changed of those kinds since a base the host names, and a pass that declares none is sent no `delta`. The payload names its `base`: `none`, the empty graph, so every node of the named kinds is `added` and a pass written for changes is correct on a cold run; `revision` with the full sha of the commit it is taken against (`check --since` and the MCP `validate` with `since`: the merge-base); or `previous`, the graph of a long-lived session's last completed check (ADR 0376 D7). `nodes` lists each changed node (`DeltaNode`: `kind`, `id`, `change` `added`, `removed` or `modified`), sorted by kind then id: a modified node names the `fields` and `aspects` (`title`, `methods`, `obligations`, `verdicts`, `edges`) that changed and its content digests `before` and `after` (`sha256:<64 hex>`), an added node its digest `after`, a removed node only its kind and id; a node whose kind changed is its old kind removed and its new kind added. `added_edges` and `removed_edges` list the edges with an end of a named kind. An empty list is absent, so a delta with nothing changed is its base alone. The full content stays in `entities`. A delta input declared twice, naming no kind or a kind no loaded extension declares is W021, as the `facts` input is. A `codes` entry may declare `settled_later` (ADR 0385; the SDK's `CodeBuilder::settled_later()`): a typed edit whose plan creates a finding's subject, or an entity under it, and alters nothing the project held there adds no error by a finding of that code (E080), and its severity does not change. A pass entity carries `title` (ADR 0387), the title its header writes, as a command's `GraphNode` does; absent for a fact written without one. A 2.2.0 guest still loads; a 2.3.0 guest is refused by a 2.2 host (E088, newer). | +| `2.3.0` | A pass may declare the `delta` input (`kinds`, ADR 0376 D6; the SDK's `Input::delta(&["item"])`): its `PassInput` then carries `delta` (`DeltaPayload`), what changed of those kinds since a base the host names, and a pass that declares none is sent no `delta`. The payload names its `base`: `none`, the empty graph, so every node of the named kinds is `added` and a pass written for changes is correct on a cold run; `revision` with the full sha of the commit it is taken against (`check --since` and the MCP `validate` with `since`: the merge-base); or `previous`, the graph of a long-lived session's last completed check (ADR 0376 D7). `nodes` lists each changed node (`DeltaNode`: `kind`, `id`, `change` `added`, `removed` or `modified`), sorted by kind then id: a modified node names the `fields` and `aspects` (`title`, `methods`, `obligations`, `verdicts`, `edges`) that changed and its content digests `before` and `after` (`sha256:<64 hex>`), an added node its digest `after`, a removed node only its kind and id; a node whose kind changed is its old kind removed and its new kind added. `added_edges` and `removed_edges` list the edges with an end of a named kind. An empty list is absent, so a delta with nothing changed is its base alone. The full content stays in `entities`. A delta input declared twice, naming no kind or a kind no loaded extension declares is W021, as the `facts` input is. A `codes` entry may declare `settled_later` (ADR 0385; the SDK's `CodeBuilder::settled_later()`): a typed edit whose plan creates a finding's subject, or an entity under it, and alters nothing the project held there adds no error by a finding of that code (E080), and its severity does not change. A pass entity carries `title` (ADR 0387), the title its header writes, as a command's `GraphNode` does; absent for a fact written without one. A `codes` entry may declare `facts`, the collected kinds it judges, a collector may declare `requires`, the other programs its command runs beside its argv's first, which `specforge doctor` looks up on PATH, and a collector's output may carry `warnings`, each reported as W203 (ADR 0389); a host that does not know them ignores them. A file read may declare `text_max` with `text` (ADR 0390 D3; the SDK's `FileReadSpec::text_up_to(bytes)`): the most text of one file it is sent, in bytes, instead of 64 KiB, at most 4 MiB, its text budget then the larger of 1 MiB and four times it; zero, over 4 MiB or without `text` is W021 and the read is served empty. A command may declare `imports` (ADR 0392; the SDK's `CommandBuilder::imports()`, which also declares `writes`): the host writes an extension's rule error about authored entities its plan adds and refuses a first-party one (E016 included) and one that judges collected facts (`code/E101`), and a host that does not know the key ignores it. A 2.2.0 guest still loads; a 2.3.0 guest is refused by a 2.2 host (E088, newer). | A host of `1.1.x` still loads a `1.0.0` guest and hands it the `1.1.0` values it knows; a host of `1.0.x` refuses a `1.1.0` guest (E088), and every host refuses a guest of another major (E088). A newer patch of the diff --git a/docs/extension-sdk.md b/docs/extension-sdk.md index 41722ab6bd..95e0644cae 100644 --- a/docs/extension-sdk.md +++ b/docs/extension-sdk.md @@ -223,6 +223,7 @@ impl Contributions for Greet { unlinked: Vec::new(), plan: None, facts: Vec::new(), + warnings: Vec::new(), }) }); }); @@ -288,7 +289,7 @@ Every contribution is a builder call. The SDK adds the matching Wasm exports and | `c.setting(name, \|s\| ..)` | a typed setting: `bool()`, `integer()`, `number()`, `string()`, `enum_values(..)`, `string_list()`, `block()`, `block_list()`, `default(..)`, `describe(..)`, `gates(..)`, `gates_when_on(..)`, `keys(..)` for a family | `settings` | | `c.preset(source, \|p\| ..)` | what each value of an enum or bool setting presets and raises: `p.when(value, \|e\| e.set(..).raise(..))` | `settings` | | `c.secret(name, env, description)` | a secret read from an environment variable | `settings` | -| `c.code(code, \|d\| ..)` | a diagnostic code the extension reports: `title(..)`, `explanation(..)`, `docs(..)` (an `http(s)` URL), `machine()`, `once_complete()` or `while_open()` (its owner state), `settled_later()` (a later step of the authoring settles it: a write that creates its subject, or under it, and alters nothing held there adds no error by it, ADR 0385) | `codes` | +| `c.code(code, \|d\| ..)` | a diagnostic code the extension reports: `title(..)`, `explanation(..)`, `docs(..)` (an `http(s)` URL), `machine()`, `once_complete()` or `while_open()` (its owner state), `settled_later()` (a later step of the authoring settles it: a write that creates its subject, or under it, and alters nothing held there adds no error by it, ADR 0385), `facts(&[..])` (the collected kinds it judges, which `specforge doctor` reads, ADR 0389) | `codes` | | `c.route(name, \|r\| ..)` | a route `specforge trace` follows from a kind: `start(..)`, `step(name, via, \|s\| ..)`, annotations | `routes` | | `c.context(name, \|r\| ..)` | a context route a role reads one entity through: `subject(..)`, `agent(..)`, `budget(..)`, `core(name, selector)`, `enrich(name, selector)`, `settings(..)`, `record(field, subject)`, `record_suggesting(field, subject, help)`, `stale(code)` | `contexts` | | `c.peer(name, range)`, `c.optional_peer(name, range)` | a peer requirement | handshake | @@ -403,7 +404,7 @@ descriptor, and routes the export to the handler. The CLI runs it as `specforge | `cmd.category(..)` | A CLI grouping | | `cmd.arg(name, \|a\| ..)` | Declares an arg (below) | | `cmd.handler(\|call\| ..)` | The function answering it: `CommandCall` in, `CommandOutput` out | -| `cmd.input(Input::files(name, FileReadSpec::field("kind.field").text()))` | Project files the host reads for the call (ADR 0293, ADR 0337): `call.files(name)` holds their facts and, with `.text()`, their capped text; `FileReadSpec::glob("src/**/*.rs")` names files by pattern. `cmd.input(Input::State)` asks for the extension's state | +| `cmd.input(Input::files(name, FileReadSpec::field("kind.field").text()))` | Project files the host reads for the call (ADR 0293, ADR 0337): `call.files(name)` holds their facts and, with `.text()`, their text capped at 64 KiB (`.text_up_to(bytes)`: at `bytes`, at most 4 MiB (`TEXT_MAX_CEILING_BYTES`), the read's budget the larger of 1 MiB and four times it); `FileReadSpec::glob("src/**/*.rs")` names files by pattern. `cmd.input(Input::State)` asks for the extension's state | A command's `call.now()` is the host's clock when it was called, `YYYY-MM-DDTHH:MM:SSZ` (RFC 3339, UTC, seconds; protocol 1.11.0, ADR 0294), the same instant as `call.today()`; a hook's `call.now()` and a writing collector's input carry it too. A prompt and a pass are not told the time. A command's `call.nonce()` is 32 lowercase hex digits of the host's entropy, fresh per call (ADR 0341): draw a command's random values from it, deterministically, so a test pins them as it pins the clock. It is randomness, not a secret; only a command is told one. @@ -516,7 +517,7 @@ A prompt is not a contract: the agent may ignore a step, and only a gate refuses ### Writing commands and collectors -An extension never writes files. A command that records what a person says declares `cmd.human()` (it writes, and the host runs it only for a person at a terminal, ADR 0301). A command declares `cmd.writes()` and answers an edit plan the host checks, judges +An extension never writes files. A command that records what a person says declares `cmd.human()` (it writes, and the host runs it only for a person at a terminal, ADR 0301). A command that imports history recorded outside the spec declares `cmd.imports()` (it writes, and its plan is judged for host errors only: an extension's rule error about authored entities lands and `check` reports it, a first-party one such as E016 or one judging collected facts such as `code/E101` refuses, ADR 0392; `@gsd/import` does). A command declares `cmd.writes()` and answers an edit plan the host checks, judges and applies all or nothing ([the wire](extension-protocol.md#writing), ADR 0289): ```rust @@ -565,7 +566,7 @@ c.collector("cargo-test", |k| { k.input_format("specforge-test-json") .detect_files(&["Cargo.toml"]) // project-root files that select it .run(&["cargo", "test", "--workspace"]) // declares its process capability; `{report}` is the report path - .report("target/specforge") // file or directory, inside the project + .report("target/specforge") // file, directory or glob, inside the project .capture_stdout() // also pass the command's stdout .collect(|input: &CollectInput| Ok(collect(input))); // the handler }); @@ -590,7 +591,16 @@ reaches the user's terminal, and the host also keeps it (in `.stdout.txt` inside a report directory) and passes it as `CollectInput::stdout`. `k.input(Input::files(name, FileReadSpec::glob("package.json").text()))` declares a project file the collector reads, as a command's `files` input does: its input's `files[name]` holds the facts (and, with `.text()`, the -capped text), read by the host after the run. The guest never runs anything itself. +capped text; `.text_up_to(bytes)` raises the 64 KiB cap to at most 4 MiB), read by the host after the run. The guest never runs anything itself. + +A report may also be a glob over project files the tool writes itself (`.report("**/rust-sbom.cdx.json")`, ADR +0389): after each run the host reads every match modified since the run started (with `--no-run`, every match), +walked as an `Input::files` glob is (build output such as `target/` and `node_modules/` skipped unless the glob names +it, no link entered, at most 20,000 entries), and removes nothing first. The glob's last segment is a literal file +name: `.report("**/*.json")` panics in the SDK and a raw declaration of one is E030, so a glob never reads every file +of a kind. A report's files hold at most 64 MiB together (what a captured output may hold), past which the collect is +E045. Such a command is told no path: `{report}` in its argv or config, or `capture_stdout()`, beside a glob is E058, +and `SPECFORGE_REPORT` is not set. A handler may also answer `facts` (protocol 1.15.0, ADR 0327), the entities it observed, each of a kind its extension declares `collected(..)`: diff --git a/docs/guides/code-report-facts.md b/docs/guides/code-report-facts.md new file mode 100644 index 0000000000..3890dcd8bf --- /dev/null +++ b/docs/guides/code-report-facts.md @@ -0,0 +1,211 @@ +# Standard reports as code facts + +Five standard reports become facts a spec can cite: coverage, API snapshots, lint findings, bills of materials and +vulnerability scans. Each is read by its own extension library, and `specforge-code-facts` mints the facts from what it +reads. `@code/core` declares the five report kinds and checks them +([ADR 0388](../adr/0388-x2-is-the-share-of-test-ids-a-standard-report-saw.md)). + +| Report | Library | Kind | Scheme | +|--------|---------|------|--------| +| LCOV tracefile | `specforge-code-lcov` | `coverage` | `cov` | +| `cargo public-api` text, api-extractor `.api.json` and `.api.md` | `specforge-code-api` | `api_item` | `api` | +| SARIF 2.1.0 log | `specforge-code-sarif` | `static_finding` | `sarif` | +| CycloneDX JSON BOM | `specforge-code-cyclonedx` | `dependency` | `dep` | +| `osv-scanner --format json` report | `specforge-code-osv` | `vulnerability` | `vuln` | + +The libraries are rlibs in `extensions/code/`. The report packs link them: each runs one standard tool, after you +approve its command once per project, and collects its report +([ADR 0389](../adr/0389-report-packs-run-standard-tools-and-doctor-names-a-missing-one.md)). Enable one with +`specforge add @rust/coverage`; it also enables the source pack whose facts it reads, and `specforge collect` runs it +when its project file is found. A report fact cites the facts the source and manifest packs collected, the `item` +holding its location or the `package` it is about, so those packs collect first. `specforge doctor` names each tool a +detected pack runs that is not installed, with its install line and the codes it feeds. + +| Pack | Collector | Tool and install line | Reader | Facts | +|------|-----------|-----------------------|--------|-------| +| `@rust/coverage` | `rust-coverage` | cargo-llvm-cov over nextest: `cargo install cargo-llvm-cov cargo-nextest --locked` | `specforge-code-lcov` | `coverage` | +| `@rust/lint` | `rust-lint` | clippy, its JSON captured: `rustup component add clippy` | its own clippy converter | `static_finding` | +| `@rust/deps` | `rust-sbom` | cargo-cyclonedx: `cargo install cargo-cyclonedx --locked` | `specforge-code-cyclonedx` | `dependency` | +| `@rust/deps` | `rust-osv` | osv-scanner on `Cargo.lock`: `go install github.com/google/osv-scanner/v2/cmd/osv-scanner@latest` | `specforge-code-osv` | `vulnerability` | +| `@rust/api` | `rust-api` | cargo public-api, captured: `cargo install cargo-public-api --locked` (and a nightly toolchain) | `specforge-code-api` | `api_item` | +| `@rust/proof` | `rust-proof` | Kani, captured: `cargo install --locked kani-verifier && cargo kani setup` | `specforge-code-kani` | `test`, `test_run` | +| `@javascript/coverage` | `javascript-coverage` | c8 around `npm test`: `npm install --save-dev c8` | `specforge-code-lcov` | `coverage` | +| `@javascript/lint` | `javascript-lint` | ESLint's SARIF formatter: `npm install --save-dev eslint @microsoft/eslint-formatter-sarif` | `specforge-code-sarif` | `static_finding` | +| `@javascript/deps` | `javascript-sbom` | cyclonedx-npm: `npm install --save-dev @cyclonedx/cyclonedx-npm` | `specforge-code-cyclonedx` | `dependency` | +| `@javascript/deps` | `javascript-osv` | osv-scanner on `package-lock.json`, as for Rust | `specforge-code-osv` | `vulnerability` | +| `@javascript/api` | `javascript-api` | api-extractor, a config the host writes: `npm install --save-dev @microsoft/api-extractor typescript` | `specforge-code-api` | `api_item` | +| `@javascript/vitest` | `javascript-vitest` | vitest's JUnit reporter: `npm install --save-dev vitest` | `specforge-code-junit` | `test`, `test_run` | +| `@javascript/jest` | `javascript-jest` | jest with jest-junit: `npm install --save-dev jest jest-junit` | `specforge-code-junit` | `test`, `test_run` | +| `@javascript/playwright` | `javascript-playwright` | Playwright's JUnit, captured: `npm install --save-dev @playwright/test` | `specforge-code-junit` | `test`, `test_run` | + +`@rust/proof` mints a `test` per Kani harness, `rust:#`, placed at its function. Kani runs on +Linux x86_64 and macOS only, not on Windows. There is no JavaScript proof pack: no JavaScript tool proves a property of +all inputs with a verdict per harness the way Kani does, property-based testing already reports as tests through the +runner packs, and TypeScript's checker proves types, not behaviour (ADR 0389 D2). The legacy `@specforge/vitest` +stays a separate pack beside `@javascript/vitest`; their collectors are `vitest` and `javascript-vitest`. + +## What each reader accepts and mints + +**LCOV.** `read` takes a tracefile as geninfo(1), `cargo llvm-cov --lcov` and c8 or istanbul `lcovonly` write it. It +reads `FN`/`FNDA` (the n-th `FNDA` of a name pairs with the n-th `FN` of it, so two impls' `new` keep their own +counts), `FNL`/`FNA`, `DA` and `BRDA`, and ignores `TN`, `VER`, the file totals, `MCDC`, comments and unknown +keys. Sections of one file merge. One `coverage` fact per innermost item holding reported lines, `cov:`, cites +that item (edge `covers`); what no item of a file holds is `cov:@`. The counts are `functions_found`/`_hit`, +`lines_found`/`_hit` and `branches_found`/`_hit`. + +**API snapshots.** `read_rust_text` reads a `cargo public-api` text snapshot; `read_js_model` reads an api-extractor +doc model. No format is sniffed: a pack calls the reader of its own. One `api_item` per public entry, +`api:rust:::` (a trait-impl member `…::::m`) or `api:js:::[.]`, cites +the item with that path (edge `api_of`). The id holds no line, no order and no source file; `signature` is kept +verbatim. The same id with another signature takes `~2`. `read_js_report` reads an api-extractor API report +(`.api.md`), the accepted side below. + +**SARIF.** `read` takes version `2.1.0` only. The rule is `ruleId`, else `rule.id`, else the driver rule its index +names; the level is the result's, else `none` for a `kind` other than `fail`, else the rule's +`defaultConfiguration.level`, else `unknown`. SARIF's own `warning` default is never applied. One `static_finding` per +result, `sarif:/#:` (`~2` on a repeat), cites the innermost item holding its line (edge +`found_in`), else the package holding its file (edge `found_in_package`). Of two packages at one directory (a crate +with a `package.json`), it is the one of the file's ecosystem, read from an item on the file, else its manifest name or +extension; with no such evidence the finding names neither. + +**CycloneDX.** `read` takes `bomFormat` `CycloneDX` with `specVersion` `1.4`, `1.5` or `1.6`, and needs +`metadata.component`, the project package the BOM describes: of two packages of one name, the one whose directory is +the root purl's subpath, else the one whose id is the purl's exactly. Components flatten depth first; a missing `scope` reads +`required`; `direct` is set only when the BOM states the root's `dependsOn`. One `dependency` per component, +`dep:/`, cites that package (edge `dependency_of`); a component with +no purl is `dep:/@<[group/]name[@version]>`. + +**OSV.** `read` takes an osv-scanner report whose sources are `lockfile` or `sbom`. Each scanned lockfile cites the +project package of its ecosystem at its directory, else each one under it. One `vulnerability` per package and OSV id, +`vuln:/`, cites that package (edge `affects`); purls, versions and aliases of one id are united. +A package of an ecosystem other than `crates.io` and `npm`, or one whose lockfile no collected package of its type +holds, mints nothing and is named in `Vulnerabilities::skipped` (name, version, lockfile, record count and reason), so +a `requirements.txt` beside a `Cargo.lock` never hides the cargo findings. + +A report id's parts are percent-encoded (`%`, `/`, `#`, `:`, `~`, `@`, `?`, whitespace and control characters), so an +id parses back to its parts and no report text forges a delimiter or a `~2` suffix. A Rust API path segment keeps a +plain space (``), and a JavaScript API name encodes its own `.` (`%2E`), which joins a member path. + +## The accepted API side + +An `api_item` says what the public API is now. The API packs also say how it moved since it was last accepted +([ADR 0390](../adr/0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md) D3). The +accepted side is the report the project commits for review, each tool's own baseline: + +| Pack | Read | Glob | The committed file | +|------|------|------|--------------------| +| `@rust/api` | `accepted` | `**/public-api.txt` | cargo-public-api's snapshot (`tests/public-api.txt`, `tests/snapshots/public-api.txt`), written with the pack's own flags: `cargo public-api --color never -ss > public-api.txt` | +| `@javascript/api` | `accepted` | `**/etc/*.api.md` | api-extractor's API report, `etc/.api.md` | +| `@javascript/api` | `reviews` | `common/reviews/api/*.api.md` | rush's API report folder | + +Never `**/*.api.md`: api-extractor's `temp/` holds the run's own copy of the report, which would hide every break. The +`.alpha.api.md`, `.beta.api.md` and `.public.api.md` variants are not read either. + +The packs read the file as a declared file read, `Input::files(..)` with +`FileReadSpec::text_up_to(TEXT_MAX_CEILING_BYTES)` (4 MiB, the SDK prelude's constant): the host refuses a file outside +the project or reached through a link (a symbolic link always; a hard link, a file with a second name, when the request +is bounded, as MCP's is, so the file reads as `unreadable` and its pack warns), and never sends a credential-looking +file as text, as for any read. `text_up_to` raises a read's text ceiling from 64 KiB to at most 4 MiB, and its budget +to the larger of 1 MiB and four times the ceiling (protocol 2.3.0). The file is not read as a report: a report is read only when the run wrote it, and a +committed file is older than the run. + +**`change`.** Each `api_item` of a crate or package present on both sides carries `change`: `added`, `unchanged`, +`changed`, `narrowed` or `removed`. A changed, narrowed or removed entry also carries `accepted_signature`, +`accepted_tag` (when the accepted entry has one) and `accepted_visibility` (when it differs). The id does not change, +and an entry gone from the code is a fact with `change` `removed`, which `code/W104` skips. A crate or package on one +side only is not judged: its facts carry no `change`. Accepted `@internal` entries are skipped. The release tags rank +Public, Beta, Alpha, Internal, and a member with no tag of its own inherits its container's, so narrowing a class +narrows each member. Entries pair by base id, then by comparable signature, never by a `~2` suffix. `changed`, +`narrowed` and `removed` are breaking, `added` is not: `@gsd/core` lists the breaking ones in `milestone.api_breaks` +and `gsd/E533` refuses to close a milestone whose version does not allow them. + +**Outcomes.** + +- No accepted file: no fact carries `change`. Committing the report is the opt-in. +- An accepted file of the run's own crate or package (its `pub mod ` line, its report title) that does not + parse (a merge-conflict marker, a broken fence), or two accepted files of one crate or package (an old + `tests/public-api.txt` kept beside `tests/snapshots/public-api.txt`): the collector's error naming them, and the + collect stores nothing of the run. +- A file the host did not serve (`too_large`, `budget`, `not_utf8`), a matched file that is no report or snapshot + (prose in an `etc/` folder), or one naming no crate or package the run read, broken or not: one warning naming it, + shown as W203, no break judged against it, and the collect goes on. + +**Accepting a break.** The packs never write the accepted file: api-extractor's `apiReport` stays disabled in the pack's +config. You accept a break by committing the updated report: `cargo public-api --color never -ss > +tests/public-api.txt`, or `api-extractor run --local` with `apiReport` enabled in your own config (it copies +`temp/.api.md` to `etc/`). Then run `specforge collect`. Write the file with the tool version CI runs: a tool +upgrade can change every line. + +**Limits.** A required method added to a trait cannot be seen in the text. A Rust visibility narrowing reads as +`removed`, because cargo public-api prints public items only. An attribute change (`#[non_exhaustive]`, `#[must_use]`) +reads as `changed`. The globs walk the whole project but the skipped folders (`.git`, `node_modules`, `target`, …), and +a walk stops after 20,000 entries (`GLOB_VISITS_MAX`) or 2,000 matches (`FILE_READ_MAX`): in a larger repository the +accepted files past the cut are not read, no break is judged for their crates or packages, and the pack's W203 says the +read stopped early, naming both caps. + +## What a reader refuses + +A reader returns an error, and the collect mints nothing from that report, when: + +- a SARIF URI is of a scheme other than `file:` (`https:`), so it names no file of the project; + + A path outside the project is not refused: an LCOV `SF` section, or a SARIF result whose `file:` URI (or relative + URI climbing out through `..`) the project does not hold, is skipped and counted, never opened, and the pack reports + the count and the paths as W203 (ADR 0389 D7). +- the version is one it does not read (SARIF other than `2.1.0`, CycloneDX other than `1.4` to `1.6`); +- the document is malformed or lacks a required key: the error names the line, the JSON path or the value; +- a BOM's `metadata.component` belongs to no collected package. + +## Reserved entity names + +The five kinds are declared by `@code/core`, so a project that loads it cannot name an entity `coverage`, `api_item`, +`static_finding`, `dependency` or `vulnerability`: the compiler reports E013. Rename the entity (for example +`test_coverage`); the reader facts are not entities and are not affected. ADR 0388 records the choice. + +## What stays unmapped + +An entry the reader cannot place is kept, never dropped, and the `reports` pass of `@code/core` raises one warning per +class. The pass is sent only the five report kinds, and skips a pending fact. + +| Code | Class | +|------|-------| +| `code/W104` | A `coverage`, an `api_item` of a kind an item can have (not a crate root), or a `static_finding` that names no item; a finding is reported only when no package holds its file either | +| `code/W105` | A `static_finding` whose rule or level reads `unknown` | +| `code/W106` | A `dependency` with no purl, named by name and version only | +| `code/W107` | A `vulnerability` whose severity is `unknown` | + +`specforge explain code/W104` prints each code's explanation and remedy. + +## Severity + +A vulnerability's severity is one of `critical`, `high`, `medium`, `low`, `unknown`, in that order. It is the OSV +record's own label (`database_specific.severity`; `MODERATE` reads `medium`). With no label, it is the rating of the +record's highest CVSS v3 base score: the v3.0 or v3.1 base formula with its integer round-up, in tenths, rated `low` +under 4.0, `medium` under 7.0, `high` under 9.0, else `critical`. A v4 or v2 vector, or a malformed v3 one, is not +rated: with nothing else the severity is `unknown` (`code/W107`), never a guess. One id merged from several records keeps the +highest. + +## The X2 line + +X2 is the share of items carrying a test id whose test a standard test report saw. `cargo gate full`'s dogfood check +computes it for SpecForge, the taskboard fixture, the ledger fixture and the vault fixture, and writes each line to its +dogfood log. SpecForge's line reads the JUnit reports of the root tests, of every extension guest +(`target/nextest//junit-guests/`) and of the `@gsd` workspace (`junit-gsd/`). A fixture's line reads its recorded test +report and the reports `gsd/parity/record-reports.sh` records under `gsd/parity/goldens//reports/`; the +fixture itself is left untouched: + +``` +X2 SpecForge: N/N (100.0%) +X2 taskboard: 3/3 (100.0%) +X2 ledger: 6/6 (100.0%) +X2 vault: 3/3 (100.0%) +``` + +X2 is a floor ([ADR 0393](../adr/0393-x2-is-a-floor-every-real-test-reaches-and-only-tests-count.md), refining +[ADR 0388](../adr/0388-x2-is-the-share-of-test-ids-a-standard-report-saw.md)): every project reaches 100% of its N +items. A project below 100%, or with no item carrying a test id (`0/0`), fails the check, which names up to ten missing +ids per project; the log lists all of them. Each run first proves the floor fails, on a copy of the ledger's report +missing one case, and logs `negative control passed: …`. The check needs `cargo-nextest`. + +The percent rounds down, so `100.0%` means no item is missing. An export of another shape is the check's error, never +a `0/0` line. diff --git a/docs/guides/javascript-facts.md b/docs/guides/javascript-facts.md index 294584320a..f72593d1dd 100644 --- a/docs/guides/javascript-facts.md +++ b/docs/guides/javascript-facts.md @@ -39,10 +39,20 @@ with the TypeScript grammar, and every `.tsx`, `.js`, `.jsx`, `.mjs` and - **A file under no named package.** A file's package is the nearest `package.json` with a `name` at or above it. A stray script outside every named package is outside the pack, as `node-test` refuses a test there. -- **Test files**: a name holding `.test.`, `.spec.`, `-test.` or `_test.`, or - starting `test-` or `test.`, and anything under a `test`, `tests`, - `__tests__` or `__mocks__` directory. A runner pack records the tests; their - helpers are no API. +- **Test files, but for their test calls**: a name holding `.test.`, + `.spec.`, `-test.` or `_test.`, or starting `test-` or `test.`, and anything + under a `test`, `tests`, `__tests__` or `__mocks__` directory. A second + query reads for its statically named test calls only, each an item + (section 5), a test file `node --test` runs by default, since node-test + names the tests: `*.test.*`, `*-test.*`, `*_test.*`, `test-*.*`, `test.*` + and anything under a `test` directory of the project, in `.js`, `.cjs`, + `.mjs`, `.ts`, `.mts` or `.cts` (node 23.6 and later run TypeScript). A + test file of a package this pack does not read (a fixture under `test/`) + gives no item, as node-test names its tests after that package. A test + file's helpers are no API and no item. A test file the reader could not + parse (too large, not UTF-8, withheld, past its deadline) gives no item and + a warning naming it; a source file the reader could not parse fails the + collector, which reads every kept source file or none. - **Generated output**: a `.min.js`, `.min.mjs` or `.min.cjs` file, and anything under `coverage`, `build`, `out`, `.nuxt`, `.svelte-kit`, `.turbo`, `.cache` or `storybook-static`. The host's walk never enters `dist`, @@ -98,6 +108,41 @@ expression handed to a call. is its path from the project root. An item id never holds `#`, a test id always does, so an item and a test of one file cannot clash. +A test call in a test file is a `function` item with the attribute `test` +([ADR 0393](../adr/0393-x2-is-a-floor-every-real-test-reaches-and-only-tests-count.md)). +Its id is `js:/::.`, the names of the calls +around it outermost first, then its own. A call node reports as a test case +(below) also carries `test_id`, +`js:/# … > name>`, the id `@javascript/node-test` +gives the same test, so X2 counts it: + +```js +// package.json: { "name": "taskboard" } test/tasks.test.js: +test('a task is added with the next id', () => { /* ... */ }) +// item js:taskboard/test/tasks.test.js::a task is added with the next id +// test_id js:taskboard/test/tasks.test.js#a task is added with the next id +``` + +- A call counts when its name is static and not empty: a string, or a + template with no substitution. It is `describe` or `suite`, `test` or `it` + with a function argument, one of those with `.skip`, `.todo` or `.only`, or + a subtest `t.test(name, fn)` inside a test. +- node's JUnit report writes a test or a suite as a `` when a + test, suite or subtest ran inside it, else as a ``. So a call + carries a test id when it has `.skip`, or when no `test`, `it`, `describe`, + `suite` or subtest call sits inside it: an empty `describe` and one with no + function are test cases. A call holding one, even one that is no item (a + subtest named by a variable or given a function reference), carries none. +- node never runs a skipped call's function, so nothing inside a `.skip` + call, or a call whose options have a `skip` key (`{ skip: true }`), is an + item. Such a call with options carries a test id only when nothing sits + inside it. A `.todo` call runs its function: what it holds is read. +- A dynamic name (`test(name, …)`, `.each`, `.concurrent`) or an empty one + (node names it `` or after its function) mints nothing, nor does + anything inside that call, and raises nothing. +- Subtests a helper registers out of the call's sight (`await check(t)`) are + not seen: the test keeps its test id though node reports it as a suite. + Two `package.json` may give one name (an example app beside the real one): the package in the shallowest directory (then the lexically first) keeps `pkg:npm/`, every other is `pkg:npm/#`, and its items and @@ -141,4 +186,4 @@ dependency on that name is the shallowest the pack reads. | `: the host's reader did not parse it ()` | The host could not read the file (too large, not UTF-8), refused it (`denied`: a name the fs port withholds, a link out of the project, a file with a second name) or its parse ran out of time. The pack reads every kept file or none: move a generated file under a skipped directory or rename it `.min.js`. | | `: its matches alone pass the host's answer cap` | One file declares more than an answer holds; it is almost always generated. | | `**/*.: the project holds more files than the host walks` | The project holds over 20,000 entries the walk visits: the files past them cannot be asked, whatever else the answer holds. | -| No item for a file you expected | It is a test file, generated output, or under no named package (section 3). | +| No item for a file you expected | It is generated output or under no named package (section 3). In a test file only the statically named test calls are items: a helper is none, and a dynamically named test has none (section 5). | diff --git a/docs/guides/node-test-facts.md b/docs/guides/node-test-facts.md index 33a84d24f8..9227002802 100644 --- a/docs/guides/node-test-facts.md +++ b/docs/guides/node-test-facts.md @@ -73,6 +73,9 @@ test('a task is added with the next id', () => { /* ... */ }) // js:taskboard/test/tasks.test.js#a task is added with the next id ``` +`@javascript/source` gives the matching test call the same id as its +`test_id`, so X2 counts it ([guide](javascript-facts.md)). + ## 4. Cite a test Cite a test by its id, quoted, in a field that names test facts. A GSD truth diff --git a/docs/guides/rust-facts.md b/docs/guides/rust-facts.md index b9836dc329..192ac565b7 100644 --- a/docs/guides/rust-facts.md +++ b/docs/guides/rust-facts.md @@ -62,6 +62,23 @@ order, each served the facts of the one before: `collect` says so, and the failing tests are recorded as `failed`. - **Your own run:** run nextest with that config yourself, then `specforge collect --runner rust-test --no-run`. +- **Fixture crates:** a `Cargo.toml` that is no package of the project (a + test fixture, an example) is left out by `@rust/cargo`'s `exclude` setting + in `specforge.json`. Each entry is a directory relative to the project root, + written with `/` (`.` segments and extra `/` are dropped: `./examples/` is + `examples`). `rust-cargo` still reads every manifest (a workspace inherits + from them) but answers no package for one under an entry, so `rust-source` + reads no item there and no test id is minted. The packs that run a tool + (`rust-test`, coverage, lint, deps) still run it over the whole cargo + workspace. An empty or absolute entry, a `..` segment, a `\`, + or an entry naming the root itself (`.`) fails the collector with + `exclude entry '' is not a project-relative directory`. + + ```json + "settings": { + "@rust/cargo": { "exclude": ["examples", "xtask/tests/fixtures"] } + } + ``` ## 3. The ids @@ -94,7 +111,19 @@ fn adds() { assert_eq!(add(1, 2), 3); } ``` nextest leaves an `#[ignore]`d test out of its report; `rust-test` records it -as `skipped` from its item, so a spec citing it is not `code/E101`. +as `skipped` from its item, so a spec citing it is not `code/E101`. A test the +report lacks whose `cfg(...)` is false on the host (`windows` on Linux or +macOS, `unix` on Windows, `target_os = "windows"`, …; the host's family is +read from the project root's path) was compiled out, and is recorded +`skipped` the same way. On a unix host `target_os = "linux"` or `"macos"` is +not decided, so such a test the report lacks stays missing. Every `cfg(...)` +that compiles an item out is in its `attrs`: its own, those of the modules +around it (`#[cfg(windows)] mod tests { … }`), its file's `#![cfg(...)]` and +those on the `mod` declarations that reach its file. An attribute naming +`__guard_only` marks no test; with several spec-link attributes stacked and +no runner attribute, the lowest one decides, as the macro registers it. A +function no test is registered for carries no `test_id` +([ADR 0393](../adr/0393-x2-is-a-floor-every-real-test-reaches-and-only-tests-count.md)). ## Things to know @@ -121,4 +150,4 @@ as `skipped` from its item, so a spec citing it is not `code/E101`. | `` `cargo-nextest` was not found on PATH `` | Install nextest: `cargo install cargo-nextest --locked`. | | `E045` rust-test produced no report at … | The build failed before nextest ran, or your own config's `specforge` profile wrote the report elsewhere. Run the command above yourself to see nextest's output. | | `: the host did not serve it ()` | The host withheld a `Cargo.toml` (too large, not UTF-8, unreadable). `rust-cargo` reads every manifest or none. | -| `the read '…' matched more files than the host serves` | The project holds over 2,000 manifests or target files of one kind. | +| `the read '…' stopped early` | The host's walk of the project reached its cap of 20,000 entries, or the project holds over 2,000 manifests or target files of one kind. | diff --git a/docs/quick-reference.md b/docs/quick-reference.md index b6aa42c8c1..088bedba95 100644 --- a/docs/quick-reference.md +++ b/docs/quick-reference.md @@ -148,7 +148,7 @@ specforge migrate # bring .spec files to the current format: specforge collect # run the test runners (with your approval) and record what they prove specforge grants # what the extensions may make the host do here, and this machine's approvals; approve, revoke, --store specforge grants approve --root workspaces --at ~/gsd-workspaces # name a root on this machine, for every project's verbs (no extension's); revoke --root --machine -specforge doctor # health-check installed extensions and the files install wrote into a host +specforge doctor # health-check installed extensions and the files install wrote into a host; also names a detected collector's missing tool (cargo-llvm-cov, Kani, ...) with its install line specforge install claude-code # write the extensions' agents, skills, slash commands and hooks into a host (codex, cursor too); --check, --dry-run, --force specforge uninstall claude-code # remove exactly what install wrote specforge mcp # start the MCP server (stdio); specforge.edit applies a list of typed edits diff --git a/evaluation/gsd-ab/tasks.json b/evaluation/gsd-ab/tasks.json index 1736cd3e5e..3d1386b4fa 100644 --- a/evaluation/gsd-ab/tasks.json +++ b/evaluation/gsd-ab/tasks.json @@ -16,7 +16,7 @@ { "id": "A", "state": "gsd-core 1.19.0 .planning/ Markdown", "tools": ["gsd-tools"], "config": null, - "drop": ["spec/", "specforge-harness", "README.md"] + "drop": ["spec/", "specforge-harness", "specforge.json", "README.md"] }, { "id": "B", "state": "SpecForge @gsd/core, gsd-strict, the .spec graph", "tools": ["specforge", "specforge mcp", "specforge collect", "specforge trace"], @@ -77,22 +77,22 @@ ] }, "fixtures": [ - { "id": "taskboard", "path": "gsd/parity/fixtures/taskboard", "tree": "e9d400f9ae7e0cf8f7c73f6495ed767677a7376d", "status": "ready", "thread": ["@code/core", "@javascript/node-test", "@javascript/source"], + { "id": "taskboard", "path": "gsd/parity/fixtures/taskboard", "tree": "fa7471e24fcb6f02fc1d3f2215afef48ed5919f7", "status": "ready", "thread": ["@code/core", "@javascript/node-test", "@javascript/source"], "baseline": [ "I213 -:0", "gsd/W311 spec/plans.spec:192", "gsd/W313 spec/plans.spec:192", "gsd/W315 spec/plans.spec:192", "gsd/W316 spec/plans.spec:192", "gsd/W407 spec/plans.spec:101", "gsd/W407 spec/plans.spec:110", "gsd/W407 spec/plans.spec:14", "gsd/W407 spec/plans.spec:23" ] }, - { "id": "vault", "path": "gsd/parity/fixtures/vault", "tree": "a00b1dfc6e163d31e52bc7828a072a6455ad68ec", "status": "ready", "thread": ["@code/core", "@javascript/node-test", "@javascript/source"], "extensions": ["@gsd/security"], + { "id": "vault", "path": "gsd/parity/fixtures/vault", "tree": "ff0fc44a4f84a55698c341825686e21a6278c2c6", "status": "ready", "thread": ["@code/core", "@javascript/node-test", "@javascript/source"], "extensions": ["@gsd/security"], "baseline": [ "I213 -:0", "W019 -:0", "gsd.security/E101 spec/plans.spec:166", "gsd.security/E101 spec/plans.spec:82", "gsd.security/W302 spec/plans.spec:176", "gsd.security/W302 spec/plans.spec:187", "gsd.security/W302 spec/plans.spec:70", "gsd.security/W302 spec/plans.spec:82", "gsd.security/W302 spec/plans.spec:94", "gsd.security/W303 spec/security.spec:1", "gsd/E501 spec/plans.spec:129", "gsd/E501 spec/plans.spec:134", "gsd/E501 spec/plans.spec:141", "gsd/E501 spec/plans.spec:32", "gsd/E501 spec/plans.spec:37", "gsd/E501 spec/plans.spec:44", - "gsd/W103 spec/v1.0.spec:17", "gsd/W311 spec/plans.spec:199", "gsd/W313 spec/plans.spec:199", "gsd/W315 spec/plans.spec:199", + "gsd/W103 spec/v1.0.spec:15", "gsd/W311 spec/plans.spec:199", "gsd/W313 spec/plans.spec:199", "gsd/W315 spec/plans.spec:199", "gsd/W316 spec/plans.spec:199", "gsd/W407 spec/plans.spec:120", "gsd/W407 spec/plans.spec:14", "gsd/W407 spec/plans.spec:23" ] }, - { "id": "ledger", "path": "gsd/parity/fixtures/ledger", "tree": "4ac8c20bb145d803f6635ea60ddd8772c6f55da9", "status": "ready", "thread": ["@code/core", "@rust/cargo", "@rust/source", "@rust/test"], + { "id": "ledger", "path": "gsd/parity/fixtures/ledger", "tree": "d7bd6006a68101d06dbeb6fbc701fd59b3756063", "status": "ready", "thread": ["@code/core", "@rust/cargo", "@rust/source", "@rust/test"], "baseline": [ "I213 -:0", "gsd/E501 spec/quick.spec:20", "gsd/E501 spec/quick.spec:25", "gsd/W311 spec/plans.spec:210", "gsd/W313 spec/plans.spec:210", "gsd/W315 spec/plans.spec:210", "gsd/W316 spec/plans.spec:210", "gsd/W407 spec/plans.spec:119", diff --git a/examples/marketing/extension/wasm/inputs.json b/examples/marketing/extension/wasm/inputs.json index b84e52bba7..11c16453ed 100644 --- a/examples/marketing/extension/wasm/inputs.json +++ b/examples/marketing/extension/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "marketing.wasm", - "artifact_sha256": "cf2be6228d2c707a8ac0679ba26b3f0ecc5867d8e7bb638191d06f0d8911e102", + "artifact_sha256": "513e0c30b9d605d128b7e570314906e6d4be07ccd77a246e116e3ddf0b337739", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,14 +55,14 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", diff --git a/examples/marketing/extension/wasm/marketing.wasm b/examples/marketing/extension/wasm/marketing.wasm index 85164218b5..979dd62788 100644 Binary files a/examples/marketing/extension/wasm/marketing.wasm and b/examples/marketing/extension/wasm/marketing.wasm differ diff --git a/extensions/cargo-test/src/lib.rs b/extensions/cargo-test/src/lib.rs index ee4dd30fd7..f261319756 100644 --- a/extensions/cargo-test/src/lib.rs +++ b/extensions/cargo-test/src/lib.rs @@ -150,6 +150,7 @@ fn collect(input: &CollectInput) -> Result { unlinked, plan: None, facts: Vec::new(), + warnings: Vec::new(), }) } diff --git a/extensions/cargo-test/wasm/inputs.json b/extensions/cargo-test/wasm/inputs.json index 3e3f98f319..71d5c3efed 100644 --- a/extensions/cargo-test/wasm/inputs.json +++ b/extensions/cargo-test/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "specforge_ext_cargo_test.wasm", - "artifact_sha256": "282a95c0215325c352df2ff54c1ff3dc34f134b821721bd484dee92945f9c146", + "artifact_sha256": "8a34fa387a9e33b5d16df494bc3c0b39d0a8d01840957126f476394c17f8b5d2", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,19 +55,19 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", "extensions/cargo-test/Cargo.lock": "7772170be2be321f7300e4efa33ab77d9a613b8da9c386f97bff377d37394c1c", "extensions/cargo-test/Cargo.toml": "44f242032f8d1ed2b21be107d0bb67036e1a2e79329395e706eb1b564efd9252", - "extensions/cargo-test/src/lib.rs": "a5c0e302f6660968fb5061693b0ed5b6dd5588a5e60aaa56609bd1cb16d6d524" + "extensions/cargo-test/src/lib.rs": "86210d5fa9461179a151dbb61aa1ec9024f92f85bd36967227007dab6e07cb7d" } } diff --git a/extensions/cargo-test/wasm/specforge_ext_cargo_test.wasm b/extensions/cargo-test/wasm/specforge_ext_cargo_test.wasm index 17da1c1a60..5b741d4fbc 100644 Binary files a/extensions/cargo-test/wasm/specforge_ext_cargo_test.wasm and b/extensions/cargo-test/wasm/specforge_ext_cargo_test.wasm differ diff --git a/extensions/checks/Cargo.lock b/extensions/checks/Cargo.lock index cce2b93c6e..b50647de3a 100644 --- a/extensions/checks/Cargo.lock +++ b/extensions/checks/Cargo.lock @@ -240,9 +240,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -1015,9 +1015,9 @@ checksum = "e9df2af067a7953e9c3831320f35c1cc0600c30d44d9f7a12b01db1cd88d6b47" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/extensions/checks/wasm/inputs.json b/extensions/checks/wasm/inputs.json index d01c14a711..e3514f4971 100644 --- a/extensions/checks/wasm/inputs.json +++ b/extensions/checks/wasm/inputs.json @@ -1,6 +1,6 @@ { "artifact": "specforge_ext_checks.wasm", - "artifact_sha256": "8a5ca53dda6d8dba09dd7519e622202db68f765d22deedbe399721bcfef7482e", + "artifact_sha256": "af2c17c9d3acab79ffe3ed0ad3377cca3007ddfafc460140587d169224578ade", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", @@ -37,12 +37,12 @@ "crates/leaf/checks-kit/src/tree.rs": "2123278c5975bfab982b1344d31066c19c28e782af894179852553647192dfb2", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -52,29 +52,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -86,18 +86,18 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", - "extensions/checks/Cargo.lock": "6f966a0d3688d74e061f888e6d89485c6486163125573ae26b97b38dcc55e25c", + "extensions/checks/Cargo.lock": "c13f026d3a3ee57fbb93feef9b7a7d842a371fd33b4cb3dc7ea3d758e2c4e9a8", "extensions/checks/Cargo.toml": "ad8a8321c379f9eaca30f9b450828be6f4609c83d639b42faa5ffaac8f14c7b6", "extensions/checks/src/codes.rs": "c9fa441405a90c41a58d58830a1d6bddfefaa77ce2b4d6878b776422c4edd3b6", "extensions/checks/src/facts.rs": "6871aeb2c801f48bccf5eac66783bb6d9ae976ddd088a0cc317e74b5865433c4", diff --git a/extensions/checks/wasm/specforge_ext_checks.wasm b/extensions/checks/wasm/specforge_ext_checks.wasm index 31badce49f..10e96f005f 100644 Binary files a/extensions/checks/wasm/specforge_ext_checks.wasm and b/extensions/checks/wasm/specforge_ext_checks.wasm differ diff --git a/extensions/code/api/Cargo.lock b/extensions/code/api/Cargo.lock new file mode 100644 index 0000000000..74b9193fad --- /dev/null +++ b/extensions/code/api/Cargo.lock @@ -0,0 +1,646 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "windows-sys", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "insta" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67d3d2e287e4b86c10b3f3b641033d1f89b74bdb39d05f34952e2b9a6fe21cd" +dependencies = [ + "console", + "once_cell", + "serde", + "similar", + "tempfile", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-api" +version = "1.0.0" +dependencies = [ + "insta", + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/code/api/Cargo.toml b/extensions/code/api/Cargo.toml new file mode 100644 index 0000000000..4e91b9b546 --- /dev/null +++ b/extensions/code/api/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "specforge-code-api" +version = "1.0.0" +edition = "2021" +description = "The API snapshot readers the api packs link (ADR 0388); no guest" +publish = false + +# An extension library (ADR 0328 D3): an rlib a builtin links, never embedded. +[lib] +crate-type = ["rlib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-facts = { path = "../facts" } +serde_json = "1.0" + +[dev-dependencies] +insta = { version = "1.46.3", features = ["json"] } diff --git a/extensions/code/api/fixtures/README.md b/extensions/code/api/fixtures/README.md new file mode 100644 index 0000000000..4d8dd2e049 --- /dev/null +++ b/extensions/code/api/fixtures/README.md @@ -0,0 +1,23 @@ +# API snapshot reader fixtures + +`cargo public-api` is not installed where these were written (it needs a nightly toolchain), so its fixture is +hand-written to the tool's grammar. The api-extractor fixtures are hand-written to its model, beside doc models +and reports recorded with the real tool. The Phase 12 recordings name no absolute path. + +| Fixture | Source | +|---------|--------| +| `rust.public-api.txt` | hand-written to the cargo-public-api snapshot grammar (the lines of the tool's own committed snapshots `comprehensive_api.txt` and `example_api-v0.3.0.txt`): crate `example_api` with a module, a `#[non_exhaustive]` struct and its field, an inherent `impl` with `new`, `impl Debug` and `impl Display` each with a `fmt`, a marker `impl` with no member, a `pub extern crate`, a `pub use`, an enum with a tuple and a unit variant, an enum with a discriminant variant, a `pub const`, a `#[repr(C)]` struct and its field, a `const fn`, a function no source item holds (`from_macro`) and a `pub(crate)` function | +| `widget.api.json` | hand-written to the api-extractor .api.json doc model (`@microsoft/api-extractor-model`'s `ApiPackage` serialization, schema version 1011): Package `@demo/widget` > EntryPoint > Class `Widget` with Method `render` and Property `size`, Interface `Options`, Function `create`, Function `parse` overloaded twice, Enum `Mode` with EnumMember `Fast`, TypeAlias `Id`, Variable `VERSION`, Namespace `util` | +| `api-extractor-7.60.1.widget.api.json` | recorded by the Phase 11 research with api-extractor 7.60.1 (`api-extractor run --local`, doc model only, the `@javascript/api` config shape) from the `.d.ts` below, package `@demo/widget`; committed unchanged. It names no absolute path. Members are alphabetical, as the tool writes them | +| `api-extractor-7.60.1.widget.d.ts` | the input that model was recorded from: the package's built `index.d.ts`, unchanged | +| `api-extractor-7.60.1.rich.api.json` | recorded by the Phase 12 research with api-extractor 7.60.1 (`api-extractor run --local`, doc model and report enabled) from the two `.d.ts` below, package `@demo/rich`; committed unchanged, no absolute path. It holds a protected constructor and an index signature (the two members the tool writes with no `name`), an accessor pair (one `Property`), a namespace with a variable, an overloaded function, a multi-line type alias and an `@alpha` const enum | +| `api-extractor-7.60.1.rich.d.ts` | the input `index.d.ts` of `@demo/rich`, unchanged; it re-exports `Other` from the file below | +| `api-extractor-7.60.1.rich-other.d.ts` | the input `other.d.ts` of `@demo/rich`, unchanged | +| `api-extractor-7.60.1.rich.api.md` | the API report (`etc/rich.api.md`) of the same run as `rich.api.json`, committed unchanged: the accessor pair as two lines, a namespace variable split by an inner comment (`const // (undocumented)`), the overloads, the multi-line type alias | +| `api-extractor-7.60.1.widget-tagged.d.ts` | the input of one run of the tool, package `@demo/widget` with release tags: a `@public` class with a `@beta` member, an `@alpha` function, an `@internal` function | +| `api-extractor-7.60.1.widget-tagged.api.json` | the doc model of that run, committed unchanged (it lists no `@internal` item) | +| `api-extractor-7.60.1.widget-tagged.api.md` | the API report of that run, committed unchanged (the accepted side) | +| `api-extractor-7.60.1.widget-changed.d.ts` | the input of a second run, the break scenario against `widget-tagged`: `create` changed, the class narrowed to `@beta`, `trial` removed, `added` added | +| `api-extractor-7.60.1.widget-changed.api.json` | the doc model of that run, committed unchanged (each member of the `@beta` class reads `Beta`) | +| `api-extractor-7.60.1.widget-changed.api.md` | the API report of that run, committed unchanged: a two-line warning comment above `create`, the class's members with no tag line of their own | +| `items.json` | hand-written served `item` facts (ids only). Rust, of the package `example-api`: most entries of `rust.public-api.txt`, not the re-export, the extern crate, the variants nor `from_macro`, and one item of a binary target of that package, which no entry may cite. JavaScript, of `@demo/widget`: the entries of `widget.api.json` in their source files, `VERSION` in two files (so neither is cited) and no `util` (only another package's) | diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.rich-other.d.ts b/extensions/code/api/fixtures/api-extractor-7.60.1.rich-other.d.ts new file mode 100644 index 0000000000..46c7b52810 --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.rich-other.d.ts @@ -0,0 +1,4 @@ +/** @public */ +export declare class Other { + id: number; +} diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.rich.api.json b/extensions/code/api/fixtures/api-extractor-7.60.1.rich.api.json new file mode 100644 index 0000000000..4da6c4d24d --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.rich.api.json @@ -0,0 +1,914 @@ +{ + "metadata": { + "toolPackage": "@microsoft/api-extractor", + "toolVersion": "7.60.1", + "schemaVersion": 1011, + "oldestForwardsCompatibleVersion": 1001, + "tsdocConfig": { + "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + "noStandardTags": true, + "tagDefinitions": [ + { + "tagName": "@alpha", + "syntaxKind": "modifier" + }, + { + "tagName": "@beta", + "syntaxKind": "modifier" + }, + { + "tagName": "@defaultValue", + "syntaxKind": "block" + }, + { + "tagName": "@decorator", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@deprecated", + "syntaxKind": "block" + }, + { + "tagName": "@eventProperty", + "syntaxKind": "modifier" + }, + { + "tagName": "@example", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@experimental", + "syntaxKind": "modifier" + }, + { + "tagName": "@inheritDoc", + "syntaxKind": "inline" + }, + { + "tagName": "@internal", + "syntaxKind": "modifier" + }, + { + "tagName": "@label", + "syntaxKind": "inline" + }, + { + "tagName": "@link", + "syntaxKind": "inline", + "allowMultiple": true + }, + { + "tagName": "@override", + "syntaxKind": "modifier" + }, + { + "tagName": "@packageDocumentation", + "syntaxKind": "modifier" + }, + { + "tagName": "@param", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@privateRemarks", + "syntaxKind": "block" + }, + { + "tagName": "@public", + "syntaxKind": "modifier" + }, + { + "tagName": "@readonly", + "syntaxKind": "modifier" + }, + { + "tagName": "@remarks", + "syntaxKind": "block" + }, + { + "tagName": "@returns", + "syntaxKind": "block" + }, + { + "tagName": "@sealed", + "syntaxKind": "modifier" + }, + { + "tagName": "@see", + "syntaxKind": "block" + }, + { + "tagName": "@throws", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@typeParam", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@virtual", + "syntaxKind": "modifier" + }, + { + "tagName": "@jsx", + "syntaxKind": "block" + }, + { + "tagName": "@jsxRuntime", + "syntaxKind": "block" + }, + { + "tagName": "@jsxFrag", + "syntaxKind": "block" + }, + { + "tagName": "@jsxImportSource", + "syntaxKind": "block" + }, + { + "tagName": "@betaDocumentation", + "syntaxKind": "modifier" + }, + { + "tagName": "@internalRemarks", + "syntaxKind": "block" + }, + { + "tagName": "@preapproved", + "syntaxKind": "modifier" + } + ], + "supportForTags": { + "@alpha": true, + "@beta": true, + "@defaultValue": true, + "@decorator": true, + "@deprecated": true, + "@eventProperty": true, + "@example": true, + "@experimental": true, + "@inheritDoc": true, + "@internal": true, + "@label": true, + "@link": true, + "@override": true, + "@packageDocumentation": true, + "@param": true, + "@privateRemarks": true, + "@public": true, + "@readonly": true, + "@remarks": true, + "@returns": true, + "@sealed": true, + "@see": true, + "@throws": true, + "@typeParam": true, + "@virtual": true, + "@betaDocumentation": true, + "@internalRemarks": true, + "@preapproved": true + }, + "reportUnsupportedHtmlElements": false + } + }, + "kind": "Package", + "canonicalReference": "@demo/rich!", + "docComment": "", + "name": "@demo/rich", + "preserveMemberOrder": false, + "members": [ + { + "kind": "EntryPoint", + "canonicalReference": "@demo/rich!", + "name": "", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Class", + "canonicalReference": "@demo/rich!Base:class", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare abstract class Base " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "typeParameters": [ + { + "typeParameterName": "T", + "constraintTokenRange": { + "startIndex": 0, + "endIndex": 0 + }, + "defaultTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + } + } + ], + "isAbstract": true, + "name": "Base", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Constructor", + "canonicalReference": "@demo/rich!Base:constructor(1)", + "docComment": "/**\n * Constructs a new instance of the `Base` class\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "protected constructor(v: " + }, + { + "kind": "Content", + "text": "T" + }, + { + "kind": "Content", + "text": ");" + } + ], + "releaseTag": "Public", + "isProtected": true, + "overloadIndex": 1, + "parameters": [ + { + "parameterName": "v", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + } + ] + }, + { + "kind": "Property", + "canonicalReference": "@demo/rich!Base.KIND:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "static readonly KIND: " + }, + { + "kind": "Content", + "text": "\"base\"" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": true, + "isOptional": false, + "releaseTag": "Public", + "name": "KIND", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isStatic": true, + "isProtected": false, + "isAbstract": false + }, + { + "kind": "Method", + "canonicalReference": "@demo/rich!Base#run:member(1)", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "abstract run(): " + }, + { + "kind": "Content", + "text": "void" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isStatic": false, + "returnTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "isProtected": false, + "overloadIndex": 1, + "parameters": [], + "isOptional": false, + "isAbstract": true, + "name": "run" + }, + { + "kind": "Method", + "canonicalReference": "@demo/rich!Base#tune:member(1)", + "docComment": "/**\n * @beta\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "tune(n: " + }, + { + "kind": "Content", + "text": "number" + }, + { + "kind": "Content", + "text": "): " + }, + { + "kind": "Content", + "text": "this" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isStatic": false, + "returnTypeTokenRange": { + "startIndex": 3, + "endIndex": 4 + }, + "releaseTag": "Beta", + "isProtected": false, + "overloadIndex": 1, + "parameters": [ + { + "parameterName": "n", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + } + ], + "isOptional": false, + "isAbstract": false, + "name": "tune" + }, + { + "kind": "Property", + "canonicalReference": "@demo/rich!Base#value:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "get value(): " + }, + { + "kind": "Content", + "text": "T" + }, + { + "kind": "Content", + "text": ";\n\nset value(v: T);" + } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Public", + "name": "value", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isStatic": false, + "isProtected": false, + "isAbstract": false + } + ], + "implementsTokenRanges": [] + }, + { + "kind": "Class", + "canonicalReference": "@demo/rich!Child:class", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare class Child extends " + }, + { + "kind": "Reference", + "text": "Base", + "canonicalReference": "@demo/rich!Base:class" + }, + { + "kind": "Content", + "text": "" + }, + { + "kind": "Content", + "text": " implements " + }, + { + "kind": "Reference", + "text": "Runnable", + "canonicalReference": "@demo/rich!Runnable:interface" + }, + { + "kind": "Content", + "text": " " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "isAbstract": false, + "name": "Child", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Method", + "canonicalReference": "@demo/rich!Child#run:member(1)", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "run(): " + }, + { + "kind": "Content", + "text": "void" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isStatic": false, + "returnTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "isProtected": false, + "overloadIndex": 1, + "parameters": [], + "isOptional": false, + "isAbstract": false, + "name": "run" + } + ], + "extendsTokenRange": { + "startIndex": 1, + "endIndex": 3 + }, + "implementsTokenRanges": [ + { + "startIndex": 4, + "endIndex": 5 + } + ] + }, + { + "kind": "Enum", + "canonicalReference": "@demo/rich!Flags:enum", + "docComment": "/**\n * @alpha\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare const enum Flags " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Alpha", + "name": "Flags", + "preserveMemberOrder": false, + "members": [ + { + "kind": "EnumMember", + "canonicalReference": "@demo/rich!Flags.A:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "A = " + }, + { + "kind": "Content", + "text": "1" + } + ], + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Alpha", + "name": "A" + }, + { + "kind": "EnumMember", + "canonicalReference": "@demo/rich!Flags.B:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "B = " + }, + { + "kind": "Content", + "text": "2" + } + ], + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Alpha", + "name": "B" + } + ] + }, + { + "kind": "Class", + "canonicalReference": "@demo/rich!Other:class", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare class Other " + } + ], + "fileUrlPath": "lib/other.d.ts", + "releaseTag": "Public", + "isAbstract": false, + "name": "Other", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Property", + "canonicalReference": "@demo/rich!Other#id:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "id: " + }, + { + "kind": "Content", + "text": "number" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Public", + "name": "id", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isStatic": false, + "isProtected": false, + "isAbstract": false + } + ], + "implementsTokenRanges": [] + }, + { + "kind": "Function", + "canonicalReference": "@demo/rich!parse:function(1)", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare function parse(input: " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": "): " + }, + { + "kind": "Content", + "text": "number" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/index.d.ts", + "returnTypeTokenRange": { + "startIndex": 3, + "endIndex": 4 + }, + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [ + { + "parameterName": "input", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + } + ], + "name": "parse" + }, + { + "kind": "Function", + "canonicalReference": "@demo/rich!parse:function(2)", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare function parse(input: " + }, + { + "kind": "Content", + "text": "number" + }, + { + "kind": "Content", + "text": "): " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/index.d.ts", + "returnTypeTokenRange": { + "startIndex": 3, + "endIndex": 4 + }, + "releaseTag": "Public", + "overloadIndex": 2, + "parameters": [ + { + "parameterName": "input", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + } + ], + "name": "parse" + }, + { + "kind": "Interface", + "canonicalReference": "@demo/rich!Runnable:interface", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export interface Runnable " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "name": "Runnable", + "preserveMemberOrder": false, + "members": [ + { + "kind": "IndexSignature", + "canonicalReference": "@demo/rich!Runnable:index(1)", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "[key: " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": "]: " + }, + { + "kind": "Content", + "text": "unknown" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "returnTypeTokenRange": { + "startIndex": 3, + "endIndex": 4 + }, + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [ + { + "parameterName": "key", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + } + ] + }, + { + "kind": "PropertySignature", + "canonicalReference": "@demo/rich!Runnable#name:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "readonly name?: " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": true, + "isOptional": true, + "releaseTag": "Public", + "name": "name", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + } + }, + { + "kind": "MethodSignature", + "canonicalReference": "@demo/rich!Runnable#run:member(1)", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "run(): " + }, + { + "kind": "Content", + "text": "void" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isOptional": false, + "returnTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [], + "name": "run" + } + ], + "extendsTokenRanges": [] + }, + { + "kind": "TypeAlias", + "canonicalReference": "@demo/rich!Shape:type", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export type Shape = " + }, + { + "kind": "Content", + "text": "{\n kind: \"a\";\n size: number;\n} | {\n kind: \"b\";\n}" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "name": "Shape", + "typeTokenRange": { + "startIndex": 1, + "endIndex": 2 + } + }, + { + "kind": "Namespace", + "canonicalReference": "@demo/rich!util:namespace", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare namespace util " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "name": "util", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Function", + "canonicalReference": "@demo/rich!util.helper:function(1)", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "function helper(x: " + }, + { + "kind": "Content", + "text": "number" + }, + { + "kind": "Content", + "text": "): " + }, + { + "kind": "Content", + "text": "number" + }, + { + "kind": "Content", + "text": ";" + } + ], + "returnTypeTokenRange": { + "startIndex": 3, + "endIndex": 4 + }, + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [ + { + "parameterName": "x", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + } + ], + "name": "helper" + }, + { + "kind": "Variable", + "canonicalReference": "@demo/rich!util.LIMIT:var", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "LIMIT = " + }, + { + "kind": "Content", + "text": "3" + } + ], + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isReadonly": true, + "releaseTag": "Public", + "name": "LIMIT", + "variableTypeTokenRange": { + "startIndex": 0, + "endIndex": 0 + } + } + ] + } + ] + } + ] +} diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.rich.api.md b/extensions/code/api/fixtures/api-extractor-7.60.1.rich.api.md new file mode 100644 index 0000000000..2550b9c17a --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.rich.api.md @@ -0,0 +1,75 @@ +## API Report File for "@demo/rich" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +// @public (undocumented) +export abstract class Base { + protected constructor(v: T); + // (undocumented) + static readonly KIND: "base"; + // (undocumented) + abstract run(): void; + // @beta (undocumented) + tune(n: number): this; + // (undocumented) + get value(): T; + set value(v: T); +} + +// @public (undocumented) +export class Child extends Base implements Runnable { + // (undocumented) + run(): void; +} + +// @alpha (undocumented) +export const enum Flags { + // (undocumented) + A = 1, + // (undocumented) + B = 2 +} + +// @public (undocumented) +export class Other { + // (undocumented) + id: number; +} + +// @public (undocumented) +export function parse(input: string): number; + +// @public (undocumented) +export function parse(input: number): string; + +// @public (undocumented) +export interface Runnable { + // (undocumented) + [key: string]: unknown; + // (undocumented) + readonly name?: string; + // (undocumented) + run(): void; +} + +// @public (undocumented) +export type Shape = { + kind: "a"; + size: number; +} | { + kind: "b"; +}; + +// @public (undocumented) +export namespace util { + // (undocumented) + export function helper(x: number): number; + const // (undocumented) + LIMIT = 3; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.rich.d.ts b/extensions/code/api/fixtures/api-extractor-7.60.1.rich.d.ts new file mode 100644 index 0000000000..8f326ff651 --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.rich.d.ts @@ -0,0 +1,42 @@ +/** @public */ +export declare abstract class Base { + protected constructor(v: T); + get value(): T; + set value(v: T); + static readonly KIND: "base"; + abstract run(): void; + /** @beta */ + tune(n: number): this; +} +/** @public */ +export declare class Child extends Base implements Runnable { + run(): void; +} +/** @public */ +export interface Runnable { + run(): void; + readonly name?: string; + [key: string]: unknown; +} +/** @public */ +export type Shape = { + kind: "a"; + size: number; +} | { + kind: "b"; +}; +/** @public */ +export declare function parse(input: string): number; +/** @public */ +export declare function parse(input: number): string; +/** @public */ +export declare namespace util { + function helper(x: number): number; + const LIMIT = 3; +} +/** @alpha */ +export declare const enum Flags { + A = 1, + B = 2 +} +export { Other } from './other'; diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.api.json b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.api.json new file mode 100644 index 0000000000..c4ee1e6cf3 --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.api.json @@ -0,0 +1,554 @@ +{ + "metadata": { + "toolPackage": "@microsoft/api-extractor", + "toolVersion": "7.60.1", + "schemaVersion": 1011, + "oldestForwardsCompatibleVersion": 1001, + "tsdocConfig": { + "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + "noStandardTags": true, + "tagDefinitions": [ + { + "tagName": "@alpha", + "syntaxKind": "modifier" + }, + { + "tagName": "@beta", + "syntaxKind": "modifier" + }, + { + "tagName": "@defaultValue", + "syntaxKind": "block" + }, + { + "tagName": "@decorator", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@deprecated", + "syntaxKind": "block" + }, + { + "tagName": "@eventProperty", + "syntaxKind": "modifier" + }, + { + "tagName": "@example", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@experimental", + "syntaxKind": "modifier" + }, + { + "tagName": "@inheritDoc", + "syntaxKind": "inline" + }, + { + "tagName": "@internal", + "syntaxKind": "modifier" + }, + { + "tagName": "@label", + "syntaxKind": "inline" + }, + { + "tagName": "@link", + "syntaxKind": "inline", + "allowMultiple": true + }, + { + "tagName": "@override", + "syntaxKind": "modifier" + }, + { + "tagName": "@packageDocumentation", + "syntaxKind": "modifier" + }, + { + "tagName": "@param", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@privateRemarks", + "syntaxKind": "block" + }, + { + "tagName": "@public", + "syntaxKind": "modifier" + }, + { + "tagName": "@readonly", + "syntaxKind": "modifier" + }, + { + "tagName": "@remarks", + "syntaxKind": "block" + }, + { + "tagName": "@returns", + "syntaxKind": "block" + }, + { + "tagName": "@sealed", + "syntaxKind": "modifier" + }, + { + "tagName": "@see", + "syntaxKind": "block" + }, + { + "tagName": "@throws", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@typeParam", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@virtual", + "syntaxKind": "modifier" + }, + { + "tagName": "@jsx", + "syntaxKind": "block" + }, + { + "tagName": "@jsxRuntime", + "syntaxKind": "block" + }, + { + "tagName": "@jsxFrag", + "syntaxKind": "block" + }, + { + "tagName": "@jsxImportSource", + "syntaxKind": "block" + }, + { + "tagName": "@betaDocumentation", + "syntaxKind": "modifier" + }, + { + "tagName": "@internalRemarks", + "syntaxKind": "block" + }, + { + "tagName": "@preapproved", + "syntaxKind": "modifier" + } + ], + "supportForTags": { + "@alpha": true, + "@beta": true, + "@defaultValue": true, + "@decorator": true, + "@deprecated": true, + "@eventProperty": true, + "@example": true, + "@experimental": true, + "@inheritDoc": true, + "@internal": true, + "@label": true, + "@link": true, + "@override": true, + "@packageDocumentation": true, + "@param": true, + "@privateRemarks": true, + "@public": true, + "@readonly": true, + "@remarks": true, + "@returns": true, + "@sealed": true, + "@see": true, + "@throws": true, + "@typeParam": true, + "@virtual": true, + "@betaDocumentation": true, + "@internalRemarks": true, + "@preapproved": true + }, + "reportUnsupportedHtmlElements": false + } + }, + "kind": "Package", + "canonicalReference": "@demo/widget!", + "docComment": "", + "name": "@demo/widget", + "preserveMemberOrder": false, + "members": [ + { + "kind": "EntryPoint", + "canonicalReference": "@demo/widget!", + "name": "", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Function", + "canonicalReference": "@demo/widget!added:function(1)", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare function added(): " + }, + { + "kind": "Content", + "text": "void" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/changed.d.ts", + "returnTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [], + "name": "added" + }, + { + "kind": "Function", + "canonicalReference": "@demo/widget!create:function(1)", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare function create(o: " + }, + { + "kind": "Reference", + "text": "Options", + "canonicalReference": "@demo/widget!Options:interface" + }, + { + "kind": "Content", + "text": ", n: " + }, + { + "kind": "Content", + "text": "number" + }, + { + "kind": "Content", + "text": "): " + }, + { + "kind": "Reference", + "text": "Widget", + "canonicalReference": "@demo/widget!Widget:class" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/changed.d.ts", + "returnTypeTokenRange": { + "startIndex": 5, + "endIndex": 6 + }, + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [ + { + "parameterName": "o", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + }, + { + "parameterName": "n", + "parameterTypeTokenRange": { + "startIndex": 3, + "endIndex": 4 + }, + "isOptional": false + } + ], + "name": "create" + }, + { + "kind": "TypeAlias", + "canonicalReference": "@demo/widget!Id:type", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export type Id = " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/changed.d.ts", + "releaseTag": "Public", + "name": "Id", + "typeTokenRange": { + "startIndex": 1, + "endIndex": 2 + } + }, + { + "kind": "Enum", + "canonicalReference": "@demo/widget!Mode:enum", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare enum Mode " + } + ], + "fileUrlPath": "lib/changed.d.ts", + "releaseTag": "Public", + "name": "Mode", + "preserveMemberOrder": false, + "members": [ + { + "kind": "EnumMember", + "canonicalReference": "@demo/widget!Mode.Fast:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "Fast = " + }, + { + "kind": "Content", + "text": "0" + } + ], + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "name": "Fast" + }, + { + "kind": "EnumMember", + "canonicalReference": "@demo/widget!Mode.Slow:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "Slow = " + }, + { + "kind": "Content", + "text": "1" + } + ], + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "name": "Slow" + } + ] + }, + { + "kind": "Interface", + "canonicalReference": "@demo/widget!Options:interface", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export interface Options " + } + ], + "fileUrlPath": "lib/changed.d.ts", + "releaseTag": "Public", + "name": "Options", + "preserveMemberOrder": false, + "members": [ + { + "kind": "PropertySignature", + "canonicalReference": "@demo/widget!Options#mode:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "mode: " + }, + { + "kind": "Reference", + "text": "Mode", + "canonicalReference": "@demo/widget!Mode:enum" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Public", + "name": "mode", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + } + } + ], + "extendsTokenRanges": [] + }, + { + "kind": "Variable", + "canonicalReference": "@demo/widget!VERSION:var", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "VERSION = " + }, + { + "kind": "Content", + "text": "\"1\"" + } + ], + "fileUrlPath": "lib/changed.d.ts", + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isReadonly": true, + "releaseTag": "Public", + "name": "VERSION", + "variableTypeTokenRange": { + "startIndex": 0, + "endIndex": 0 + } + }, + { + "kind": "Class", + "canonicalReference": "@demo/widget!Widget:class", + "docComment": "/**\n * A widget.\n *\n * @beta\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare class Widget " + } + ], + "fileUrlPath": "lib/changed.d.ts", + "releaseTag": "Beta", + "isAbstract": false, + "name": "Widget", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Method", + "canonicalReference": "@demo/widget!Widget#experimental:member(1)", + "docComment": "/**\n * @beta\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "experimental(): " + }, + { + "kind": "Content", + "text": "void" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isStatic": false, + "returnTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Beta", + "isProtected": false, + "overloadIndex": 1, + "parameters": [], + "isOptional": false, + "isAbstract": false, + "name": "experimental" + }, + { + "kind": "Method", + "canonicalReference": "@demo/widget!Widget#render:member(1)", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "render(): " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isStatic": false, + "returnTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Beta", + "isProtected": false, + "overloadIndex": 1, + "parameters": [], + "isOptional": false, + "isAbstract": false, + "name": "render" + }, + { + "kind": "Property", + "canonicalReference": "@demo/widget!Widget#size:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "size: " + }, + { + "kind": "Content", + "text": "number" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Beta", + "name": "size", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isStatic": false, + "isProtected": false, + "isAbstract": false + } + ], + "implementsTokenRanges": [] + } + ] + } + ] +} diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.api.md b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.api.md new file mode 100644 index 0000000000..d7c6e64a05 --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.api.md @@ -0,0 +1,50 @@ +## API Report File for "@demo/widget" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +// @public (undocumented) +export function added(): void; + +// Warning: (ae-incompatible-release-tags) The symbol "create" is marked as @public, but its signature references "Widget" which is marked as @beta +// +// @public (undocumented) +export function create(o: Options, n: number): Widget; + +// @internal (undocumented) +export function _hidden(): void; + +// @public (undocumented) +export type Id = string; + +// @public (undocumented) +export enum Mode { + // (undocumented) + Fast = 0, + // (undocumented) + Slow = 1 +} + +// @public (undocumented) +export interface Options { + // (undocumented) + mode: Mode; +} + +// @public (undocumented) +export const VERSION = "1"; + +// @beta +export class Widget { + // (undocumented) + experimental(): void; + // (undocumented) + render(): string; + // (undocumented) + size: number; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.d.ts b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.d.ts new file mode 100644 index 0000000000..557210b2f3 --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-changed.d.ts @@ -0,0 +1,29 @@ +/** + * A widget. + * @beta + */ +export declare class Widget { + size: number; + render(): string; + /** @beta */ + experimental(): void; +} +/** @public */ +export interface Options { + mode: Mode; +} +/** @public */ +export declare enum Mode { + Fast = 0, + Slow = 1 +} +/** @public */ +export declare function create(o: Options, n: number): Widget; +/** @public */ +export type Id = string; +/** @public */ +export declare const VERSION = "1"; +/** @internal */ +export declare function _hidden(): void; +/** @public */ +export declare function added(): void; diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.widget-tagged.api.json b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-tagged.api.json new file mode 100644 index 0000000000..301e6a672e --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-tagged.api.json @@ -0,0 +1,538 @@ +{ + "metadata": { + "toolPackage": "@microsoft/api-extractor", + "toolVersion": "7.60.1", + "schemaVersion": 1011, + "oldestForwardsCompatibleVersion": 1001, + "tsdocConfig": { + "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + "noStandardTags": true, + "tagDefinitions": [ + { + "tagName": "@alpha", + "syntaxKind": "modifier" + }, + { + "tagName": "@beta", + "syntaxKind": "modifier" + }, + { + "tagName": "@defaultValue", + "syntaxKind": "block" + }, + { + "tagName": "@decorator", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@deprecated", + "syntaxKind": "block" + }, + { + "tagName": "@eventProperty", + "syntaxKind": "modifier" + }, + { + "tagName": "@example", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@experimental", + "syntaxKind": "modifier" + }, + { + "tagName": "@inheritDoc", + "syntaxKind": "inline" + }, + { + "tagName": "@internal", + "syntaxKind": "modifier" + }, + { + "tagName": "@label", + "syntaxKind": "inline" + }, + { + "tagName": "@link", + "syntaxKind": "inline", + "allowMultiple": true + }, + { + "tagName": "@override", + "syntaxKind": "modifier" + }, + { + "tagName": "@packageDocumentation", + "syntaxKind": "modifier" + }, + { + "tagName": "@param", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@privateRemarks", + "syntaxKind": "block" + }, + { + "tagName": "@public", + "syntaxKind": "modifier" + }, + { + "tagName": "@readonly", + "syntaxKind": "modifier" + }, + { + "tagName": "@remarks", + "syntaxKind": "block" + }, + { + "tagName": "@returns", + "syntaxKind": "block" + }, + { + "tagName": "@sealed", + "syntaxKind": "modifier" + }, + { + "tagName": "@see", + "syntaxKind": "block" + }, + { + "tagName": "@throws", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@typeParam", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@virtual", + "syntaxKind": "modifier" + }, + { + "tagName": "@jsx", + "syntaxKind": "block" + }, + { + "tagName": "@jsxRuntime", + "syntaxKind": "block" + }, + { + "tagName": "@jsxFrag", + "syntaxKind": "block" + }, + { + "tagName": "@jsxImportSource", + "syntaxKind": "block" + }, + { + "tagName": "@betaDocumentation", + "syntaxKind": "modifier" + }, + { + "tagName": "@internalRemarks", + "syntaxKind": "block" + }, + { + "tagName": "@preapproved", + "syntaxKind": "modifier" + } + ], + "supportForTags": { + "@alpha": true, + "@beta": true, + "@defaultValue": true, + "@decorator": true, + "@deprecated": true, + "@eventProperty": true, + "@example": true, + "@experimental": true, + "@inheritDoc": true, + "@internal": true, + "@label": true, + "@link": true, + "@override": true, + "@packageDocumentation": true, + "@param": true, + "@privateRemarks": true, + "@public": true, + "@readonly": true, + "@remarks": true, + "@returns": true, + "@sealed": true, + "@see": true, + "@throws": true, + "@typeParam": true, + "@virtual": true, + "@betaDocumentation": true, + "@internalRemarks": true, + "@preapproved": true + }, + "reportUnsupportedHtmlElements": false + } + }, + "kind": "Package", + "canonicalReference": "@demo/widget!", + "docComment": "", + "name": "@demo/widget", + "preserveMemberOrder": false, + "members": [ + { + "kind": "EntryPoint", + "canonicalReference": "@demo/widget!", + "name": "", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Function", + "canonicalReference": "@demo/widget!create:function(1)", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare function create(o: " + }, + { + "kind": "Reference", + "text": "Options", + "canonicalReference": "@demo/widget!Options:interface" + }, + { + "kind": "Content", + "text": "): " + }, + { + "kind": "Reference", + "text": "Widget", + "canonicalReference": "@demo/widget!Widget:class" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/index.d.ts", + "returnTypeTokenRange": { + "startIndex": 3, + "endIndex": 4 + }, + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [ + { + "parameterName": "o", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + } + ], + "name": "create" + }, + { + "kind": "TypeAlias", + "canonicalReference": "@demo/widget!Id:type", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export type Id = " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "name": "Id", + "typeTokenRange": { + "startIndex": 1, + "endIndex": 2 + } + }, + { + "kind": "Enum", + "canonicalReference": "@demo/widget!Mode:enum", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare enum Mode " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "name": "Mode", + "preserveMemberOrder": false, + "members": [ + { + "kind": "EnumMember", + "canonicalReference": "@demo/widget!Mode.Fast:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "Fast = " + }, + { + "kind": "Content", + "text": "0" + } + ], + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "name": "Fast" + }, + { + "kind": "EnumMember", + "canonicalReference": "@demo/widget!Mode.Slow:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "Slow = " + }, + { + "kind": "Content", + "text": "1" + } + ], + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "name": "Slow" + } + ] + }, + { + "kind": "Interface", + "canonicalReference": "@demo/widget!Options:interface", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export interface Options " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "name": "Options", + "preserveMemberOrder": false, + "members": [ + { + "kind": "PropertySignature", + "canonicalReference": "@demo/widget!Options#mode:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "mode: " + }, + { + "kind": "Reference", + "text": "Mode", + "canonicalReference": "@demo/widget!Mode:enum" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Public", + "name": "mode", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + } + } + ], + "extendsTokenRanges": [] + }, + { + "kind": "Function", + "canonicalReference": "@demo/widget!trial:function(1)", + "docComment": "/**\n * @alpha\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare function trial(): " + }, + { + "kind": "Content", + "text": "void" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/index.d.ts", + "returnTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Alpha", + "overloadIndex": 1, + "parameters": [], + "name": "trial" + }, + { + "kind": "Variable", + "canonicalReference": "@demo/widget!VERSION:var", + "docComment": "/**\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "VERSION = " + }, + { + "kind": "Content", + "text": "\"1\"" + } + ], + "fileUrlPath": "lib/index.d.ts", + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isReadonly": true, + "releaseTag": "Public", + "name": "VERSION", + "variableTypeTokenRange": { + "startIndex": 0, + "endIndex": 0 + } + }, + { + "kind": "Class", + "canonicalReference": "@demo/widget!Widget:class", + "docComment": "/**\n * A widget.\n *\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare class Widget " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "isAbstract": false, + "name": "Widget", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Method", + "canonicalReference": "@demo/widget!Widget#experimental:member(1)", + "docComment": "/**\n * @beta\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "experimental(): " + }, + { + "kind": "Content", + "text": "void" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isStatic": false, + "returnTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Beta", + "isProtected": false, + "overloadIndex": 1, + "parameters": [], + "isOptional": false, + "isAbstract": false, + "name": "experimental" + }, + { + "kind": "Method", + "canonicalReference": "@demo/widget!Widget#render:member(1)", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "render(): " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isStatic": false, + "returnTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "isProtected": false, + "overloadIndex": 1, + "parameters": [], + "isOptional": false, + "isAbstract": false, + "name": "render" + }, + { + "kind": "Property", + "canonicalReference": "@demo/widget!Widget#size:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "size: " + }, + { + "kind": "Content", + "text": "number" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Public", + "name": "size", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isStatic": false, + "isProtected": false, + "isAbstract": false + } + ], + "implementsTokenRanges": [] + } + ] + } + ] +} diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.widget-tagged.api.md b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-tagged.api.md new file mode 100644 index 0000000000..469dfe1588 --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-tagged.api.md @@ -0,0 +1,48 @@ +## API Report File for "@demo/widget" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +// @public (undocumented) +export function create(o: Options): Widget; + +// @internal (undocumented) +export function _hidden(): void; + +// @public (undocumented) +export type Id = string; + +// @public (undocumented) +export enum Mode { + // (undocumented) + Fast = 0, + // (undocumented) + Slow = 1 +} + +// @public (undocumented) +export interface Options { + // (undocumented) + mode: Mode; +} + +// @alpha (undocumented) +export function trial(): void; + +// @public (undocumented) +export const VERSION = "1"; + +// @public +export class Widget { + // @beta (undocumented) + experimental(): void; + // (undocumented) + render(): string; + // (undocumented) + size: number; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.widget-tagged.d.ts b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-tagged.d.ts new file mode 100644 index 0000000000..00c6d201fd --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.widget-tagged.d.ts @@ -0,0 +1,29 @@ +/** + * A widget. + * @public + */ +export declare class Widget { + size: number; + render(): string; + /** @beta */ + experimental(): void; +} +/** @public */ +export interface Options { + mode: Mode; +} +/** @public */ +export declare enum Mode { + Fast = 0, + Slow = 1 +} +/** @public */ +export declare function create(o: Options): Widget; +/** @public */ +export type Id = string; +/** @public */ +export declare const VERSION = "1"; +/** @alpha */ +export declare function trial(): void; +/** @internal */ +export declare function _hidden(): void; diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.widget.api.json b/extensions/code/api/fixtures/api-extractor-7.60.1.widget.api.json new file mode 100644 index 0000000000..4266303ccd --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.widget.api.json @@ -0,0 +1,479 @@ +{ + "metadata": { + "toolPackage": "@microsoft/api-extractor", + "toolVersion": "7.60.1", + "schemaVersion": 1011, + "oldestForwardsCompatibleVersion": 1001, + "tsdocConfig": { + "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + "noStandardTags": true, + "tagDefinitions": [ + { + "tagName": "@alpha", + "syntaxKind": "modifier" + }, + { + "tagName": "@beta", + "syntaxKind": "modifier" + }, + { + "tagName": "@defaultValue", + "syntaxKind": "block" + }, + { + "tagName": "@decorator", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@deprecated", + "syntaxKind": "block" + }, + { + "tagName": "@eventProperty", + "syntaxKind": "modifier" + }, + { + "tagName": "@example", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@experimental", + "syntaxKind": "modifier" + }, + { + "tagName": "@inheritDoc", + "syntaxKind": "inline" + }, + { + "tagName": "@internal", + "syntaxKind": "modifier" + }, + { + "tagName": "@label", + "syntaxKind": "inline" + }, + { + "tagName": "@link", + "syntaxKind": "inline", + "allowMultiple": true + }, + { + "tagName": "@override", + "syntaxKind": "modifier" + }, + { + "tagName": "@packageDocumentation", + "syntaxKind": "modifier" + }, + { + "tagName": "@param", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@privateRemarks", + "syntaxKind": "block" + }, + { + "tagName": "@public", + "syntaxKind": "modifier" + }, + { + "tagName": "@readonly", + "syntaxKind": "modifier" + }, + { + "tagName": "@remarks", + "syntaxKind": "block" + }, + { + "tagName": "@returns", + "syntaxKind": "block" + }, + { + "tagName": "@sealed", + "syntaxKind": "modifier" + }, + { + "tagName": "@see", + "syntaxKind": "block" + }, + { + "tagName": "@throws", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@typeParam", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@virtual", + "syntaxKind": "modifier" + }, + { + "tagName": "@jsx", + "syntaxKind": "block" + }, + { + "tagName": "@jsxRuntime", + "syntaxKind": "block" + }, + { + "tagName": "@jsxFrag", + "syntaxKind": "block" + }, + { + "tagName": "@jsxImportSource", + "syntaxKind": "block" + }, + { + "tagName": "@betaDocumentation", + "syntaxKind": "modifier" + }, + { + "tagName": "@internalRemarks", + "syntaxKind": "block" + }, + { + "tagName": "@preapproved", + "syntaxKind": "modifier" + } + ], + "supportForTags": { + "@alpha": true, + "@beta": true, + "@defaultValue": true, + "@decorator": true, + "@deprecated": true, + "@eventProperty": true, + "@example": true, + "@experimental": true, + "@inheritDoc": true, + "@internal": true, + "@label": true, + "@link": true, + "@override": true, + "@packageDocumentation": true, + "@param": true, + "@privateRemarks": true, + "@public": true, + "@readonly": true, + "@remarks": true, + "@returns": true, + "@sealed": true, + "@see": true, + "@throws": true, + "@typeParam": true, + "@virtual": true, + "@betaDocumentation": true, + "@internalRemarks": true, + "@preapproved": true + }, + "reportUnsupportedHtmlElements": false + } + }, + "kind": "Package", + "canonicalReference": "@demo/widget!", + "docComment": "", + "name": "@demo/widget", + "preserveMemberOrder": false, + "members": [ + { + "kind": "EntryPoint", + "canonicalReference": "@demo/widget!", + "name": "", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Function", + "canonicalReference": "@demo/widget!create:function(1)", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare function create(o: " + }, + { + "kind": "Reference", + "text": "Options", + "canonicalReference": "@demo/widget!Options:interface" + }, + { + "kind": "Content", + "text": "): " + }, + { + "kind": "Reference", + "text": "Widget", + "canonicalReference": "@demo/widget!Widget:class" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/index.d.ts", + "returnTypeTokenRange": { + "startIndex": 3, + "endIndex": 4 + }, + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [ + { + "parameterName": "o", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + } + ], + "name": "create" + }, + { + "kind": "TypeAlias", + "canonicalReference": "@demo/widget!Id:type", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "export type Id = " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "name": "Id", + "typeTokenRange": { + "startIndex": 1, + "endIndex": 2 + } + }, + { + "kind": "Enum", + "canonicalReference": "@demo/widget!Mode:enum", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare enum Mode " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "name": "Mode", + "preserveMemberOrder": false, + "members": [ + { + "kind": "EnumMember", + "canonicalReference": "@demo/widget!Mode.Fast:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "Fast = " + }, + { + "kind": "Content", + "text": "0" + } + ], + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "name": "Fast" + }, + { + "kind": "EnumMember", + "canonicalReference": "@demo/widget!Mode.Slow:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "Slow = " + }, + { + "kind": "Content", + "text": "1" + } + ], + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "name": "Slow" + } + ] + }, + { + "kind": "Interface", + "canonicalReference": "@demo/widget!Options:interface", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "export interface Options " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "name": "Options", + "preserveMemberOrder": false, + "members": [ + { + "kind": "PropertySignature", + "canonicalReference": "@demo/widget!Options#mode:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "mode: " + }, + { + "kind": "Reference", + "text": "Mode", + "canonicalReference": "@demo/widget!Mode:enum" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Public", + "name": "mode", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + } + } + ], + "extendsTokenRanges": [] + }, + { + "kind": "Variable", + "canonicalReference": "@demo/widget!VERSION:var", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "VERSION = " + }, + { + "kind": "Content", + "text": "\"1\"" + } + ], + "fileUrlPath": "lib/index.d.ts", + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isReadonly": true, + "releaseTag": "Public", + "name": "VERSION", + "variableTypeTokenRange": { + "startIndex": 0, + "endIndex": 0 + } + }, + { + "kind": "Class", + "canonicalReference": "@demo/widget!Widget:class", + "docComment": "/**\n * A widget.\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare class Widget " + } + ], + "fileUrlPath": "lib/index.d.ts", + "releaseTag": "Public", + "isAbstract": false, + "name": "Widget", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Method", + "canonicalReference": "@demo/widget!Widget#render:member(1)", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "render(): " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isStatic": false, + "returnTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "isProtected": false, + "overloadIndex": 1, + "parameters": [], + "isOptional": false, + "isAbstract": false, + "name": "render" + }, + { + "kind": "Property", + "canonicalReference": "@demo/widget!Widget#size:member", + "docComment": "", + "excerptTokens": [ + { + "kind": "Content", + "text": "size: " + }, + { + "kind": "Content", + "text": "number" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Public", + "name": "size", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isStatic": false, + "isProtected": false, + "isAbstract": false + } + ], + "implementsTokenRanges": [] + } + ] + } + ] +} diff --git a/extensions/code/api/fixtures/api-extractor-7.60.1.widget.d.ts b/extensions/code/api/fixtures/api-extractor-7.60.1.widget.d.ts new file mode 100644 index 0000000000..b94e9a0007 --- /dev/null +++ b/extensions/code/api/fixtures/api-extractor-7.60.1.widget.d.ts @@ -0,0 +1,15 @@ +/** A widget. */ +export declare class Widget { + size: number; + render(): string; +} +export interface Options { + mode: Mode; +} +export declare enum Mode { + Fast = 0, + Slow = 1 +} +export declare function create(o: Options): Widget; +export type Id = string; +export declare const VERSION = "1"; diff --git a/extensions/code/api/fixtures/items.json b/extensions/code/api/fixtures/items.json new file mode 100644 index 0000000000..ef01b3038e --- /dev/null +++ b/extensions/code/api/fixtures/items.json @@ -0,0 +1,29 @@ +[ + {"kind": "item", "id": "rust:example-api::Struct"}, + {"kind": "item", "id": "rust:example-api::Struct::v1_field"}, + {"kind": "item", "id": "rust:example-api::Struct::new"}, + {"kind": "item", "id": "rust:example-api::::fmt"}, + {"kind": "item", "id": "rust:example-api::::fmt"}, + {"kind": "item", "id": "rust:example-api::enums"}, + {"kind": "item", "id": "rust:example-api::enums::DiverseVariants"}, + {"kind": "item", "id": "rust:example-api::enums::EnumWithExplicitDiscriminants"}, + {"kind": "item", "id": "rust:example-api::constants"}, + {"kind": "item", "id": "rust:example-api::constants::CONST_BOOL"}, + {"kind": "item", "id": "rust:example-api::attributes"}, + {"kind": "item", "id": "rust:example-api::attributes::C"}, + {"kind": "item", "id": "rust:example-api::attributes::C::b"}, + {"kind": "item", "id": "rust:example-api::function"}, + {"kind": "item", "id": "rust:example-api::restricted"}, + {"kind": "item", "id": "rust:example-api/bin/tool::function"}, + {"kind": "item", "id": "js:@demo/widget/src/widget.ts::Widget"}, + {"kind": "item", "id": "js:@demo/widget/src/widget.ts::Widget.render"}, + {"kind": "item", "id": "js:@demo/widget/src/widget.ts::Widget.size"}, + {"kind": "item", "id": "js:@demo/widget/src/options.ts::Options"}, + {"kind": "item", "id": "js:@demo/widget/src/widget.ts::create"}, + {"kind": "item", "id": "js:@demo/widget/src/parse.ts::parse"}, + {"kind": "item", "id": "js:@demo/widget/src/mode.ts::Mode"}, + {"kind": "item", "id": "js:@demo/widget/src/widget.ts::Id"}, + {"kind": "item", "id": "js:@demo/widget/src/index.ts::VERSION"}, + {"kind": "item", "id": "js:@demo/widget/src/version.ts::VERSION"}, + {"kind": "item", "id": "js:@demo/other/src/util.ts::util"} +] diff --git a/extensions/code/api/fixtures/rust.public-api.txt b/extensions/code/api/fixtures/rust.public-api.txt new file mode 100644 index 0000000000..9bd7f671f2 --- /dev/null +++ b/extensions/code/api/fixtures/rust.public-api.txt @@ -0,0 +1,26 @@ +pub mod example_api +#[non_exhaustive] pub struct example_api::Struct +pub example_api::Struct::v1_field: usize +impl example_api::Struct +pub fn example_api::Struct::new(v1_field: usize) -> Self +impl core::fmt::Debug for example_api::Struct +pub fn example_api::Struct::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::fmt::Display for example_api::Struct +pub fn example_api::Struct::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::marker::Send for example_api::Struct +pub extern crate example_api::serde +pub use example_api::StructV2 +pub mod example_api::enums +pub enum example_api::enums::DiverseVariants +pub example_api::enums::DiverseVariants::Tuple(usize, bool) +pub example_api::enums::DiverseVariants::Unit +pub enum example_api::enums::EnumWithExplicitDiscriminants +pub example_api::enums::EnumWithExplicitDiscriminants::First = 1 +pub mod example_api::constants +pub const example_api::constants::CONST_BOOL: bool +pub mod example_api::attributes +#[repr(C)] pub struct example_api::attributes::C +pub example_api::attributes::C::b: bool +pub const fn example_api::function(x: u32) -> u32 +pub fn example_api::from_macro() +pub(crate) fn example_api::restricted() diff --git a/extensions/code/api/fixtures/widget.api.json b/extensions/code/api/fixtures/widget.api.json new file mode 100644 index 0000000000..d6834e7518 --- /dev/null +++ b/extensions/code/api/fixtures/widget.api.json @@ -0,0 +1,201 @@ +{ + "metadata": { + "toolPackage": "@microsoft/api-extractor", + "toolVersion": "7.52.8", + "schemaVersion": 1011, + "oldestForwardsCompatibleVersion": 1001 + }, + "kind": "Package", + "canonicalReference": "@demo/widget!", + "docComment": "", + "name": "@demo/widget", + "preserveMemberOrder": false, + "members": [ + { + "kind": "EntryPoint", + "canonicalReference": "@demo/widget!", + "name": "", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Class", + "canonicalReference": "@demo/widget!Widget:class", + "docComment": "/**\n * A widget.\n *\n * @public\n */\n", + "excerptTokens": [ + { "kind": "Content", "text": "export declare class Widget " } + ], + "fileUrlPath": "dist/widget.d.ts", + "releaseTag": "Public", + "isAbstract": false, + "name": "Widget", + "preserveMemberOrder": false, + "members": [ + { + "kind": "Method", + "canonicalReference": "@demo/widget!Widget#render:member(1)", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "render(): " }, + { "kind": "Content", "text": "string" }, + { "kind": "Content", "text": ";" } + ], + "isStatic": false, + "returnTypeTokenRange": { "startIndex": 1, "endIndex": 2 }, + "releaseTag": "Public", + "isProtected": false, + "overloadIndex": 1, + "parameters": [], + "isOptional": false, + "isAbstract": false, + "name": "render" + }, + { + "kind": "Property", + "canonicalReference": "@demo/widget!Widget#size:member", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "size: " }, + { "kind": "Content", "text": "number" }, + { "kind": "Content", "text": ";" } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Beta", + "name": "size", + "propertyTypeTokenRange": { "startIndex": 1, "endIndex": 2 }, + "isStatic": false, + "isProtected": false, + "isAbstract": false + } + ], + "implementsTokenRanges": [] + }, + { + "kind": "Interface", + "canonicalReference": "@demo/widget!Options:interface", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "export interface Options " } + ], + "fileUrlPath": "dist/options.d.ts", + "releaseTag": "Public", + "name": "Options", + "preserveMemberOrder": false, + "members": [], + "extendsTokenRanges": [] + }, + { + "kind": "Function", + "canonicalReference": "@demo/widget!create:function(1)", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "export declare function create(options?: " }, + { "kind": "Reference", "text": "Options", "canonicalReference": "@demo/widget!Options:interface" }, + { "kind": "Content", "text": "): " }, + { "kind": "Reference", "text": "Widget", "canonicalReference": "@demo/widget!Widget:class" }, + { "kind": "Content", "text": ";" } + ], + "fileUrlPath": "dist/widget.d.ts", + "returnTypeTokenRange": { "startIndex": 3, "endIndex": 4 }, + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [], + "name": "create" + }, + { + "kind": "Function", + "canonicalReference": "@demo/widget!parse:function(1)", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "export declare function parse(text: string): Widget;" } + ], + "fileUrlPath": "dist/parse.d.ts", + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [], + "name": "parse" + }, + { + "kind": "Function", + "canonicalReference": "@demo/widget!parse:function(2)", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "export declare function parse(bytes: Uint8Array): Widget;" } + ], + "fileUrlPath": "dist/parse.d.ts", + "releaseTag": "Public", + "overloadIndex": 2, + "parameters": [], + "name": "parse" + }, + { + "kind": "Enum", + "canonicalReference": "@demo/widget!Mode:enum", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "export declare enum Mode " } + ], + "fileUrlPath": "dist/mode.d.ts", + "releaseTag": "Public", + "name": "Mode", + "preserveMemberOrder": false, + "members": [ + { + "kind": "EnumMember", + "canonicalReference": "@demo/widget!Mode.Fast:member", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "Fast = " }, + { "kind": "Content", "text": "0" } + ], + "initializerTokenRange": { "startIndex": 1, "endIndex": 2 }, + "releaseTag": "Public", + "name": "Fast" + } + ] + }, + { + "kind": "TypeAlias", + "canonicalReference": "@demo/widget!Id:type", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "export type Id = " }, + { "kind": "Content", "text": "string" }, + { "kind": "Content", "text": ";" } + ], + "fileUrlPath": "dist/widget.d.ts", + "releaseTag": "Public", + "name": "Id", + "typeTokenRange": { "startIndex": 1, "endIndex": 2 } + }, + { + "kind": "Variable", + "canonicalReference": "@demo/widget!VERSION:var", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "VERSION: " }, + { "kind": "Content", "text": "string" } + ], + "fileUrlPath": "dist/version.d.ts", + "isReadonly": true, + "releaseTag": "Public", + "name": "VERSION", + "variableTypeTokenRange": { "startIndex": 1, "endIndex": 2 } + }, + { + "kind": "Namespace", + "canonicalReference": "@demo/widget!util:namespace", + "docComment": "", + "excerptTokens": [ + { "kind": "Content", "text": "export declare namespace util " } + ], + "fileUrlPath": "dist/util.d.ts", + "releaseTag": "Alpha", + "name": "util", + "preserveMemberOrder": false, + "members": [] + } + ] + } + ] +} diff --git a/extensions/code/api/src/js_model.rs b/extensions/code/api/src/js_model.rs new file mode 100644 index 0000000000..9738db42a6 --- /dev/null +++ b/extensions/code/api/src/js_model.rs @@ -0,0 +1,127 @@ +//! The api-extractor `.api.json` doc model: a Package, its EntryPoints, and their members, nested. + +use serde_json::Value; +use specforge_code_facts::{ApiEntry, ApiKind, ItemKind, Scheme, Visibility}; + +/// The public entries of the api-extractor doc model `text`, in document order: one per member below each +/// `EntryPoint` of the root `Package`, at any depth, its path the member names from the entry point down. The kinds: +/// Class class, Interface interface, Function function, Method, MethodSignature and Constructor method, Property +/// and PropertySignature field, Variable variable, TypeAlias type, Enum enum, EnumMember variant, Namespace namespace, +/// any other (IndexSignature, CallSignature, ConstructSignature included) `other`. A member the tool writes with no +/// `name` is named by its kind: Constructor `constructor`, IndexSignature `[]`, CallSignature `()`, +/// ConstructSignature `new()`. The signature is its `excerptTokens`' texts joined, the tag its `releaseTag`. An error: +/// text that is no JSON (nesting deeper than serde_json's limit included), a root that is no Package with a name, and +/// a member with no `kind`, or no `name` and none of those four kinds, named by its JSON path (`members[0].members[3]`). +pub fn read_js_model(text: &str) -> Result, String> { + let root: Value = serde_json::from_str(text).map_err(|e| format!("no JSON: {e}"))?; + if root.get("kind").and_then(Value::as_str) != Some("Package") { + return Err("the root is no api-extractor Package (kind \"Package\")".to_string()); + } + let package = root + .get("name") + .and_then(Value::as_str) + .ok_or("the Package has no name")?; + let mut entries = Vec::new(); + for (i, entry_point) in members(&root, "")?.iter().enumerate() { + let at = format!("members[{i}]"); + if named(entry_point, &at)?.0 == "EntryPoint" { + walk(entry_point, &at, package, &[], &mut entries)?; + } + } + Ok(entries) +} + +/// One entry per member of `parent` (at the JSON path `at`) and its members, below the names `path`. +fn walk( + parent: &Value, + at: &str, + package: &str, + path: &[String], + entries: &mut Vec, +) -> Result<(), String> { + for (i, member) in members(parent, at)?.iter().enumerate() { + let here = format!("{at}.members[{i}]"); + let (kind, name) = named(member, &here)?; + let mut path = path.to_vec(); + path.push(name.to_string()); + let signature = member + .get("excerptTokens") + .and_then(Value::as_array) + .map(|tokens| { + tokens + .iter() + .filter_map(|token| token.get("text").and_then(Value::as_str)) + .collect::() + }) + .unwrap_or_default(); + entries.push(ApiEntry { + scheme: Scheme::Js, + container: package.to_string(), + path: path.clone(), + owner: None, + kind: api_kind(kind), + visibility: Visibility::Public, + signature, + tag: member + .get("releaseTag") + .and_then(Value::as_str) + .map(str::to_string), + }); + walk(member, &here, package, &path, entries)?; + } + Ok(()) +} + +/// The `members` of `parent`: none when absent, an error when not an array. +fn members<'v>(parent: &'v Value, at: &str) -> Result<&'v [Value], String> { + match parent.get("members") { + None => Ok(&[]), + Some(Value::Array(members)) => Ok(members), + Some(_) => Err(format!("{at}: members is no array")), + } +} + +/// A member's `kind` and `name`, or an error naming its JSON path `at`. The tool writes no `name` for a constructor or +/// a signature member, so one is named by its kind: `constructor`, `[]`, `()`, `new()`. +fn named<'v>(member: &'v Value, at: &str) -> Result<(&'v str, &'v str), String> { + let none = |key: &str| format!("{at}: a member has no {key}"); + let kind = member + .get("kind") + .and_then(Value::as_str) + .ok_or_else(|| none("kind"))?; + let name = member + .get("name") + .and_then(Value::as_str) + .or(nameless(kind)) + .ok_or_else(|| none("name"))?; + Ok((kind, name)) +} + +/// The name of a member of the api-extractor kind `kind`, which the tool writes with none. +pub(crate) fn nameless(kind: &str) -> Option<&'static str> { + match kind { + "Constructor" => Some("constructor"), + "IndexSignature" => Some("[]"), + "CallSignature" => Some("()"), + "ConstructSignature" => Some("new()"), + _ => None, + } +} + +/// The kind of an api-extractor member kind. +pub(crate) fn api_kind(kind: &str) -> ApiKind { + let item = match kind { + "Class" => ItemKind::Class, + "Interface" => ItemKind::Interface, + "Function" => ItemKind::Function, + "Method" | "MethodSignature" | "Constructor" => ItemKind::Method, + "Property" | "PropertySignature" => ItemKind::Field, + "Variable" => ItemKind::Variable, + "TypeAlias" => ItemKind::Type, + "Enum" => ItemKind::Enum, + "Namespace" => ItemKind::Namespace, + "EnumMember" => return ApiKind::Variant, + _ => return ApiKind::Other, + }; + ApiKind::Item(item) +} diff --git a/extensions/code/api/src/js_report.rs b/extensions/code/api/src/js_report.rs new file mode 100644 index 0000000000..bd8045de47 --- /dev/null +++ b/extensions/code/api/src/js_report.rs @@ -0,0 +1,429 @@ +//! The api-extractor `.api.md` report: the API a package accepted, the file a project commits for review. + +use specforge_code_facts::{ApiEntry, Scheme, Visibility}; + +use crate::js_model::{api_kind, nameless}; + +/// The release tags a tag line writes, and their names as the doc model spells them. +const TAGS: [(&str, &str); 4] = [ + ("@public", "Public"), + ("@beta", "Beta"), + ("@alpha", "Alpha"), + ("@internal", "Internal"), +]; + +/// The deepest a body may nest: a report nests two or three; more is a hostile file. +const DEPTH_MAX: usize = 64; + +/// The most entries a report holds: a large package's holds a few thousand; more is a hostile file. +const ENTRIES_MAX: usize = 100_000; + +/// The most bytes the entries' name paths hold together, each name counted with a `String`'s own size: every entry +/// copies the names of the bodies around it, so depth alone does not bound what a 4 MiB file costs. +const NAMES_MAX: usize = 16 * 1024 * 1024; + +/// Words before a declaration's keyword. +const MODIFIERS: [&str; 4] = ["export", "declare", "default", "abstract"]; + +/// Words before a member's name. +const MEMBER_MODIFIERS: [&str; 9] = [ + "static", + "readonly", + "abstract", + "protected", + "public", + "private", + "declare", + "override", + "async", +]; + +/// What an open body holds. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Body { + /// A class's or an interface's members. + Members, + Enum, + /// A namespace's declarations. + Namespace, +} + +/// A declaration whose body is open. +struct Frame { + name: String, + /// The tag its members inherit. + tag: &'static str, + indent: usize, + body: Body, + line: usize, +} + +/// A declaration or member read over more than one line. +struct Pending { + text: String, + line: usize, + indent: usize, + /// Its own tag line's. + tag: Option<&'static str>, +} + +/// The entries of the api-extractor report `text`, in document order (the tool writes them alphabetically). +/// +/// The grammar, as api-extractor 7.60.1 writes it: an H2 title `## API Report File for ""` names the package +/// (every entry's container), and the body is the one ```` ```ts ```` fence after it. In the fence, `import` lines +/// are skipped; a declaration is a top-level line `export [declare] [default] [abstract]` then `function`, `class`, +/// `interface`, `[const] enum`, `type`, `const`, `let`, `var` or `namespace`, then its name; a class, interface, enum +/// or namespace line ending `{` opens a body, closed by the `}` line at its own indent. A class's or interface's +/// members are the indented lines of its body: a method (`name(`, `name<`), a property, a `get`/`set` accessor (a +/// pair on consecutive lines is one entry, its two texts joined by one space, as the doc model holds one property), +/// a `constructor`, and the nameless `[key: …]` (`[]`), `(…)` (`()`) and `new (…)` (`new()`) the doc model names +/// that way; an enum's members are its lines; a namespace's are declarations. A declaration or member ends at the +/// first line at or left of its own indent ending `;` or `,` (an enum member at its line), so a multi-line type alias +/// is one entry. The release tag is the first `@public`, `@beta`, `@alpha` or `@internal` among the leading `@` words +/// of the comment lines directly above (a warning's prose and a blank line are no tag line), as the doc model spells +/// it (`Public`, …); a member with none inherits its container's, a declaration with none is `Public`. +/// +/// Each entry: the path its names (a namespace's members below it), the kind as [`crate::read_js_model`] maps the +/// doc model's, visibility public, no owner, the signature its text as the report wrote it, a `//` comment inside it +/// removed and its lines trimmed and joined by one space. One pass over the lines, no recursion. An error, naming +/// why: no title before the fence, no fence, a fence or a body never closed, a declaration never ended, a closing +/// brace with no body open, a line that is no declaration or member, a body nested deeper than 64, more than 100,000 +/// entries or 16 MiB of names in their paths (each entry holds its enclosing bodies' names), a line starting +/// `<<<<<<<`, `=======` or `>>>>>>>` (a merge conflict), each with its 1-based line. +pub fn read_js_report(text: &str) -> Result, String> { + let mut package: Option<&str> = None; + let mut reader: Option = None; + let mut opened = 0; + let mut closed = false; + for (n, line) in text.lines().enumerate() { + let n = n + 1; + let line = line.strip_suffix('\r').unwrap_or(line); + if ["<<<<<<<", "=======", ">>>>>>>"] + .iter() + .any(|marker| line.starts_with(marker)) + { + return Err(format!("line {n}: a merge-conflict marker")); + } + if closed { + continue; + } + match reader.as_mut() { + Some(open) if line.trim_end() == "```" => { + open.finish(n)?; + closed = true; + } + Some(open) => open.line(line, n)?, + None if line.trim_end() == "```ts" => { + let package = package.ok_or_else(no_title)?; + reader = Some(Reader::new(package)); + opened = n; + } + None => package = package.or_else(|| title(line)), + } + } + match reader { + None if package.is_none() => Err(no_title()), + None => Err("no ```ts fence holds the report's body".to_string()), + Some(_) if !closed => Err(format!("line {opened}: the ```ts fence is never closed")), + Some(open) => Ok(open.entries), + } +} + +/// The package the first title line of `text` names, `## API Report File for ""`, wherever it is: what a +/// file the report reader refuses was meant to be the report of (a conflicted report still has its title). +pub fn js_report_package(text: &str) -> Option<&str> { + text.lines().find_map(title) +} + +/// The package `line` names when it is the report's title. +fn title(line: &str) -> Option<&str> { + line.strip_prefix("## API Report File for \"") + .and_then(|rest| rest.trim_end().strip_suffix('"')) + .filter(|name| !name.is_empty()) +} + +fn no_title() -> String { + "no `## API Report File for \"\"` title before the ```ts fence".to_string() +} + +/// The fence's state between its lines. +struct Reader<'t> { + package: &'t str, + entries: Vec, + frames: Vec, + pending: Option, + /// The tag of the comment lines read since the last blank line, declaration or member. + tag: Option<&'static str>, + /// The last entry, when it is an accessor its pair joins. + accessor: Option, + /// The bytes the entries' paths hold so far, against [`NAMES_MAX`]. + names: usize, +} + +impl<'t> Reader<'t> { + fn new(package: &'t str) -> Self { + Reader { + package, + entries: Vec::new(), + frames: Vec::new(), + pending: None, + tag: None, + accessor: None, + names: 0, + } + } + + /// Read the fence's line `line`, the `n`th of the file. + fn line(&mut self, line: &str, n: usize) -> Result<(), String> { + let trimmed = line.trim(); + let indent = line.len() - line.trim_start().len(); + let code = without_comment(trimmed); + if let Some(pending) = &mut self.pending { + if !code.is_empty() { + pending.text.push(' '); + pending.text.push_str(code); + } + if indent <= pending.indent && ends(code) { + return self.complete(n); + } + return Ok(()); + } + if trimmed.is_empty() { + self.tag = None; + return Ok(()); + } + if let Some(comment) = trimmed.strip_prefix("//") { + self.tag = self.tag.or_else(|| release_tag(comment)); + return Ok(()); + } + let body = self.frames.last().map(|frame| (frame.indent, frame.body)); + if trimmed.starts_with('}') { + return match body { + Some((open, _)) if open == indent => { + self.frames.pop(); + self.tag = None; + self.accessor = None; + Ok(()) + } + _ => Err(format!( + "line {n}: a closing brace with no body open at its indent" + )), + }; + } + if body.is_none() && trimmed.starts_with("import ") { + self.tag = None; + return Ok(()); + } + self.pending = Some(Pending { + text: code.to_string(), + line: n, + indent, + tag: self.tag.take(), + }); + let opens = !matches!(body, Some((_, Body::Members))) + && code.ends_with('{') + && declaration(code).is_some_and(|(_, _, opens)| opens.is_some()); + if matches!(body, Some((_, Body::Enum))) || ends(code) || opens { + return self.complete(n); + } + Ok(()) + } + + /// The pending declaration or member is whole: its entry, and its body when it opens one. + fn complete(&mut self, n: usize) -> Result<(), String> { + let Some(pending) = self.pending.take() else { + return Ok(()); + }; + let parent = self.frames.last(); + let text = pending.text.as_str(); + let (kind, name, accessor, opens) = match parent.map(|frame| frame.body) { + Some(Body::Enum) => (Some("EnumMember"), identifier(text), false, None), + Some(Body::Members) => match member(text) { + Some((kind, name, accessor)) => (Some(kind), Some(name), accessor, None), + None => (None, None, false, None), + }, + _ => match declaration(text) { + Some((kind, name, opens)) => (Some(kind), Some(name), false, opens), + None => (None, None, false, None), + }, + }; + let (Some(kind), Some(name)) = (kind, name) else { + return Err(format!( + "line {}: neither a declaration nor a member the report grammar knows", + pending.line + )); + }; + let tag = pending + .tag + .or(parent.map(|frame| frame.tag)) + .unwrap_or("Public"); + let mut path: Vec = self.frames.iter().map(|f| f.name.clone()).collect(); + path.push(name.to_string()); + self.tag = None; + if let Some(last) = self.accessor.filter(|_| accessor) { + if self.entries[last].path == path { + self.entries[last].signature.push(' '); + self.entries[last].signature.push_str(text); + self.accessor = None; + return Ok(()); + } + } + if self.entries.len() == ENTRIES_MAX { + return Err(format!( + "line {}: more than {ENTRIES_MAX} entries", + pending.line + )); + } + self.names += path + .iter() + .map(|name| name.len() + std::mem::size_of::()) + .sum::(); + if self.names > NAMES_MAX { + return Err(format!( + "line {}: the entries' name paths hold more than {NAMES_MAX} bytes", + pending.line + )); + } + self.accessor = accessor.then_some(self.entries.len()); + self.entries.push(ApiEntry { + scheme: Scheme::Js, + container: self.package.to_string(), + path, + owner: None, + kind: api_kind(kind), + visibility: Visibility::Public, + signature: text.to_string(), + tag: Some(tag.to_string()), + }); + if let Some(body) = opens.filter(|_| text.ends_with('{')) { + if self.frames.len() == DEPTH_MAX { + return Err(format!("line {n}: a body nested deeper than {DEPTH_MAX}")); + } + self.frames.push(Frame { + name: name.to_string(), + tag, + indent: pending.indent, + body, + line: pending.line, + }); + } + Ok(()) + } + + /// The fence closes at line `n`: nothing may still be open. + fn finish(&self, n: usize) -> Result<(), String> { + if let Some(pending) = &self.pending { + return Err(format!( + "line {}: a declaration never ended before the fence closes at line {n}", + pending.line + )); + } + match self.frames.last() { + // The name is the report's text: quoted escaped, so no control character reaches a message. + Some(frame) => Err(format!( + "line {}: the body of {:?} is never closed", + frame.line, frame.name + )), + None => Ok(()), + } + } +} + +/// Whether a line's code ends a declaration or member. +fn ends(code: &str) -> bool { + code.ends_with(';') || code.ends_with(',') +} + +/// The first release tag among the leading `@` words of a comment, as the doc model spells it. +fn release_tag(comment: &str) -> Option<&'static str> { + comment + .split_whitespace() + .take_while(|word| word.starts_with('@')) + .find_map(|word| TAGS.iter().find(|(at, _)| *at == word).map(|(_, tag)| *tag)) +} + +/// `code` up to a `//` outside a string, trimmed. +// shortcut: a backslash-escaped quote inside a string is not seen; the report prints string literal types only. +fn without_comment(code: &str) -> &str { + let mut quote = None; + for (at, c) in code.char_indices() { + match quote { + Some(open) if c == open => quote = None, + Some(_) => {} + None if matches!(c, '"' | '\'' | '`') => quote = Some(c), + None if code[at..].starts_with("//") => return code[..at].trim_end(), + None => {} + } + } + code +} + +/// The name a word starts with: up to the first character that ends a name. +fn identifier(word: &str) -> Option<&str> { + let end = word + .find(|c: char| c.is_whitespace() || "(<:=;,?!{".contains(c)) + .unwrap_or(word.len()); + (end > 0).then(|| &word[..end]) +} + +/// The doc model's kind, the name and the body of the declaration `code` (top-level or in a namespace). +fn declaration(code: &str) -> Option<(&'static str, &str, Option)> { + let words: Vec<&str> = code.split_whitespace().collect(); + let mut at = words.iter().position(|word| !MODIFIERS.contains(word))?; + if words[at] == "const" && words.get(at + 1) == Some(&"enum") { + at += 1; + } + let (kind, body) = match words[at] { + "function" => ("Function", None), + "class" => ("Class", Some(Body::Members)), + "interface" => ("Interface", Some(Body::Members)), + "enum" => ("Enum", Some(Body::Enum)), + "namespace" | "module" => ("Namespace", Some(Body::Namespace)), + "type" => ("TypeAlias", None), + "const" | "let" | "var" => ("Variable", None), + _ => return None, + }; + Some((kind, identifier(words.get(at + 1)?)?, body)) +} + +/// The doc model's kind and the name of the class or interface member `code`, and whether it is an accessor. +fn member(code: &str) -> Option<(&'static str, &str, bool)> { + let mut rest = code; + while let Some((word, after)) = rest.split_once(' ') { + if !MEMBER_MODIFIERS.contains(&word) { + break; + } + rest = after.trim_start(); + } + if let Some(("get" | "set", after)) = rest.split_once(' ') { + return Some(("Property", identifier(after.trim_start())?, true)); + } + let signature = |kind| Some((kind, nameless(kind)?, false)); + if rest.starts_with('(') || rest.starts_with('<') { + return signature("CallSignature"); + } + if rest + .strip_prefix("new") + .is_some_and(|after| after.trim_start().starts_with(['(', '<'])) + { + return signature("ConstructSignature"); + } + let (name, after) = match rest.strip_prefix('[') { + Some(inner) => { + let close = inner.find(']')?; + if inner[..close].contains(':') { + return signature("IndexSignature"); + } + rest.split_at(close + 2) + } + None => { + let name = identifier(rest)?; + (name, &rest[name.len()..]) + } + }; + if name == "constructor" { + return signature("Constructor"); + } + let method = after.trim_start_matches(['?', '!']).starts_with(['(', '<']); + Some((if method { "Method" } else { "Property" }, name, false)) +} diff --git a/extensions/code/api/src/lib.rs b/extensions/code/api/src/lib.rs new file mode 100644 index 0000000000..a38e6d901c --- /dev/null +++ b/extensions/code/api/src/lib.rs @@ -0,0 +1,24 @@ +//! `specforge-code-api`: the API snapshot readers the api packs link (ADR 0388). +//! +//! An extension library (ADR 0328 D3): an rlib a builtin links, never a component of its own. The wire has no +//! guest-to-guest call, so an api pack reads its snapshot here; `specforge-code-facts` mints the `api_item` facts from +//! what it reads ([`specforge_code_facts::api_facts`]). No format is sniffed: a pack calls the reader of its own. +//! +//! - [`read_rust_text`] reads a `cargo public-api` text snapshot into one [`ApiEntry`] per public entry. +//! - [`read_js_model`] reads an api-extractor `.api.json` doc model into one [`ApiEntry`] per member. +//! - [`read_js_report`] reads an api-extractor `.api.md` report, the API a package accepted, into one [`ApiEntry`] +//! per declaration and member. +//! - [`js_report_package`] and [`rust_text_crate`] name the package or crate a file was meant to hold the API of, even +//! when its reader refuses it: a pack fails a broken accepted file of its own run, and skips one of another. + +#[cfg(test)] +mod tests; + +mod js_model; +mod js_report; +mod rust_text; + +pub use js_model::read_js_model; +pub use js_report::{js_report_package, read_js_report}; +pub use rust_text::{read_rust_text, rust_text_crate}; +pub use specforge_code_facts::ApiEntry; diff --git a/extensions/code/api/src/rust_text.rs b/extensions/code/api/src/rust_text.rs new file mode 100644 index 0000000000..36e46515ed --- /dev/null +++ b/extensions/code/api/src/rust_text.rs @@ -0,0 +1,362 @@ +//! The `cargo public-api` text snapshot: one entry per line, a parent before its children, an `impl` header before the +//! members it owns. + +use std::collections::HashMap; + +use specforge_code_facts::{ApiEntry, ApiKind, ItemKind, Owner, Scheme, Visibility}; + +/// What an entry line writes between its visibility and its path. +#[derive(Clone, Copy)] +enum Keyword { + Known(ApiKind), + /// No keyword: a field or a variant, told apart by its parent. + Absent, + /// A word the table lacks. + Unknown, +} + +/// An open `impl` header: the self type's path without generics, and the owner its members are defined on. +struct Header { + self_path: String, + owner: Owner, +} + +/// The public entries of the `cargo public-api` snapshot `text`, in document order. A line is +/// `[#[attr] …] [qualifiers] [keyword] `, its visibility `pub` or `pub(…)`; the keywords are +/// `mod`, `fn` (a method when its parent is the open `impl`'s self type or a type seen earlier), `struct`, `enum`, +/// `union`, `trait`, `type`, `const`, `static`, `macro`, `use` (a re-export) and `extern crate`; the qualifiers +/// `const`, `async`, `unsafe`, `auto` and `extern "…"` stay in the signature only. A line starting `impl` opens the +/// header of the members that follow and is no entry. A line with no keyword is a field when its parent is a struct +/// or union, a variant when it is an enum or a variant, `other` otherwise; a word the table lacks before a path reads +/// `other`. Any other line is an error naming its 1-based line; blank lines are skipped. +pub fn read_rust_text(text: &str) -> Result, String> { + let mut entries = Vec::new(); + let mut kinds: HashMap = HashMap::new(); + let mut header: Option
= None; + for (n, line) in text.lines().enumerate() { + let line = line.strip_suffix('\r').unwrap_or(line); + if line.trim().is_empty() { + continue; + } + let bad = || { + format!( + "line {}: neither a cargo public-api entry nor an impl header", + n + 1 + ) + }; + let body = without_attributes(line.trim()).ok_or_else(bad)?; + if let Some(rest) = impl_header(body) { + header = Some(parse_header(rest).ok_or_else(bad)?); + continue; + } + let (visibility, keyword, path) = entry_parts(body).ok_or_else(bad)?; + let segments = segments(path).ok_or_else(bad)?; + let parents = &segments[..segments.len() - 1]; + let parent = bare_path(parents); + let parent_kind = kinds.get(&parent).copied(); + let parent_owner = Owner { + self_ty: parents.join("::"), + trait_ty: None, + }; + let typed_parent = matches!( + parent_kind, + Some(ApiKind::Item( + ItemKind::Struct | ItemKind::Enum | ItemKind::Union | ItemKind::Trait + )) + ); + let member_owner = header + .as_ref() + .filter(|open| !parents.is_empty() && open.self_path == parent) + .map(|open| open.owner.clone()) + .or_else(|| typed_parent.then(|| parent_owner.clone())); + let (kind, owner) = match keyword { + Keyword::Known(ApiKind::Item(ItemKind::Function)) => match member_owner { + Some(owner) => (ApiKind::Item(ItemKind::Method), Some(owner)), + None => (ApiKind::Item(ItemKind::Function), None), + }, + Keyword::Known(kind @ ApiKind::Item(ItemKind::Type | ItemKind::Const)) => { + (kind, member_owner) + } + Keyword::Known(kind) => (kind, None), + Keyword::Unknown => (ApiKind::Other, None), + Keyword::Absent => match parent_kind { + Some(ApiKind::Item(ItemKind::Struct | ItemKind::Union)) => { + (ApiKind::Item(ItemKind::Field), Some(parent_owner)) + } + Some(ApiKind::Item(ItemKind::Enum) | ApiKind::Variant) => (ApiKind::Variant, None), + _ => (ApiKind::Other, None), + }, + }; + kinds.insert(bare_path(&segments), kind); + entries.push(ApiEntry { + scheme: Scheme::Rust, + container: bare(&segments[0]), + path: segments, + owner, + kind, + visibility, + signature: line.to_string(), + tag: None, + }); + } + Ok(entries) +} + +/// The crate the root module line of `text` names, `pub mod `, wherever it is: what a snapshot the reader +/// refuses was meant to be of (cargo public-api lists the root module first; a conflicted file still has it). +pub fn rust_text_crate(text: &str) -> Option<&str> { + text.lines().find_map(|line| { + line.trim() + .strip_prefix("pub mod ") + .filter(|name| !name.is_empty() && !name.contains([':', ' '])) + }) +} + +/// `line` after its leading `#[…]` attributes, or `None` when one does not close. +fn without_attributes(mut line: &str) -> Option<&str> { + while line.starts_with("#[") { + let mut depth = 0usize; + let mut quoted = false; + let mut escaped = false; + let mut close = None; + for (at, c) in line.char_indices() { + match c { + _ if escaped => escaped = false, + '\\' if quoted => escaped = true, + '"' => quoted = !quoted, + '[' if !quoted => depth += 1, + ']' if !quoted => { + depth -= 1; + if depth == 0 { + close = Some(at); + break; + } + } + _ => {} + } + } + line = line[close? + 1..].trim_start(); + } + Some(line) +} + +/// What follows `impl` when `body` is an `impl` header (`unsafe` allowed before it). +fn impl_header(body: &str) -> Option<&str> { + let rest = body.strip_prefix("unsafe ").unwrap_or(body).trim_start(); + let rest = rest.strip_prefix("impl")?; + (rest.starts_with(char::is_whitespace) || rest.starts_with('<')).then_some(rest) +} + +/// The header `impl[] [Trait for] SelfTy [where …]` (`rest` after `impl`): `None` with no self type. +fn parse_header(rest: &str) -> Option
{ + let mut rest = rest.trim_start(); + if rest.starts_with('<') { + rest = &rest[group_end(rest)?..]; + } + let rest = rest.trim(); + let rest = find_top(rest, " where ") + .map_or(rest, |at| &rest[..at]) + .trim(); + let (trait_ty, self_ty) = match find_top(rest, " for ") { + Some(at) => (Some(rest[..at].trim()), rest[at + " for ".len()..].trim()), + None => (None, rest), + }; + if self_ty.is_empty() || trait_ty.is_some_and(str::is_empty) { + return None; + } + Some(Header { + self_path: bare_path(&split_top(self_ty, "::")), + owner: Owner { + self_ty: self_ty.to_string(), + trait_ty: trait_ty.map(str::to_string), + }, + }) +} + +/// An entry line's visibility, keyword and path, or `None` when it has none of these shapes. +fn entry_parts(body: &str) -> Option<(Visibility, Keyword, &str)> { + let rest = body.strip_prefix("pub")?; + let (modifier, mut s) = if rest.starts_with('(') { + let close = rest.find(')')?; + (&body[.."pub".len() + close + 1], &rest[close + 1..]) + } else if rest.starts_with(char::is_whitespace) { + ("pub", rest) + } else { + return None; + }; + let visibility = Visibility::rust(Some(modifier)); + let mut keyword = Keyword::Absent; + loop { + s = s.trim_start(); + let (word, after) = s.split_once(char::is_whitespace).unwrap_or((s, "")); + let after = after.trim_start(); + let next = after.split(char::is_whitespace).next().unwrap_or(""); + let kind = match word { + "async" | "unsafe" | "auto" => { + s = after; + continue; + } + "const" if matches!(next, "fn" | "unsafe" | "async" | "extern") => { + s = after; + continue; + } + "extern" if next == "crate" => { + s = after.strip_prefix("crate").unwrap_or(after); + keyword = Keyword::Known(ApiKind::ExternCrate); + break; + } + "extern" => { + s = match after.strip_prefix('"') { + Some(abi) => &abi[abi.find('"')? + 1..], + None => after, + }; + continue; + } + "static" => { + s = after.strip_prefix("mut ").unwrap_or(after); + keyword = Keyword::Known(ApiKind::Item(ItemKind::Static)); + break; + } + "mod" => ItemKind::Module, + "fn" => ItemKind::Function, + "struct" => ItemKind::Struct, + "enum" => ItemKind::Enum, + "union" => ItemKind::Union, + "trait" => ItemKind::Trait, + "type" => ItemKind::Type, + "const" => ItemKind::Const, + "macro" => ItemKind::Macro, + "use" => { + s = after; + keyword = Keyword::Known(ApiKind::Reexport); + break; + } + _ => break, + }; + s = after; + keyword = Keyword::Known(ApiKind::Item(kind)); + break; + } + let s = s.trim_start(); + let end = path_end(s); + let path = &s[..end]; + if !path.starts_with(|c: char| c.is_alphanumeric() || c == '_') { + return None; + } + match keyword { + // `pub frobnicate a::b`: a word the table lacks, then a path. + Keyword::Absent if !path.contains("::") => { + let rest = &s[end..]; + if !rest.starts_with(char::is_whitespace) { + return None; + } + let rest = rest.trim_start(); + let path = &rest[..path_end(rest)]; + path.starts_with(|c: char| c.is_alphanumeric() || c == '_') + .then_some((visibility, Keyword::Unknown, path)) + } + keyword => Some((visibility, keyword, path)), + } +} + +/// Where the path at the start of `s` ends: at whitespace, `(`, `{`, `=`, `;`, `,`, `!` or a lone `:` outside its +/// generic arguments. +fn path_end(s: &str) -> usize { + let mut depth = 0usize; + let mut prev = ' '; + let mut chars = s.char_indices().peekable(); + while let Some((at, c)) = chars.next() { + match c { + '<' => depth += 1, + '>' if prev != '-' => depth = depth.saturating_sub(1), + ':' if depth == 0 => { + if chars.peek().map(|&(_, next)| next) != Some(':') { + return at; + } + chars.next(); + } + c if depth == 0 && (c.is_whitespace() || "({=;,!".contains(c)) => return at, + _ => {} + } + prev = c; + } + s.len() +} + +/// The `::` segments of `path`, generic arguments kept; `None` when one is empty. +fn segments(path: &str) -> Option> { + let segments: Vec = split_top(path, "::") + .into_iter() + .map(str::to_string) + .collect(); + segments.iter().all(|s| !s.is_empty()).then_some(segments) +} + +/// `text` split at each `pat` outside `<…>`, `(…)` and `[…]`. +fn split_top<'t>(mut text: &'t str, pat: &str) -> Vec<&'t str> { + let mut parts = Vec::new(); + while let Some(at) = find_top(text, pat) { + parts.push(&text[..at]); + text = &text[at + pat.len()..]; + } + parts.push(text); + parts +} + +/// The first `pat` in `text` outside `<…>`, `(…)` and `[…]` (the `>` of `->` closes nothing). +fn find_top(text: &str, pat: &str) -> Option { + let mut depth = 0usize; + let mut prev = ' '; + for (at, c) in text.char_indices() { + if depth == 0 && text[at..].starts_with(pat) { + return Some(at); + } + match c { + '<' | '(' | '[' => depth += 1, + '>' if prev == '-' => {} + '>' | ')' | ']' => depth = depth.saturating_sub(1), + _ => {} + } + prev = c; + } + None +} + +/// The end of the `<…>` group `text` starts with, past its closing `>`. +fn group_end(text: &str) -> Option { + let mut depth = 0usize; + let mut prev = ' '; + for (at, c) in text.char_indices() { + match c { + '<' => depth += 1, + '>' if prev != '-' => { + depth = depth.checked_sub(1)?; + if depth == 0 { + return Some(at + 1); + } + } + _ => {} + } + prev = c; + } + None +} + +/// A segment without its generic arguments: `Gen` is `Gen`. +fn bare(segment: &str) -> String { + segment + .split('<') + .next() + .unwrap_or(segment) + .trim() + .to_string() +} + +/// A path's segments without generic arguments, joined by `::`: how a parent is looked up. +fn bare_path(segments: &[impl AsRef]) -> String { + segments + .iter() + .map(|s| bare(s.as_ref())) + .collect::>() + .join("::") +} diff --git a/extensions/code/api/src/snapshots/specforge_code_api__tests__api_extractor_7_60_1.snap b/extensions/code/api/src/snapshots/specforge_code_api__tests__api_extractor_7_60_1.snap new file mode 100644 index 0000000000..74952d6ee1 --- /dev/null +++ b/extensions/code/api/src/snapshots/specforge_code_api__tests__api_extractor_7_60_1.snap @@ -0,0 +1,134 @@ +--- +source: src/tests.rs +expression: "api_facts(&entries, &served())" +--- +[ + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Id", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Id", + "kind": "type", + "path": "Id", + "signature": "export type Id = string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode", + "fields": { + "item": "js:@demo/widget/src/mode.ts::Mode", + "kind": "enum", + "path": "Mode", + "signature": "export declare enum Mode ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode.Fast", + "fields": { + "kind": "variant", + "path": "Mode.Fast", + "signature": "Fast = 0", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode.Slow", + "fields": { + "kind": "variant", + "path": "Mode.Slow", + "signature": "Slow = 1", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Options", + "fields": { + "item": "js:@demo/widget/src/options.ts::Options", + "kind": "interface", + "path": "Options", + "signature": "export interface Options ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Options.mode", + "fields": { + "kind": "field", + "path": "Options.mode", + "signature": "mode: Mode;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::VERSION", + "fields": { + "kind": "variable", + "path": "VERSION", + "signature": "VERSION = \"1\"", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget", + "kind": "class", + "path": "Widget", + "signature": "export declare class Widget ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.render", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget.render", + "kind": "method", + "path": "Widget.render", + "signature": "render(): string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.size", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget.size", + "kind": "field", + "path": "Widget.size", + "signature": "size: number;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::create", + "fields": { + "item": "js:@demo/widget/src/widget.ts::create", + "kind": "function", + "path": "create", + "signature": "export declare function create(o: Options): Widget;", + "tag": "Public", + "visibility": "public" + } + } +] diff --git a/extensions/code/api/src/snapshots/specforge_code_api__tests__api_extractor_7_60_1_rich.snap b/extensions/code/api/src/snapshots/specforge_code_api__tests__api_extractor_7_60_1_rich.snap new file mode 100644 index 0000000000..c7a4e3947a --- /dev/null +++ b/extensions/code/api/src/snapshots/specforge_code_api__tests__api_extractor_7_60_1_rich.snap @@ -0,0 +1,259 @@ +--- +source: src/tests.rs +expression: "api_facts(&entries, &served())" +--- +[ + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base", + "fields": { + "kind": "class", + "path": "Base", + "signature": "export declare abstract class Base ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base.KIND", + "fields": { + "kind": "field", + "path": "Base.KIND", + "signature": "static readonly KIND: \"base\";", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base.constructor", + "fields": { + "kind": "method", + "path": "Base.constructor", + "signature": "protected constructor(v: T);", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base.run", + "fields": { + "kind": "method", + "path": "Base.run", + "signature": "abstract run(): void;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base.tune", + "fields": { + "kind": "method", + "path": "Base.tune", + "signature": "tune(n: number): this;", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base.value", + "fields": { + "kind": "field", + "path": "Base.value", + "signature": "get value(): T;\n\nset value(v: T);", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Child", + "fields": { + "kind": "class", + "path": "Child", + "signature": "export declare class Child extends Base implements Runnable ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Child.run", + "fields": { + "kind": "method", + "path": "Child.run", + "signature": "run(): void;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Flags", + "fields": { + "kind": "enum", + "path": "Flags", + "signature": "export declare const enum Flags ", + "tag": "Alpha", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Flags.A", + "fields": { + "kind": "variant", + "path": "Flags.A", + "signature": "A = 1", + "tag": "Alpha", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Flags.B", + "fields": { + "kind": "variant", + "path": "Flags.B", + "signature": "B = 2", + "tag": "Alpha", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Other", + "fields": { + "kind": "class", + "path": "Other", + "signature": "export declare class Other ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Other.id", + "fields": { + "kind": "field", + "path": "Other.id", + "signature": "id: number;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Runnable", + "fields": { + "kind": "interface", + "path": "Runnable", + "signature": "export interface Runnable ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Runnable.[]", + "fields": { + "kind": "other", + "path": "Runnable.[]", + "signature": "[key: string]: unknown;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Runnable.name", + "fields": { + "kind": "field", + "path": "Runnable.name", + "signature": "readonly name?: string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Runnable.run", + "fields": { + "kind": "method", + "path": "Runnable.run", + "signature": "run(): void;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Shape", + "fields": { + "kind": "type", + "path": "Shape", + "signature": "export type Shape = {\n kind: \"a\";\n size: number;\n} | {\n kind: \"b\";\n};", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::parse", + "fields": { + "kind": "function", + "path": "parse", + "signature": "export declare function parse(input: string): number;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::parse~2", + "fields": { + "kind": "function", + "path": "parse", + "signature": "export declare function parse(input: number): string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::util", + "fields": { + "kind": "namespace", + "path": "util", + "signature": "export declare namespace util ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::util.LIMIT", + "fields": { + "kind": "variable", + "path": "util.LIMIT", + "signature": "LIMIT = 3", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::util.helper", + "fields": { + "kind": "function", + "path": "util.helper", + "signature": "function helper(x: number): number;", + "tag": "Public", + "visibility": "public" + } + } +] diff --git a/extensions/code/api/src/snapshots/specforge_code_api__tests__js.snap b/extensions/code/api/src/snapshots/specforge_code_api__tests__js.snap new file mode 100644 index 0000000000..93b07960f2 --- /dev/null +++ b/extensions/code/api/src/snapshots/specforge_code_api__tests__js.snap @@ -0,0 +1,147 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Id", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Id", + "kind": "type", + "path": "Id", + "signature": "export type Id = string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode", + "fields": { + "item": "js:@demo/widget/src/mode.ts::Mode", + "kind": "enum", + "path": "Mode", + "signature": "export declare enum Mode ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode.Fast", + "fields": { + "kind": "variant", + "path": "Mode.Fast", + "signature": "Fast = 0", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Options", + "fields": { + "item": "js:@demo/widget/src/options.ts::Options", + "kind": "interface", + "path": "Options", + "signature": "export interface Options ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::VERSION", + "fields": { + "kind": "variable", + "path": "VERSION", + "signature": "VERSION: string", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget", + "kind": "class", + "path": "Widget", + "signature": "export declare class Widget ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.render", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget.render", + "kind": "method", + "path": "Widget.render", + "signature": "render(): string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.size", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget.size", + "kind": "field", + "path": "Widget.size", + "signature": "size: number;", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::create", + "fields": { + "item": "js:@demo/widget/src/widget.ts::create", + "kind": "function", + "path": "create", + "signature": "export declare function create(options?: Options): Widget;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::parse", + "fields": { + "item": "js:@demo/widget/src/parse.ts::parse", + "kind": "function", + "path": "parse", + "signature": "export declare function parse(text: string): Widget;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::parse~2", + "fields": { + "item": "js:@demo/widget/src/parse.ts::parse", + "kind": "function", + "path": "parse", + "signature": "export declare function parse(bytes: Uint8Array): Widget;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::util", + "fields": { + "kind": "namespace", + "path": "util", + "signature": "export declare namespace util ", + "tag": "Alpha", + "visibility": "public" + } + } +] diff --git a/extensions/code/api/src/snapshots/specforge_code_api__tests__rich_report.snap b/extensions/code/api/src/snapshots/specforge_code_api__tests__rich_report.snap new file mode 100644 index 0000000000..a6a1698c02 --- /dev/null +++ b/extensions/code/api/src/snapshots/specforge_code_api__tests__rich_report.snap @@ -0,0 +1,259 @@ +--- +source: src/tests.rs +expression: "api_facts(&entries, &served())" +--- +[ + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base", + "fields": { + "kind": "class", + "path": "Base", + "signature": "export abstract class Base {", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base.KIND", + "fields": { + "kind": "field", + "path": "Base.KIND", + "signature": "static readonly KIND: \"base\";", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base.constructor", + "fields": { + "kind": "method", + "path": "Base.constructor", + "signature": "protected constructor(v: T);", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base.run", + "fields": { + "kind": "method", + "path": "Base.run", + "signature": "abstract run(): void;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base.tune", + "fields": { + "kind": "method", + "path": "Base.tune", + "signature": "tune(n: number): this;", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Base.value", + "fields": { + "kind": "field", + "path": "Base.value", + "signature": "get value(): T; set value(v: T);", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Child", + "fields": { + "kind": "class", + "path": "Child", + "signature": "export class Child extends Base implements Runnable {", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Child.run", + "fields": { + "kind": "method", + "path": "Child.run", + "signature": "run(): void;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Flags", + "fields": { + "kind": "enum", + "path": "Flags", + "signature": "export const enum Flags {", + "tag": "Alpha", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Flags.A", + "fields": { + "kind": "variant", + "path": "Flags.A", + "signature": "A = 1,", + "tag": "Alpha", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Flags.B", + "fields": { + "kind": "variant", + "path": "Flags.B", + "signature": "B = 2", + "tag": "Alpha", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Other", + "fields": { + "kind": "class", + "path": "Other", + "signature": "export class Other {", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Other.id", + "fields": { + "kind": "field", + "path": "Other.id", + "signature": "id: number;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Runnable", + "fields": { + "kind": "interface", + "path": "Runnable", + "signature": "export interface Runnable {", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Runnable.[]", + "fields": { + "kind": "other", + "path": "Runnable.[]", + "signature": "[key: string]: unknown;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Runnable.name", + "fields": { + "kind": "field", + "path": "Runnable.name", + "signature": "readonly name?: string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Runnable.run", + "fields": { + "kind": "method", + "path": "Runnable.run", + "signature": "run(): void;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::Shape", + "fields": { + "kind": "type", + "path": "Shape", + "signature": "export type Shape = { kind: \"a\"; size: number; } | { kind: \"b\"; };", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::parse", + "fields": { + "kind": "function", + "path": "parse", + "signature": "export function parse(input: string): number;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::parse~2", + "fields": { + "kind": "function", + "path": "parse", + "signature": "export function parse(input: number): string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::util", + "fields": { + "kind": "namespace", + "path": "util", + "signature": "export namespace util {", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::util.LIMIT", + "fields": { + "kind": "variable", + "path": "util.LIMIT", + "signature": "const LIMIT = 3;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Frich::util.helper", + "fields": { + "kind": "function", + "path": "util.helper", + "signature": "export function helper(x: number): number;", + "tag": "Public", + "visibility": "public" + } + } +] diff --git a/extensions/code/api/src/snapshots/specforge_code_api__tests__rust.snap b/extensions/code/api/src/snapshots/specforge_code_api__tests__rust.snap new file mode 100644 index 0000000000..583145be91 --- /dev/null +++ b/extensions/code/api/src/snapshots/specforge_code_api__tests__rust.snap @@ -0,0 +1,241 @@ +--- +source: src/tests.rs +expression: "api_facts(&entries, &served())" +--- +[ + { + "kind": "api_item", + "id": "api:rust:example_api", + "fields": { + "kind": "module", + "path": "example_api", + "signature": "pub mod example_api", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::::fmt", + "fields": { + "item": "rust:example-api::::fmt", + "kind": "method", + "path": "example_api::Struct::fmt", + "signature": "pub fn example_api::Struct::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::::fmt", + "fields": { + "item": "rust:example-api::::fmt", + "kind": "method", + "path": "example_api::Struct::fmt", + "signature": "pub fn example_api::Struct::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::Struct", + "fields": { + "item": "rust:example-api::Struct", + "kind": "struct", + "path": "example_api::Struct", + "signature": "#[non_exhaustive] pub struct example_api::Struct", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::Struct::new", + "fields": { + "item": "rust:example-api::Struct::new", + "kind": "method", + "path": "example_api::Struct::new", + "signature": "pub fn example_api::Struct::new(v1_field: usize) -> Self", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::Struct::v1_field", + "fields": { + "item": "rust:example-api::Struct::v1_field", + "kind": "field", + "path": "example_api::Struct::v1_field", + "signature": "pub example_api::Struct::v1_field: usize", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::StructV2", + "fields": { + "kind": "reexport", + "path": "example_api::StructV2", + "signature": "pub use example_api::StructV2", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::attributes", + "fields": { + "item": "rust:example-api::attributes", + "kind": "module", + "path": "example_api::attributes", + "signature": "pub mod example_api::attributes", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::attributes::C", + "fields": { + "item": "rust:example-api::attributes::C", + "kind": "struct", + "path": "example_api::attributes::C", + "signature": "#[repr(C)] pub struct example_api::attributes::C", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::attributes::C::b", + "fields": { + "item": "rust:example-api::attributes::C::b", + "kind": "field", + "path": "example_api::attributes::C::b", + "signature": "pub example_api::attributes::C::b: bool", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::constants", + "fields": { + "item": "rust:example-api::constants", + "kind": "module", + "path": "example_api::constants", + "signature": "pub mod example_api::constants", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::constants::CONST_BOOL", + "fields": { + "item": "rust:example-api::constants::CONST_BOOL", + "kind": "const", + "path": "example_api::constants::CONST_BOOL", + "signature": "pub const example_api::constants::CONST_BOOL: bool", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::enums", + "fields": { + "item": "rust:example-api::enums", + "kind": "module", + "path": "example_api::enums", + "signature": "pub mod example_api::enums", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::enums::DiverseVariants", + "fields": { + "item": "rust:example-api::enums::DiverseVariants", + "kind": "enum", + "path": "example_api::enums::DiverseVariants", + "signature": "pub enum example_api::enums::DiverseVariants", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::enums::DiverseVariants::Tuple", + "fields": { + "kind": "variant", + "path": "example_api::enums::DiverseVariants::Tuple", + "signature": "pub example_api::enums::DiverseVariants::Tuple(usize, bool)", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::enums::DiverseVariants::Unit", + "fields": { + "kind": "variant", + "path": "example_api::enums::DiverseVariants::Unit", + "signature": "pub example_api::enums::DiverseVariants::Unit", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::enums::EnumWithExplicitDiscriminants", + "fields": { + "item": "rust:example-api::enums::EnumWithExplicitDiscriminants", + "kind": "enum", + "path": "example_api::enums::EnumWithExplicitDiscriminants", + "signature": "pub enum example_api::enums::EnumWithExplicitDiscriminants", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::enums::EnumWithExplicitDiscriminants::First", + "fields": { + "kind": "variant", + "path": "example_api::enums::EnumWithExplicitDiscriminants::First", + "signature": "pub example_api::enums::EnumWithExplicitDiscriminants::First = 1", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::from_macro", + "fields": { + "kind": "function", + "path": "example_api::from_macro", + "signature": "pub fn example_api::from_macro()", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::function", + "fields": { + "item": "rust:example-api::function", + "kind": "function", + "path": "example_api::function", + "signature": "pub const fn example_api::function(x: u32) -> u32", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::restricted", + "fields": { + "item": "rust:example-api::restricted", + "kind": "function", + "path": "example_api::restricted", + "signature": "pub(crate) fn example_api::restricted()", + "visibility": "crate" + } + }, + { + "kind": "api_item", + "id": "api:rust:example_api::serde", + "fields": { + "kind": "extern_crate", + "path": "example_api::serde", + "signature": "pub extern crate example_api::serde", + "visibility": "public" + } + } +] diff --git a/extensions/code/api/src/snapshots/specforge_code_api__tests__widget_changed_against_tagged.snap b/extensions/code/api/src/snapshots/specforge_code_api__tests__widget_changed_against_tagged.snap new file mode 100644 index 0000000000..38926016e1 --- /dev/null +++ b/extensions/code/api/src/snapshots/specforge_code_api__tests__widget_changed_against_tagged.snap @@ -0,0 +1,184 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Id", + "fields": { + "change": "unchanged", + "kind": "type", + "path": "Id", + "signature": "export type Id = string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode", + "fields": { + "change": "unchanged", + "kind": "enum", + "path": "Mode", + "signature": "export declare enum Mode ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode.Fast", + "fields": { + "change": "unchanged", + "kind": "variant", + "path": "Mode.Fast", + "signature": "Fast = 0", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode.Slow", + "fields": { + "change": "unchanged", + "kind": "variant", + "path": "Mode.Slow", + "signature": "Slow = 1", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Options", + "fields": { + "change": "unchanged", + "kind": "interface", + "path": "Options", + "signature": "export interface Options ", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Options.mode", + "fields": { + "change": "unchanged", + "kind": "field", + "path": "Options.mode", + "signature": "mode: Mode;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::VERSION", + "fields": { + "change": "unchanged", + "kind": "variable", + "path": "VERSION", + "signature": "VERSION = \"1\"", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget", + "fields": { + "accepted_signature": "export class Widget {", + "accepted_tag": "Public", + "change": "narrowed", + "kind": "class", + "path": "Widget", + "signature": "export declare class Widget ", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.experimental", + "fields": { + "change": "unchanged", + "kind": "method", + "path": "Widget.experimental", + "signature": "experimental(): void;", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.render", + "fields": { + "accepted_signature": "render(): string;", + "accepted_tag": "Public", + "change": "narrowed", + "kind": "method", + "path": "Widget.render", + "signature": "render(): string;", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.size", + "fields": { + "accepted_signature": "size: number;", + "accepted_tag": "Public", + "change": "narrowed", + "kind": "field", + "path": "Widget.size", + "signature": "size: number;", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::added", + "fields": { + "change": "added", + "kind": "function", + "path": "added", + "signature": "export declare function added(): void;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::create", + "fields": { + "accepted_signature": "export function create(o: Options): Widget;", + "accepted_tag": "Public", + "change": "changed", + "kind": "function", + "path": "create", + "signature": "export declare function create(o: Options, n: number): Widget;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::trial", + "fields": { + "accepted_signature": "export function trial(): void;", + "accepted_tag": "Alpha", + "change": "removed", + "kind": "function", + "path": "trial", + "signature": "export function trial(): void;", + "tag": "Alpha", + "visibility": "public" + } + } +] diff --git a/extensions/code/api/src/snapshots/specforge_code_api__tests__widget_changed_report.snap b/extensions/code/api/src/snapshots/specforge_code_api__tests__widget_changed_report.snap new file mode 100644 index 0000000000..8da4728033 --- /dev/null +++ b/extensions/code/api/src/snapshots/specforge_code_api__tests__widget_changed_report.snap @@ -0,0 +1,167 @@ +--- +source: src/tests.rs +expression: "api_facts(&entries, &served())" +--- +[ + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Id", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Id", + "kind": "type", + "path": "Id", + "signature": "export type Id = string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode", + "fields": { + "item": "js:@demo/widget/src/mode.ts::Mode", + "kind": "enum", + "path": "Mode", + "signature": "export enum Mode {", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode.Fast", + "fields": { + "kind": "variant", + "path": "Mode.Fast", + "signature": "Fast = 0,", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode.Slow", + "fields": { + "kind": "variant", + "path": "Mode.Slow", + "signature": "Slow = 1", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Options", + "fields": { + "item": "js:@demo/widget/src/options.ts::Options", + "kind": "interface", + "path": "Options", + "signature": "export interface Options {", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Options.mode", + "fields": { + "kind": "field", + "path": "Options.mode", + "signature": "mode: Mode;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::VERSION", + "fields": { + "kind": "variable", + "path": "VERSION", + "signature": "export const VERSION = \"1\";", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget", + "kind": "class", + "path": "Widget", + "signature": "export class Widget {", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.experimental", + "fields": { + "kind": "method", + "path": "Widget.experimental", + "signature": "experimental(): void;", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.render", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget.render", + "kind": "method", + "path": "Widget.render", + "signature": "render(): string;", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.size", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget.size", + "kind": "field", + "path": "Widget.size", + "signature": "size: number;", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::_hidden", + "fields": { + "kind": "function", + "path": "_hidden", + "signature": "export function _hidden(): void;", + "tag": "Internal", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::added", + "fields": { + "kind": "function", + "path": "added", + "signature": "export function added(): void;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::create", + "fields": { + "item": "js:@demo/widget/src/widget.ts::create", + "kind": "function", + "path": "create", + "signature": "export function create(o: Options, n: number): Widget;", + "tag": "Public", + "visibility": "public" + } + } +] diff --git a/extensions/code/api/src/snapshots/specforge_code_api__tests__widget_tagged_report.snap b/extensions/code/api/src/snapshots/specforge_code_api__tests__widget_tagged_report.snap new file mode 100644 index 0000000000..f0e28727b1 --- /dev/null +++ b/extensions/code/api/src/snapshots/specforge_code_api__tests__widget_tagged_report.snap @@ -0,0 +1,167 @@ +--- +source: src/tests.rs +expression: "api_facts(&entries, &served())" +--- +[ + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Id", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Id", + "kind": "type", + "path": "Id", + "signature": "export type Id = string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode", + "fields": { + "item": "js:@demo/widget/src/mode.ts::Mode", + "kind": "enum", + "path": "Mode", + "signature": "export enum Mode {", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode.Fast", + "fields": { + "kind": "variant", + "path": "Mode.Fast", + "signature": "Fast = 0,", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Mode.Slow", + "fields": { + "kind": "variant", + "path": "Mode.Slow", + "signature": "Slow = 1", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Options", + "fields": { + "item": "js:@demo/widget/src/options.ts::Options", + "kind": "interface", + "path": "Options", + "signature": "export interface Options {", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Options.mode", + "fields": { + "kind": "field", + "path": "Options.mode", + "signature": "mode: Mode;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::VERSION", + "fields": { + "kind": "variable", + "path": "VERSION", + "signature": "export const VERSION = \"1\";", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget", + "kind": "class", + "path": "Widget", + "signature": "export class Widget {", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.experimental", + "fields": { + "kind": "method", + "path": "Widget.experimental", + "signature": "experimental(): void;", + "tag": "Beta", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.render", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget.render", + "kind": "method", + "path": "Widget.render", + "signature": "render(): string;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::Widget.size", + "fields": { + "item": "js:@demo/widget/src/widget.ts::Widget.size", + "kind": "field", + "path": "Widget.size", + "signature": "size: number;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::_hidden", + "fields": { + "kind": "function", + "path": "_hidden", + "signature": "export function _hidden(): void;", + "tag": "Internal", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::create", + "fields": { + "item": "js:@demo/widget/src/widget.ts::create", + "kind": "function", + "path": "create", + "signature": "export function create(o: Options): Widget;", + "tag": "Public", + "visibility": "public" + } + }, + { + "kind": "api_item", + "id": "api:js:%40demo%2Fwidget::trial", + "fields": { + "kind": "function", + "path": "trial", + "signature": "export function trial(): void;", + "tag": "Alpha", + "visibility": "public" + } + } +] diff --git a/extensions/code/api/src/tests.rs b/extensions/code/api/src/tests.rs new file mode 100644 index 0000000000..80e8fcfa9d --- /dev/null +++ b/extensions/code/api/src/tests.rs @@ -0,0 +1,730 @@ +use specforge_code_facts::{ + api_facts, api_facts_against, comparable, ApiKind, ItemKind, Scheme, Visibility, +}; +use specforge_extension_sdk::prelude::Fact; + +use super::*; + +/// A `cargo public-api` snapshot, hand-written to the tool's own snapshot lines: crate `example_api`. +const RUST: &str = include_str!("../fixtures/rust.public-api.txt"); +/// An api-extractor `.api.json` doc model, hand-written to the model: package `@demo/widget`. +const WIDGET: &str = include_str!("../fixtures/widget.api.json"); +/// api-extractor 7.60.1's doc model of `@demo/widget`, recorded (see `fixtures/README.md`). +const API_EXTRACTOR_7_60_1: &str = include_str!("../fixtures/api-extractor-7.60.1.widget.api.json"); +/// api-extractor 7.60.1's doc model of `@demo/rich`: a constructor, an index signature, an accessor pair, a namespace. +const API_EXTRACTOR_7_60_1_RICH: &str = + include_str!("../fixtures/api-extractor-7.60.1.rich.api.json"); +/// The served `item` facts an api collector receives, as JSON. +const ITEMS: &str = include_str!("../fixtures/items.json"); +/// api-extractor 7.60.1's report and doc model of `@demo/widget` with release tags, one run (see `fixtures/README.md`). +const TAGGED_REPORT: &str = include_str!("../fixtures/api-extractor-7.60.1.widget-tagged.api.md"); +const TAGGED_MODEL: &str = include_str!("../fixtures/api-extractor-7.60.1.widget-tagged.api.json"); +/// The same package after a break: `create` changed, the class narrowed to Beta, `trial` removed, `added` added. +const CHANGED_REPORT: &str = include_str!("../fixtures/api-extractor-7.60.1.widget-changed.api.md"); +const CHANGED_MODEL: &str = + include_str!("../fixtures/api-extractor-7.60.1.widget-changed.api.json"); +/// The report of `@demo/rich`, the run of `API_EXTRACTOR_7_60_1_RICH`. +const RICH_REPORT: &str = include_str!("../fixtures/api-extractor-7.60.1.rich.api.md"); + +/// Each entry's path, kind and tag, sorted. +fn tagged(entries: &[ApiEntry]) -> Vec<(String, &'static str, Option)> { + let mut read: Vec<_> = entries + .iter() + .map(|e| (e.path.join("."), e.kind.as_str(), e.tag.clone())) + .collect(); + read.sort(); + read +} + +/// A report of package `p` whose fence holds `body`. +fn report(body: &str) -> String { + format!("## API Report File for \"p\"\n\n> Do not edit this file.\n\n```ts\n\n{body}\n```\n") +} + +fn served() -> Vec { + serde_json::from_str(ITEMS).expect("the served facts parse") +} + +#[test] +fn an_api_extractor_model_mints_api_items_citing_their_js_items() { + let entries = read_js_model(WIDGET).expect("the model reads"); + let facts = api_facts(&entries, &served()); + assert!(facts.iter().any(|f| f.id.ends_with("::parse~2"))); + assert!( + facts + .iter() + .all(|f| !f.id.contains(".ts") && !f.id.contains(".js")), + "{facts:?}" + ); + insta::assert_json_snapshot!("js", facts); +} + +#[test] +fn a_recorded_api_extractor_7_60_1_model_mints_api_items_of_every_member() { + let entries = read_js_model(API_EXTRACTOR_7_60_1).expect("the recording reads"); + let read: Vec<(String, &str)> = entries + .iter() + .map(|e| (e.path.join("."), e.kind.as_str())) + .collect(); + // api-extractor writes members alphabetically. + let expected = [ + ("create", "function"), + ("Id", "type"), + ("Mode", "enum"), + ("Mode.Fast", "variant"), + ("Mode.Slow", "variant"), + ("Options", "interface"), + ("Options.mode", "field"), + ("VERSION", "variable"), + ("Widget", "class"), + ("Widget.render", "method"), + ("Widget.size", "field"), + ]; + let expected: Vec<(String, &str)> = expected + .iter() + .map(|(path, kind)| (path.to_string(), *kind)) + .collect(); + assert_eq!(read, expected); + assert!(entries.iter().all(|e| e.container == "@demo/widget")); + insta::assert_json_snapshot!("api_extractor_7_60_1", api_facts(&entries, &served())); +} + +#[test] +fn a_recorded_model_with_a_constructor_and_an_index_signature_reads_them_named_by_kind() { + let entries = read_js_model(API_EXTRACTOR_7_60_1_RICH).expect("the recording reads"); + let read: Vec<(String, &str, Option<&str>)> = entries + .iter() + .map(|e| (e.path.join("."), e.kind.as_str(), e.tag.as_deref())) + .collect(); + let at = |path: &str| { + read.iter() + .find(|(p, _, _)| p == path) + .unwrap_or_else(|| panic!("{path} in {read:?}")) + }; + assert_eq!(at("Base.constructor").1, "method"); + assert_eq!(at("Runnable.[]").1, "other"); + assert_eq!(at("Base.tune").2, Some("Beta")); + assert_eq!(at("Flags").2, Some("Alpha")); + assert_eq!(at("util.LIMIT").1, "variable"); + assert_eq!(read.iter().filter(|(p, _, _)| p == "parse").count(), 2); + assert!(entries.iter().all(|e| e.container == "@demo/rich")); + insta::assert_json_snapshot!("api_extractor_7_60_1_rich", api_facts(&entries, &served())); +} + +#[test] +fn a_nameless_member_of_a_kind_the_reader_does_not_name_is_an_error_naming_its_place() { + let model = |member: &str| { + format!( + r#"{{"kind": "Package", "name": "p", "members": [{{"kind": "EntryPoint", "name": "", + "members": [{{"kind": "Interface", "name": "I", "members": [{member}]}}]}}]}}"# + ) + }; + let named: Vec = [ + "CallSignature", + "ConstructSignature", + "IndexSignature", + "Constructor", + ] + .iter() + .map(|kind| { + let entries = read_js_model(&model(&format!(r#"{{"kind": "{kind}"}}"#))) + .unwrap_or_else(|e| panic!("{kind}: {e}")); + entries[1].path[1].clone() + }) + .collect(); + assert_eq!(named, ["()", "new()", "[]", "constructor"]); + for member in [r#"{"kind": "Mystery"}"#, "{}"] { + let error = read_js_model(&model(member)).expect_err(member); + assert!( + error.contains("members[0].members[0].members[0]"), + "{error}" + ); + } +} + +#[test] +fn each_member_reads_its_kind_path_signature_and_tag() { + let entries = read_js_model(WIDGET).expect("the model reads"); + let read: Vec<(String, &str)> = entries + .iter() + .map(|e| (e.path.join("."), e.kind.as_str())) + .collect(); + let expected = [ + ("Widget", "class"), + ("Widget.render", "method"), + ("Widget.size", "field"), + ("Options", "interface"), + ("create", "function"), + ("parse", "function"), + ("parse", "function"), + ("Mode", "enum"), + ("Mode.Fast", "variant"), + ("Id", "type"), + ("VERSION", "variable"), + ("util", "namespace"), + ]; + let expected: Vec<(String, &str)> = expected + .iter() + .map(|(path, kind)| (path.to_string(), *kind)) + .collect(); + assert_eq!(read, expected); + let create = &entries[4]; + assert_eq!(create.container, "@demo/widget"); + assert_eq!( + create.signature, + "export declare function create(options?: Options): Widget;" + ); + assert_eq!(create.tag.as_deref(), Some("Public")); + assert_eq!(entries[2].tag.as_deref(), Some("Beta")); + assert!(entries + .iter() + .all(|e| e.visibility == Visibility::Public && e.owner.is_none())); +} + +#[test] +fn an_unknown_member_kind_reads_other() { + let model = r#"{"kind": "Package", "name": "p", "members": [{"kind": "EntryPoint", "name": "", + "members": [{"kind": "CallSignature", "name": "(call)"}]}]}"#; + let entries = read_js_model(model).expect("the model reads"); + assert_eq!(entries[0].kind, ApiKind::Other); +} + +#[test] +fn a_bad_model_is_an_error_naming_its_place() { + let member = |fields: &str| { + format!( + r#"{{"kind": "Package", "name": "p", "members": [{{"kind": "EntryPoint", "name": "", "members": [ + {{"kind": "Class", "name": "A"}}, {{"kind": "Class", "name": "B"}}, + {{"kind": "Class", "name": "C"}}, {{{fields}}}]}}]}}"# + ) + }; + let deep = format!( + r#"{{"kind": "Package", "name": "p", "members": {}{}}}"#, + "[".repeat(200), + "]".repeat(200) + ); + let cases = [ + ("not json", "no JSON".to_string()), + (r#"{"kind": "Class", "name": "p"}"#, "Package".to_string()), + (r#"{"kind": "Package"}"#, "name".to_string()), + ( + &member(r#""name": "D""#), + "members[0].members[3]".to_string(), + ), + ( + &member(r#""kind": "Class""#), + "members[0].members[3]".to_string(), + ), + (&deep, "no JSON".to_string()), + ]; + for (model, named) in cases { + let error = read_js_model(model).expect_err(model); + assert!(error.contains(&named), "{model}: {error}"); + } + let kindless = read_js_model(&member(r#""name": "D""#)).unwrap_err(); + assert!(kindless.contains("kind"), "{kindless}"); + let nameless = read_js_model(&member(r#""kind": "Class""#)).unwrap_err(); + assert!(nameless.contains("name"), "{nameless}"); +} + +#[test] +fn a_bad_rust_line_is_an_error_naming_it_and_an_unknown_keyword_reads_other() { + let error = read_rust_text("pub mod demo\ngarbage\n").unwrap_err(); + assert!(error.contains("line 2"), "{error}"); + for bad in [ + "pub", + "pub fn", + "pub demo: u8", + "#[unclosed pub fn demo::f", + "impl", + ] { + assert!(read_rust_text(bad).is_err(), "{bad}"); + } + let entries = read_rust_text("pub frobnicate a::b").expect("reads"); + assert_eq!(entries[0].kind, ApiKind::Other); + assert_eq!(entries[0].path, ["a", "b"]); +} + +#[test] +fn a_cargo_public_api_snapshot_mints_api_items_citing_their_items() { + let entries = read_rust_text(RUST).expect("the snapshot reads"); + insta::assert_json_snapshot!("rust", api_facts(&entries, &served())); +} + +#[test] +fn each_line_reads_its_kind_owner_and_visibility() { + let entries = read_rust_text(RUST).expect("the snapshot reads"); + let kinds: Vec<(String, &str)> = entries + .iter() + .map(|e| (e.path.join("::"), e.kind.as_str())) + .collect(); + let expected = [ + ("example_api", "module"), + ("example_api::Struct", "struct"), + ("example_api::Struct::v1_field", "field"), + ("example_api::Struct::new", "method"), + ("example_api::Struct::fmt", "method"), + ("example_api::Struct::fmt", "method"), + ("example_api::serde", "extern_crate"), + ("example_api::StructV2", "reexport"), + ("example_api::enums", "module"), + ("example_api::enums::DiverseVariants", "enum"), + ("example_api::enums::DiverseVariants::Tuple", "variant"), + ("example_api::enums::DiverseVariants::Unit", "variant"), + ("example_api::enums::EnumWithExplicitDiscriminants", "enum"), + ( + "example_api::enums::EnumWithExplicitDiscriminants::First", + "variant", + ), + ("example_api::constants", "module"), + ("example_api::constants::CONST_BOOL", "const"), + ("example_api::attributes", "module"), + ("example_api::attributes::C", "struct"), + ("example_api::attributes::C::b", "field"), + ("example_api::function", "function"), + ("example_api::from_macro", "function"), + ("example_api::restricted", "function"), + ]; + let expected: Vec<(String, &str)> = expected + .iter() + .map(|(path, kind)| (path.to_string(), *kind)) + .collect(); + assert_eq!(kinds, expected); + let display = &entries[5]; + let owner = display.owner.as_ref().expect("a trait impl member"); + assert_eq!( + (owner.self_ty.as_str(), owner.trait_ty.as_deref()), + ("example_api::Struct", Some("core::fmt::Display")) + ); + assert!(entries[3] + .owner + .as_ref() + .is_some_and(|o| o.trait_ty.is_none())); + assert_eq!( + entries[1].signature, + "#[non_exhaustive] pub struct example_api::Struct" + ); + assert_eq!(entries[21].visibility, Visibility::Crate); + assert!(entries[..21] + .iter() + .all(|e| e.visibility == Visibility::Public)); + assert!(entries.iter().all(|e| e.container == "example_api")); +} + +#[test] +fn generics_qualifiers_and_a_where_clause_read_through() { + let text = "\ +pub struct demo::Gen +impl core::fmt::Debug for demo::Gen where T: Clone +pub fn demo::Gen::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub unsafe extern \"C\" fn demo::raw(p: *const u8) +pub unsafe trait demo::Marker +pub static mut demo::COUNTER: usize +pub macro demo::shout! +"; + let entries = read_rust_text(text).expect("the snapshot reads"); + let fmt = &entries[1]; + assert_eq!(fmt.kind, ApiKind::Item(ItemKind::Method)); + assert_eq!(fmt.path, ["demo", "Gen", "fmt"]); + assert_eq!( + fmt.owner.as_ref().map(|o| o.trait_ty.as_deref()), + Some(Some("core::fmt::Debug")) + ); + let facts = api_facts(&entries[1..2], &[]); + assert_eq!(facts[0].id, "api:rust:demo::::fmt"); + let rest: Vec<(&str, &str)> = entries[2..] + .iter() + .map(|e| (e.path[1].as_str(), e.kind.as_str())) + .collect(); + assert_eq!( + rest, + [ + ("raw", "function"), + ("Marker", "trait"), + ("COUNTER", "static"), + ("shout", "macro") + ] + ); +} + +#[test] +fn a_snapshot_path_cannot_forge_a_repeat_suffix_nor_carry_an_escape_into_an_id() { + let text = + "pub fn c::a~2()\npub fn c::a(x: u8)\npub fn c::a(y: u16)\npub fn c::b\u{1b}[31m()\n"; + let entries = read_rust_text(text).expect("the snapshot reads"); + let facts = api_facts(&entries, &[]); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + [ + "api:rust:c::a", + "api:rust:c::a%7E2", + "api:rust:c::a~2", + "api:rust:c::b%1B[31m" + ], + "four entries, four facts: none overwrites another" + ); +} + +#[test] +fn crlf_and_blank_lines_read_like_lf() { + let lf = read_rust_text("pub mod demo\n\npub fn demo::f()\n").expect("reads"); + let crlf = read_rust_text("pub mod demo\r\n\r\npub fn demo::f()\r\n").expect("reads"); + assert_eq!(lf, crlf); + assert_eq!(lf.len(), 2); + assert!(read_rust_text("").expect("reads").is_empty()); +} + +#[test] +fn a_recorded_report_reads_one_tagged_entry_per_declaration_and_member() { + let entries = read_js_report(TAGGED_REPORT).expect("the report reads"); + let read: Vec<(String, &str, Option<&str>)> = entries + .iter() + .map(|e| (e.path.join("."), e.kind.as_str(), e.tag.as_deref())) + .collect(); + let expected = [ + ("create", "function", "Public"), + ("_hidden", "function", "Internal"), + ("Id", "type", "Public"), + ("Mode", "enum", "Public"), + ("Mode.Fast", "variant", "Public"), + ("Mode.Slow", "variant", "Public"), + ("Options", "interface", "Public"), + ("Options.mode", "field", "Public"), + ("trial", "function", "Alpha"), + ("VERSION", "variable", "Public"), + ("Widget", "class", "Public"), + ("Widget.experimental", "method", "Beta"), + ("Widget.render", "method", "Public"), + ("Widget.size", "field", "Public"), + ]; + let expected: Vec<(String, &str, Option<&str>)> = expected + .iter() + .map(|(path, kind, tag)| (path.to_string(), *kind, Some(*tag))) + .collect(); + assert_eq!(read, expected); + assert!(entries.iter().all(|e| e.container == "@demo/widget" + && e.visibility == Visibility::Public + && e.owner.is_none())); + assert_eq!( + entries[0].signature, + "export function create(o: Options): Widget;" + ); + insta::assert_json_snapshot!("widget_tagged_report", api_facts(&entries, &served())); +} + +#[test] +fn a_report_and_the_doc_model_of_one_run_read_the_same_entries_but_internal_ones() { + for (report, model) in [ + (TAGGED_REPORT, TAGGED_MODEL), + (CHANGED_REPORT, CHANGED_MODEL), + (RICH_REPORT, API_EXTRACTOR_7_60_1_RICH), + ] { + let mut accepted = read_js_report(report).expect("the report reads"); + accepted.retain(|e| e.tag.as_deref() != Some("Internal")); + let fresh = read_js_model(model).expect("the model reads"); + assert_eq!(tagged(&accepted), tagged(&fresh)); + } +} + +#[test] +fn a_member_with_no_tag_inherits_its_containers_and_a_warning_comment_is_skipped() { + let entries = read_js_report(CHANGED_REPORT).expect("the report reads"); + let tag = |path: &str| { + entries + .iter() + .find(|e| e.path.join(".") == path) + .unwrap_or_else(|| panic!("{path}")) + .tag + .as_deref() + }; + for path in [ + "Widget", + "Widget.experimental", + "Widget.render", + "Widget.size", + ] { + assert_eq!(tag(path), Some("Beta"), "{path}"); + } + // The warning above `create` names `@beta` in its prose; the tag line below it is `@public`. + assert_eq!(tag("create"), Some("Public")); + assert_eq!(tag("added"), Some("Public")); + assert!(entries.iter().all(|e| e.path != ["trial"])); + let create = entries + .iter() + .find(|e| e.path == ["create"]) + .expect("create"); + assert_eq!( + create.signature, + "export function create(o: Options, n: number): Widget;" + ); + insta::assert_json_snapshot!("widget_changed_report", api_facts(&entries, &served())); +} + +#[test] +fn an_accessor_pair_joins_a_split_declaration_reads_whole_and_overloads_repeat() { + let entries = read_js_report(RICH_REPORT).expect("the report reads"); + let all = |path: &str| -> Vec<&ApiEntry> { + entries + .iter() + .filter(|e| e.path.join(".") == path) + .collect() + }; + let value = all("Base.value"); + assert_eq!(value.len(), 1); + assert_eq!(value[0].signature, "get value(): T; set value(v: T);"); + assert_eq!(value[0].kind, ApiKind::Item(ItemKind::Field)); + let limit = all("util.LIMIT"); + assert_eq!(limit.len(), 1); + assert_eq!(limit[0].signature, "const LIMIT = 3;"); + assert_eq!(limit[0].kind, ApiKind::Item(ItemKind::Variable)); + assert_eq!(all("parse").len(), 2); + assert_eq!( + all("Shape")[0].signature, + "export type Shape = { kind: \"a\"; size: number; } | { kind: \"b\"; };" + ); + assert_eq!( + all("Base.constructor")[0].kind, + ApiKind::Item(ItemKind::Method) + ); + assert_eq!(all("Runnable.[]")[0].kind, ApiKind::Other); + assert_eq!(all("Flags.B")[0].tag.as_deref(), Some("Alpha")); + assert!(entries.iter().all(|e| e.container == "@demo/rich")); + insta::assert_json_snapshot!("rich_report", api_facts(&entries, &served())); +} + +/// Each fact's path, `change`, and the accepted signature and tag it carries. +type Judged = (String, String, Option, Option); + +fn judged(facts: &[Fact]) -> Vec { + let text = |fact: &Fact, name: &str| { + fact.fields + .get(name) + .and_then(|v| v.as_str()) + .map(str::to_string) + }; + facts + .iter() + .map(|f| { + ( + text(f, "path").unwrap_or_default(), + text(f, "change").unwrap_or_default(), + text(f, "accepted_signature"), + text(f, "accepted_tag"), + ) + }) + .collect() +} + +#[test] +fn a_fresh_model_against_the_report_of_its_own_run_is_all_unchanged() { + let key = "function create(o: Options): Widget"; + assert_eq!( + comparable( + Scheme::Js, + "export declare function create(o: Options): Widget;" + ), + key + ); + assert_eq!( + comparable(Scheme::Js, "export function create(o: Options): Widget;"), + key + ); + let fresh = read_js_model(TAGGED_MODEL).expect("the model reads"); + let accepted = read_js_report(TAGGED_REPORT).expect("the report reads"); + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!(facts.len(), fresh.len()); + for (path, change, signature, tag) in judged(&facts) { + assert_eq!(change, "unchanged", "{path}"); + assert_eq!((signature, tag), (None, None), "{path}"); + } + assert!(facts.iter().all(|f| !f.id.contains("_hidden"))); +} + +#[test] +fn the_rich_model_against_its_own_report_is_all_unchanged() { + let fresh = read_js_model(API_EXTRACTOR_7_60_1_RICH).expect("the model reads"); + let accepted = read_js_report(RICH_REPORT).expect("the report reads"); + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!(facts.len(), fresh.len()); + for (path, change, signature, _) in judged(&facts) { + assert_eq!((change.as_str(), signature), ("unchanged", None), "{path}"); + } + // The accessor pair, `LIMIT = 3` and the multi-line type alias are among them. + for path in ["Base.value", "util.LIMIT", "Shape", "parse"] { + assert!(judged(&facts).iter().any(|j| j.0 == path), "{path}"); + } +} + +#[test] +fn a_recorded_break_reads_changed_narrowed_removed_and_added() { + let fresh = read_js_model(CHANGED_MODEL).expect("the model reads"); + let accepted = read_js_report(TAGGED_REPORT).expect("the report reads"); + let facts = api_facts_against(&fresh, &accepted, &[]); + let at = |path: &str| -> Judged { + judged(&facts) + .into_iter() + .find(|j| j.0 == path) + .unwrap_or_else(|| panic!("{path}")) + }; + let some = |text: &str| Some(text.to_string()); + let create = at("create"); + assert_eq!( + (create.1.as_str(), create.2), + ( + "changed", + some("export function create(o: Options): Widget;") + ) + ); + // The class went `@beta`, and its members with no tag of their own with it. + for member in ["Widget", "Widget.render", "Widget.size"] { + assert_eq!( + (at(member).1.as_str(), at(member).3), + ("narrowed", some("Public")) + ); + } + let trial = at("trial"); + assert_eq!( + (trial.1.as_str(), trial.2, trial.3), + ( + "removed", + some("export function trial(): void;"), + some("Alpha") + ) + ); + assert_eq!(at("added").1, "added"); + let changes: Vec = judged(&facts).into_iter().map(|j| j.1).collect(); + assert_eq!(changes.iter().filter(|c| *c == "removed").count(), 1); + assert!(facts.iter().all(|f| !f.id.contains("_hidden"))); + insta::assert_json_snapshot!("widget_changed_against_tagged", facts); +} + +#[test] +fn a_tag_line_with_more_modifiers_reads_its_release_tag() { + let text = report( + "// Warning: (ae-internal-missing-underscore) The name \"Old\" should be prefixed\n//\n\ + // @internal @deprecated (undocumented)\nexport class Old {\n // (undocumented)\n \ + static get kind(): string;\n [Symbol.iterator](): Iterator;\n new (x: number): Old;\n \ + (y: string): void;\n}\n\nexport function untagged(): void;", + ); + let entries = read_js_report(&text).expect("the report reads"); + let read: Vec<(String, &str, Option<&str>)> = entries + .iter() + .map(|e| (e.path.join("."), e.kind.as_str(), e.tag.as_deref())) + .collect(); + let expected = [ + ("Old", "class", "Internal"), + ("Old.kind", "field", "Internal"), + ("Old.[Symbol.iterator]", "method", "Internal"), + ("Old.new()", "other", "Internal"), + ("Old.()", "other", "Internal"), + ("untagged", "function", "Public"), + ]; + let expected: Vec<(String, &str, Option<&str>)> = expected + .iter() + .map(|(path, kind, tag)| (path.to_string(), *kind, Some(*tag))) + .collect(); + assert_eq!(read, expected); +} + +#[test] +fn a_malformed_report_is_an_error_naming_why() { + let ok = report("export function f(): void;"); + assert_eq!(read_js_report(&ok).expect("reads").len(), 1); + let cases = [ + ( + ok.replacen("## API Report File for \"p\"", "## Something else", 1), + "title", + ), + (ok.replacen("```ts", "```js", 1), "fence"), + ( + ok.trim_end().trim_end_matches('`').to_string(), + "never closed", + ), + ( + report("<<<<<<< HEAD\nexport function f(): void;"), + "merge-conflict", + ), + ( + report("export function f(): void;\n======="), + "merge-conflict", + ), + (report(">>>>>>> theirs"), "merge-conflict"), + (report("export class W {\n m(): void;"), "never closed"), + (report("export type T = {\n a: string;"), "never ended"), + (report("}"), "closing brace"), + (report("export { X } from './x';"), "line 7"), + (report(&"export namespace n {\n".repeat(65)), "deeper"), + ]; + for (text, why) in cases { + let error = read_js_report(&text).expect_err(&text); + assert!(error.contains(why), "{text}: {error}"); + } + assert!( + read_js_report(&report("export function f(): void;\n=======")) + .unwrap_err() + .contains("line 8") + ); +} + +#[test] +fn a_hostile_reports_depth_entries_and_names_are_bounded() { + let nested = |depth: usize| { + report(&format!( + "{}export const a: 1;\n{}", + "export namespace n {\n".repeat(depth), + "}\n".repeat(depth) + )) + }; + // 64 bodies deep reads; one more is the error. + let deepest = read_js_report(&nested(64)).expect("64 deep reads"); + assert_eq!(deepest.len(), 65); + assert_eq!(deepest[64].path.len(), 65); + assert!(read_js_report(&nested(65)) + .unwrap_err() + .contains("deeper than 64")); + + let many = |count: usize| report(&"export const a: 1;\n".repeat(count)); + assert_eq!( + read_js_report(&many(100_000)).expect("reads").len(), + 100_000 + ); + let error = read_js_report(&many(100_001)).unwrap_err(); + assert_eq!(error, "line 100007: more than 100000 entries"); + + // A 200 KB namespace name, copied into each of its 100 members' paths: about 20 MB of names. + let long = format!( + "export namespace {} {{\n{}}}", + "n".repeat(200_000), + " export const a: 1;\n".repeat(100) + ); + let error = read_js_report(&report(&long)).unwrap_err(); + assert!( + error.ends_with("the entries' name paths hold more than 16777216 bytes"), + "{error}" + ); +} + +#[test] +fn an_unclosed_body_names_its_declaration_escaped() { + let error = read_js_report(&report("export class \u{1b}[2J {\n m(): void;")).unwrap_err(); + assert_eq!(error, "line 7: the body of \"\\u{1b}[2J\" is never closed"); + assert!(!error.contains('\u{1b}'), "{error:?}"); +} + +#[test] +fn a_refused_file_still_names_the_package_or_crate_it_was_meant_for() { + let conflicted = report("<<<<<<< HEAD\nexport function f(): void;"); + assert!(read_js_report(&conflicted).is_err()); + assert_eq!(js_report_package(&conflicted), Some("p")); + assert_eq!(js_report_package("# Notes\n\nprose\n"), None); + assert_eq!(js_report_package("## API Report File for \"\"\n"), None); + + assert_eq!( + rust_text_crate("<<<<<<< HEAD\npub mod demo\ngarbage\n"), + Some("demo") + ); + assert_eq!(rust_text_crate(RUST), Some("example_api")); + assert_eq!(rust_text_crate("pub mod demo::inner\nprose\n"), None); + assert_eq!(rust_text_crate("prose\n"), None); +} diff --git a/extensions/code/core/Cargo.lock b/extensions/code/core/Cargo.lock index 317770ee01..a588bc7157 100644 --- a/extensions/code/core/Cargo.lock +++ b/extensions/code/core/Cargo.lock @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "specforge-ext-code-core" -version = "1.1.0" +version = "1.4.0" dependencies = [ "specforge-code-facts", "specforge-extension-sdk", diff --git a/extensions/code/core/Cargo.toml b/extensions/code/core/Cargo.toml index 769f5cc0f0..cab986f7f6 100644 --- a/extensions/code/core/Cargo.toml +++ b/extensions/code/core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "specforge-ext-code-core" -version = "1.1.0" +version = "1.4.0" edition = "2021" [lib] diff --git a/extensions/code/core/src/kinds.rs b/extensions/code/core/src/kinds.rs new file mode 100644 index 0000000000..429ec8bfa8 --- /dev/null +++ b/extensions/code/core/src/kinds.rs @@ -0,0 +1,256 @@ +//! The kinds of the facts a standard report's reader mints (ADR 0388), and their edges. + +use specforge_code_facts::{API_ITEM, COVERAGE, DEPENDENCY, STATIC_FINDING, VULNERABILITY}; +use specforge_extension_sdk::prelude::*; + +use crate::{ + referencing, API_CHANGES, API_KINDS, ITEM_KIND, LEVELS, PACKAGE_KIND, SCOPES, SEVERITIES, + VISIBILITY, +}; + +/// Declares the report kinds and the edges their references draw. +pub(crate) fn report_kinds(c: &mut ContributionsBuilder) { + c.kind(COVERAGE.kind, |k| { + k.description( + "What a coverage report (LCOV) says of one item, written by a coverage pack's collector (ADR 0388): \ + cov: for the innermost item holding the report's lines, cov:@ for what no item of a file \ + holds (W104)", + ) + .collected(&[COVERAGE.scheme]) + .field("item", |f| { + referencing(f, COVERAGE.kind, "item") + .field_type(FieldType::Reference) + .description("The item holding the lines; absent when no collected item does"); + }) + .field("file", |f| { + f.field_type(FieldType::String) + .description("The report's file, project-relative, with / separators"); + }); + let counts = [ + ("functions_found", "The functions the report lists in it"), + ("functions_hit", "Those of its functions that ran"), + ("lines_found", "The lines the report measured in it"), + ("lines_hit", "Those of its lines that ran"), + ("branches_found", "The branches the report measured in it"), + ("branches_hit", "Those of its branches that were taken"), + ]; + for (name, description) in counts { + k.field(name, |f| { + f.field_type(FieldType::Integer).description(description); + }); + } + }); + c.edge("covers", |e| { + e.description("The item a coverage fact reports on") + .source_kind(COVERAGE.kind) + .target_kind(ITEM_KIND); + }); + c.kind(API_ITEM.kind, |k| { + k.description( + "One public entry of an API snapshot, written by an api pack's collector (ADR 0388): \ + api:rust::: (cargo public-api, a trait-impl member ...::::m), \ + api:js::: (api-extractor), the id holding no line, order nor source file", + ) + .collected(&[API_ITEM.scheme]) + .field("item", |f| { + referencing(f, API_ITEM.kind, "item") + .field_type(FieldType::Reference) + .description( + "The item the entry is the API of; absent when no collected item has its path (W104 for a kind \ + an item can have)", + ); + }) + .field("path", |f| { + f.field_type(FieldType::String) + .description("The entry's qualified path as the snapshot wrote it"); + }) + .field("kind", |f| { + f.vocabulary(&API_KINDS).description( + "What the entry is: an item kind, or variant, reexport, extern_crate, other, which no item is", + ); + }) + .field("visibility", |f| { + f.vocabulary(&VISIBILITY) + .description("Who may name it, as the snapshot wrote it"); + }) + .field("signature", |f| { + f.field_type(FieldType::String) + .description("The entry exactly as the snapshot wrote it, attributes included"); + }) + .field("tag", |f| { + f.field_type(FieldType::String) + .description("The api-extractor release tag (Public, Beta, Alpha, Internal)"); + }) + .field("change", |f| { + f.vocabulary(&API_CHANGES).description( + "The entry against the committed accepted report; absent when no accepted report covers its \ + crate or package", + ); + }) + .field("accepted_signature", |f| { + f.field_type(FieldType::String).description( + "The accepted report's entry as it wrote it, for a changed, narrowed or removed entry", + ); + }) + .field("accepted_tag", |f| { + f.field_type(FieldType::String).description( + "The accepted report's release tag, for a changed, narrowed or removed entry that has one", + ); + }) + .field("accepted_visibility", |f| { + f.vocabulary(&VISIBILITY).description( + "The accepted report's visibility, for a changed or narrowed entry whose visibility differs", + ); + }); + }); + c.edge("api_of", |e| { + e.description("The item an API snapshot's entry is the API of") + .source_kind(API_ITEM.kind) + .target_kind(ITEM_KIND); + }); + c.kind(STATIC_FINDING.kind, |k| { + k.description( + "One result of a SARIF run (a lint or static analysis finding), written by a lint pack's collector \ + (ADR 0388): sarif:/#:, # with no line, neither with no location, ~2 on \ + a repeat in document order", + ) + .collected(&[STATIC_FINDING.scheme]) + .field("tool", |f| { + f.field_type(FieldType::String) + .description("The run's tool (tool.driver.name)"); + }) + .field("rule", |f| { + f.field_type(FieldType::String) + .description("The rule id the result states; unknown when it states none (W105)"); + }) + .field("level", |f| { + f.vocabulary(&LEVELS).description( + "The level the result or its rule's defaultConfiguration states; unknown when neither does (W105), \ + never SARIF's own warning default", + ); + }) + .field("message", |f| { + f.field_type(FieldType::String) + .description("The result's message.text"); + }) + .field("file", |f| { + f.field_type(FieldType::String) + .description("The file of its first location, project-relative, with / separators"); + }) + .field("line", |f| { + f.field_type(FieldType::Integer) + .description("The 1-based start line of its first location"); + }) + .field("item", |f| { + referencing(f, STATIC_FINDING.kind, "item") + .field_type(FieldType::Reference) + .description("The innermost item holding its line; absent when no collected item does"); + }) + .field("package", |f| { + referencing(f, STATIC_FINDING.kind, "package") + .field_type(FieldType::Reference) + .description( + "The package holding its file, when no item holds its line; absent with neither (W104)", + ); + }); + }); + c.edge("found_in", |e| { + e.description("The item a static finding lies in") + .source_kind(STATIC_FINDING.kind) + .target_kind(ITEM_KIND); + }); + c.edge("found_in_package", |e| { + e.description("The package a static finding lies in, when no item holds it") + .source_kind(STATIC_FINDING.kind) + .target_kind(PACKAGE_KIND); + }); + c.kind(DEPENDENCY.kind, |k| { + k.description( + "One component of a CycloneDX bill of materials, written by an SBOM pack's collector (ADR 0388): \ + dep:/, or dep:/@<[group/]name[@version]> \ + for a component with no purl (W106); one fact per id, a purl listed twice merged", + ) + .collected(&[DEPENDENCY.scheme]) + .field("package", |f| { + referencing(f, DEPENDENCY.kind, "package") + .field_type(FieldType::Reference) + .description("The project package the BOM describes (its metadata.component)"); + }) + .field("purl", |f| { + f.field_type(FieldType::String) + .description("The component's package URL as written; absent when it has none (W106)"); + }) + .field("name", |f| { + f.field_type(FieldType::String) + .description("The component's name, group/name when it states a group"); + }) + .field("version", |f| { + f.field_type(FieldType::String) + .description("The component's version, when it states one"); + }) + .field("scope", |f| { + f.vocabulary(&SCOPES).description( + "The component's scope, required when the BOM states none (the spec's default); the widest of a \ + purl listed twice", + ); + }) + .field("direct", |f| { + f.field_type(FieldType::Bool).description( + "Whether the project package depends on it directly; present only when the BOM states a \ + dependency graph for its root, never false for a graph it does not state", + ); + }); + }); + c.edge("dependency_of", |e| { + e.description("The project package a dependency is a component of the BOM of") + .source_kind(DEPENDENCY.kind) + .target_kind(PACKAGE_KIND); + }); + c.kind(VULNERABILITY.kind, |k| { + k.description( + "One OSV record of an osv-scanner report, written by a vulnerability pack's collector (ADR 0388): \ + vuln:/, one fact per project package the scanned lockfile belongs to and OSV id, \ + the versions of one dependency merged; severity critical, high, medium, low, else unknown (W107)", + ) + .collected(&[VULNERABILITY.scheme]) + .field("package", |f| { + referencing(f, VULNERABILITY.kind, "package") + .field_type(FieldType::Reference) + .description( + "The project package the scanned lockfile belongs to: the one at its directory, else each \ + one under it", + ); + }) + .field("osv_id", |f| { + f.field_type(FieldType::String) + .description("The OSV record's id (GHSA-…, RUSTSEC-…)"); + }) + .field("aliases", |f| { + f.field_type(FieldType::StringList) + .description("The record's aliases (CVE ids and the like), sorted"); + }) + .field("summary", |f| { + f.field_type(FieldType::String) + .description("The record's one-line summary; absent when it states none"); + }) + .field("purl", |f| { + f.field_type(FieldType::StringList) + .description("The affected dependency's package URL at each affected version"); + }) + .field("version", |f| { + f.field_type(FieldType::StringList) + .description("The affected dependency's versions the lockfile pins"); + }) + .field("severity", |f| { + f.vocabulary(&SEVERITIES).description( + "The record's own severity label (MODERATE reads medium), else the rating of its highest CVSS v3 \ + base score, else unknown (W107); the highest of the records merged", + ); + }); + }); + c.edge("affects", |e| { + e.description("The project package a vulnerability affects") + .source_kind(VULNERABILITY.kind) + .target_kind(PACKAGE_KIND); + }); +} diff --git a/extensions/code/core/src/lib.rs b/extensions/code/core/src/lib.rs index 648ae446a6..c8008770a5 100644 --- a/extensions/code/core/src/lib.rs +++ b/extensions/code/core/src/lib.rs @@ -12,7 +12,19 @@ //! `js:/::`, with its `package` (edge `in_package`), file, kinds, visibility, signature digest, //! doc, attrs, `names` and the `test_id` it runs as (edge `runs_as`); //! - `package` (scheme `pkg`): a cargo or npm package, a purl without version, with its manifest's values and the -//! project packages it `depends_on` (edge `uses_package`). +//! project packages it `depends_on` (edge `uses_package`); +//! - the report facts a standard report's reader mints (ADR 0388): `coverage` (scheme `cov`), what a coverage report +//! says of the `item` it `covers` (`cov:`), or of a file's lines no item holds (`cov:@`); `api_item` +//! (scheme `api`), one public entry of an API snapshot, `api:rust:::` or `api:js:::`, with the `item` it is the API of (`api_of`), its kind, visibility, signature as written and release tag, +//! and its `change` against the committed accepted report with what that report said (ADR 0390 D3); +//! `static_finding` (scheme `sarif`), one result of a SARIF run, `sarif:/#:`, with its tool, +//! rule, level, message, file and line, and the `item` it is `found_in`, else the `package` (`found_in_package`); +//! `dependency` (scheme `dep`), one component of a CycloneDX BOM, `dep:/` or +//! `dep:/@` with no purl, with its purl, name, version, scope and whether the project uses +//! it directly, and the project `package` the BOM describes (`dependency_of`); `vulnerability` (scheme `vuln`), one +//! OSV record of an osv-scanner report, `vuln:/`, with its OSV id, aliases, summary, affected +//! purls and versions and severity, and the project `package` it `affects`. //! //! Every kind is collector-written and none is scoped: a scheme reference names the fact whole. `@code/core` declares //! no collector: a pack collects, minting the facts with the linked `specforge-code-facts` library, so every pack @@ -23,13 +35,22 @@ //! holds one, W102 naming the pack otherwise), unless the citing entity is pending (ADR 0329 D4, ADR 0347 D9); its //! check pass `proof` reports a complete entity linking a failed test (W401), a test or item naming no entity (I402) //! (ADR 0329 D6, ADR 0347 D11) and a fact's own reference that answers nothing (E101, ADR 0346 D4). `refs` is sent -//! the `test` and `test_run` facts, `proof` the facts of every kind (ADR 0353 D6). +//! the `test` and `test_run` facts, `proof` the facts of its four kinds (ADR 0353 D6). Its check pass `reports` is +//! sent only the report facts, and reports an entry that names no item (W104), a finding whose rule or level its +//! report states nowhere (W105), a dependency with no purl (W106) and a vulnerability whose severity is unknown (W107) +//! (ADR 0388). Each code names the collected kinds it judges, which `specforge doctor` reads to say which codes a +//! missing tool switches off (ADR 0389 D4). -use specforge_code_facts::{ItemKind, Scheme, Visibility}; +use specforge_code_facts::{ + ApiChange, ApiKind, ItemKind, Level, Scheme, Scope, Severity, Visibility, API_ITEM, COVERAGE, + DEPENDENCY, STATIC_FINDING, VULNERABILITY, +}; use specforge_extension_sdk::prelude::*; +mod kinds; mod proof; mod refs; +mod reports; /// The kind of a test fact. const TEST_KIND: &str = "test"; @@ -39,8 +60,17 @@ const RUN_KIND: &str = "test_run"; const ITEM_KIND: &str = "item"; /// The kind of a package a manifest pack read. const PACKAGE_KIND: &str = "package"; -/// Every kind `@code/core` declares. +/// The kinds of the test, item and package facts, which `refs` and `proof` read. const KINDS: [&str; 4] = [TEST_KIND, RUN_KIND, ITEM_KIND, PACKAGE_KIND]; +/// The report kinds, the facts a standard report's reader mints (ADR 0388): the only kinds the `reports` pass is +/// sent. They stay out of [`KINDS`], which `refs` and `proof` read. +const REPORT_KINDS: [&str; 5] = [ + COVERAGE.kind, + API_ITEM.kind, + STATIC_FINDING.kind, + DEPENDENCY.kind, + VULNERABILITY.kind, +]; /// The schemes of a `test`'s id. const TEST_SCHEMES: [&str; 2] = [Scheme::Js.as_str(), Scheme::Rust.as_str()]; /// The scheme of a `test_run`'s id. @@ -67,7 +97,7 @@ pub(crate) struct Reference { /// Every reference field `@code/core` declares with a target kind: the one table its declarations read for the /// target and the edge, and `refs` for what a mistyped reference should have named and whose an unheld one is. -pub(crate) const REFERENCES: [Reference; 4] = [ +pub(crate) const REFERENCES: [Reference; 10] = [ Reference { kind: ITEM_KIND, field: "package", @@ -96,6 +126,50 @@ pub(crate) const REFERENCES: [Reference; 4] = [ edge: "run_of", together: true, }, + // Another collector answers items, so an unheld one is no disagreement. + Reference { + kind: COVERAGE.kind, + field: "item", + target: ITEM_KIND, + edge: "covers", + together: false, + }, + Reference { + kind: API_ITEM.kind, + field: "item", + target: ITEM_KIND, + edge: "api_of", + together: false, + }, + // Two labels: one label cannot restrict two target kinds. + Reference { + kind: STATIC_FINDING.kind, + field: "item", + target: ITEM_KIND, + edge: "found_in", + together: false, + }, + Reference { + kind: STATIC_FINDING.kind, + field: "package", + target: PACKAGE_KIND, + edge: "found_in_package", + together: false, + }, + Reference { + kind: DEPENDENCY.kind, + field: "package", + target: PACKAGE_KIND, + edge: "dependency_of", + together: false, + }, + Reference { + kind: VULNERABILITY.kind, + field: "package", + target: PACKAGE_KIND, + edge: "affects", + together: false, + }, ]; /// The row of [`REFERENCES`] for the field `field` of `kind`. @@ -117,11 +191,21 @@ const STATUS: Vocabulary = Vocabulary::new(&["passed", "failed", "skipped"]); const ITEM_KINDS: Vocabulary = Vocabulary::new(&ItemKind::NAMES); /// Who may name a definition: the library's `Visibility` names, widest first. const VISIBILITY: Vocabulary = Vocabulary::new(&Visibility::NAMES); +/// What an API snapshot's entry is: the library's `ApiKind` names, the item kinds first. +const API_KINDS: Vocabulary = Vocabulary::new(&ApiKind::NAMES); +/// What an API snapshot's entry is against the committed accepted report: the library's `ApiChange` names. +const API_CHANGES: Vocabulary = Vocabulary::new(&ApiChange::NAMES); +/// A SARIF result's level as its report states it: the library's `Level` names, `unknown` last. +const LEVELS: Vocabulary = Vocabulary::new(&Level::NAMES); +/// A BOM component's scope: the library's `Scope` names, widest first. +const SCOPES: Vocabulary = Vocabulary::new(&Scope::NAMES); +/// A vulnerability's severity: the library's `Severity` names, highest first, `unknown` last. +const SEVERITIES: Vocabulary = Vocabulary::new(&Severity::NAMES); #[specforge_extension_sdk::extension( name = "@code/core", - version = "1.1.0", - description = "The neutral base of code facts: the test, test_run, item and package kinds the code packs collect, and the checks of the references a spec writes to them" + version = "1.4.0", + description = "The neutral base of code facts: the test, test_run, item and package kinds the code packs collect, the report facts (coverage, api_item, static_finding, dependency, vulnerability) a standard report's reader mints, and the checks of the references a spec writes to them and of what a report leaves unmapped" )] struct CodeCore; @@ -299,6 +383,7 @@ impl Contributions for CodeCore { .source_kind(ITEM_KIND) .target_kind(TEST_KIND); }); + kinds::report_kinds(c); // A pass is sent the facts of the kinds it declares (ADR 0353): `refs` names the closest held test or run, // and `proof` judges what the facts of every kind say, so item facts cross into one guest. @@ -312,6 +397,12 @@ impl Contributions for CodeCore { .input(Input::facts(&KINDS)) .run(proof::proof); }); + // `reports` is sent only the report kinds (ADR 0353, ADR 0388): nothing is decoded when no report was collected. + c.pass("reports", |p| { + p.phase("check") + .input(Input::facts(&REPORT_KINDS)) + .run(reports::reports); + }); c.code("E101", |d| { d.title("A fact reference names no fact").explanation( @@ -325,7 +416,8 @@ impl Contributions for CodeCore { that names an entity of another kind, is reported at the place its collector read it, addressed \ to that collector: its facts disagree, and running `specforge collect` again, or fixing the pack, \ is the remedy (ADR 0346).", - ); + ) + .facts(&[ITEM_KIND, PACKAGE_KIND, TEST_KIND, RUN_KIND]); }); c.code("W102", |d| { d.title("No facts of the reference's kinds were collected").explanation( @@ -333,7 +425,8 @@ impl Contributions for CodeCore { its field admits (narrowed to those its id is shaped as) in its scheme: on a fresh clone, or before \ the pack that writes them ran, there is nothing to check it against. It is reported once per cited \ reference, and not while the citing entity's owner is pending. Run `specforge collect` with the \ - pack the finding names: `@javascript/node-test` for `js` tests, `@rust/test` for `rust` tests, \ + pack the finding names: `@javascript/node-test`, `@javascript/vitest`, `@javascript/jest` or \ + `@javascript/playwright` for `js` tests, `@rust/test` or `@rust/proof` for `rust` tests, \ `@rust/source` for `rust` items, `@javascript/source` for `js` items, `@rust/cargo` for \ `pkg:cargo` packages, `@javascript/source` for `pkg:npm` packages.", ); @@ -343,15 +436,18 @@ impl Contributions for CodeCore { "An entity whose owner is complete links a test whose last collected status is `failed`: the proof \ it cites does not hold. A pending owner's failing test is not reported (TDD). Fix the code or the \ test, and run `specforge collect` again.", - ); + ) + .facts(&[TEST_KIND]); }); c.code("I402", |d| { d.title("A test or item names an entity that does not exist").explanation( "A test or item fact's `names` (the entities its source's idiom says it proves or implements) \ holds a name that is no entity of the project, or the short name of several: the entity was \ renamed or deleted, or the name is misspelled. Fix the name in the source, then collect again.", - ); + ) + .facts(&[ITEM_KIND, TEST_KIND]); }); + reports::catalogue(c); } } diff --git a/extensions/code/core/src/refs.rs b/extensions/code/core/src/refs.rs index 27879822b3..e0ce10eb16 100644 --- a/extensions/code/core/src/refs.rs +++ b/extensions/code/core/src/refs.rs @@ -7,15 +7,28 @@ use specforge_extension_sdk::UnheldReference; use crate::{ITEM_KIND, KINDS, PACKAGE_KIND, RUN_KIND, TEST_KIND}; -/// The pack that collects each kind of `@code/core`, by the scheme of a test's or an item's id and the purl type of a -/// package's: what W102 tells to run. -pub(crate) const PACKS: [(&str, &str, &str); 6] = [ - (TEST_KIND, Scheme::Js.as_str(), "@javascript/node-test"), - (TEST_KIND, Scheme::Rust.as_str(), "@rust/test"), - (ITEM_KIND, Scheme::Rust.as_str(), "@rust/source"), - (ITEM_KIND, Scheme::Js.as_str(), "@javascript/source"), - (PACKAGE_KIND, "cargo", "@rust/cargo"), - (PACKAGE_KIND, "npm", "@javascript/source"), +/// The packs that collect each kind of `@code/core`, by the scheme of a test's or an item's id and the purl type of a +/// package's: what W102 tells to run. A test scheme has one pack per runner. +pub(crate) const PACKS: [(&str, &str, &[&str]); 6] = [ + ( + TEST_KIND, + Scheme::Js.as_str(), + &[ + "@javascript/node-test", + "@javascript/vitest", + "@javascript/jest", + "@javascript/playwright", + ], + ), + ( + TEST_KIND, + Scheme::Rust.as_str(), + &["@rust/test", "@rust/proof"], + ), + (ITEM_KIND, Scheme::Rust.as_str(), &["@rust/source"]), + (ITEM_KIND, Scheme::Js.as_str(), &["@javascript/source"]), + (PACKAGE_KIND, "cargo", &["@rust/cargo"]), + (PACKAGE_KIND, "npm", &["@javascript/source"]), ]; /// Each unheld reference whose collected kinds (`UnheldReference.kinds`, narrowed to those its id is shaped as) meet @@ -94,10 +107,16 @@ fn held<'k>(input: &PassInput, scheme: &str, kinds: &[&'k str]) -> Vec<&'k str> /// The W102 of `item`, whose `kinds` no served store holds in `scheme`. fn uncollected(item: &UnheldReference, scheme: &str, kinds: &[&str]) -> PassDiagnostic { - let packs: Vec<&str> = kinds + let mut packs: Vec<&str> = Vec::new(); + for pack in kinds .iter() - .filter_map(|kind| pack(scheme, &item.id, kind)) - .collect(); + .filter_map(|kind| packs_of(scheme, &item.id, kind)) + .flatten() + { + if !packs.contains(pack) { + packs.push(pack); + } + } let remedy = match packs.is_empty() { true => "run `specforge collect`".to_string(), false => format!("run `specforge collect` with {}", quoted(&packs)), @@ -113,14 +132,17 @@ fn uncollected(item: &UnheldReference, scheme: &str, kinds: &[&str]) -> PassDiag ) } -/// `words`, each in backticks, joined by `or`. -fn quoted(words: &[&str]) -> String { +/// `words`, each in backticks: "`a`, `b` or `c`". +pub(crate) fn quoted(words: &[&str]) -> String { let quoted: Vec = words.iter().map(|word| format!("`{word}`")).collect(); - quoted.join(" or ") + match quoted.split_last() { + Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")), + _ => quoted.concat(), + } } -/// The pack that writes `kind` facts like `id`, in `scheme`: a run's is its test's, a package's its purl type's. -fn pack(scheme: &str, id: &str, kind: &str) -> Option<&'static str> { +/// The packs that write `kind` facts like `id`, in `scheme`: a run's are its test's, a package's its purl type's. +fn packs_of(scheme: &str, id: &str, kind: &str) -> Option<&'static [&'static str]> { let (kind, family) = match kind { RUN_KIND => (TEST_KIND, TestId::of_run(id).ok()?.scheme().as_str()), PACKAGE_KIND => (kind, id.parse::().ok()?.purl_type()), @@ -129,7 +151,7 @@ fn pack(scheme: &str, id: &str, kind: &str) -> Option<&'static str> { PACKS .iter() .find(|(k, f, _)| *k == kind && *f == family) - .map(|(_, _, pack)| *pack) + .map(|(_, _, packs)| *packs) } /// `diagnostic` at `span`, when there is one. diff --git a/extensions/code/core/src/reports.rs b/extensions/code/core/src/reports.rs new file mode 100644 index 0000000000..7e444e77d9 --- /dev/null +++ b/extensions/code/core/src/reports.rs @@ -0,0 +1,166 @@ +//! The check pass `reports` (ADR 0388): what the facts a standard report's reader minted leave unmapped, one code per +//! class, and the catalogue of those codes. + +use specforge_code_facts::{ + shown, ApiChange, ItemKind, API_ITEM, COVERAGE, DEPENDENCY, STATIC_FINDING, UNKNOWN, + VULNERABILITY, +}; +use specforge_extension_sdk::prelude::*; + +use crate::REPORT_KINDS; + +/// For each report fact that is not pending: W104 when it names no `item` (a `coverage`; an `api_item` of a kind an +/// item can have, not a variant, re-export, extern crate nor `other`, not a crate root, which no item is, nor one whose +/// `change` is `removed`; a +/// `static_finding` naming no `package` either), then W105 for a `static_finding` whose rule or level is `unknown`, +/// then W106 for a `dependency` with no `purl`, then W107 for a `vulnerability` whose severity is `unknown`. +pub(crate) fn reports(input: &PassInput) -> Vec { + input + .entities + .iter() + .filter(|e| !e.pending && REPORT_KINDS.contains(&e.kind.as_str())) + .flat_map(|fact| { + unmapped(fact) + .into_iter() + .chain(unknown(fact)) + .chain(purl_less(fact)) + .chain(unrated(fact)) + }) + .collect() +} + +/// W104 when `fact` names no item and is a report entry an item should hold: an `api_item` the run no longer has +/// (`change` `removed`) is gone, so no item can hold it. +fn unmapped(fact: &PassEntity) -> Option { + let field = |name: &str| fact.fields.get(name).map_or("", String::as_str); + if fact.fields.contains_key("item") || field("change") == ApiChange::Removed.as_str() { + return None; + } + let message = if fact.kind == COVERAGE.kind { + format!( + "the coverage fact '{}' names no item: no collected item holds its lines of `{}`", + fact.id, + shown(field("file")) + ) + } else if fact.kind == API_ITEM.kind + && ItemKind::NAMES.contains(&field("kind")) + && !is_crate_root(&fact.id) + { + format!( + "the api_item '{}' names no item: no collected item has its path `{}`", + fact.id, + shown(field("path")) + ) + } else if fact.kind == STATIC_FINDING.kind && !fact.fields.contains_key("package") { + format!( + "the static_finding '{}' names no item and no package: no collected item or package holds its location", + fact.id + ) + } else { + return None; + }; + Some(PassDiagnostic::warning("W104", message).with_entity(&fact.id)) +} + +/// W105 when `fact` is a `static_finding` whose rule or level (or both) reads `unknown`, saying which. +fn unknown(fact: &PassEntity) -> Option { + if fact.kind != STATIC_FINDING.kind { + return None; + } + let unstated: Vec<&str> = ["rule", "level"] + .into_iter() + .filter(|name| fact.fields.get(*name).map(String::as_str) == Some(UNKNOWN)) + .collect(); + if unstated.is_empty() { + return None; + } + let message = format!( + "the static_finding '{}' states no {}: its SARIF result reads `{UNKNOWN}`", + fact.id, + unstated.join(" and ") + ); + Some(PassDiagnostic::warning("W105", message).with_entity(&fact.id)) +} + +/// W106 when `fact` is a `dependency` with no `purl`, naming it by its name. +fn purl_less(fact: &PassEntity) -> Option { + if fact.kind != DEPENDENCY.kind || fact.fields.contains_key("purl") { + return None; + } + let message = format!( + "the dependency '{}' has no purl: its BOM component `{}` is named by name and version only", + fact.id, + shown(fact.fields.get("name").map_or("", String::as_str)) + ); + Some(PassDiagnostic::warning("W106", message).with_entity(&fact.id)) +} + +/// W107 when `fact` is a `vulnerability` whose severity reads `unknown`, naming its OSV id. +fn unrated(fact: &PassEntity) -> Option { + if fact.kind != VULNERABILITY.kind + || fact.fields.get("severity").map(String::as_str) != Some(UNKNOWN) + { + return None; + } + let message = format!( + "the vulnerability '{}' has an unknown severity: its OSV record `{}` states no label and no CVSS v3 vector \ + this reader rates", + fact.id, + shown(fact.fields.get("osv_id").map_or("", String::as_str)) + ); + Some(PassDiagnostic::warning("W107", message).with_entity(&fact.id)) +} + +/// Whether `id` is a Rust crate root's `api:rust:`: a crate is no item. +fn is_crate_root(id: &str) -> bool { + id.strip_prefix("api:rust:") + .is_some_and(|krate| !krate.contains("::")) +} + +/// The codes the `reports` pass raises. +pub(crate) fn catalogue(c: &mut ContributionsBuilder) { + c.code("W104", |d| { + d.title("A report entry names no item").explanation( + "A fact a report reader minted cites no item, because the report's file or line lies in no collected \ + item (a macro expansion, top-level statements, or a file no source pack collected), or because an API \ + snapshot's entry has a path no collected item has: a re-exported path whose definition path differs, \ + an item a macro generates, or a crate whose library is named apart from its package. A static finding \ + is reported only when no collected package holds its file either, or it has no location. The entry is \ + kept with what the report says of it, so nothing is lost. Collect the source pack for those files \ + (`@rust/source`, `@javascript/source`) and the manifest pack for their packages, then collect the \ + report again.", + ) + .facts(&[API_ITEM.kind, COVERAGE.kind, STATIC_FINDING.kind]); + }); + c.code("W105", |d| { + d.title("A finding's rule or level is unknown").explanation( + "A static finding's SARIF result states no rule (no `ruleId`, no `rule`, and no rule index naming a \ + rule of its tool's driver), or states no level (none on the result, and none in its rule's \ + `defaultConfiguration`): the field reads `unknown`. The finding is kept, never dropped. SARIF's own \ + default level is `warning`; it is not applied, so a level the tool never wrote cannot pass for one \ + it did. Make the tool write its rule ids and levels in its SARIF output, or the rule metadata \ + (`tool.driver.rules` with a `defaultConfiguration.level`), then collect the report again.", + ) + .facts(&[STATIC_FINDING.kind]); + }); + c.code("W106", |d| { + d.title("A dependency has no purl").explanation( + "A component of a CycloneDX bill of materials carries no package URL (`purl`), so its dependency is \ + named by name and version only (`dep:/@`). The dependency is kept, never \ + dropped, but no other report can be matched to it: an OSV scan or another BOM names a package by its \ + purl. Generate the BOM with an SBOM tool that writes a purl for every component (cargo-cyclonedx, \ + cyclonedx-npm), then collect it again.", + ) + .facts(&[DEPENDENCY.kind]); + }); + c.code("W107", |d| { + d.title("A vulnerability's severity is unknown").explanation( + "An OSV record of a vulnerability scan has no severity label (`database_specific.severity`) and no \ + CVSS v3 vector this reader rates: its only severity entries are CVSS v4 or v2 vectors, or its v3 \ + vector is malformed. The vulnerability is kept with severity `unknown`, never dropped and never given \ + a guessed rating, so a gate on severity cannot pass it by mistake. Read the advisory by its OSV id \ + (osv.dev, or the database its id names) and judge its severity there.", + ) + .facts(&[VULNERABILITY.kind]); + }); +} diff --git a/extensions/code/core/src/tests.rs b/extensions/code/core/src/tests.rs index c3b7733fac..69ffa308d8 100644 --- a/extensions/code/core/src/tests.rs +++ b/extensions/code/core/src/tests.rs @@ -95,7 +95,19 @@ fn item_and_package_reference_their_facts() { let labels: Vec<&str> = declared.edges.iter().map(|e| e.label.as_str()).collect(); assert_eq!( labels, - ["run_of", "names", "in_package", "uses_package", "runs_as"] + [ + "run_of", + "names", + "in_package", + "uses_package", + "runs_as", + "covers", + "api_of", + "found_in", + "found_in_package", + "dependency_of", + "affects" + ] ); } @@ -157,12 +169,12 @@ fn a_status_is_a_test_status_name() { fn the_w102_explanation_names_every_pack_of_the_table() { let declared = declaration(); let w102 = declared.codes.iter().find(|c| c.code == "W102").unwrap(); - for (kind, family, pack) in refs::PACKS { + for (kind, family, packs) in refs::PACKS { let told = match kind { "package" => format!("`pkg:{family}` packages"), _ => format!("`{family}` {kind}s"), }; - let named = format!("`{pack}` for {told}"); + let named = format!("{} for {told}", refs::quoted(packs)); assert!(w102.explanation.contains(&named), "{named}"); } } @@ -170,7 +182,10 @@ fn the_w102_explanation_names_every_pack_of_the_table() { #[test] fn it_catalogues_the_codes_it_reports() { let codes: Vec = declaration().codes.into_iter().map(|c| c.code).collect(); - assert_eq!(codes, ["E101", "W102", "W401", "I402"]); + assert_eq!( + codes, + ["E101", "W102", "W401", "I402", "W104", "W105", "W106", "W107"] + ); } /// A pass input holding `entities`, with a store of `served` schemes when there is one: `js` holding tests, `run` runs. @@ -315,7 +330,8 @@ fn a_scheme_no_store_serves_is_w102() { assert!( diagnostics[0] .message - .contains("no `js` `test` facts were collected: run `specforge collect` with `@javascript/node-test`"), + .contains("no `js` `test` facts were collected: run `specforge collect` with `@javascript/node-test`, \ + `@javascript/vitest`, `@javascript/jest` or `@javascript/playwright`"), "{}", diagnostics[0].message ); @@ -331,7 +347,7 @@ fn a_store_of_another_kind_in_the_scheme_is_w102() { assert_eq!( diagnostics[0].message, "`proof` names `js:app/test/a.test.js#adds`, but no `js` `test` facts were collected: run `specforge \ - collect` with `@javascript/node-test`" + collect` with `@javascript/node-test`, `@javascript/vitest`, `@javascript/jest` or `@javascript/playwright`" ); } @@ -345,7 +361,7 @@ fn a_rust_test_ref_beside_rust_items_only_is_w102() { assert_eq!(found(&diagnostics), [("W102", "t1", 2, None)]); assert!( diagnostics[0].message.ends_with( - "no `rust` `test` facts were collected: run `specforge collect` with `@rust/test`" + "no `rust` `test` facts were collected: run `specforge collect` with `@rust/test` or `@rust/proof`" ), "{}", diagnostics[0].message @@ -388,7 +404,7 @@ fn a_test_id_in_a_field_of_no_target_beside_only_items_is_w102() { assert_eq!(found(&diagnostics), [("W102", "t1", 2, None)]); assert!( diagnostics[0].message.ends_with( - "no `rust` `test` facts were collected: run `specforge collect` with `@rust/test`" + "no `rust` `test` facts were collected: run `specforge collect` with `@rust/test` or `@rust/proof`" ), "{}", diagnostics[0].message @@ -642,6 +658,16 @@ fn its_passes_declare_the_facts_they_read() { }; assert_eq!(facts("refs"), ["test", "test_run"]); assert_eq!(facts("proof"), ["item", "package", "test", "test_run"]); + assert_eq!( + facts("reports"), + [ + "api_item", + "coverage", + "dependency", + "static_finding", + "vulnerability" + ] + ); } #[test] @@ -661,4 +687,6 @@ fn the_edit_distance_counts_insertions_deletions_and_substitutions() { } } +mod facts; mod proof_findings; +mod reports; diff --git a/extensions/code/core/src/tests/facts.rs b/extensions/code/core/src/tests/facts.rs new file mode 100644 index 0000000000..178002d01d --- /dev/null +++ b/extensions/code/core/src/tests/facts.rs @@ -0,0 +1,79 @@ +//! The collected kinds each code judges (ADR 0389 D4), which doctor reads, and the packs W102 names. + +use super::*; + +/// The kinds each catalogued code names, as the declaration carries them. +fn judged() -> Vec<(String, Vec)> { + declaration() + .codes + .into_iter() + .map(|code| (code.code, code.facts)) + .collect() +} + +#[test] +fn each_code_names_the_collected_kinds_it_judges() { + let expected: Vec<(String, Vec)> = [ + ("E101", &["item", "package", "test", "test_run"][..]), + ("W102", &[]), + ("W401", &["test"]), + ("I402", &["item", "test"]), + ("W104", &["api_item", "coverage", "static_finding"]), + ("W105", &["static_finding"]), + ("W106", &["dependency"]), + ("W107", &["vulnerability"]), + ] + .iter() + .map(|(code, kinds)| (code.to_string(), strings(kinds))) + .collect(); + + assert_eq!(judged(), expected); +} + +#[test] +fn every_judged_kind_is_a_kind_it_declares() { + let declared = declaration(); + for (code, kinds) in judged() { + for kind in kinds { + assert!( + KINDS.contains(&kind.as_str()) || REPORT_KINDS.contains(&kind.as_str()), + "{code} judges {kind}" + ); + assert!( + declared.entities.iter().any(|k| k.name == kind), + "{code} judges {kind}, which the declaration has no kind of" + ); + } + } +} + +#[test] +fn w102_names_every_runner_pack_of_a_test_scheme_and_one_pack_otherwise() { + let packs = |kind: &str, family: &str| -> Vec<&str> { + refs::PACKS + .iter() + .find(|(k, f, _)| *k == kind && *f == family) + .map(|(_, _, packs)| packs.to_vec()) + .unwrap_or_default() + }; + assert_eq!( + packs("test", "js"), + [ + "@javascript/node-test", + "@javascript/vitest", + "@javascript/jest", + "@javascript/playwright" + ] + ); + assert_eq!(packs("test", "rust"), ["@rust/test", "@rust/proof"]); + for (kind, family, named) in refs::PACKS { + if kind != "test" { + assert_eq!(named.len(), 1, "{kind} {family}: {named:?}"); + } + } +} + +#[test] +fn the_handshake_is_version_1_4_0() { + assert_eq!(declaration().handshake.version, "1.4.0"); +} diff --git a/extensions/code/core/src/tests/reports.rs b/extensions/code/core/src/tests/reports.rs new file mode 100644 index 0000000000..930f352b8b --- /dev/null +++ b/extensions/code/core/src/tests/reports.rs @@ -0,0 +1,737 @@ +//! The report facts' kinds, and the `reports` pass: a report entry that names no item (W104). + +use specforge_code_facts::{ + api_facts, api_facts_against, coverage_facts, dependency_facts, finding_facts, + vulnerability_facts, ApiChange, ApiEntry, ApiKind, Bom, Branch, Component, CoverageFile, + Function, ItemKind, Level, OsvPackage, OsvRecord, OsvReport, OsvSource, Owner, SarifResult, + Scheme, Scope, Severity, Visibility, +}; + +use super::*; + +/// A `coverage` fact of `file`, citing `item` when there is one. +fn coverage(id: &str, file: &str, item: Option<&str>) -> PassEntity { + let mut fact = entity(id, "coverage"); + fact.fields.insert("file".to_string(), file.to_string()); + if let Some(item) = item { + fact.fields.insert("item".to_string(), item.to_string()); + } + fact +} + +fn reported(entities: Vec) -> Vec { + crate::reports::reports(&PassInput { + entities, + ..PassInput::default() + }) +} + +#[test] +fn a_coverage_naming_no_item_is_w104() { + let found = reported(vec![coverage("cov:@src%2Fbuild.rs", "src/build.rs", None)]); + assert_eq!(found.len(), 1, "{found:?}"); + let w104 = &found[0]; + assert_eq!( + (w104.code.as_str(), w104.severity, w104.entity.as_deref()), + ("W104", PassSeverity::Warning, Some("cov:@src%2Fbuild.rs")) + ); + assert!( + w104.message.contains("cov:@src%2Fbuild.rs"), + "{}", + w104.message + ); + assert!(w104.message.contains("src/build.rs"), "{}", w104.message); +} + +#[test] +fn a_warning_shows_the_reports_text_bounded_and_escaped() { + let hostile = format!("\u{1b}]0;{}", "a".repeat(5_000)); + let mut api = api_item("api:rust:demo::f", "function", None); + api.fields.insert("path".to_string(), hostile.clone()); + let mut purl_less = dependency("x", None); + purl_less.fields.insert("name".to_string(), hostile.clone()); + let mut unrated = vulnerability("X-1", "unknown"); + unrated.fields.insert("osv_id".to_string(), hostile.clone()); + let found = reported(vec![ + coverage("cov:@x", &hostile, None), + api, + purl_less, + unrated, + ]); + let codes: Vec<&str> = found.iter().map(|d| d.code.as_str()).collect(); + assert_eq!(codes, ["W104", "W104", "W106", "W107"]); + for warning in &found { + let message = &warning.message; + assert!( + !message.contains('\u{1b}') && message.contains("\\u{1b}"), + "{message}" + ); + assert!(message.len() < 500, "{} bytes", message.len()); + } +} + +#[test] +fn a_coverage_citing_an_item_or_another_kind_is_not_w104() { + let mut pending = coverage("cov:@src%2Fa.rs", "src/a.rs", None); + pending.pending = true; + let found = reported(vec![ + coverage("cov:rust:demo::add", "src/lib.rs", Some("rust:demo::add")), + entity("rust:demo::add", "item"), + entity("t1", "truth"), + pending, + ]); + assert!(found.is_empty(), "{found:?}"); +} + +#[test] +fn coverage_is_collected_and_covers_an_item() { + let declared = declaration(); + let coverage = kind(&declared, "coverage"); + assert_eq!( + (coverage.writer.as_deref(), &coverage.schemes[..]), + (Some("collector"), &strings(&["cov"])[..]) + ); + let item = coverage.fields.iter().find(|f| f.name == "item").unwrap(); + assert_eq!( + ( + item.field_type.as_str(), + item.target_kind.as_deref(), + item.edge.as_deref() + ), + ("reference", Some("item"), Some("covers")) + ); + for count in [ + "functions_found", + "functions_hit", + "lines_found", + "lines_hit", + "branches_found", + "branches_hit", + ] { + let field = coverage.fields.iter().find(|f| f.name == count).unwrap(); + assert_eq!(field.field_type, "integer", "{count}"); + } + let covers = declared.edges.iter().find(|e| e.label == "covers").unwrap(); + assert_eq!( + (covers.source_kind.as_deref(), covers.target_kind.as_deref()), + (Some("coverage"), Some("item")) + ); +} + +#[test] +fn every_field_a_coverage_fact_is_minted_with_is_declared() { + let served = [Fact::new("item", "rust:demo::add").at(FactLocation { + file: "src/lib.rs".to_string(), + start_line: 1, + start_col: 1, + end_line: 5, + end_col: 2, + })]; + let files = [CoverageFile { + file: "src/lib.rs".to_string(), + functions: vec![Function { + line: 1, + name: "add".to_string(), + hits: 1, + }], + lines: vec![(2, 1), (9, 0)], + branches: vec![Branch { + line: 2, + block: "0".to_string(), + branch: "0".to_string(), + taken: None, + }], + }]; + let minted = coverage_facts(&files, &served); + assert_eq!(minted.len(), 2, "one citing the item, one of the file"); + let declared = declaration(); + let fields: Vec<&str> = kind(&declared, "coverage") + .fields + .iter() + .map(|f| f.name.as_str()) + .collect(); + for fact in &minted { + assert_eq!(fact.kind, "coverage"); + for name in fact.fields.keys() { + assert!(fields.contains(&name.as_str()), "{name} of {}", fact.id); + } + } +} + +/// An `api_item` fact of `kind` at `path`, citing `item` when there is one. +fn api_item(id: &str, kind: &str, item: Option<&str>) -> PassEntity { + let mut fact = entity(id, "api_item"); + let path = id.strip_prefix("api:rust:").unwrap_or(id); + fact.fields.insert("path".to_string(), path.to_string()); + fact.fields.insert("kind".to_string(), kind.to_string()); + if let Some(item) = item { + fact.fields.insert("item".to_string(), item.to_string()); + } + fact +} + +#[test] +fn an_item_capable_api_item_naming_no_item_is_w104() { + let found = reported(vec![api_item( + "api:rust:demo::from_macro", + "function", + None, + )]); + assert_eq!(found.len(), 1, "{found:?}"); + let w104 = &found[0]; + assert_eq!( + (w104.code.as_str(), w104.severity, w104.entity.as_deref()), + ( + "W104", + PassSeverity::Warning, + Some("api:rust:demo::from_macro") + ) + ); + assert!( + w104.message.contains("api:rust:demo::from_macro"), + "{}", + w104.message + ); + assert!( + w104.message.contains("demo::from_macro"), + "{}", + w104.message + ); +} + +#[test] +fn an_api_item_no_item_can_hold_or_citing_one_is_not_w104() { + let mut entities: Vec = ["variant", "reexport", "extern_crate", "other"] + .iter() + .map(|kind| api_item(&format!("api:rust:demo::{kind}"), kind, None)) + .collect(); + entities.push(api_item( + "api:rust:demo::add", + "function", + Some("rust:demo::add"), + )); + // The crate root, which no item is. + entities.push(api_item("api:rust:demo", "module", None)); + let found = reported(entities); + assert!(found.is_empty(), "{found:?}"); +} + +#[test] +fn a_removed_api_item_is_not_w104_and_another_change_still_is() { + let marked = |change: &str| { + let mut fact = api_item(&format!("api:rust:demo::{change}"), "function", None); + fact.fields.insert("change".to_string(), change.to_string()); + fact + }; + assert!(reported(vec![marked("removed")]).is_empty()); + let found = reported(vec![marked("changed")]); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0].code, "W104"); +} + +#[test] +fn api_item_is_collected_and_is_the_api_of_an_item() { + let declared = declaration(); + let api = kind(&declared, "api_item"); + assert_eq!( + (api.writer.as_deref(), &api.schemes[..]), + (Some("collector"), &strings(&["api"])[..]) + ); + let field = |name: &str| api.fields.iter().find(|f| f.name == name).unwrap(); + let item = field("item"); + assert_eq!( + ( + item.field_type.as_str(), + item.target_kind.as_deref(), + item.edge.as_deref() + ), + ("reference", Some("item"), Some("api_of")) + ); + assert_eq!(field("kind").enum_values, strings(&ApiKind::NAMES)); + assert_eq!(field("visibility").enum_values, strings(&Visibility::NAMES)); + assert_eq!(field("change").enum_values, strings(&ApiChange::NAMES)); + assert_eq!( + field("accepted_visibility").enum_values, + strings(&Visibility::NAMES) + ); + for text in [ + "path", + "signature", + "tag", + "accepted_signature", + "accepted_tag", + ] { + assert_eq!(field(text).field_type, "string", "{text}"); + } + let api_of = declared.edges.iter().find(|e| e.label == "api_of").unwrap(); + assert_eq!( + (api_of.source_kind.as_deref(), api_of.target_kind.as_deref()), + (Some("api_item"), Some("item")) + ); +} + +#[test] +fn every_field_an_api_item_fact_is_minted_with_is_declared() { + let entry = |scheme, container: &str, path: &[&str], owner, kind, tag: Option<&str>| ApiEntry { + scheme, + container: container.to_string(), + path: strings(path), + owner, + kind, + visibility: Visibility::Public, + signature: "as written".to_string(), + tag: tag.map(str::to_string), + }; + let entries = [ + entry( + Scheme::Rust, + "demo", + &["demo", "S", "fmt"], + Some(Owner { + self_ty: "demo::S".to_string(), + trait_ty: Some("core::fmt::Debug".to_string()), + }), + ApiKind::Item(ItemKind::Method), + None, + ), + entry( + Scheme::Js, + "@demo/widget", + &["Widget"], + None, + ApiKind::Item(ItemKind::Class), + Some("Public"), + ), + ]; + let served = [ + Fact::new("item", "rust:demo::::fmt"), + Fact::new("item", "js:@demo/widget/src/widget.ts::Widget"), + ]; + let mut minted = api_facts(&entries, &served); + assert_eq!(minted.len(), 2); + let function = |name: &str, visibility, signature: &str| ApiEntry { + visibility, + signature: signature.to_string(), + ..entry( + Scheme::Rust, + "demo", + &["demo", name], + None, + ApiKind::Item(ItemKind::Function), + None, + ) + }; + let mut fresh = entries.to_vec(); + fresh.push(function("g", Visibility::Crate, "pub(crate) fn demo::g()")); + let mut widget = entries[1].clone(); + widget.signature = "accepted".to_string(); + let accepted = [ + function("g", Visibility::Public, "pub fn demo::g()"), + function("gone", Visibility::Public, "pub fn demo::gone()"), + widget, + ]; + let against = api_facts_against(&fresh, &accepted, &served); + let changes: Vec<&str> = against + .iter() + .filter_map(|f| f.fields.get("change").and_then(|v| v.as_str())) + .collect(); + for change in ["added", "changed", "narrowed", "removed"] { + assert!(changes.contains(&change), "{change} in {changes:?}"); + } + for field in ["accepted_signature", "accepted_tag", "accepted_visibility"] { + assert!( + against.iter().any(|f| f.fields.contains_key(field)), + "{field}" + ); + } + minted.extend(against); + let declared = declaration(); + let fields: Vec<&str> = kind(&declared, "api_item") + .fields + .iter() + .map(|f| f.name.as_str()) + .collect(); + for fact in &minted[..2] { + assert!(fact.fields.contains_key("item"), "{fact:?}"); + } + for fact in &minted { + assert_eq!(fact.kind, "api_item"); + for name in fact.fields.keys() { + assert!(fields.contains(&name.as_str()), "{name} of {}", fact.id); + } + } +} + +/// A `static_finding` fact stating `rule` and `level`, citing `item` or `package` when given. +fn finding(rule: &str, level: &str, item: Option<&str>, package: Option<&str>) -> PassEntity { + let mut fact = entity( + &format!("sarif:clippy/{rule}#src%2Flib.rs:3"), + "static_finding", + ); + let stated = [ + ("tool", Some("clippy")), + ("rule", Some(rule)), + ("level", Some(level)), + ("item", item), + ("package", package), + ]; + for (name, value) in stated { + if let Some(value) = value { + fact.fields.insert(name.to_string(), value.to_string()); + } + } + fact +} + +#[test] +fn a_finding_with_an_unknown_rule_or_level_is_one_w105_saying_which() { + let package = Some("pkg:cargo/demo"); + for (rule, level, told) in [ + ("unknown", "warning", "rule"), + ("r", "unknown", "level"), + ("unknown", "unknown", "rule and level"), + ] { + let found = reported(vec![finding(rule, level, None, package)]); + assert_eq!(found.len(), 1, "{found:?}"); + let w105 = &found[0]; + assert_eq!( + (w105.code.as_str(), w105.severity, w105.entity.is_some()), + ("W105", PassSeverity::Warning, true) + ); + assert!( + w105.message.contains(&format!("states no {told}:")), + "{}", + w105.message + ); + } + let known = reported(vec![finding("r", "none", None, package)]); + assert!(known.is_empty(), "{known:?}"); +} + +#[test] +fn a_finding_citing_neither_item_nor_package_is_w104() { + let found = reported(vec![finding("r", "warning", None, None)]); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0].code, "W104"); + assert!( + found[0].message.contains("sarif:clippy/r"), + "{}", + found[0].message + ); + let cited = reported(vec![ + finding("r", "warning", None, Some("pkg:cargo/demo")), + finding("r", "warning", Some("rust:demo::add"), None), + ]); + assert!(cited.is_empty(), "{cited:?}"); + let both = reported(vec![finding("unknown", "warning", None, None)]); + let codes: Vec<&str> = both.iter().map(|d| d.code.as_str()).collect(); + assert_eq!(codes, ["W104", "W105"]); +} + +#[test] +fn static_finding_is_collected_and_found_in_an_item_or_a_package() { + let declared = declaration(); + assert!(declared.entities.iter().all(|k| k.name != "finding")); + let finding = kind(&declared, "static_finding"); + assert_eq!( + (finding.writer.as_deref(), &finding.schemes[..]), + (Some("collector"), &strings(&["sarif"])[..]) + ); + let field = |name: &str| finding.fields.iter().find(|f| f.name == name).unwrap(); + for (name, target, edge) in [ + ("item", "item", "found_in"), + ("package", "package", "found_in_package"), + ] { + let reference = field(name); + assert_eq!( + ( + reference.field_type.as_str(), + reference.target_kind.as_deref(), + reference.edge.as_deref() + ), + ("reference", Some(target), Some(edge)) + ); + let drawn = declared.edges.iter().find(|e| e.label == edge).unwrap(); + assert_eq!( + (drawn.source_kind.as_deref(), drawn.target_kind.as_deref()), + (Some("static_finding"), Some(target)) + ); + } + assert_eq!(field("level").enum_values, strings(&Level::NAMES)); + assert_eq!(field("line").field_type, "integer"); + for text in ["tool", "rule", "message", "file"] { + assert_eq!(field(text).field_type, "string", "{text}"); + } +} + +#[test] +fn every_field_a_static_finding_fact_is_minted_with_is_declared() { + let served = [ + Fact::new("item", "rust:demo::add").at(FactLocation { + file: "src/lib.rs".to_string(), + start_line: 1, + start_col: 1, + end_line: 5, + end_col: 2, + }), + Fact::new("package", "pkg:cargo/demo").field("path", ""), + ]; + let result = |line| SarifResult { + tool: "clippy".to_string(), + rule: "clippy::unwrap_used".to_string(), + level: Level::Warning, + message: "used `unwrap()`".to_string(), + file: Some("src/lib.rs".to_string()), + line: Some(line), + end_line: None, + }; + let minted = finding_facts(&[result(2), result(9)], &served); + assert!(minted[0].fields.contains_key("item"), "{minted:?}"); + assert!(minted[1].fields.contains_key("package"), "{minted:?}"); + let declared = declaration(); + let fields: Vec<&str> = kind(&declared, "static_finding") + .fields + .iter() + .map(|f| f.name.as_str()) + .collect(); + for fact in &minted { + assert_eq!(fact.kind, "static_finding"); + for name in fact.fields.keys() { + assert!(fields.contains(&name.as_str()), "{name} of {}", fact.id); + } + } +} + +/// A `dependency` fact of `name` in `pkg:cargo/demo`, with `purl` when given. +fn dependency(name: &str, purl: Option<&str>) -> PassEntity { + let mut fact = entity(&format!("dep:pkg:cargo/demo/@{name}"), "dependency"); + let stated = [ + ("package", Some("pkg:cargo/demo")), + ("name", Some(name)), + ("scope", Some("required")), + ("purl", purl), + ]; + for (field, value) in stated { + if let Some(value) = value { + fact.fields.insert(field.to_string(), value.to_string()); + } + } + fact +} + +#[test] +fn a_dependency_with_no_purl_is_one_w106_naming_it() { + let found = reported(vec![dependency("left-pad", None)]); + assert_eq!(found.len(), 1, "{found:?}"); + let w106 = &found[0]; + assert_eq!( + (w106.code.as_str(), w106.severity, w106.entity.as_deref()), + ( + "W106", + PassSeverity::Warning, + Some("dep:pkg:cargo/demo/@left-pad") + ) + ); + assert!( + w106.message.contains("dep:pkg:cargo/demo/@left-pad"), + "{}", + w106.message + ); + assert!(w106.message.contains("`left-pad`"), "{}", w106.message); + let with_purl = reported(vec![dependency("serde", Some("pkg:cargo/serde@1.0.0"))]); + assert!(with_purl.is_empty(), "{with_purl:?}"); +} + +#[test] +fn dependency_is_collected_and_a_dependency_of_a_package() { + let declared = declaration(); + let dependency = kind(&declared, "dependency"); + assert_eq!( + (dependency.writer.as_deref(), &dependency.schemes[..]), + (Some("collector"), &strings(&["dep"])[..]) + ); + let field = |name: &str| dependency.fields.iter().find(|f| f.name == name).unwrap(); + let package = field("package"); + assert_eq!( + ( + package.field_type.as_str(), + package.target_kind.as_deref(), + package.edge.as_deref() + ), + ("reference", Some("package"), Some("dependency_of")) + ); + assert_eq!(field("scope").enum_values, strings(&Scope::NAMES)); + assert_eq!(field("direct").field_type, "bool"); + for text in ["purl", "name", "version"] { + assert_eq!(field(text).field_type, "string", "{text}"); + } + let drawn = declared + .edges + .iter() + .find(|e| e.label == "dependency_of") + .unwrap(); + assert_eq!( + (drawn.source_kind.as_deref(), drawn.target_kind.as_deref()), + (Some("dependency"), Some("package")) + ); +} + +#[test] +fn every_field_a_dependency_fact_is_minted_with_is_declared() { + let component = |bom_ref: &str, purl: Option<&str>| Component { + bom_ref: Some(bom_ref.to_string()), + purl: purl.map(str::to_string), + group: None, + name: bom_ref.to_string(), + version: Some("1.0.0".to_string()), + scope: Scope::Optional, + }; + let bom = Bom { + root: component("demo", Some("pkg:cargo/demo@0.1.0")), + components: vec![ + component("serde", Some("pkg:cargo/serde@1.0.0")), + component("tool", None), + ], + direct: Some(vec!["serde".to_string()]), + }; + let served = [Fact::new("package", "pkg:cargo/demo").field("path", "")]; + let minted = dependency_facts(&[bom], &served).expect("the root is served"); + assert_eq!(minted.len(), 2); + let declared = declaration(); + let fields: Vec<&str> = kind(&declared, "dependency") + .fields + .iter() + .map(|f| f.name.as_str()) + .collect(); + for fact in &minted { + assert_eq!(fact.kind, "dependency"); + assert!(fact.fields.contains_key("direct"), "{fact:?}"); + for name in fact.fields.keys() { + assert!(fields.contains(&name.as_str()), "{name} of {}", fact.id); + } + } +} + +/// A `vulnerability` fact of `osv_id` in `pkg:cargo/demo`, of `severity`. +fn vulnerability(osv_id: &str, severity: &str) -> PassEntity { + let mut fact = entity(&format!("vuln:pkg:cargo/demo/{osv_id}"), "vulnerability"); + for (field, value) in [ + ("package", "pkg:cargo/demo"), + ("osv_id", osv_id), + ("severity", severity), + ] { + fact.fields.insert(field.to_string(), value.to_string()); + } + fact +} + +#[test] +fn a_vulnerability_of_unknown_severity_is_one_w107_naming_it() { + let found = reported(vec![vulnerability("RUSTSEC-2099-0002", "unknown")]); + assert_eq!(found.len(), 1, "{found:?}"); + let w107 = &found[0]; + assert_eq!( + (w107.code.as_str(), w107.severity, w107.entity.as_deref()), + ( + "W107", + PassSeverity::Warning, + Some("vuln:pkg:cargo/demo/RUSTSEC-2099-0002") + ) + ); + assert!( + w107.message + .contains("vuln:pkg:cargo/demo/RUSTSEC-2099-0002"), + "{}", + w107.message + ); + assert!( + w107.message.contains("`RUSTSEC-2099-0002`"), + "{}", + w107.message + ); + for severity in Severity::NAMES.iter().filter(|name| **name != "unknown") { + let rated = reported(vec![vulnerability("GHSA-x", severity)]); + assert!(rated.is_empty(), "{severity}: {rated:?}"); + } +} + +#[test] +fn vulnerability_is_collected_and_affects_a_package() { + let declared = declaration(); + let vulnerability = kind(&declared, "vulnerability"); + assert_eq!( + (vulnerability.writer.as_deref(), &vulnerability.schemes[..]), + (Some("collector"), &strings(&["vuln"])[..]) + ); + let field = |name: &str| { + vulnerability + .fields + .iter() + .find(|f| f.name == name) + .unwrap() + }; + let package = field("package"); + assert_eq!( + ( + package.field_type.as_str(), + package.target_kind.as_deref(), + package.edge.as_deref() + ), + ("reference", Some("package"), Some("affects")) + ); + assert_eq!(field("severity").enum_values, strings(&Severity::NAMES)); + for list in ["aliases", "purl", "version"] { + assert_eq!(field(list).field_type, "string_list", "{list}"); + } + for text in ["osv_id", "summary"] { + assert_eq!(field(text).field_type, "string", "{text}"); + } + let drawn = declared + .edges + .iter() + .find(|e| e.label == "affects") + .unwrap(); + assert_eq!( + (drawn.source_kind.as_deref(), drawn.target_kind.as_deref()), + (Some("vulnerability"), Some("package")) + ); +} + +#[test] +fn every_field_a_vulnerability_fact_is_minted_with_is_declared() { + let record = OsvRecord { + id: "GHSA-x".to_string(), + aliases: vec!["CVE-1".to_string()], + summary: Some("a flaw".to_string()), + label: Some("HIGH".to_string()), + scores: Vec::new(), + purl: Some("pkg:cargo/x".to_string()), + }; + let report = OsvReport { + sources: vec![OsvSource { + lockfile: "Cargo.lock".to_string(), + packages: vec![OsvPackage { + name: "x".to_string(), + version: "1.0.0".to_string(), + ecosystem: "crates.io".to_string(), + records: vec![record], + }], + }], + }; + let served = [Fact::new("package", "pkg:cargo/demo").field("path", "")]; + let minted = vulnerability_facts(&report, &served).facts; + assert_eq!(minted.len(), 1); + let declared = declaration(); + let fields: Vec<&str> = kind(&declared, "vulnerability") + .fields + .iter() + .map(|f| f.name.as_str()) + .collect(); + for fact in &minted { + assert_eq!(fact.kind, "vulnerability"); + assert!(fact.fields.contains_key("summary"), "{fact:?}"); + for name in fact.fields.keys() { + assert!(fields.contains(&name.as_str()), "{name} of {}", fact.id); + } + } +} diff --git a/extensions/code/core/wasm/inputs.json b/extensions/code/core/wasm/inputs.json index e844cdca46..7c45e82893 100644 --- a/extensions/code/core/wasm/inputs.json +++ b/extensions/code/core/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "specforge_ext_code_core.wasm", - "artifact_sha256": "9fe9327c90a23be46b1d23722d72b9118837e9a9e756d261f180384e2dcc5419", + "artifact_sha256": "ee9d198eb2783b12fff50e3e339eb99e247e872b792db185187726e573737647", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,30 +55,41 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", - "extensions/code/core/Cargo.lock": "2ff834f2e0f553e152b77292d787d7085e24ec9fc488ff1184f579c72d17cc73", - "extensions/code/core/Cargo.toml": "1da9b82819ac76815d49a6c0bf140fca604f8a5313a7d8cd32590be91931007a", - "extensions/code/core/src/lib.rs": "dc3a630907569f67e2ae263b889ce39ae1cef989a0e00a4a2e68079b488bdcc7", + "extensions/code/core/Cargo.lock": "177bf9f58eec0379e423eb30710f62cc2f88a021bb28b1133ccab00495db8845", + "extensions/code/core/Cargo.toml": "32a45f910bc2588774e1f4876a6a87fcdef8afa0b9184ab805af8ae331669659", + "extensions/code/core/src/kinds.rs": "42874ba959c98bff7e5a3f51d4308925cff6eba3b2af59dd21700f00d73a6088", + "extensions/code/core/src/lib.rs": "aad4a6f14f1d7898f46e67e29f72b0950de9dad222fa0d48cc606478981f4954", "extensions/code/core/src/proof.rs": "3c476265a52bdb88d55ca5cc2c693c070385a66cb0bd73a943035353a3346bdd", - "extensions/code/core/src/refs.rs": "fc2129b35e117906b79c18af1e19396fabe0cb1cf55281a3c64b8ebe660fc2f5", + "extensions/code/core/src/refs.rs": "ffb68f464a2a10c94469008c0206855c7808183dcfa3a71f2b0f7cd0d4019be1", + "extensions/code/core/src/reports.rs": "04bc911788f7efd4bf58d2d85fdce99954ba6d4887a9cae1ec5598a9bec68f4d", "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", - "extensions/code/facts/src/ids.rs": "e3f1f07f70da4786c0ca0b301594b1dc812c2a45808dbe1a5f4905805eccce97", - "extensions/code/facts/src/lib.rs": "5a9733980787f23265ab7f374840d6f61bf2ecbdad3471df86e68c0f2e699769", - "extensions/code/facts/src/mint.rs": "e71f130aaeaeeca2d4c5afa59a36c60fa5ac8bc26db2f4a8276c71024305925e", - "extensions/code/facts/src/paths.rs": "890973baefd07c33e93c6c12ae882083c2d969de91bb3c697bc271ec03474eae", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", - "extensions/code/junit/src/lib.rs": "dfeb44e386f4865b2c5570d389bfd6ff246ccf69122ee36ec7feb9db8a394f35", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20" } } diff --git a/extensions/code/core/wasm/specforge_ext_code_core.wasm b/extensions/code/core/wasm/specforge_ext_code_core.wasm index 6e157aea79..a80b49d1c0 100644 Binary files a/extensions/code/core/wasm/specforge_ext_code_core.wasm and b/extensions/code/core/wasm/specforge_ext_code_core.wasm differ diff --git a/extensions/code/cyclonedx/Cargo.lock b/extensions/code/cyclonedx/Cargo.lock new file mode 100644 index 0000000000..f810a947bb --- /dev/null +++ b/extensions/code/cyclonedx/Cargo.lock @@ -0,0 +1,646 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "windows-sys", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "insta" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67d3d2e287e4b86c10b3f3b641033d1f89b74bdb39d05f34952e2b9a6fe21cd" +dependencies = [ + "console", + "once_cell", + "serde", + "similar", + "tempfile", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-cyclonedx" +version = "1.0.0" +dependencies = [ + "insta", + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/code/cyclonedx/Cargo.toml b/extensions/code/cyclonedx/Cargo.toml new file mode 100644 index 0000000000..3535a7ca8e --- /dev/null +++ b/extensions/code/cyclonedx/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "specforge-code-cyclonedx" +version = "1.0.0" +edition = "2021" +description = "The CycloneDX JSON reader the SBOM packs link (ADR 0388); no guest" +publish = false + +# An extension library (ADR 0328 D3): an rlib a builtin links, never embedded. +[lib] +crate-type = ["rlib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-facts = { path = "../facts" } +serde_json = "1.0" + +[dev-dependencies] +insta = { version = "1.46.3", features = ["json"] } diff --git a/extensions/code/cyclonedx/fixtures/README.md b/extensions/code/cyclonedx/fixtures/README.md new file mode 100644 index 0000000000..ff95491953 --- /dev/null +++ b/extensions/code/cyclonedx/fixtures/README.md @@ -0,0 +1,13 @@ +# CycloneDX reader fixtures + +Neither cargo-cyclonedx nor cyclonedx-npm is installed where these were written, so each fixture is hand-written to +the CycloneDX 1.6 JSON reference and the tool shape named below. Which `specVersion` cargo-cyclonedx writes by default +is unverified: Phase 11's packs ask the tool for one the reader accepts (1.4, 1.5 or 1.6) and re-record these with the +real tools. + +| Fixture | Source | +|---------|--------| +| `cargo.cdx.json` | hand-written to the CycloneDX 1.6 JSON reference and the cargo-cyclonedx shape: specVersion `1.5`, root `pkg:cargo/demo@0.1.0?download_url=file://.` with a `bom-ref` and a nested target component (the root's own nesting is not read as components), the components `serde`, `serde_derive` and `itoa` with purls and registry bom-refs, and a `dependencies` graph where the root depends on `serde` only | +| `npm.cdx.json` | hand-written to the cyclonedx-npm shape: specVersion `1.6`, root `pkg:npm/%40demo/board@1.0.0` (group `@demo`), a scoped `@babel/runtime`, `fsevents` of scope `optional`, `loose-envify` and `js-tokens` nested inside `react`, and `js-tokens` listed a second time at the top with scope `optional`; the graph has the root depend on `@babel/runtime`, `fsevents` and `react` | +| `no-purl.cdx.json` | hand-written to CycloneDX 1.4, no dependency graph: root `pkg:cargo/demo@0.1.0`, `anyhow` with a purl, and `madler/zlib` 1.3.1 of scope `excluded` with a name, group and version but no purl | +| `packages.json` | hand-written served facts: the `package` facts an SBOM collector receives, `pkg:cargo/demo` at the project root and `pkg:npm/%40demo/board` at `web` | diff --git a/extensions/code/cyclonedx/fixtures/cargo.cdx.json b/extensions/code/cyclonedx/fixtures/cargo.cdx.json new file mode 100644 index 0000000000..e7d975662a --- /dev/null +++ b/extensions/code/cyclonedx/fixtures/cargo.cdx.json @@ -0,0 +1,79 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "serialNumber": "urn:uuid:5b1c3c1e-0f6a-4b8e-9d55-1f7e2a3c4d5e", + "metadata": { + "timestamp": "2026-11-22T12:00:00.000000000Z", + "tools": [{"vendor": "CycloneDX", "name": "cargo-cyclonedx", "version": "0.5.7"}], + "component": { + "type": "application", + "bom-ref": "path+file:///project#demo@0.1.0", + "name": "demo", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/demo@0.1.0?download_url=file://.", + "components": [ + { + "type": "library", + "bom-ref": "path+file:///project#demo@0.1.0 bin-target-0", + "name": "demo", + "version": "0.1.0", + "purl": "pkg:cargo/demo@0.1.0?download_url=file://.#src/lib.rs" + } + ] + } + }, + "components": [ + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.215", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde", + "version": "1.0.215", + "description": "A generic serialization/deserialization framework", + "scope": "required", + "licenses": [{"expression": "MIT OR Apache-2.0"}], + "purl": "pkg:cargo/serde@1.0.215" + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.215", + "name": "serde_derive", + "version": "1.0.215", + "scope": "required", + "licenses": [{"expression": "MIT OR Apache-2.0"}], + "purl": "pkg:cargo/serde_derive@1.0.215" + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.14", + "name": "itoa", + "version": "1.0.14", + "scope": "required", + "licenses": [{"expression": "MIT OR Apache-2.0"}], + "purl": "pkg:cargo/itoa@1.0.14" + } + ], + "dependencies": [ + { + "ref": "path+file:///project#demo@0.1.0", + "dependsOn": ["registry+https://github.com/rust-lang/crates.io-index#serde@1.0.215"] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.215", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.215", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.14" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.215", + "dependsOn": [] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.14", + "dependsOn": [] + } + ] +} diff --git a/extensions/code/cyclonedx/fixtures/no-purl.cdx.json b/extensions/code/cyclonedx/fixtures/no-purl.cdx.json new file mode 100644 index 0000000000..c1b74e8c36 --- /dev/null +++ b/extensions/code/cyclonedx/fixtures/no-purl.cdx.json @@ -0,0 +1,31 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.4", + "version": 1, + "metadata": { + "component": { + "type": "application", + "bom-ref": "demo", + "name": "demo", + "version": "0.1.0", + "purl": "pkg:cargo/demo@0.1.0" + } + }, + "components": [ + { + "type": "library", + "bom-ref": "anyhow", + "name": "anyhow", + "version": "1.0.93", + "purl": "pkg:cargo/anyhow@1.0.93" + }, + { + "type": "library", + "bom-ref": "vendored-zlib", + "name": "zlib", + "group": "madler", + "version": "1.3.1", + "scope": "excluded" + } + ] +} diff --git a/extensions/code/cyclonedx/fixtures/npm.cdx.json b/extensions/code/cyclonedx/fixtures/npm.cdx.json new file mode 100644 index 0000000000..2d2aa7d759 --- /dev/null +++ b/extensions/code/cyclonedx/fixtures/npm.cdx.json @@ -0,0 +1,86 @@ +{ + "$schema": "http://cyclonedx.org/schema/bom-1.6.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.6", + "version": 1, + "serialNumber": "urn:uuid:2f0f8e5a-6c3b-4f39-a1de-7c4b9e0d1a23", + "metadata": { + "timestamp": "2026-11-22T12:00:00.000Z", + "lifecycles": [{"phase": "build"}], + "tools": { + "components": [ + {"type": "application", "name": "cyclonedx-npm", "group": "@cyclonedx", "version": "1.19.3"} + ] + }, + "component": { + "type": "application", + "name": "board", + "group": "@demo", + "version": "1.0.0", + "bom-ref": "@demo/board@1.0.0", + "purl": "pkg:npm/%40demo/board@1.0.0" + } + }, + "components": [ + { + "type": "library", + "name": "runtime", + "group": "@babel", + "version": "7.26.0", + "bom-ref": "@babel/runtime@7.26.0", + "purl": "pkg:npm/%40babel/runtime@7.26.0", + "licenses": [{"license": {"id": "MIT"}}] + }, + { + "type": "library", + "name": "fsevents", + "version": "2.3.3", + "scope": "optional", + "bom-ref": "fsevents@2.3.3", + "purl": "pkg:npm/fsevents@2.3.3" + }, + { + "type": "library", + "name": "react", + "version": "18.3.1", + "bom-ref": "react@18.3.1", + "purl": "pkg:npm/react@18.3.1", + "components": [ + { + "type": "library", + "name": "loose-envify", + "version": "1.4.0", + "bom-ref": "react@18.3.1|loose-envify@1.4.0", + "purl": "pkg:npm/loose-envify@1.4.0" + }, + { + "type": "library", + "name": "js-tokens", + "version": "4.0.0", + "bom-ref": "react@18.3.1|js-tokens@4.0.0", + "purl": "pkg:npm/js-tokens@4.0.0" + } + ] + }, + { + "type": "library", + "name": "js-tokens", + "version": "4.0.0", + "scope": "optional", + "bom-ref": "js-tokens@4.0.0", + "purl": "pkg:npm/js-tokens@4.0.0" + } + ], + "dependencies": [ + { + "ref": "@demo/board@1.0.0", + "dependsOn": ["@babel/runtime@7.26.0", "fsevents@2.3.3", "react@18.3.1"] + }, + {"ref": "@babel/runtime@7.26.0"}, + {"ref": "fsevents@2.3.3"}, + {"ref": "react@18.3.1", "dependsOn": ["react@18.3.1|loose-envify@1.4.0"]}, + {"ref": "react@18.3.1|loose-envify@1.4.0", "dependsOn": ["react@18.3.1|js-tokens@4.0.0"]}, + {"ref": "react@18.3.1|js-tokens@4.0.0"}, + {"ref": "js-tokens@4.0.0"} + ] +} diff --git a/extensions/code/cyclonedx/fixtures/packages.json b/extensions/code/cyclonedx/fixtures/packages.json new file mode 100644 index 0000000000..49c0220116 --- /dev/null +++ b/extensions/code/cyclonedx/fixtures/packages.json @@ -0,0 +1,6 @@ +[ + {"kind": "package", "id": "pkg:cargo/demo", + "fields": {"name": "demo", "version": "0.1.0", "path": ""}}, + {"kind": "package", "id": "pkg:npm/%40demo/board", + "fields": {"name": "@demo/board", "version": "1.0.0", "path": "web"}} +] diff --git a/extensions/code/cyclonedx/src/lib.rs b/extensions/code/cyclonedx/src/lib.rs new file mode 100644 index 0000000000..e414d5f095 --- /dev/null +++ b/extensions/code/cyclonedx/src/lib.rs @@ -0,0 +1,130 @@ +//! `specforge-code-cyclonedx`: the CycloneDX JSON reader the SBOM packs link (ADR 0388). +//! +//! An extension library (ADR 0328 D3): an rlib a builtin links, never a component of its own. The wire has no +//! guest-to-guest call, so an SBOM pack reads its BOM here; `specforge-code-facts` mints the `dependency` facts from +//! what it reads ([`specforge_code_facts::dependency_facts`]). +//! +//! - [`read`] reads a CycloneDX 1.4, 1.5 or 1.6 JSON BOM into a [`Bom`]: its root, its components and the root's +//! direct dependencies when its dependency graph states them. + +#[cfg(test)] +mod tests; + +use serde_json::Value; +use specforge_code_facts::{shown_json, Component, Scope}; + +pub use specforge_code_facts::Bom; + +/// The `specVersion`s read: the CycloneDX versions whose JSON shape of components and dependencies this reader knows. +const SPEC_VERSIONS: [&str; 3] = ["1.4", "1.5", "1.6"]; + +/// The BOM in the CycloneDX JSON `text`. +/// +/// The root is `metadata.component`. The components are `components` and each component's nested `components`, +/// flattened depth first (nesting is no dependency tree). Per component: `bom-ref`, `purl`, `group`, `name`, `version`, +/// and `scope`, `required` when absent (the spec's default). `direct` is the `dependsOn` refs of the `dependencies` +/// entry whose `ref` is the root's `bom-ref`; `None` when the BOM has no `dependencies` array, no such entry, or a root +/// with no `bom-ref`: the BOM then states no graph for its root, and whether a component is direct is unknown. +/// +/// An error, naming the JSON path or the value, and nothing is read: text that is no JSON (nesting deeper than +/// serde_json's limit included), a `bomFormat` other than `"CycloneDX"`, a `specVersion` other than `"1.4"`, `"1.5"` +/// or `"1.6"`, no `metadata.component`, a `components` or `dependencies` that is no array, a component with no +/// `name`, and a scope other than CycloneDX's three. +pub fn read(text: &str) -> Result { + let bom: Value = serde_json::from_str(text).map_err(|e| format!("no JSON: {e}"))?; + match bom.get("bomFormat") { + Some(Value::String(format)) if format == "CycloneDX" => {} + Some(format) => { + return Err(format!( + "bomFormat: {} is not read, only \"CycloneDX\"", + shown_json(format) + )) + } + None => return Err("bomFormat: absent, only \"CycloneDX\" is read".to_string()), + } + let accepted = SPEC_VERSIONS.map(|v| format!("\"{v}\"")).join(", "); + match bom.get("specVersion") { + Some(Value::String(version)) if SPEC_VERSIONS.contains(&version.as_str()) => {} + Some(version) => { + return Err(format!( + "specVersion: {} is not read, only {accepted}", + shown_json(version) + )) + } + None => return Err(format!("specVersion: absent, only {accepted} are read")), + } + let root = bom + .pointer("/metadata/component") + .ok_or("metadata.component: absent, so the BOM describes no package")?; + let root = component(root, "metadata.component")?; + let mut components = Vec::new(); + if let Some(list) = bom.get("components") { + flatten(list, "components", &mut components)?; + } + let direct = match bom.get("dependencies") { + None => None, + Some(Value::Array(graph)) => root.bom_ref.as_deref().and_then(|root_ref| { + graph + .iter() + .find(|entry| entry.get("ref").and_then(Value::as_str) == Some(root_ref)) + .map(|entry| { + array(entry.get("dependsOn")) + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }) + }), + Some(_) => return Err("dependencies: no array".to_string()), + }; + Ok(Bom { + root, + components, + direct, + }) +} + +/// Appends each component of the `components` array `list` (at the JSON path `at`) to `out`, each followed by its own +/// nested `components`, depth first. +fn flatten(list: &Value, at: &str, out: &mut Vec) -> Result<(), String> { + let Value::Array(list) = list else { + return Err(format!("{at}: no array")); + }; + for (i, value) in list.iter().enumerate() { + let here = format!("{at}[{i}]"); + out.push(component(value, &here)?); + if let Some(nested) = value.get("components") { + flatten(nested, &format!("{here}.components"), out)?; + } + } + Ok(()) +} + +/// The component `value` at the JSON path `at`. +fn component(value: &Value, at: &str) -> Result { + let text = |key: &str| value.get(key).and_then(Value::as_str).map(str::to_string); + let name = text("name").ok_or_else(|| format!("{at}.name: absent"))?; + let scope = match value.get("scope") { + None => Scope::Required, + Some(scope) => scope.as_str().and_then(Scope::parse).ok_or_else(|| { + format!( + "{at}.scope: {} is not one of {}", + shown_json(scope), + Scope::NAMES.join(", ") + ) + })?, + }; + Ok(Component { + bom_ref: text("bom-ref"), + purl: text("purl"), + group: text("group"), + name, + version: text("version"), + scope, + }) +} + +/// The elements of `value` when it is an array, else none. +fn array(value: Option<&Value>) -> &[Value] { + value.and_then(Value::as_array).map_or(&[], Vec::as_slice) +} diff --git a/extensions/code/cyclonedx/src/snapshots/specforge_code_cyclonedx__tests__cargo.snap b/extensions/code/cyclonedx/src/snapshots/specforge_code_cyclonedx__tests__cargo.snap new file mode 100644 index 0000000000..4660cde9e7 --- /dev/null +++ b/extensions/code/cyclonedx/src/snapshots/specforge_code_cyclonedx__tests__cargo.snap @@ -0,0 +1,42 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "dependency", + "id": "dep:pkg:cargo/demo/pkg%3Acargo%2Fitoa%401.0.14", + "fields": { + "direct": false, + "name": "itoa", + "package": "pkg:cargo/demo", + "purl": "pkg:cargo/itoa@1.0.14", + "scope": "required", + "version": "1.0.14" + } + }, + { + "kind": "dependency", + "id": "dep:pkg:cargo/demo/pkg%3Acargo%2Fserde%401.0.215", + "fields": { + "direct": true, + "name": "serde", + "package": "pkg:cargo/demo", + "purl": "pkg:cargo/serde@1.0.215", + "scope": "required", + "version": "1.0.215" + } + }, + { + "kind": "dependency", + "id": "dep:pkg:cargo/demo/pkg%3Acargo%2Fserde_derive%401.0.215", + "fields": { + "direct": false, + "name": "serde_derive", + "package": "pkg:cargo/demo", + "purl": "pkg:cargo/serde_derive@1.0.215", + "scope": "required", + "version": "1.0.215" + } + } +] diff --git a/extensions/code/cyclonedx/src/snapshots/specforge_code_cyclonedx__tests__no_purl.snap b/extensions/code/cyclonedx/src/snapshots/specforge_code_cyclonedx__tests__no_purl.snap new file mode 100644 index 0000000000..1d0059ab0b --- /dev/null +++ b/extensions/code/cyclonedx/src/snapshots/specforge_code_cyclonedx__tests__no_purl.snap @@ -0,0 +1,27 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "dependency", + "id": "dep:pkg:cargo/demo/@madler%2Fzlib%401.3.1", + "fields": { + "name": "madler/zlib", + "package": "pkg:cargo/demo", + "scope": "excluded", + "version": "1.3.1" + } + }, + { + "kind": "dependency", + "id": "dep:pkg:cargo/demo/pkg%3Acargo%2Fanyhow%401.0.93", + "fields": { + "name": "anyhow", + "package": "pkg:cargo/demo", + "purl": "pkg:cargo/anyhow@1.0.93", + "scope": "required", + "version": "1.0.93" + } + } +] diff --git a/extensions/code/cyclonedx/src/snapshots/specforge_code_cyclonedx__tests__npm.snap b/extensions/code/cyclonedx/src/snapshots/specforge_code_cyclonedx__tests__npm.snap new file mode 100644 index 0000000000..9fa6815d5e --- /dev/null +++ b/extensions/code/cyclonedx/src/snapshots/specforge_code_cyclonedx__tests__npm.snap @@ -0,0 +1,66 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "dependency", + "id": "dep:pkg:npm/%40demo/board/pkg%3Anpm%2F%2540babel%2Fruntime%407.26.0", + "fields": { + "direct": true, + "name": "@babel/runtime", + "package": "pkg:npm/%40demo/board", + "purl": "pkg:npm/%40babel/runtime@7.26.0", + "scope": "required", + "version": "7.26.0" + } + }, + { + "kind": "dependency", + "id": "dep:pkg:npm/%40demo/board/pkg%3Anpm%2Ffsevents%402.3.3", + "fields": { + "direct": true, + "name": "fsevents", + "package": "pkg:npm/%40demo/board", + "purl": "pkg:npm/fsevents@2.3.3", + "scope": "optional", + "version": "2.3.3" + } + }, + { + "kind": "dependency", + "id": "dep:pkg:npm/%40demo/board/pkg%3Anpm%2Fjs-tokens%404.0.0", + "fields": { + "direct": false, + "name": "js-tokens", + "package": "pkg:npm/%40demo/board", + "purl": "pkg:npm/js-tokens@4.0.0", + "scope": "required", + "version": "4.0.0" + } + }, + { + "kind": "dependency", + "id": "dep:pkg:npm/%40demo/board/pkg%3Anpm%2Floose-envify%401.4.0", + "fields": { + "direct": false, + "name": "loose-envify", + "package": "pkg:npm/%40demo/board", + "purl": "pkg:npm/loose-envify@1.4.0", + "scope": "required", + "version": "1.4.0" + } + }, + { + "kind": "dependency", + "id": "dep:pkg:npm/%40demo/board/pkg%3Anpm%2Freact%4018.3.1", + "fields": { + "direct": true, + "name": "react", + "package": "pkg:npm/%40demo/board", + "purl": "pkg:npm/react@18.3.1", + "scope": "required", + "version": "18.3.1" + } + } +] diff --git a/extensions/code/cyclonedx/src/tests.rs b/extensions/code/cyclonedx/src/tests.rs new file mode 100644 index 0000000000..1c57be52fb --- /dev/null +++ b/extensions/code/cyclonedx/src/tests.rs @@ -0,0 +1,260 @@ +use specforge_code_facts::dependency_facts; +use specforge_extension_sdk::prelude::Fact; + +use super::*; + +/// A cargo-cyclonedx BOM, hand-written to CycloneDX 1.6 and the tool's shape: crate `demo` at the project root. +const CARGO: &str = include_str!("../fixtures/cargo.cdx.json"); +/// A cyclonedx-npm BOM, hand-written to CycloneDX 1.6 and the tool's shape: package `@demo/board` at `web`. +const NPM: &str = include_str!("../fixtures/npm.cdx.json"); +/// A CycloneDX 1.4 BOM with no dependency graph and a component with no purl, hand-written. +const NO_PURL: &str = include_str!("../fixtures/no-purl.cdx.json"); +/// The served `package` facts an SBOM collector receives, as JSON. +const PACKAGES: &str = include_str!("../fixtures/packages.json"); + +fn served() -> Vec { + serde_json::from_str(PACKAGES).expect("the served facts parse") +} + +fn field<'f>(fact: &'f Fact, name: &str) -> Option<&'f Value> { + fact.fields.get(name) +} + +#[test] +fn a_cargo_bom_mints_dependencies_citing_the_project_package() { + let bom = read(CARGO).expect("the BOM reads"); + let facts = dependency_facts(&[bom], &served()).expect("the root is a served package"); + let named: Vec<(&str, Option)> = facts + .iter() + .map(|f| { + assert_eq!( + field(f, "package").and_then(Value::as_str), + Some("pkg:cargo/demo") + ); + assert!( + f.id.starts_with("dep:pkg:cargo/demo/pkg%3Acargo%2F"), + "{}", + f.id + ); + ( + field(f, "name").and_then(Value::as_str).unwrap_or_default(), + field(f, "direct").and_then(Value::as_bool), + ) + }) + .collect(); + assert_eq!( + named, + [ + ("itoa", Some(false)), + ("serde", Some(true)), + ("serde_derive", Some(false)), + ] + ); + insta::assert_json_snapshot!("cargo", facts); +} + +#[test] +fn a_cargo_bom_reads_its_root_and_components_and_the_roots_direct_refs() { + let bom = read(CARGO).expect("the BOM reads"); + assert_eq!( + bom.root.purl.as_deref(), + Some("pkg:cargo/demo@0.1.0?download_url=file://.") + ); + let names: Vec<&str> = bom.components.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["serde", "serde_derive", "itoa"]); + assert_eq!( + bom.direct, + Some(vec![ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.215".to_string() + ]) + ); +} + +/// Each fact's name, scope and directness. +fn read_out(facts: &[Fact]) -> Vec<(&str, &str, Option)> { + facts + .iter() + .map(|f| { + let text = |name: &str| field(f, name).and_then(Value::as_str).unwrap_or_default(); + ( + text("name"), + text("scope"), + field(f, "direct").and_then(Value::as_bool), + ) + }) + .collect() +} + +#[test] +fn an_npm_bom_flattens_nesting_and_merges_a_repeated_purl() { + let bom = read(NPM).expect("the BOM reads"); + let names: Vec<&str> = bom.components.iter().map(|c| c.name.as_str()).collect(); + assert_eq!( + names, + [ + "runtime", + "fsevents", + "react", + "loose-envify", + "js-tokens", + "js-tokens" + ] + ); + let facts = dependency_facts(&[bom], &served()).expect("the root is a served package"); + assert!(facts.iter().all(|f| { + f.id.starts_with("dep:pkg:npm/%40demo/board/") + && field(f, "package").and_then(Value::as_str) == Some("pkg:npm/%40demo/board") + })); + assert_eq!( + read_out(&facts), + [ + ("@babel/runtime", "required", Some(true)), + ("fsevents", "optional", Some(true)), + ("js-tokens", "required", Some(false)), + ("loose-envify", "required", Some(false)), + ("react", "required", Some(true)), + ] + ); + insta::assert_json_snapshot!("npm", facts); +} + +#[test] +fn a_no_purl_bom_states_no_directness_and_names_a_purl_less_component() { + let bom = read(NO_PURL).expect("the BOM reads"); + assert_eq!(bom.direct, None); + let facts = dependency_facts(&[bom], &served()).expect("the root is a served package"); + assert!(facts.iter().all(|f| !f.fields.contains_key("direct"))); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + [ + "dep:pkg:cargo/demo/@madler%2Fzlib%401.3.1", + "dep:pkg:cargo/demo/pkg%3Acargo%2Fanyhow%401.0.93", + ] + ); + assert_eq!( + read_out(&facts), + [ + ("madler/zlib", "excluded", None), + ("anyhow", "required", None) + ] + ); + insta::assert_json_snapshot!("no_purl", facts); +} + +/// A minimal BOM of `spec_version` and `format` describing `root_purl`, with one component of `scope`. +fn bom_text(spec_version: &str, format: &str, root_purl: &str, scope: &str) -> String { + serde_json::json!({ + "bomFormat": format, + "specVersion": spec_version, + "metadata": {"component": {"type": "application", "name": "demo", "purl": root_purl}}, + "components": [{"type": "library", "name": "serde", "purl": "pkg:cargo/serde@1.0.0", "scope": scope}] + }) + .to_string() +} + +#[test] +fn an_error_shows_the_boms_values_bounded_and_escaped() { + let hostile = format!("\u{1b}]0;{}", "a".repeat(5_000)); + let root = "pkg:cargo/demo@0.1.0"; + for text in [ + bom_text("1.5", &hostile, root, "required"), + bom_text(&hostile, "CycloneDX", root, "required"), + bom_text("1.5", "CycloneDX", root, &hostile), + ] { + let error = read(&text).expect_err("refused"); + assert!( + !error.contains('\u{1b}') && error.contains("\\u{1b}"), + "{error}" + ); + assert!(error.len() < 400, "{} bytes", error.len()); + } +} + +#[test] +fn a_bad_bom_is_an_error_naming_its_value_or_key_and_mints_nothing() { + let root = "pkg:cargo/demo@0.1.0"; + let ok = |version: &str| bom_text(version, "CycloneDX", root, "required"); + let mut no_root: Value = serde_json::from_str(&ok("1.5")).unwrap(); + no_root["metadata"] = serde_json::json!({}); + let mut no_name: Value = serde_json::from_str(&ok("1.5")).unwrap(); + no_name["components"][0] + .as_object_mut() + .unwrap() + .remove("name"); + let mut not_listed: Value = serde_json::from_str(&ok("1.5")).unwrap(); + not_listed["components"] = serde_json::json!({"name": "serde"}); + let twins = vec![ + Fact::new("package", "pkg:cargo/demo#crates/demo").field("path", "crates/demo"), + Fact::new("package", "pkg:cargo/demo#tools/demo").field("path", "tools/demo"), + ]; + let rows: [(&str, String, Vec, &[&str]); 10] = [ + ( + "specVersion 1.3", + ok("1.3"), + served(), + &["specVersion", "\"1.3\""], + ), + ( + "specVersion 2.0", + ok("2.0"), + served(), + &["specVersion", "\"2.0\""], + ), + ( + "bomFormat SPDX", + bom_text("1.5", "SPDX", root, "required"), + served(), + &["bomFormat", "\"SPDX\""], + ), + ( + "no metadata.component", + no_root.to_string(), + served(), + &["metadata.component"], + ), + ( + "a root no package names", + bom_text("1.5", "CycloneDX", "pkg:cargo/elsewhere@1.0.0", "required"), + served(), + &["pkg:cargo/elsewhere@1.0.0"], + ), + ( + "a root two packages name", + ok("1.5"), + twins, + &[root, "pkg:cargo/demo#crates/demo"], + ), + ( + "scope mandatory", + bom_text("1.5", "CycloneDX", root, "mandatory"), + served(), + &["components[0].scope", "\"mandatory\""], + ), + ( + "no JSON", + "{\"bomFormat\":".to_string(), + served(), + &["no JSON"], + ), + ( + "a component with no name", + no_name.to_string(), + served(), + &["components[0].name"], + ), + ( + "components no array", + not_listed.to_string(), + served(), + &["components: no array"], + ), + ]; + for (case, text, served, named) in rows { + let minted = read(&text).and_then(|bom| dependency_facts(&[bom], &served)); + let error = minted.expect_err(case); + for name in named { + assert!(error.contains(name), "{case}: {error}"); + } + } +} diff --git a/extensions/code/facts/src/accepted.rs b/extensions/code/facts/src/accepted.rs new file mode 100644 index 0000000000..ecd0a3158f --- /dev/null +++ b/extensions/code/facts/src/accepted.rs @@ -0,0 +1,277 @@ +//! The accepted side of an API snapshot (ADR 0390 D3): each public entry of a run judged against the committed +//! accepted report of its crate or package, and the `change` its `api_item` fact carries. + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; + +use specforge_extension_sdk::prelude::Fact; + +use crate::api::{api_facts, fact, insert, ApiEntry, Served}; +use crate::ids::Scheme; +use crate::report::Repeats; + +/// What an entry is against the accepted report: `@code/core`'s vocabulary of `api_item.change`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ApiChange { + /// In the run, not in the accepted report. + Added, + /// The same comparable signature, as wide as accepted. + Unchanged, + /// Another signature. + Changed, + /// The same comparable signature with a lower release tag or a narrower visibility. + Narrowed, + /// In the accepted report, not in the run. + Removed, +} + +/// Every change, in vocabulary order. +const CHANGES: [ApiChange; 5] = [ + ApiChange::Added, + ApiChange::Unchanged, + ApiChange::Changed, + ApiChange::Narrowed, + ApiChange::Removed, +]; + +impl ApiChange { + /// Every change's name: `added`, `unchanged`, `changed`, `narrowed`, `removed`. + pub const NAMES: [&'static str; 5] = { + let mut names = [""; 5]; + let mut at = 0; + while at < names.len() { + names[at] = CHANGES[at].as_str(); + at += 1; + } + names + }; + + /// Its name: an exhaustive match, so a new change names itself or fails to compile. + pub const fn as_str(self) -> &'static str { + match self { + ApiChange::Added => "added", + ApiChange::Unchanged => "unchanged", + ApiChange::Changed => "changed", + ApiChange::Narrowed => "narrowed", + ApiChange::Removed => "removed", + } + } +} + +/// The api-extractor release tags, lowest first. +const TAGS: [&str; 4] = ["Internal", "Alpha", "Beta", "Public"]; + +/// The tag the accepted side skips: the doc model never lists an `@internal` entry, so its absence is no break. +const INTERNAL: &str = "Internal"; + +/// The leading words [`comparable`] drops, at most one of each row, in row order. +const PREFIXES: [&[&str]; 3] = [&["export "], &["declare "], &["const ", "let ", "var "]]; + +/// A signature of the `scheme` as both spellings of one declaration compare: whitespace collapsed to one space, a +/// leading `export `, then `declare `, then `const `, `let ` or `var ` dropped, and trailing `;`, `,` and `{` dropped. +/// api-extractor's doc model writes `export declare function f(): void;` and `LIMIT = 3` where its report writes +/// `export function f(): void;` and `const LIMIT = 3;`. For [`Scheme::Rust`] only, the first visibility word (`pub`, +/// `pub(crate)`, …) is dropped too: cargo public-api writes it in the line, and the entry's `visibility` judges it. A +/// JavaScript `function pub(a: string)` keeps its parameters. +pub fn comparable(scheme: Scheme, signature: &str) -> String { + let collapsed = signature.split_whitespace().collect::>().join(" "); + let mut rest = collapsed.as_str(); + for words in PREFIXES { + if let Some(word) = words.iter().find(|word| rest.starts_with(**word)) { + rest = &rest[word.len()..]; + } + } + let rest = match scheme { + Scheme::Rust => without_visibility(rest), + Scheme::Js => rest.to_string(), + }; + rest.trim_end_matches([';', ',', '{', ' ']).to_string() +} + +/// `text` without its first word `pub` or `pub(…)`, the space after it included. +fn without_visibility(text: &str) -> String { + let word = text.match_indices("pub").map(|(at, _)| at).find(|&at| { + (at == 0 || text[..at].ends_with(' ')) + && matches!(text[at + 3..].chars().next(), Some(' ' | '(')) + }); + let Some(at) = word else { + return text.to_string(); + }; + let mut end = at + 3; + if text[end..].starts_with('(') { + end = text[end..] + .find(')') + .map_or(text.len(), |close| end + close + 1); + } + format!("{}{}", &text[..at], text[end..].trim_start()) +} + +/// The `api_item` facts of `entries` judged against `accepted`, the entries the committed accepted report holds, each +/// citing the one `served` item its path names, sorted by id (ADR 0390 D3): +/// +/// - Only a crate or package on both sides is judged; the facts of any other are [`api_facts`]'s, with no `change`, +/// and an accepted one the run did not cover mints nothing. +/// - An accepted entry tagged `Internal` is skipped. +/// - Both sides are grouped by base id. Inside a group, entries of equal [`comparable`] signature pair first, then the +/// leftovers in document order, never by their `~N`. +/// - A pair of equal comparable signatures is `narrowed` when the run's tag is lower (Public, Beta, Alpha, Internal) +/// or its visibility narrower, else `unchanged`; a pair of different ones is `changed`. A run's entry left alone is +/// `added`; an accepted one is `removed`, minted from the accepted entry with no item and the next repeat suffix +/// after the run's. +/// - `changed`, `narrowed` and `removed` carry `accepted_signature`, `accepted_tag` when the accepted entry has a tag, +/// and `accepted_visibility` when its visibility differs. +/// +/// A member with no tag of its own has its container's: the report reader resolves it, the doc model states it. +pub fn api_facts_against( + entries: &[ApiEntry], + accepted: &[ApiEntry], + served: &[Fact], +) -> Vec { + let side = |entries: &[ApiEntry]| -> BTreeSet<_> { + entries + .iter() + .map(|e| (e.scheme, e.container.clone())) + .collect() + }; + let (fresh_side, accepted_side) = (side(entries), side(accepted)); + let on_both_sides = |e: &ApiEntry| { + let container = (e.scheme, e.container.clone()); + fresh_side.contains(&container) && accepted_side.contains(&container) + }; + let alone: Vec = entries + .iter() + .filter(|e| !on_both_sides(e)) + .cloned() + .collect(); + let mut facts: BTreeMap = api_facts(&alone, served) + .into_iter() + .map(|fact| (fact.id.clone(), fact)) + .collect(); + + let served = Served::new(served); + let mut repeats = Repeats::default(); + let mut groups: BTreeMap = BTreeMap::new(); + let mut seen = BTreeSet::new(); + for entry in entries.iter().filter(|e| on_both_sides(e)) { + let (base, item, written) = served.minted(entry); + if seen.insert((base.clone(), entry.signature.as_str())) { + let id = repeats.id(base.clone()); + let group = groups.entry(base).or_default(); + group.fresh.push(Minted { + entry, + id, + item, + written, + }); + } + } + let mut seen = BTreeSet::new(); + for entry in accepted + .iter() + .filter(|e| on_both_sides(e) && e.tag.as_deref() != Some(INTERNAL)) + { + let (base, _, written) = served.minted(entry); + if seen.insert((base.clone(), entry.signature.as_str())) { + let group = groups.entry(base).or_default(); + group.accepted.push((entry, written)); + } + } + + for (base, group) in groups { + let (pairs, removed) = pair(&group); + for (minted, paired) in group.fresh.into_iter().zip(pairs) { + let fresh = minted.entry; + let minted_fact = fact(minted.id, fresh, minted.item, minted.written); + let scored = match paired.map(|at| group.accepted[at].0) { + None => minted_fact.field("change", ApiChange::Added.as_str()), + Some(old) if key(old) != key(fresh) => { + against(minted_fact, ApiChange::Changed, old, Some(fresh)) + } + Some(old) if narrower(fresh, old) => { + against(minted_fact, ApiChange::Narrowed, old, Some(fresh)) + } + Some(_) => minted_fact.field("change", ApiChange::Unchanged.as_str()), + }; + insert(&mut facts, scored); + } + for at in removed { + let (old, written) = &group.accepted[at]; + let id = repeats.id(base.clone()); + let gone = fact(id, old, None, written.clone()); + insert(&mut facts, against(gone, ApiChange::Removed, old, None)); + } + } + facts.into_values().collect() +} + +/// One base id's entries: the run's, minted, and the accepted ones with their paths as written, in document order. +#[derive(Default)] +struct Group<'e> { + fresh: Vec>, + accepted: Vec<(&'e ApiEntry, String)>, +} + +/// A run's entry, its id taken, the item it cites and its path as written. +struct Minted<'e> { + entry: &'e ApiEntry, + id: String, + item: Option, + written: String, +} + +/// For each of `group`'s run entries, the accepted entry it pairs with, and the accepted entries left alone: equal +/// comparable signatures first, then the leftovers of both sides in document order. +fn pair(group: &Group) -> (Vec>, Vec) { + // Each comparable signature's accepted entries, in document order: a keyed lookup, so pairing is not quadratic. + let mut by_key: BTreeMap> = BTreeMap::new(); + for (at, (e, _)) in group.accepted.iter().enumerate() { + by_key.entry(key(e)).or_default().push_back(at); + } + let mut taken = vec![false; group.accepted.len()]; + let mut pairs: Vec> = group + .fresh + .iter() + .map(|minted| { + let at = by_key.get_mut(&key(minted.entry))?.pop_front()?; + taken[at] = true; + Some(at) + }) + .collect(); + let mut left = (0..taken.len()).filter(|&at| !taken[at]); + for slot in pairs.iter_mut().filter(|slot| slot.is_none()) { + *slot = left.next(); + } + (pairs, left.collect()) +} + +/// The [`comparable`] signature of `entry`, in its own scheme. +fn key(entry: &ApiEntry) -> String { + comparable(entry.scheme, &entry.signature) +} + +/// Whether `fresh` is narrower than `accepted`: a lower release tag, or a visibility later in `Visibility::NAMES`. +fn narrower(fresh: &ApiEntry, accepted: &ApiEntry) -> bool { + let rank = |tag: &Option| TAGS.iter().position(|t| tag.as_deref() == Some(*t)); + let lower = + matches!((rank(&fresh.tag), rank(&accepted.tag)), (Some(new), Some(old)) if new < old); + lower || fresh.visibility < accepted.visibility +} + +/// `fact` marked `change` with what `accepted` said: its signature, its tag when it has one, its visibility when it +/// differs from `fresh`'s. +fn against( + mut fact: Fact, + change: ApiChange, + accepted: &ApiEntry, + fresh: Option<&ApiEntry>, +) -> Fact { + fact = fact + .field("change", change.as_str()) + .field("accepted_signature", accepted.signature.clone()); + if let Some(tag) = &accepted.tag { + fact = fact.field("accepted_tag", tag.clone()); + } + if fresh.is_some_and(|fresh| fresh.visibility != accepted.visibility) { + fact = fact.field("accepted_visibility", accepted.visibility.as_str()); + } + fact +} diff --git a/extensions/code/facts/src/api.rs b/extensions/code/facts/src/api.rs new file mode 100644 index 0000000000..6f343a83a1 --- /dev/null +++ b/extensions/code/facts/src/api.rs @@ -0,0 +1,265 @@ +//! The `api_item` facts of an API snapshot (ADR 0388): what a reader (`specforge-code-api`) read for each public +//! entry, and the facts minted from it, each citing the one served `item` its path names. + +use std::collections::{BTreeMap, BTreeSet}; +use std::str::FromStr; + +use specforge_extension_sdk::prelude::Fact; + +use crate::ids::{ItemId, Owner, Scheme}; +use crate::mint::{ItemKind, Visibility}; +use crate::report::{id_part, rust_id_part, Repeats, API_ITEM}; + +/// What a public entry is: an item's kind, or one no `item` fact can have. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ApiKind { + Item(ItemKind), + /// An enum variant (Rust) or enum member (JavaScript). + Variant, + /// A `pub use`. + Reexport, + /// A `pub extern crate`. + ExternCrate, + /// An entry of a shape the reader knows, with a keyword it does not. + Other, +} + +/// The kinds beyond [`ItemKind`]'s, in vocabulary order. +const NON_ITEM_KINDS: [ApiKind; 4] = [ + ApiKind::Variant, + ApiKind::Reexport, + ApiKind::ExternCrate, + ApiKind::Other, +]; + +impl ApiKind { + /// Every kind's name: [`ItemKind::NAMES`], then `variant`, `reexport`, `extern_crate`, `other`. `@code/core`'s + /// vocabulary of `api_item.kind`. + pub const NAMES: [&'static str; 20] = { + let mut names = [""; 20]; + let mut at = 0; + while at < ItemKind::NAMES.len() { + names[at] = ItemKind::NAMES[at]; + at += 1; + } + let mut more = 0; + while more < NON_ITEM_KINDS.len() { + names[at + more] = NON_ITEM_KINDS[more].as_str(); + more += 1; + } + names + }; + + /// Its name: an exhaustive match, so a new kind names itself or fails to compile. + pub const fn as_str(self) -> &'static str { + match self { + ApiKind::Item(kind) => kind.as_str(), + ApiKind::Variant => "variant", + ApiKind::Reexport => "reexport", + ApiKind::ExternCrate => "extern_crate", + ApiKind::Other => "other", + } + } + + /// Whether an `item` fact can have this kind, so an entry of it should cite one. + pub fn is_item(self) -> bool { + matches!(self, ApiKind::Item(_)) + } +} + +/// One public entry of an API snapshot, as its reader read it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ApiEntry { + pub scheme: Scheme, + /// The crate as the snapshot writes it (`example_api`), or the npm package (`@demo/widget`). + pub container: String, + /// Rust: the qualified path, the crate first (`[example_api, Struct, fmt]`); JavaScript: the member names below + /// the entry point (`[Widget, render]`). Each segment as written. + pub path: Vec, + /// The type a Rust member is defined on: its `impl`'s, or its parent type's. + pub owner: Option, + pub kind: ApiKind, + pub visibility: Visibility, + /// The entry exactly as the snapshot wrote it: the whole line (Rust), the excerpt's text (JavaScript). + pub signature: String, + /// The api-extractor release tag (`Public`, `Beta`, …). + pub tag: Option, +} + +/// The `api_item` facts of `entries`, each citing the one `served` `item` its path names, sorted by id: +/// +/// - Rust: `api:rust:::::…::`, a member `…::::m` or `…::::m` as +/// [`ItemId::rust`] writes it, the crate root `api:rust:`, each part through [`id_part`] (a segment keeping a +/// plain space, as an owner's type has one). Its item is the served id of a library crate whose name, `-` read as +/// `_`, is the snapshot's crate, built from the parts as written: exactly one held, else none. +/// - JavaScript: `api:js:::[.…]`, no source file, each part through [`id_part`] and a name's +/// own `.` written `%2E`. Its item is the one served `js` item of the package with that name path; none or several +/// cite nothing. +/// +/// Encoded parts hold no `~`, so no entry can forge another's repeat suffix. +/// +/// Only an entry whose kind an item can have cites one. Entries of one id with one signature merge; another +/// signature takes the next [`Repeats`] suffix, in document order (`~2`). Fields: `path` (as written), `kind`, +/// `visibility`, `signature`, `item` when cited, `tag` when stated. +pub fn api_facts(entries: &[ApiEntry], served: &[Fact]) -> Vec { + let served = Served::new(served); + let mut repeats = Repeats::default(); + let mut seen = BTreeSet::new(); + let mut facts = BTreeMap::new(); + for entry in entries { + let (base, item, written) = served.minted(entry); + if !seen.insert((base.clone(), entry.signature.as_str())) { + continue; + } + let id = repeats.id(base); + insert(&mut facts, fact(id, entry, item, written)); + } + facts.into_values().collect() +} + +/// The served `item` facts an entry's path is looked up among. +pub(crate) struct Served<'s> { + held: BTreeSet<&'s str>, + parsed: Vec, +} + +impl<'s> Served<'s> { + pub(crate) fn new(served: &'s [Fact]) -> Self { + let held: BTreeSet<&str> = served + .iter() + .filter(|fact| fact.kind == "item") + .map(|fact| fact.id.as_str()) + .collect(); + let parsed = held + .iter() + .filter_map(|id| ItemId::from_str(id).ok()) + .collect(); + Served { held, parsed } + } + + /// `entry`'s base id (no repeat suffix), the served item its path names and its path as written. + pub(crate) fn minted(&self, entry: &ApiEntry) -> (String, Option, String) { + match entry.scheme { + Scheme::Rust => rust(entry, &self.parsed, &self.held), + Scheme::Js => js(entry, &self.parsed), + } + } +} + +/// The `api_item` fact `id` of `entry`: its path as `written`, kind, visibility, signature, `item` when its kind can +/// have one, `tag` when stated. +pub(crate) fn fact(id: String, entry: &ApiEntry, item: Option, written: String) -> Fact { + let mut fact = Fact::new(API_ITEM.kind, id) + .field("path", written) + .field("kind", entry.kind.as_str()) + .field("visibility", entry.visibility.as_str()) + .field("signature", entry.signature.clone()); + if let Some(item) = item.filter(|_| entry.kind.is_item()) { + fact = fact.field("item", item); + } + if let Some(tag) = &entry.tag { + fact = fact.field("tag", tag.clone()); + } + fact +} + +/// `fact` into `facts` by its id. +pub(crate) fn insert(facts: &mut BTreeMap, fact: Fact) { + let replaced = facts.insert(fact.id.clone(), fact); + // A base never holds `~` (each part is encoded), so a repeat suffix is never met twice. + debug_assert!( + replaced.is_none(), + "an api_item id minted twice: {replaced:?}" + ); +} + +/// A Rust entry's id, its item and its path as written. +fn rust( + entry: &ApiEntry, + parsed: &[ItemId], + held: &BTreeSet<&str>, +) -> (String, Option, String) { + let written = entry.path.join("::"); + let names = entry.path.get(1..).unwrap_or_default(); + let Some((name, parents)) = names.split_last() else { + // The crate root, which no item is. + return ( + format!("{}:rust:{}", API_ITEM.scheme, id_part(&entry.container)), + None, + written, + ); + }; + let skip = usize::from(entry.owner.is_some()).min(parents.len()); + let module: Vec = parents[..parents.len() - skip] + .iter() + .map(|s| bare(s)) + .collect(); + let name = bare(name); + let owner = entry.owner.as_ref(); + // The id is the item id's shape, each part encoded; the item is looked up by the parts as written. + let path = ItemId::rust(&entry.container, &module, owner, &name); + let base = std::iter::once(id_part(&entry.container)) + .chain(path.segments().iter().map(|s| rust_id_part(s))) + .collect::>() + .join("::"); + let base = format!("{}:rust:{base}", API_ITEM.scheme); + let krate = entry.container.replace('-', "_"); + let libs: BTreeSet<&str> = parsed + .iter() + .filter(|id| id.scheme() == Scheme::Rust) + .map(ItemId::container_text) + .filter(|container| !container.contains('/') && container.replace('-', "_") == krate) + .collect(); + let found: Vec = libs + .into_iter() + .map(|lib| ItemId::rust(lib, &module, owner, &name).to_string()) + .filter(|candidate| held.contains(candidate.as_str())) + .collect(); + (base, single(found), written) +} + +/// A JavaScript entry's id, its item and its path as written. +fn js(entry: &ApiEntry, parsed: &[ItemId]) -> (String, Option, String) { + // `.` joins the names, so a name holding one (a quoted member `"a.b"`) has it encoded. + let names: Vec = entry + .path + .iter() + .map(|name| id_part(name).replace('.', "%2E")) + .collect(); + let base = format!( + "{}:js:{}::{}", + API_ITEM.scheme, + id_part(&entry.container), + names.join(".") + ); + let prefix = format!("{}/", entry.container); + let found: Vec = parsed + .iter() + .filter(|id| { + id.scheme() == Scheme::Js + && id.container_text().starts_with(&prefix) + && id.segments() == entry.path.as_slice() + }) + .map(ItemId::to_string) + .collect(); + (base, single(found), entry.path.join(".")) +} + +/// The one candidate, or none when there are none or several. +fn single(mut found: Vec) -> Option { + found.dedup(); + match found.len() { + 1 => found.pop(), + _ => None, + } +} + +/// A path segment without its generic arguments: `Gen` is `Gen`. +fn bare(segment: &str) -> String { + segment + .split('<') + .next() + .unwrap_or(segment) + .trim() + .to_string() +} diff --git a/extensions/code/facts/src/coverage.rs b/extensions/code/facts/src/coverage.rs new file mode 100644 index 0000000000..a7cfac660a --- /dev/null +++ b/extensions/code/facts/src/coverage.rs @@ -0,0 +1,160 @@ +//! The `coverage` facts of a coverage report (ADR 0388): what a reader (`specforge-code-lcov`) read for each file, and +//! the per-item counts minted from it, each citing the innermost served `item` that holds the report's lines. + +use std::collections::BTreeMap; + +use specforge_extension_sdk::prelude::Fact; + +use crate::places::Places; +use crate::report::{id_part, COVERAGE}; + +/// What a coverage report says of one file. An empty vector means the report gave no record of that family for it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CoverageFile { + /// The file, project-relative, with `/` separators. + pub file: String, + pub functions: Vec, + /// Each line's `(1-based line, hits)`. + pub lines: Vec<(usize, u64)>, + pub branches: Vec, +} + +/// A function of a coverage report: where it starts, its name as the report wrote it, and how often it ran. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Function { + /// Its 1-based start line; 0 when the report gave none. + pub line: usize, + pub name: String, + pub hits: u64, +} + +/// A branch of a coverage report: its line, block and branch as written, and how often it was taken (`None`: its +/// condition was never evaluated, LCOV's `-`). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Branch { + pub line: usize, + pub block: String, + pub branch: String, + pub taken: Option, +} + +/// One file's records, its sections merged: a line's hits add up, a function by `(line, name)` and a branch by +/// `(line, block, branch)`, a branch untaken (`None`) only when every record of it was. +#[derive(Default)] +struct Merged<'f> { + lines: BTreeMap, + functions: BTreeMap<(usize, &'f str), u64>, + branches: BTreeMap<(usize, &'f str, &'f str), Option>, +} + +/// The `(found, hit)` counts of each family one fact gathers; `None` for a family its files held no record of. +#[derive(Default)] +struct Counts { + item: Option, + file: String, + functions: Option<(u64, u64)>, + lines: Option<(u64, u64)>, + branches: Option<(u64, u64)>, +} + +/// The `coverage` facts of `files`, attributed by the places of the `served` `item` facts, sorted by id: +/// +/// - `cov:` for each item the innermost holder of a line, a branch's line or a function's start line, with +/// `item`, `file` (the smallest file attributed to it) and the counts `functions_found`/`functions_hit` (distinct +/// functions, those run), `lines_found`/`lines_hit` and `branches_found`/`branches_hit` (taken), a family's two only +/// when its file held a record of it; +/// - `cov:@` for what no item holds in a file, with `file` and the counts and no `item`. +/// +/// The report's own file totals (LCOV `LF`, `FNF`, …) are never read: a total is not an item's. +pub fn coverage_facts(files: &[CoverageFile], served: &[Fact]) -> Vec { + let places = Places::new(served); + let mut merged: BTreeMap<&str, Merged> = BTreeMap::new(); + for file in files { + let into = merged.entry(file.file.as_str()).or_default(); + for &(line, hits) in &file.lines { + let kept = into.lines.entry(line).or_default(); + *kept = kept.saturating_add(hits); + } + for function in &file.functions { + let kept = into + .functions + .entry((function.line, function.name.as_str())) + .or_default(); + *kept = kept.saturating_add(function.hits); + } + for branch in &file.branches { + let key = (branch.line, branch.block.as_str(), branch.branch.as_str()); + let kept = into.branches.entry(key).or_insert(None); + *kept = match (*kept, branch.taken) { + (Some(a), Some(b)) => Some(a.saturating_add(b)), + (a, b) => a.or(b), + }; + } + } + let mut facts: BTreeMap = BTreeMap::new(); + for (&file, records) in &merged { + // Each fact a record of this file reaches holds every family the file has, at zero until counted. + let mut count = + |line: usize, family: fn(&mut Counts) -> &mut Option<(u64, u64)>, hit: bool| { + let item = places.innermost(file, line); + let id = match item { + Some(item) => format!("{}:{item}", COVERAGE.scheme), + None => format!("{}:@{}", COVERAGE.scheme, id_part(file)), + }; + let counts = facts.entry(id).or_insert_with(|| Counts { + item: item.map(str::to_string), + file: file.to_string(), + ..Counts::default() + }); + if file < counts.file.as_str() { + counts.file = file.to_string(); + } + let present = [ + (!records.functions.is_empty(), &mut counts.functions), + (!records.lines.is_empty(), &mut counts.lines), + (!records.branches.is_empty(), &mut counts.branches), + ]; + for (held, slot) in present { + if held { + slot.get_or_insert((0, 0)); + } + } + if let Some((found, hits)) = family(counts) { + *found += 1; + *hits += u64::from(hit); + } + }; + for (&(line, _), &hits) in &records.functions { + count(line, |c| &mut c.functions, hits > 0); + } + for (&line, &hits) in &records.lines { + count(line, |c| &mut c.lines, hits > 0); + } + for (&(line, _, _), &taken) in &records.branches { + count(line, |c| &mut c.branches, taken.is_some_and(|t| t > 0)); + } + } + facts + .into_iter() + .map(|(id, counts)| { + let mut fact = Fact::new(COVERAGE.kind, id); + if let Some(item) = counts.item { + fact = fact.field("item", item); + } + fact = fact.field("file", counts.file); + let families = [ + ("functions", counts.functions), + ("lines", counts.lines), + ("branches", counts.branches), + ]; + for (family, found_hit) in families { + if let Some((found, hit)) = found_hit { + fact = fact + .field(format!("{family}_found"), found) + .field(format!("{family}_hit"), hit); + } + } + fact + }) + .collect() +} diff --git a/extensions/code/facts/src/cvss.rs b/extensions/code/facts/src/cvss.rs new file mode 100644 index 0000000000..bf414d51d0 --- /dev/null +++ b/extensions/code/facts/src/cvss.rs @@ -0,0 +1,127 @@ +//! The CVSS v3.x base score of a vector, as the FIRST CVSS v3.1 specification computes it (section 7 and Appendix +//! A), and the severity it rates (ADR 0388). The one place a float is computed: from the Roundup on, a score is an +//! integer number of tenths, so no float boundary can flip a rating. + +use crate::vulnerability::Severity; + +/// The base metrics, each with its values and their weights. `PR`'s weight is the one of scope unchanged; scope +/// changed raises `L` and `H` ([`PR_CHANGED`]). `S` has no weight: it picks the formula. +const BASE: [(&str, &[(&str, f64)]); 8] = [ + ("AV", &[("N", 0.85), ("A", 0.62), ("L", 0.55), ("P", 0.2)]), + ("AC", &[("L", 0.77), ("H", 0.44)]), + ("PR", &[("N", 0.85), ("L", 0.62), ("H", 0.27)]), + ("UI", &[("N", 0.85), ("R", 0.62)]), + ("S", &[("U", 0.0), ("C", 0.0)]), + ("C", &[("H", 0.56), ("L", 0.22), ("N", 0.0)]), + ("I", &[("H", 0.56), ("L", 0.22), ("N", 0.0)]), + ("A", &[("H", 0.56), ("L", 0.22), ("N", 0.0)]), +]; + +/// `PR`'s weights when the scope is changed. +const PR_CHANGED: [(&str, f64); 3] = [("N", 0.85), ("L", 0.68), ("H", 0.5)]; + +/// The temporal and environmental metrics of the v3.1 specification and their values: allowed at most once each, +/// and ignored by the base score. +const IGNORED: [(&str, &[&str]); 14] = [ + ("E", &["X", "H", "F", "P", "U"]), + ("RL", &["X", "U", "W", "T", "O"]), + ("RC", &["X", "C", "R", "U"]), + ("CR", &["X", "H", "M", "L"]), + ("IR", &["X", "H", "M", "L"]), + ("AR", &["X", "H", "M", "L"]), + ("MAV", &["X", "N", "A", "L", "P"]), + ("MAC", &["X", "L", "H"]), + ("MPR", &["X", "N", "L", "H"]), + ("MUI", &["X", "N", "R"]), + ("MS", &["X", "U", "C"]), + ("MC", &["X", "H", "L", "N"]), + ("MI", &["X", "H", "L", "N"]), + ("MA", &["X", "H", "L", "N"]), +]; + +/// The base score of the CVSS v3.0 or v3.1 `vector`, in tenths (`0..=100`). +/// +/// The vector is `CVSS:3.0/` or `CVSS:3.1/` then `KEY:VALUE` pairs split on `/`, in any order: each base metric +/// exactly once with a value of its table, each temporal or environmental metric at most once with a value of its +/// table. `None` for anything else: another prefix (a v2 or v4 vector), a missing or repeated metric, an unknown +/// metric or value, an empty pair. +pub fn base_score(vector: &str) -> Option { + let pairs = vector + .strip_prefix("CVSS:3.1/") + .or_else(|| vector.strip_prefix("CVSS:3.0/"))?; + let mut base: [Option<&str>; 8] = [None; 8]; + let mut ignored = [false; 14]; + for pair in pairs.split('/') { + let (key, value) = pair.split_once(':')?; + if let Some(at) = BASE.iter().position(|(name, _)| *name == key) { + let known = BASE[at].1.iter().any(|(name, _)| *name == value); + if !known || base[at].replace(value).is_some() { + return None; + } + } else { + let at = IGNORED.iter().position(|(name, _)| *name == key)?; + if !IGNORED[at].1.contains(&value) || std::mem::replace(&mut ignored[at], true) { + return None; + } + } + } + let [av, ac, pr, ui, s, c, i, a] = base; + let changed = s? == "C"; + let weight = |at: usize, value: Option<&str>| -> Option { + let table = if at == 2 && changed { + &PR_CHANGED[..] + } else { + BASE[at].1 + }; + let value = value?; + table + .iter() + .find(|(name, _)| *name == value) + .map(|(_, w)| *w) + }; + let (av, ac, pr, ui) = ( + weight(0, av)?, + weight(1, ac)?, + weight(2, pr)?, + weight(3, ui)?, + ); + let (c, i, a) = (weight(5, c)?, weight(6, i)?, weight(7, a)?); + let iss = 1.0 - (1.0 - c) * (1.0 - i) * (1.0 - a); + let impact = if changed { + 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02).powi(15) + } else { + 6.42 * iss + }; + if impact <= 0.0 { + return Some(0); + } + let exploitability = 8.22 * av * ac * pr * ui; + let sum = if changed { + 1.08 * (impact + exploitability) + } else { + impact + exploitability + }; + Some(roundup(sum.min(10.0))) +} + +/// The v3.1 Appendix A Roundup of `x`, in tenths: the smallest number of tenths not below `x`, computed on the +/// integer `round(x * 100000)` so a float a hair above a tenth does not round up to the next. +fn roundup(x: f64) -> u32 { + let i = (x * 100_000.0).round() as u32; + if i.is_multiple_of(10_000) { + i / 10_000 + } else { + i / 10_000 + 1 + } +} + +/// The severity a base score of `tenths` rates: 9.0 and above critical, 7.0 high, 4.0 medium, below low. 0.0, which +/// the specification calls None, reads low: the vocabulary has no `none`. +pub fn rating(tenths: u32) -> Severity { + match tenths { + 90.. => Severity::Critical, + 70..=89 => Severity::High, + 40..=69 => Severity::Medium, + _ => Severity::Low, + } +} diff --git a/extensions/code/facts/src/dependency.rs b/extensions/code/facts/src/dependency.rs new file mode 100644 index 0000000000..322ba05afc --- /dev/null +++ b/extensions/code/facts/src/dependency.rs @@ -0,0 +1,219 @@ +//! The `dependency` facts of a CycloneDX bill of materials (ADR 0388): what a reader (`specforge-code-cyclonedx`) read +//! of a BOM, and the facts minted from it, each citing the served project `package` the BOM describes. Whether a +//! dependency is direct is what the BOM's own dependency graph states, and stays unknown (absent) when it states none. + +use std::collections::BTreeMap; +use std::str::FromStr; + +use specforge_extension_sdk::prelude::Fact; + +use crate::ids::PackageId; +use crate::places::Places; +use crate::report::{id_part, shown, unescape, DEPENDENCY}; + +/// A component's scope: CycloneDX's three, widest first. A BOM stating none means `required`, the spec's default. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Scope { + Required, + Optional, + Excluded, +} + +/// Every scope, widest first: the order [`Scope::NAMES`] and [`Scope::parse`] read. +const SCOPES: [Scope; 3] = [Scope::Required, Scope::Optional, Scope::Excluded]; + +impl Scope { + /// Every scope's name, widest first: `@code/core`'s vocabulary of `dependency.scope`. + pub const NAMES: [&'static str; 3] = { + let mut names = [""; 3]; + let mut at = 0; + while at < names.len() { + names[at] = SCOPES[at].as_str(); + at += 1; + } + names + }; + + /// Its name: an exhaustive match, so a new scope names itself or fails to compile. + pub const fn as_str(self) -> &'static str { + match self { + Scope::Required => "required", + Scope::Optional => "optional", + Scope::Excluded => "excluded", + } + } + + /// One of CycloneDX's three scope values; `None` for any other text. + pub fn parse(text: &str) -> Option { + SCOPES.into_iter().find(|scope| scope.as_str() == text) + } +} + +/// What a BOM says of one component. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Component { + /// Its `bom-ref`, the name the BOM's dependency graph knows it by. + pub bom_ref: Option, + /// Its package URL as written, qualifiers and subpath included. + pub purl: Option, + pub group: Option, + pub name: String, + pub version: Option, + pub scope: Scope, +} + +/// What a reader read of one BOM. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Bom { + /// `metadata.component`: the component the BOM describes, a project package. + pub root: Component, + /// Every component, nested ones flattened depth first (nesting is no dependency tree). + pub components: Vec, + /// The `dependsOn` refs of the dependency graph's entry for the root; `None` when the BOM has no `dependencies` + /// array, no entry for the root, or a root with no `bom-ref`: unknown, not "none". + pub direct: Option>, +} + +/// The `dependency` facts of `boms`, sorted by id, each citing the served `package` its BOM describes. +/// +/// A BOM's project package is a served package [`Places::packages_named`] finds by the root's purl with its +/// qualifiers (`?…`), subpath (`#…`) and version (after the last `@` of the last segment) removed, a namespace +/// starting with a literal `@` written `%40`: the one whose directory is the purl's subpath (decoded, no leading or +/// trailing `/`), else the one whose id is exactly that, else the only one. No such package, several with none of +/// them selected, or a root with no purl is an error naming the root's purl or name: a BOM about no collected package +/// is no report about this project. +/// +/// The id is `dep:/`, or +/// `dep:/@` for a component with no purl ([`id_part`] encodes `@`, so the +/// two forms never meet). Fields: `package`, `purl` as written, `name` (`group/name` with a group), `version`, +/// `scope`, and `direct` only when the BOM states a graph entry for its root and the component has a `bom-ref`. +/// Components of one id merge across `boms` (F4): the widest scope, `direct` true when any is, absent only when every +/// one is absent; the first one's other fields. +pub fn dependency_facts(boms: &[Bom], served: &[Fact]) -> Result, String> { + let places = Places::new(served); + let mut merged: BTreeMap = BTreeMap::new(); + for bom in boms { + let package = project_package(&bom.root, &places)?; + for component in &bom.components { + let direct = match (&bom.direct, &component.bom_ref) { + (Some(refs), Some(bom_ref)) => Some(refs.contains(bom_ref)), + _ => None, + }; + let id = match &component.purl { + Some(purl) => format!("{}:{package}/{}", DEPENDENCY.scheme, id_part(bare(purl))), + None => { + let mut named = full_name(component); + if let Some(version) = &component.version { + named.push('@'); + named.push_str(version); + } + format!("{}:{package}/@{}", DEPENDENCY.scheme, id_part(&named)) + } + }; + merged + .entry(id) + .and_modify(|seen| { + seen.scope = seen.scope.min(component.scope); + seen.direct = match (seen.direct, direct) { + (Some(a), Some(b)) => Some(a || b), + (a, b) => a.or(b), + }; + }) + .or_insert(Merged { + package, + component, + scope: component.scope, + direct, + }); + } + } + Ok(merged.into_iter().map(|(id, seen)| seen.fact(id)).collect()) +} + +/// The components of one id seen so far: the first, and the merged scope and directness. +struct Merged<'a> { + package: &'a str, + component: &'a Component, + scope: Scope, + direct: Option, +} + +impl Merged<'_> { + fn fact(self, id: String) -> Fact { + let mut fact = Fact::new(DEPENDENCY.kind, id).field("package", self.package); + if let Some(purl) = &self.component.purl { + fact = fact.field("purl", purl.as_str()); + } + fact = fact.field("name", full_name(self.component)); + if let Some(version) = &self.component.version { + fact = fact.field("version", version.as_str()); + } + fact = fact.field("scope", self.scope.as_str()); + match self.direct { + Some(direct) => fact.field("direct", direct), + None => fact, + } + } +} + +/// `group/name` when the component has a group, else its name. +fn full_name(component: &Component) -> String { + match &component.group { + Some(group) => format!("{group}/{}", component.name), + None => component.name.clone(), + } +} + +/// `purl` without its qualifiers (`?…`) and subpath (`#…`). +fn bare(purl: &str) -> &str { + purl.split(['?', '#']).next().unwrap_or(purl) +} + +/// The id of the one served package the BOM root `root` names, else an error naming the root. +fn project_package<'a>(root: &Component, places: &Places<'a>) -> Result<&'a str, String> { + let Some(purl) = &root.purl else { + return Err(format!( + "the BOM's root component '{}' has no purl, so it names no collected package", + shown(&root.name) + )); + }; + let base = package_base(purl); + let named = places.packages_named(&base); + // The purl's subpath (`#crates/demo`) names the directory of a second package of one name. + let subpath = purl + .split_once('#') + .map(|(_, subpath)| unescape(subpath).trim_matches('/').to_string()); + let by_subpath = named.iter().find(|id| { + subpath.is_some() && PackageId::from_str(id).is_ok_and(|id| id.dir() == subpath.as_deref()) + }); + if let Some(package) = by_subpath.or_else(|| named.iter().find(|id| **id == base)) { + return Ok(*package); + } + match named.as_slice() { + [package] => Ok(*package), + [] => Err(format!( + "the BOM's root component '{}' names no collected package (looked for '{}')", + shown(purl), + shown(&base) + )), + several => Err(format!( + "the BOM's root component '{}' names several collected packages: {}", + shown(purl), + several.join(", ") + )), + } +} + +/// The package id a purl names: no qualifiers, subpath or version, a namespace starting with `@` written `%40`. +fn package_base(purl: &str) -> String { + let bare = bare(purl); + let last = bare.rfind('/').map_or(0, |at| at + 1); + let unversioned = match bare[last..].rfind('@') { + Some(at) => &bare[..last + at], + None => bare, + }; + match unversioned.split_once('/') { + Some((head, rest)) if rest.starts_with('@') => format!("{head}/%40{}", &rest[1..]), + _ => unversioned.to_string(), + } +} diff --git a/extensions/code/facts/src/finding.rs b/extensions/code/facts/src/finding.rs new file mode 100644 index 0000000000..9417fd5cac --- /dev/null +++ b/extensions/code/facts/src/finding.rs @@ -0,0 +1,131 @@ +//! The `static_finding` facts of a SARIF report (ADR 0388): what a reader (`specforge-code-sarif`) read of each +//! result, and the facts minted from it, each citing the innermost served `item` holding its location, else the +//! `package` holding its file. A level is what the report states, never SARIF's own `warning` default (F5). + +use specforge_extension_sdk::prelude::{Fact, FactLocation}; + +use crate::places::Places; +use crate::report::{id_part, Repeats, STATIC_FINDING, UNKNOWN}; + +/// A result's level: SARIF's four, or [`UNKNOWN`] when the report states none (F5). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Level { + Error, + Warning, + Note, + None, + Unknown, +} + +/// Every level, SARIF's four then `unknown`: the order [`Level::NAMES`] and [`Level::parse`] read. +const LEVELS: [Level; 5] = [ + Level::Error, + Level::Warning, + Level::Note, + Level::None, + Level::Unknown, +]; + +impl Level { + /// Every level's name, SARIF's four then `unknown`: `@code/core`'s vocabulary of `static_finding.level`. + pub const NAMES: [&'static str; 5] = { + let mut names = [""; 5]; + let mut at = 0; + while at < names.len() { + names[at] = LEVELS[at].as_str(); + at += 1; + } + names + }; + + /// Its name: an exhaustive match, so a new level names itself or fails to compile. + pub const fn as_str(self) -> &'static str { + match self { + Level::Error => "error", + Level::Warning => "warning", + Level::Note => "note", + Level::None => "none", + Level::Unknown => UNKNOWN, + } + } + + /// One of SARIF's four level values (`error`, `warning`, `note`, `none`); `None` for any other text, `unknown` + /// included, which no report writes. + pub fn parse(text: &str) -> Option { + LEVELS + .into_iter() + .find(|level| *level != Level::Unknown && level.as_str() == text) + } +} + +/// What a SARIF report says of one result. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SarifResult { + /// The run's `tool.driver.name`. + pub tool: String, + /// The rule id, [`UNKNOWN`] when the result states none. + pub rule: String, + pub level: Level, + /// `message.text`, empty when absent. + pub message: String, + /// The file of its first physical location, project-relative, with `/` separators. + pub file: Option, + /// Its 1-based start line. + pub line: Option, + /// Its 1-based end line, inclusive. + pub end_line: Option, +} + +/// The `static_finding` facts of `results`, in document order, attributed by the places of the `served` facts. +/// +/// The id is `sarif:/`, then `#:` when both are known or `#` when only the file is, each +/// part through [`id_part`]; a second and later result of one id take `~2`, `~3`, … (F4). Fields: `tool`, `rule`, +/// `level`, `message`, and `file` and `line` when known; `item`, the innermost served item holding the line, else +/// `package`, the served package holding the file, else neither. Its place spans whole lines, `line` to `end_line`: +/// SARIF columns have no fixed unit, so none is claimed. +pub fn finding_facts(results: &[SarifResult], served: &[Fact]) -> Vec { + let places = Places::new(served); + let mut repeats = Repeats::default(); + results + .iter() + .map(|result| { + let mut id = format!( + "{}:{}/{}", + STATIC_FINDING.scheme, + id_part(&result.tool), + id_part(&result.rule) + ); + match (&result.file, result.line) { + (Some(file), Some(line)) => id.push_str(&format!("#{}:{line}", id_part(file))), + (Some(file), None) => id.push_str(&format!("#{}", id_part(file))), + _ => {} + } + let mut fact = Fact::new(STATIC_FINDING.kind, repeats.id(id)) + .field("tool", result.tool.as_str()) + .field("rule", result.rule.as_str()) + .field("level", result.level.as_str()) + .field("message", result.message.as_str()); + let Some(file) = &result.file else { + return fact; + }; + fact = fact.field("file", file.as_str()); + if let Some(line) = result.line { + let last = result.end_line.unwrap_or(line).max(line); + fact = fact.field("line", line).at(FactLocation { + file: file.clone(), + start_line: line, + start_col: 1, + end_line: last.saturating_add(1), + end_col: 1, + }); + } + match result.line.and_then(|line| places.innermost(file, line)) { + Some(item) => fact.field("item", item), + None => match places.package_of(file) { + Some(package) => fact.field("package", package), + None => fact, + }, + } + }) + .collect() +} diff --git a/extensions/code/facts/src/ids.rs b/extensions/code/facts/src/ids.rs index 8d596bf10f..51177156bd 100644 --- a/extensions/code/facts/src/ids.rs +++ b/extensions/code/facts/src/ids.rs @@ -4,6 +4,8 @@ use std::collections::BTreeMap; use std::fmt; use std::str::FromStr; +use crate::report::unescape; + /// What a run id starts with, before its test's id. const RUN: &str = "run:"; /// What a `js` id's `` percent-encodes: `#` ends the container of a test id, `:` starts an item's names. @@ -256,6 +258,16 @@ impl ItemId { format!("{}:{}::", self.scheme.as_str(), self.container) } + /// The crate segment (`rust`) or `/` (`js`), as the id writes it. + pub(crate) fn container_text(&self) -> &str { + &self.container + } + + /// The segments after the container: modules, owner and name (`rust`), the name path (`js`), unescaped. + pub(crate) fn segments(&self) -> &[String] { + &self.path + } + /// The item's own unqualified name: its last segment (`add` for `…::Board::add`, `fmt` for /// `…::::fmt`, `add` for `js:…::Board.add`). pub fn name(&self) -> &str { @@ -652,30 +664,6 @@ fn escape(text: &str, escapes: &[char]) -> String { out } -/// `text` with each `%XX` decoded; a `%` that starts no valid sequence is kept. -fn unescape(text: &str) -> String { - let bytes = text.as_bytes(); - let mut out = Vec::with_capacity(bytes.len()); - let mut at = 0; - while at < bytes.len() { - let hex = bytes - .get(at + 1..at + 3) - .and_then(|pair| std::str::from_utf8(pair).ok()) - .and_then(|pair| u8::from_str_radix(pair, 16).ok()); - match (bytes[at], hex) { - (b'%', Some(byte)) => { - out.push(byte); - at += 3; - } - (byte, _) => { - out.push(byte); - at += 1; - } - } - } - String::from_utf8(out).unwrap_or_else(|_| text.to_string()) -} - /// A Rust identifier without its `r#`. fn unraw(name: &str) -> &str { name.strip_prefix("r#").unwrap_or(name) diff --git a/extensions/code/facts/src/lib.rs b/extensions/code/facts/src/lib.rs index 73077081d7..6b06362462 100644 --- a/extensions/code/facts/src/lib.rs +++ b/extensions/code/facts/src/lib.rs @@ -14,20 +14,59 @@ //! - [`item_facts`] mints one `item` per item id from a source pack's [`Definition`]s, every place and kind listed; //! [`signature_spelling`] is the one spelling a pack gives a signature in. //! - [`Package::fact`] mints a `package`; [`location`] turns the reader's points into a fact's place; [`joined`] -//! resolves a path a manifest or a source file writes against the project-relative directory it is written in. +//! resolves a path a manifest or a source file writes against the project-relative directory it is written in; +//! [`place`] says what a report's file path names, whatever spelling the host's root has: a project file, a path +//! outside the project, or no file (the root itself, rustc's ``), and [`relative`] keeps only the file; +//! [`file_uri_path`] decodes a report's `file:` URI to a path for it to judge; [`outside_line`] and +//! [`no_file_line`] are the warnings a pack returns for the paths a reader skipped (ADR 0389 D7). //! - [`parse_all`] asks the host's source reader until it has answered every file a source pack keeps, the files an //! answer's cap left unparsed asked again. +//! - [`Places`] finds where a report's location lies among the served facts: the innermost `item` holding a file's +//! line, the `package` holding a file or a directory (ADR 0388). +//! - [`ReportKind`]s name the five kinds a standard report mints and their schemes ([`COVERAGE`], [`API_ITEM`], +//! [`STATIC_FINDING`], [`DEPENDENCY`], [`VULNERABILITY`]), [`UNKNOWN`] what a report leaves unstated; [`id_part`] +//! makes report text safe in an id, [`shown`] and [`shown_json`] in an error or a diagnostic message, and +//! [`Repeats`] suffixes an id +//! answered twice `~2`, `~3`, …. +//! - [`coverage_facts`] mints a `coverage` per item a coverage report's [`CoverageFile`]s reach, and one per file for +//! what no item holds. +//! - [`api_facts`] mints an `api_item` per public entry an API snapshot's reader read ([`ApiEntry`], [`ApiKind`]), +//! citing the one served item its path names; [`api_facts_against`] also judges each entry against the committed +//! accepted report ([`ApiChange`], paired by [`comparable`] signature, ADR 0390 D3). +//! - [`finding_facts`] mints a `static_finding` per result a SARIF reader read ([`SarifResult`], [`Level`]), citing +//! the innermost served item holding its location, else the package holding its file. +//! - [`dependency_facts`] mints a `dependency` per component of the CycloneDX [`Bom`]s a reader read ([`Component`], +//! [`Scope`]), citing the one served package each BOM describes. +//! - [`vulnerability_facts`] mints a `vulnerability` per OSV record and project package of an osv-scanner +//! [`OsvReport`] a reader read ([`OsvSource`], [`OsvPackage`], [`OsvRecord`], [`OsvScore`]), citing the packages the +//! scanned lockfile belongs to, with a [`Severity`]: the record's label, else the [`rating`] of its highest CVSS v3 +//! [`base_score`]; a package it cannot place is named in [`Vulnerabilities::skipped`], never the whole report lost. //! //! Every id parses back to itself (`FromStr`), and a SCIP symbol of rust-analyzer or scip-typescript maps into exactly //! one (ADR 0347 D4). +mod accepted; +mod api; +mod coverage; +mod cvss; +mod dependency; +mod finding; mod ids; mod mint; mod paths; +mod places; +mod report; mod syntax; #[cfg(test)] mod tests; +mod vulnerability; +pub use accepted::{api_facts_against, comparable, ApiChange}; +pub use api::{api_facts, ApiEntry, ApiKind}; +pub use coverage::{coverage_facts, Branch, CoverageFile, Function}; +pub use cvss::{base_score, rating}; +pub use dependency::{dependency_facts, Bom, Component, Scope}; +pub use finding::{finding_facts, Level, SarifResult}; pub use ids::{ crate_segment, js_segment, Edition, IdError, ItemId, Owner, PackageId, Scheme, TargetKind, TestId, @@ -36,5 +75,14 @@ pub use mint::{ item_facts, location, signature_spelling, test_facts, Definition, ItemKind, Names, Package, Signature, Target, TestCase, Visibility, }; -pub use paths::joined; +pub use paths::{file_uri_path, joined, no_file_line, outside_line, place, relative, Place}; +pub use places::Places; +pub use report::{ + id_part, shown, shown_json, Repeats, ReportKind, API_ITEM, COVERAGE, DEPENDENCY, + STATIC_FINDING, UNKNOWN, VULNERABILITY, +}; pub use syntax::parse_all; +pub use vulnerability::{ + vulnerability_facts, OsvPackage, OsvRecord, OsvReport, OsvScore, OsvSource, Severity, + Vulnerabilities, +}; diff --git a/extensions/code/facts/src/mint.rs b/extensions/code/facts/src/mint.rs index 276ffb8f57..d8a680d89f 100644 --- a/extensions/code/facts/src/mint.rs +++ b/extensions/code/facts/src/mint.rs @@ -68,6 +68,40 @@ impl TestCase { ran: false, } } + + /// This test placed at `item`, the source item `@rust/source` answered for it: a runner pack places a reported + /// test there. It takes the item's places, its `names` (each at the places the item names it), and the item's + /// `file` when the test has none of its own. + pub fn placed(self, item: &Fact) -> TestCase { + let names: Names = item + .fields + .get("names") + .and_then(|names| names.as_array()) + .into_iter() + .flatten() + .filter_map(|name| name.as_str()) + .map(|name| { + let places = item + .named_at + .get("names") + .and_then(|named| named.get(name)) + .cloned() + .unwrap_or_default(); + (name.to_string(), places) + }) + .collect(); + TestCase { + file: self.file.or_else(|| { + item.fields + .get("file") + .and_then(|f| f.as_str()) + .map(str::to_string) + }), + names, + at: item.at.clone(), + ..self + } + } } /// The `test` and `test_run` facts of `cases`, by id (ADR 0329 D3, ADR 0347): @@ -162,54 +196,57 @@ pub enum ItemKind { Namespace, } -/// Each kind and its name, in vocabulary order: the one table [`ItemKind::ALL`], [`ItemKind::NAMES`] and -/// [`ItemKind::as_str`] read. -const ITEM_KINDS: [(ItemKind, &str); 16] = [ - (ItemKind::Module, "module"), - (ItemKind::Function, "function"), - (ItemKind::Method, "method"), - (ItemKind::Field, "field"), - (ItemKind::Struct, "struct"), - (ItemKind::Enum, "enum"), - (ItemKind::Union, "union"), - (ItemKind::Trait, "trait"), - (ItemKind::Type, "type"), - (ItemKind::Const, "const"), - (ItemKind::Static, "static"), - (ItemKind::Macro, "macro"), - (ItemKind::Class, "class"), - (ItemKind::Interface, "interface"), - (ItemKind::Variable, "variable"), - (ItemKind::Namespace, "namespace"), -]; - impl ItemKind { - /// Every kind, in vocabulary order. - pub const ALL: [ItemKind; 16] = { - let mut all = [ItemKind::Module; 16]; - let mut at = 0; - while at < all.len() { - all[at] = ITEM_KINDS[at].0; - at += 1; - } - all - }; + /// Every kind, in vocabulary order: the order [`ItemKind::NAMES`] reads. + pub const ALL: [ItemKind; 16] = [ + ItemKind::Module, + ItemKind::Function, + ItemKind::Method, + ItemKind::Field, + ItemKind::Struct, + ItemKind::Enum, + ItemKind::Union, + ItemKind::Trait, + ItemKind::Type, + ItemKind::Const, + ItemKind::Static, + ItemKind::Macro, + ItemKind::Class, + ItemKind::Interface, + ItemKind::Variable, + ItemKind::Namespace, + ]; /// Every kind's name, in vocabulary order: `@code/core`'s vocabulary of `item.kind`. pub const NAMES: [&'static str; 16] = { let mut names = [""; 16]; let mut at = 0; while at < names.len() { - names[at] = ITEM_KINDS[at].1; + names[at] = ItemKind::ALL[at].as_str(); at += 1; } names }; - pub fn as_str(self) -> &'static str { - ITEM_KINDS - .iter() - .find(|(kind, _)| *kind == self) - .map_or("", |(_, name)| name) + /// Its name: an exhaustive match, so a new kind names itself or fails to compile. + pub const fn as_str(self) -> &'static str { + match self { + ItemKind::Module => "module", + ItemKind::Function => "function", + ItemKind::Method => "method", + ItemKind::Field => "field", + ItemKind::Struct => "struct", + ItemKind::Enum => "enum", + ItemKind::Union => "union", + ItemKind::Trait => "trait", + ItemKind::Type => "type", + ItemKind::Const => "const", + ItemKind::Static => "static", + ItemKind::Macro => "macro", + ItemKind::Class => "class", + ItemKind::Interface => "interface", + ItemKind::Variable => "variable", + ItemKind::Namespace => "namespace", + } } } @@ -222,12 +259,12 @@ pub enum Visibility { Public, } -/// Each visibility and its name, widest first: the one table [`Visibility::NAMES`] and [`Visibility::as_str`] read. -const VISIBILITIES: [(Visibility, &str); 4] = [ - (Visibility::Public, "public"), - (Visibility::Crate, "crate"), - (Visibility::Restricted, "restricted"), - (Visibility::Private, "private"), +/// Every visibility, widest first: the order [`Visibility::NAMES`] reads. +const VISIBILITIES: [Visibility; 4] = [ + Visibility::Public, + Visibility::Crate, + Visibility::Restricted, + Visibility::Private, ]; impl Visibility { @@ -236,17 +273,20 @@ impl Visibility { let mut names = [""; 4]; let mut at = 0; while at < names.len() { - names[at] = VISIBILITIES[at].1; + names[at] = VISIBILITIES[at].as_str(); at += 1; } names }; - pub fn as_str(self) -> &'static str { - VISIBILITIES - .iter() - .find(|(visibility, _)| *visibility == self) - .map_or("", |(_, name)| name) + /// Its name: an exhaustive match, so a new visibility names itself or fails to compile. + pub const fn as_str(self) -> &'static str { + match self { + Visibility::Public => "public", + Visibility::Crate => "crate", + Visibility::Restricted => "restricted", + Visibility::Private => "private", + } } /// From the `visibility_modifier` text a pack captured (`None`: none written), whitespace ignored (D10): `pub` diff --git a/extensions/code/facts/src/paths.rs b/extensions/code/facts/src/paths.rs index 9be2f71824..af7598c079 100644 --- a/extensions/code/facts/src/paths.rs +++ b/extensions/code/facts/src/paths.rs @@ -1,4 +1,6 @@ -//! Project-relative paths as the packs compute them from what a manifest or a source file writes. +//! Project-relative paths as the packs compute them from what a manifest, a source file or a report writes. + +use crate::report::unescape; /// `path` (relative, `/` or `\` separated) under the project-relative directory `dir`, its `.` and `..` resolved; /// `None` when it leaves the project, or is absolute (`/…`, `\…`, a drive or a scheme: any `:`). @@ -18,3 +20,205 @@ pub fn joined(dir: &str, path: &str) -> Option { } Some(segments.join("/")) } + +/// The path a report's URI names (a SARIF `artifactLocation.uri`), percent-decoded. A `file:` URI loses `file://` +/// and an empty or `localhost` host (`file:///p/x` and `file://localhost/p/x` give `/p/x`; another host gives +/// `//host/rest`, a UNC path), and `/C:/…` loses its leading `/`. Text with no scheme is a relative reference (as SARIF +/// writes with `uriBaseId`) and comes back decoded. Either way a `?` query or `#` fragment is dropped. A URI of +/// another scheme gives `None`. Only a path: [`relative`] decides whether it lies in the project, so a decoded `..` +/// cannot climb out. +pub fn file_uri_path(uri: &str) -> Option { + let uri = uri.split(['?', '#']).next().unwrap_or(uri); + let path = match uri.split_once(':') { + Some((scheme, rest)) if is_scheme(scheme) => { + if !scheme.eq_ignore_ascii_case("file") { + return None; + } + match rest.strip_prefix("//") { + Some(authority) => { + let (host, path) = + authority.split_at(authority.find('/').unwrap_or(authority.len())); + if host.is_empty() || host.eq_ignore_ascii_case("localhost") { + path.to_string() + } else { + format!("//{host}{path}") + } + } + None => rest.to_string(), + } + } + _ => uri.to_string(), + }; + let path = unescape(&path); + match path.strip_prefix('/') { + Some(rest) + if drive(rest).is_some() && matches!(rest.as_bytes().get(2), None | Some(b'/')) => + { + Some(rest.to_string()) + } + _ => Some(path), + } +} + +/// Whether `text` is a URI scheme (RFC 3986): a letter, then letters, digits, `+`, `-` or `.`; one letter alone is a +/// drive, not a scheme. +fn is_scheme(text: &str) -> bool { + let mut chars = text.chars(); + text.len() > 1 + && chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) +} + +/// The one warning line a pack returns for the paths a reader of `report` skipped as outside the project (ADR 0389 D7), +/// each already [`shown`](crate::shown): `None` when there is none, else the count and the first five, then how many +/// more. The host turns the line into a W203. +pub fn outside_line(report: &str, outside: &[String]) -> Option { + skipped_line(report, "file(s) outside the project", outside) +} + +/// The one warning line a pack returns for the paths a reader of `report` skipped as naming no file ([`Place::NoFile`]), +/// each already [`shown`](crate::shown), worded as [`outside_line`]'s: `None` when there is none. +pub fn no_file_line(report: &str, no_file: &[String]) -> Option { + skipped_line(report, "path(s) naming no file", no_file) +} + +/// `: skipped : ` and the first five `paths`, then how many more; `None` for no path. +fn skipped_line(report: &str, what: &str, paths: &[String]) -> Option { + const NAMED: usize = 5; + if paths.is_empty() { + return None; + } + let mut line = format!( + "{report}: skipped {} {what}: {}", + paths.len(), + paths[..paths.len().min(NAMED)].join(", ") + ); + if paths.len() > NAMED { + line.push_str(&format!(", and {} more", paths.len() - NAMED)); + } + Some(line) +} + +/// What a report's path names against the project root ([`place`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Place { + /// A project file, relative to the root, with `/` separators. + File(String), + /// A path outside the project: absolute elsewhere, or climbing out through `..`. + Outside, + /// No file: a path that resolves to the project root itself (`.`, `a/..`, the root's own absolute path), or a + /// compiler's pseudo file name in angle brackets (rustc's ``, ``). + NoFile, +} + +/// What `path` names against the project root `cwd`. Both are read the same way first: a `\\?\` (or `\\?\UNC\`) +/// verbatim prefix is stripped, `\` is folded to `/`, a drive letter compares case-insensitively and a trailing `/` is +/// dropped. The host's `cwd` is the canonical root, so the other spelling of macOS's `/private` alias (`/private/var` +/// and `/var`, `/private/tmp` and `/tmp`) is tried too. A relative `path` is taken as project-relative already. Either +/// way its `.` and `..` segments are resolved: a path that climbs out of the project through `..` is +/// [`Place::Outside`], as an absolute one elsewhere is, and one that resolves to nothing is [`Place::NoFile`], as a +/// name in angle brackets is. +pub fn place(path: &str, cwd: &str) -> Place { + if path.starts_with('<') && path.ends_with('>') { + return Place::NoFile; + } + let path = normal(path); + if !is_absolute(&path) { + return contained(&path); + } + let cwd = normal(cwd); + aliases(&cwd) + .iter() + .find_map(|root| { + aliases(&path) + .iter() + .find_map(|spelling| under(spelling, root)) + }) + .map_or(Place::Outside, |rest| contained(&rest)) +} + +/// `path` relative to the project root `cwd` when it names a project file ([`place`]); `None` when it lies outside the +/// project or names no file. +pub fn relative(path: &str, cwd: &str) -> Option { + match place(path, cwd) { + Place::File(file) => Some(file), + Place::Outside | Place::NoFile => None, + } +} + +/// The project-relative `path` with its `.` and `..` segments resolved: [`Place::Outside`] when a `..` climbs out of +/// the project, [`Place::NoFile`] when nothing is left. +fn contained(path: &str) -> Place { + let mut kept: Vec<&str> = Vec::new(); + for segment in path.split('/') { + match segment { + "" | "." => {} + ".." => { + if kept.pop().is_none() { + return Place::Outside; + } + } + name => kept.push(name), + } + } + if kept.is_empty() { + Place::NoFile + } else { + Place::File(kept.join("/")) + } +} + +/// `path` with no verbatim prefix, `/` separators and no trailing `/`. +fn normal(path: &str) -> String { + let path = match path.strip_prefix(r"\\?\UNC\") { + Some(share) => format!(r"\\{share}"), + None => path.strip_prefix(r"\\?\").unwrap_or(path).to_string(), + }; + let path = path.replace('\\', "/"); + match path.trim_end_matches('/') { + "" if path.starts_with('/') => "/".to_string(), + trimmed => trimmed.to_string(), + } +} + +/// Whether `path` (read by [`normal`]) is rooted: `/…` or a drive, `C:/…`. +fn is_absolute(path: &str) -> bool { + path.starts_with('/') || drive(path).is_some() +} + +/// The drive letter `path` starts with, `C:`, if any. +fn drive(path: &str) -> Option { + let mut chars = path.chars(); + let letter = chars.next().filter(char::is_ascii_alphabetic)?; + (chars.next() == Some(':')).then_some(letter) +} + +/// `path`, and its other spelling under macOS's `/private` alias. +fn aliases(path: &str) -> Vec { + let mut spellings = vec![path.to_string()]; + for (long, short) in [("/private/var", "/var"), ("/private/tmp", "/tmp")] { + for (from, to) in [(long, short), (short, long)] { + match path.strip_prefix(from) { + Some(rest) if rest.is_empty() || rest.starts_with('/') => { + spellings.push(format!("{to}{rest}")); + } + _ => {} + } + } + } + spellings +} + +/// `path` at or below `root`, both read by [`normal`]: what follows `root/`, empty for `root` itself, or `None`. +fn under(path: &str, root: &str) -> Option { + let (path, root) = match (drive(path), drive(root)) { + (Some(a), Some(b)) if a.eq_ignore_ascii_case(&b) => (&path[2..], &root[2..]), + (None, None) => (path, root), + _ => return None, + }; + let rest = path.strip_prefix(root.trim_end_matches('/'))?; + match rest.strip_prefix('/') { + Some(rest) => Some(rest.to_string()), + None => rest.is_empty().then(String::new), + } +} diff --git a/extensions/code/facts/src/places.rs b/extensions/code/facts/src/places.rs new file mode 100644 index 0000000000..18ac15a735 --- /dev/null +++ b/extensions/code/facts/src/places.rs @@ -0,0 +1,162 @@ +//! Where a report's location lies among the served facts: the innermost `item` holding a file's line, and the +//! `package` holding a file or a directory (ADR 0388). + +use std::collections::BTreeMap; + +use specforge_extension_sdk::prelude::{Fact, FactLocation}; + +/// The served `item` facts by the files their places are on, and the served `package` facts by their directories. +#[derive(Debug, Default)] +pub struct Places<'a> { + /// File → each place of an item on it, with the item's id. + items: BTreeMap<&'a str, Vec<(&'a FactLocation, &'a str)>>, + /// Each package's `(path, id)`; `path` is project-relative, `""` at the root (and when the field is absent). + packages: Vec<(&'a str, &'a str)>, +} + +impl<'a> Places<'a> { + /// The places of `served`'s `item` facts, by file, and the directories of its `package` facts. + pub fn new(served: &'a [Fact]) -> Places<'a> { + let mut places = Places::default(); + for fact in served { + match fact.kind.as_str() { + "item" => { + for place in &fact.at { + places + .items + .entry(place.file.as_str()) + .or_default() + .push((place, fact.id.as_str())); + } + } + "package" => { + let path = fact.fields.get("path").and_then(|p| p.as_str()); + places.packages.push((path.unwrap_or(""), fact.id.as_str())); + } + _ => {} + } + } + places + } + + /// The id of the item whose place on `file` holds the 1-based `line`; among several, the one of fewest lines, then + /// the smaller id. `None` when no served item is there. + pub fn innermost(&self, file: &str, line: usize) -> Option<&'a str> { + self.items + .get(file)? + .iter() + .filter(|(place, _)| holds(place, line)) + .min_by_key(|(place, id)| (place.end_line.saturating_sub(place.start_line), *id)) + .map(|(_, id)| *id) + } + + /// The id of the package whose directory is the longest one holding `file` (`""` holds every file, `crates/a` holds + /// `crates/a/x.rs` but not `crates/ab/x.rs`). Of several at that directory (a crate with a `package.json` beside + /// its `Cargo.toml`), the one of the file's ecosystem: the scheme of a served item on it, else its manifest's name + /// or its extension. `None` when that leaves none or several, never the one whose id sorts first. + pub fn package_of(&self, file: &str) -> Option<&'a str> { + let holding = self + .packages + .iter() + .filter(|(path, _)| path.is_empty() || below(file, path)); + let longest = holding.clone().map(|(path, _)| path.len()).max()?; + let tied: Vec<&'a str> = holding + .filter(|(path, _)| path.len() == longest) + .map(|(_, id)| *id) + .collect(); + if let [only] = tied[..] { + return Some(only); + } + let prefix = format!("pkg:{}/", self.purl_type_of(file)?); + match tied + .iter() + .filter(|id| id.starts_with(&prefix)) + .collect::>()[..] + { + [only] => Some(*only), + _ => None, + } + } + + /// The purl type `file` belongs to by its own evidence: the scheme of a served item on it (`rust:` is `cargo`, + /// `js:` is `npm`), else its manifest's name (`Cargo.toml`, `package.json`, …) or its extension (`.rs`; `.js`, + /// `.ts` and their module and JSX forms). `None` without evidence, or with items of both schemes. + fn purl_type_of(&self, file: &str) -> Option<&'static str> { + let mut schemes = self + .items + .get(file) + .into_iter() + .flatten() + .filter_map(|(_, id)| match id.split_once(':')?.0 { + "rust" => Some("cargo"), + "js" => Some("npm"), + _ => None, + }); + if let Some(first) = schemes.next() { + return schemes.all(|other| other == first).then_some(first); + } + let name = file.rsplit('/').next().unwrap_or(file); + let extension = name.rsplit_once('.').map(|(_, extension)| extension); + match (name, extension) { + ("Cargo.toml" | "Cargo.lock", _) | (_, Some("rs")) => Some("cargo"), + ("package.json" | "package-lock.json" | "npm-shrinkwrap.json", _) + | (_, Some("js" | "mjs" | "cjs" | "jsx" | "ts" | "mts" | "cts" | "tsx")) => Some("npm"), + _ => None, + } + } + + /// The ids of the packages of purl type `purl_type` (`pkg:/…`) at the directory `dir`, else of those + /// under it (`""` covers all), sorted. The type is filtered first, so a root `Cargo.lock` beside a root npm package + /// still finds the cargo members below it. + pub fn packages_of_dir(&self, dir: &str, purl_type: &str) -> Vec<&'a str> { + let prefix = format!("pkg:{purl_type}/"); + let typed: Vec<(&str, &'a str)> = self + .packages + .iter() + .filter(|(_, id)| id.starts_with(&prefix)) + .copied() + .collect(); + let mut found: Vec<&'a str> = typed + .iter() + .filter(|(path, _)| *path == dir) + .map(|(_, id)| *id) + .collect(); + if found.is_empty() { + found = typed + .iter() + .filter(|(path, _)| dir.is_empty() || below(path, dir)) + .map(|(_, id)| *id) + .collect(); + } + found.sort_unstable(); + found + } + + /// The served package ids equal to `base` or starting with `base#` (a second package of one name), sorted. + pub fn packages_named(&self, base: &str) -> Vec<&'a str> { + let mut found: Vec<&'a str> = self + .packages + .iter() + .map(|(_, id)| *id) + .filter(|id| { + id.strip_prefix(base) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('#')) + }) + .collect(); + found.sort_unstable(); + found + } +} + +/// Whether `place` holds the 1-based `line`: from its start line to its end, which is exclusive, so a place ending at +/// column 1 of a line does not hold that line. +fn holds(place: &FactLocation, line: usize) -> bool { + place.start_line <= line + && (line < place.end_line || (line == place.end_line && place.end_col > 1)) +} + +/// Whether `path` lies below the directory `dir`: it starts with `dir/`. +fn below(path: &str, dir: &str) -> bool { + path.strip_prefix(dir) + .is_some_and(|rest| rest.starts_with('/')) +} diff --git a/extensions/code/facts/src/report.rs b/extensions/code/facts/src/report.rs new file mode 100644 index 0000000000..b92a4d105b --- /dev/null +++ b/extensions/code/facts/src/report.rs @@ -0,0 +1,162 @@ +//! The shared pieces of the report facts (ADR 0388): the five kinds a standard report mints, what a report leaves +//! unstated, and the id parts and repeat suffixes every report reader builds an id from. + +use std::collections::BTreeMap; + +/// A kind a report reader mints, and the scheme its ids start with (`:…`). These schemes are not +/// [`Scheme`](crate::Scheme)'s, which names test and item ids. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReportKind { + pub kind: &'static str, + pub scheme: &'static str, +} + +/// A coverage report's entry for one file (LCOV). +pub const COVERAGE: ReportKind = ReportKind { + kind: "coverage", + scheme: "cov", +}; +/// One entry of an API snapshot. +pub const API_ITEM: ReportKind = ReportKind { + kind: "api_item", + scheme: "api", +}; +/// One result of a SARIF run; never `finding`, which `@gsd/core` declares (F1). +pub const STATIC_FINDING: ReportKind = ReportKind { + kind: "static_finding", + scheme: "sarif", +}; +/// One component of a CycloneDX bill of materials. +pub const DEPENDENCY: ReportKind = ReportKind { + kind: "dependency", + scheme: "dep", +}; +/// One OSV record. +pub const VULNERABILITY: ReportKind = ReportKind { + kind: "vulnerability", + scheme: "vuln", +}; + +/// The value a field holds when the report does not state it (F5). +pub const UNKNOWN: &str = "unknown"; + +/// What [`id_part`] percent-encodes besides whitespace and control characters: `%` itself and every id delimiter. +const ID_ESCAPES: &[char] = &['%', '/', '#', ':', '~', '@', '?']; + +/// Report text made safe to place in a fact id: `%`, `/`, `#`, `:`, `~`, `@`, `?`, whitespace and control characters +/// percent-encoded as `%XX` (uppercase hex of each UTF-8 byte), every other character kept. Report text can then forge +/// no scheme, separator or repeat suffix, nor carry a terminal escape into a diagnostic naming the id. +pub fn id_part(text: &str) -> String { + encoded(text, char::is_whitespace) +} + +/// [`id_part`] with a plain space kept: a Rust path segment of an `api_item` id, whose owner a Rust type writes with +/// spaces (``, `dyn Tr`) as the item id it names does. +pub(crate) fn rust_id_part(text: &str) -> String { + encoded(text, |c| c.is_whitespace() && c != ' ') +} + +/// `text` with every id delimiter, control character and character `space` encodes percent-encoded. +fn encoded(text: &str, space: impl Fn(char) -> bool) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + if ID_ESCAPES.contains(&c) || space(c) || c.is_control() { + let mut bytes = [0; 4]; + for byte in c.encode_utf8(&mut bytes).bytes() { + out.push_str(&format!("%{byte:02X}")); + } + } else { + out.push(c); + } + } + out +} + +/// The most characters of report text [`shown`] keeps. +const SHOWN: usize = 80; + +/// Report text made safe to place in an error or a diagnostic message: its first 80 characters, control characters, +/// quotes and backslashes escaped as Rust writes them (`\u{1b}`, `\"`), and `…` when more followed. A report can then +/// carry no terminal escape, nor a megabyte of text, into the user's terminal or a log. +pub fn shown(text: &str) -> String { + let mut shown: String = text + .chars() + .take(SHOWN) + .flat_map(char::escape_debug) + .collect(); + if text.chars().nth(SHOWN).is_some() { + shown.push('…'); + } + shown +} + +/// A report's JSON value made safe to place in a message as [`shown`] does: a string quoted (`"2.0"`), any other value +/// as its JSON text, either way bounded and escaped. +pub fn shown_json(value: &serde_json::Value) -> String { + match value { + serde_json::Value::String(text) => format!("\"{}\"", shown(text)), + other => shown(&other.to_string()), + } +} + +/// `text` with each `%XX` (`%` and two ASCII hex digits) decoded: an id this crate wrote, or a report's URI. A `%` +/// that starts no such escape is kept, and so is a run of escapes whose bytes are no UTF-8, spelled as written, while +/// every other escape of `text` still decodes. +pub(crate) fn unescape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(at) = rest.find('%') { + out.push_str(&rest[..at]); + let run = &rest[at..]; + let mut bytes = Vec::new(); + while let Some(byte) = escaped_byte(&run[3 * bytes.len()..]) { + bytes.push(byte); + } + if bytes.is_empty() { + out.push('%'); + rest = &run[1..]; + continue; + } + // Each byte of the run is the three characters `%XX` of `run`, so an invalid one is kept as written. + let mut done = 0; + for chunk in bytes.utf8_chunks() { + out.push_str(chunk.valid()); + done += chunk.valid().len(); + let invalid = chunk.invalid().len(); + out.push_str(&run[3 * done..3 * (done + invalid)]); + done += invalid; + } + rest = &run[3 * bytes.len()..]; + } + out.push_str(rest); + out +} + +/// The byte `text`'s leading `%XX` encodes, if it starts with `%` and two ASCII hex digits (no sign, as +/// `u8::from_str_radix` would take). +fn escaped_byte(text: &str) -> Option { + let pair = text.strip_prefix('%')?.get(..2)?; + if !pair.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + u8::from_str_radix(pair, 16).ok() +} + +/// The ids a reader has answered so far, so one answered twice gets a suffix: the host refuses a collect that answers +/// one id twice (F4). +#[derive(Debug, Default)] +pub struct Repeats { + seen: BTreeMap, +} + +impl Repeats { + /// `base` the first time it is asked, then `base~2`, `base~3`, …, in the order asked (document order). + pub fn id(&mut self, base: String) -> String { + let count = self.seen.entry(base.clone()).or_insert(0); + *count += 1; + match *count { + 1 => base, + n => format!("{base}~{n}"), + } + } +} diff --git a/extensions/code/facts/src/tests.rs b/extensions/code/facts/src/tests.rs index af39738f60..faf81a9697 100644 --- a/extensions/code/facts/src/tests.rs +++ b/extensions/code/facts/src/tests.rs @@ -3,8 +3,18 @@ use std::collections::BTreeSet; use super::*; use specforge_test::prelude::*; +mod accepted; +mod api; +mod coverage; +mod cvss; +mod dependency; +mod finding; mod mint; +mod paths; +mod places; +mod report; mod syntax; +mod vulnerability; fn strings(items: &[&str]) -> Vec { items.iter().map(|s| s.to_string()).collect() diff --git a/extensions/code/facts/src/tests/accepted.rs b/extensions/code/facts/src/tests/accepted.rs new file mode 100644 index 0000000000..a64426a330 --- /dev/null +++ b/extensions/code/facts/src/tests/accepted.rs @@ -0,0 +1,437 @@ +//! An API snapshot's entries judged against the committed accepted report (ADR 0390 D3): pairing, narrowing, +//! one-sided containers and Rust lines. + +use crate::*; +use specforge_extension_sdk::prelude::Fact; + +const FUNCTION: ApiKind = ApiKind::Item(ItemKind::Function); + +/// A JavaScript entry of package `@demo/w` at `path` (`.`-joined), written `signature`, tagged `tag`. +fn js(path: &str, signature: &str, tag: &str) -> ApiEntry { + js_in("@demo/w", path, signature, tag) +} + +fn js_in(package: &str, path: &str, signature: &str, tag: &str) -> ApiEntry { + ApiEntry { + scheme: Scheme::Js, + container: package.to_string(), + path: path.split('.').map(str::to_string).collect(), + owner: None, + kind: FUNCTION, + visibility: Visibility::Public, + signature: signature.to_string(), + tag: Some(tag.to_string()), + } +} + +/// A Rust function `name` of crate `demo`, its whole line `line`, of `visibility`. +fn rust(name: &str, line: &str, visibility: Visibility) -> ApiEntry { + ApiEntry { + scheme: Scheme::Rust, + container: "demo".to_string(), + path: vec!["demo".to_string(), name.to_string()], + owner: None, + kind: FUNCTION, + visibility, + signature: line.to_string(), + tag: None, + } +} + +fn field<'f>(fact: &'f Fact, name: &str) -> Option<&'f str> { + fact.fields.get(name).and_then(|value| value.as_str()) +} + +/// Each fact's id, `change`, `signature` and `accepted_signature`. +fn judged(facts: &[Fact]) -> Vec<(&str, Option<&str>, &str, Option<&str>)> { + facts + .iter() + .map(|f| { + ( + f.id.as_str(), + field(f, "change"), + field(f, "signature").unwrap_or_default(), + field(f, "accepted_signature"), + ) + }) + .collect() +} + +/// The one fact of `facts` whose signature is `signature`. +fn written<'f>(facts: &'f [Fact], signature: &str) -> &'f Fact { + let found: Vec<&Fact> = facts + .iter() + .filter(|f| field(f, "signature") == Some(signature)) + .collect(); + assert_eq!(found.len(), 1, "{signature} in {facts:?}"); + found[0] +} + +const F: &str = "api:js:%40demo%2Fw::f"; + +#[test] +fn the_comparison_key_bridges_the_report_and_the_doc_model() { + let js = |signature| comparable(Scheme::Js, signature); + let rust = |signature| comparable(Scheme::Rust, signature); + let key = "function create(o: Options): Widget"; + assert_eq!( + js("export declare function create(o: Options): Widget;"), + key + ); + assert_eq!(js("export function create(o: Options):\n Widget;"), key); + assert_eq!(js("LIMIT = 3"), js("const LIMIT = 3;")); + assert_eq!(js("A = 1"), js("A = 1,")); + assert_eq!(js("export declare class W "), js("export class W {")); + assert_eq!(rust("pub fn demo::f()"), rust("pub(crate) fn demo::f()")); + assert_eq!( + rust("#[non_exhaustive] pub struct demo::S"), + "#[non_exhaustive] struct demo::S" + ); + assert_ne!( + rust("pub fn demo::f(a: u8)"), + rust("pub fn demo::f(a: u16)") + ); + assert_eq!(js("publish(): void;"), "publish(): void"); + // The visibility word is Rust's: a JavaScript function named `pub` keeps its parameters. + assert_eq!( + js("export function pub(a: string): void;"), + "function pub(a: string): void" + ); + assert_ne!( + js("export function pub(a: string): void;"), + js("export function pub(a: number): void;") + ); + assert_eq!( + ApiChange::NAMES, + ["added", "unchanged", "changed", "narrowed", "removed"] + ); +} + +#[test] +fn an_overload_inserted_before_another_leaves_it_unchanged() { + let accepted = [js("f", "export function f(a: number): void;", "Public")]; + let fresh = [ + js("f", "export declare function f(s: string): void;", "Public"), + js("f", "export declare function f(a: number): void;", "Public"), + ]; + let facts = api_facts_against(&fresh, &accepted, &[]); + let ids: Vec = vec![F.to_string(), format!("{F}~2")]; + assert_eq!( + facts.iter().map(|f| &f.id).collect::>(), + ids.iter().collect::>() + ); + assert_eq!( + field( + written(&facts, "export declare function f(s: string): void;"), + "change" + ), + Some("added") + ); + assert_eq!( + field( + written(&facts, "export declare function f(a: number): void;"), + "change" + ), + Some("unchanged") + ); +} + +#[test] +fn two_changed_overloads_pair_in_document_order() { + let accepted = [ + js("f", "export function f(a: number): void;", "Public"), + js("f", "export function f(a: string): void;", "Public"), + ]; + let fresh = [ + js("f", "export declare function f(a: bigint): void;", "Public"), + js( + "f", + "export declare function f(a: boolean): void;", + "Public", + ), + ]; + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!( + judged(&facts), + [ + ( + F, + Some("changed"), + "export declare function f(a: bigint): void;", + Some("export function f(a: number): void;") + ), + ( + &*format!("{F}~2"), + Some("changed"), + "export declare function f(a: boolean): void;", + Some("export function f(a: string): void;") + ), + ] + ); +} + +#[test] +fn a_removed_entry_takes_the_next_repeat_suffix_after_the_runs() { + let accepted = [ + js("f", "export function f(a: number): void;", "Public"), + js("f", "export function f(a: string): void;", "Public"), + ]; + let fresh = [js( + "f", + "export declare function f(a: number): void;", + "Public", + )]; + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!( + judged(&facts), + [ + ( + F, + Some("unchanged"), + "export declare function f(a: number): void;", + None + ), + ( + &*format!("{F}~2"), + Some("removed"), + "export function f(a: string): void;", + Some("export function f(a: string): void;") + ), + ] + ); + assert_eq!(field(&facts[1], "accepted_tag"), Some("Public")); + assert!(!facts[1].fields.contains_key("item")); +} + +#[test] +fn a_container_on_one_side_only_is_not_judged() { + let fresh = [ + js_in("a", "f", "export declare function f(): void;", "Public"), + js_in("b", "g", "export declare function g(): void;", "Public"), + ]; + let accepted = [ + js_in("a", "f", "export function f(): void;", "Public"), + js_in("c", "h", "export function h(): void;", "Public"), + ]; + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!( + judged(&facts), + [ + ( + "api:js:a::f", + Some("unchanged"), + "export declare function f(): void;", + None + ), + ( + "api:js:b::g", + None, + "export declare function g(): void;", + None + ), + ] + ); + assert_eq!(facts[1], api_facts(&fresh[1..], &[])[0]); +} + +#[test] +fn an_accepted_internal_entry_with_no_counterpart_mints_nothing() { + let accepted = [ + js("f", "export function f(): void;", "Public"), + js("_hidden", "export function _hidden(): void;", "Internal"), + ]; + let fresh = [js("f", "export declare function f(): void;", "Public")]; + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!(facts.len(), 1, "{facts:?}"); + assert_eq!(field(&facts[0], "change"), Some("unchanged")); +} + +#[test] +fn a_wider_tag_is_unchanged() { + let accepted = [js("f", "export function f(): void;", "Beta")]; + let fresh = [js("f", "export declare function f(): void;", "Public")]; + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!(field(&facts[0], "change"), Some("unchanged")); + assert!(!facts[0].fields.contains_key("accepted_tag")); +} + +#[test] +fn a_narrower_tag_with_another_signature_is_changed_naming_the_accepted_tag() { + let accepted = [js("f", "export function f(): void;", "Public")]; + let fresh = [js( + "f", + "export declare function f(a: number): void;", + "Beta", + )]; + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!(field(&facts[0], "change"), Some("changed")); + assert_eq!(field(&facts[0], "accepted_tag"), Some("Public")); + assert_eq!(field(&facts[0], "tag"), Some("Beta")); +} + +#[test] +fn a_class_narrowed_to_beta_narrows_each_member_inheriting_its_tag() { + let accepted = [ + js("W", "export class W {", "Public"), + js("W.render", "render(): string;", "Public"), + js("W.size", "size: number;", "Public"), + js("W.beta", "beta(): void;", "Beta"), + ]; + let fresh = [ + js("W", "export declare class W ", "Beta"), + js("W.render", "render(): string;", "Beta"), + js("W.size", "size: number;", "Beta"), + js("W.beta", "beta(): void;", "Beta"), + ]; + let facts = api_facts_against(&fresh, &accepted, &[]); + let changes: Vec<(&str, Option<&str>, Option<&str>)> = facts + .iter() + .map(|f| (f.id.as_str(), field(f, "change"), field(f, "accepted_tag"))) + .collect(); + assert_eq!( + changes, + [ + ("api:js:%40demo%2Fw::W", Some("narrowed"), Some("Public")), + ("api:js:%40demo%2Fw::W.beta", Some("unchanged"), None), + ( + "api:js:%40demo%2Fw::W.render", + Some("narrowed"), + Some("Public") + ), + ( + "api:js:%40demo%2Fw::W.size", + Some("narrowed"), + Some("Public") + ), + ] + ); +} + +#[test] +fn a_rename_is_one_removed_and_one_added() { + let accepted = [js("f", "export function f(): void;", "Public")]; + let fresh = [js("g", "export declare function g(): void;", "Public")]; + let facts = api_facts_against(&fresh, &accepted, &[]); + let changes: Vec<(&str, Option<&str>)> = facts + .iter() + .map(|f| (f.id.as_str(), field(f, "change"))) + .collect(); + assert_eq!( + changes, + [ + (F, Some("removed")), + ("api:js:%40demo%2Fw::g", Some("added")) + ] + ); +} + +#[test] +fn a_rust_line_on_both_sides_is_unchanged_and_another_parameter_type_is_changed() { + let accepted = [ + rust("same", "pub fn demo::same()", Visibility::Public), + rust("f", "pub fn demo::f(a: u8)", Visibility::Public), + ]; + let fresh = [ + rust("same", "pub fn demo::same()", Visibility::Public), + rust("f", "pub fn demo::f(a: u16)", Visibility::Public), + ]; + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!( + judged(&facts), + [ + ( + "api:rust:demo::f", + Some("changed"), + "pub fn demo::f(a: u16)", + Some("pub fn demo::f(a: u8)") + ), + ( + "api:rust:demo::same", + Some("unchanged"), + "pub fn demo::same()", + None + ), + ] + ); + assert!(facts + .iter() + .all(|f| !f.fields.contains_key("accepted_tag") + && !f.fields.contains_key("accepted_visibility"))); +} + +#[test] +fn a_rust_line_gone_is_removed() { + let accepted = [ + rust("kept", "pub fn demo::kept()", Visibility::Public), + rust("gone", "pub fn demo::gone()", Visibility::Public), + ]; + let fresh = [rust("kept", "pub fn demo::kept()", Visibility::Public)]; + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!( + judged(&facts)[0], + ( + "api:rust:demo::gone", + Some("removed"), + "pub fn demo::gone()", + Some("pub fn demo::gone()") + ) + ); + assert_eq!(field(&facts[0], "visibility"), Some("public")); +} + +#[test] +fn a_rust_item_made_pub_crate_is_narrowed_naming_the_accepted_visibility() { + let accepted = [rust("f", "pub fn demo::f()", Visibility::Public)]; + let fresh = [rust("f", "pub(crate) fn demo::f()", Visibility::Crate)]; + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!(field(&facts[0], "change"), Some("narrowed")); + assert_eq!(field(&facts[0], "accepted_visibility"), Some("public")); + assert_eq!( + field(&facts[0], "accepted_signature"), + Some("pub fn demo::f()") + ); + // The other way is wider: unchanged. + let wider = api_facts_against(&accepted, &fresh, &[]); + assert_eq!(field(&wider[0], "change"), Some("unchanged")); +} + +#[test] +fn a_rust_attribute_added_reads_changed_whatever_it_means() { + let accepted = [rust("S", "pub struct demo::S", Visibility::Public)]; + let fresh = [rust( + "S", + "#[non_exhaustive] pub struct demo::S", + Visibility::Public, + )]; + let facts = api_facts_against(&fresh, &accepted, &[]); + assert_eq!(field(&facts[0], "change"), Some("changed")); +} + +#[test] +fn a_forged_accepted_name_is_minted_encoded_and_collides_with_no_fresh_id() { + let fresh = [ + js("f", "export declare function f(a: number): void;", "Public"), + js("f", "export declare function f(a: string): void;", "Public"), + ]; + let mut accepted = vec![ + js("f", "export function f(a: number): void;", "Public"), + js("f", "export function f(a: string): void;", "Public"), + ]; + for forged in ["f~2", "f#x", "f@y"] { + accepted.push(js(forged, "export function forged(): void;", "Public")); + } + let facts = api_facts_against(&fresh, &accepted, &[]); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + [ + F, + "api:js:%40demo%2Fw::f%23x", + "api:js:%40demo%2Fw::f%40y", + "api:js:%40demo%2Fw::f%7E2", + "api:js:%40demo%2Fw::f~2", + ], + "five entries, five facts: none overwrites another" + ); + assert_eq!(field(&facts[4], "change"), Some("unchanged")); +} diff --git a/extensions/code/facts/src/tests/api.rs b/extensions/code/facts/src/tests/api.rs new file mode 100644 index 0000000000..0b19102c73 --- /dev/null +++ b/extensions/code/facts/src/tests/api.rs @@ -0,0 +1,312 @@ +//! The `api_item` facts minted from an API snapshot's entries and the served items. + +use crate::*; +use specforge_extension_sdk::prelude::Fact; + +fn item(id: &str) -> Fact { + Fact::new("item", id) +} + +fn strings(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() +} + +/// A public Rust entry of `kind` at `path` (the crate first), written `signature`. +fn rust(path: &[&str], owner: Option, kind: ApiKind, signature: &str) -> ApiEntry { + ApiEntry { + scheme: Scheme::Rust, + container: path[0].to_string(), + path: strings(path), + owner, + kind, + visibility: Visibility::Public, + signature: signature.to_string(), + tag: None, + } +} + +fn owner(self_ty: &str, trait_ty: Option<&str>) -> Option { + Some(Owner { + self_ty: self_ty.to_string(), + trait_ty: trait_ty.map(str::to_string), + }) +} + +fn field<'f>(fact: &'f Fact, name: &str) -> Option<&'f str> { + fact.fields.get(name).and_then(|value| value.as_str()) +} + +const FUNCTION: ApiKind = ApiKind::Item(ItemKind::Function); +const METHOD: ApiKind = ApiKind::Item(ItemKind::Method); + +#[test] +fn the_kind_vocabulary_is_the_item_kinds_then_four_more() { + assert_eq!(&ApiKind::NAMES[..16], &ItemKind::NAMES[..]); + assert_eq!( + &ApiKind::NAMES[16..], + &["variant", "reexport", "extern_crate", "other"] + ); + assert_eq!(ApiKind::ExternCrate.as_str(), "extern_crate"); + assert_eq!(METHOD.as_str(), "method"); + assert!(METHOD.is_item() && !ApiKind::Reexport.is_item()); +} + +#[test] +fn a_snapshot_crate_maps_to_the_served_lib_reading_dash_as_underscore() { + let entries = [rust( + &["example_api", "function"], + None, + FUNCTION, + "pub fn example_api::function()", + )]; + let served = [ + item("rust:example-api::function"), + item("rust:example-api/bin/tool::function"), + ]; + let facts = api_facts(&entries, &served); + assert_eq!(facts.len(), 1); + assert_eq!(facts[0].id, "api:rust:example_api::function"); + assert_eq!(field(&facts[0], "item"), Some("rust:example-api::function")); + assert_eq!(field(&facts[0], "path"), Some("example_api::function")); + assert_eq!(field(&facts[0], "kind"), Some("function")); + assert_eq!(field(&facts[0], "visibility"), Some("public")); +} + +#[test] +fn two_trait_impls_of_one_type_are_two_facts_each_citing_its_item() { + let debug = "pub fn example_api::Struct::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result"; + let entries = [ + rust( + &["example_api", "Struct", "fmt"], + owner("example_api::Struct", Some("core::fmt::Debug")), + METHOD, + debug, + ), + rust( + &["example_api", "Struct", "fmt"], + owner("example_api::Struct", Some("core::fmt::Display")), + METHOD, + debug, + ), + ]; + let served = [ + item("rust:example-api::::fmt"), + item("rust:example-api::::fmt"), + ]; + let facts = api_facts(&entries, &served); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + [ + "api:rust:example_api::::fmt", + "api:rust:example_api::::fmt" + ] + ); + assert_eq!( + field(&facts[1], "item"), + Some("rust:example-api::::fmt") + ); +} + +#[test] +fn an_entry_repeated_merges_and_another_signature_takes_a_suffix() { + let entries = [ + rust(&["demo", "f"], None, FUNCTION, "pub fn demo::f()"), + rust(&["demo", "f"], None, FUNCTION, "pub fn demo::f()"), + rust(&["demo", "f"], None, FUNCTION, "pub fn demo::f(x: u8)"), + ]; + let facts = api_facts(&entries, &[item("rust:demo::f")]); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!(ids, ["api:rust:demo::f", "api:rust:demo::f~2"]); + assert_eq!(field(&facts[1], "signature"), Some("pub fn demo::f(x: u8)")); +} + +#[test] +fn a_rust_path_is_encoded_in_the_id_and_cannot_forge_a_suffix() { + let entries = [ + rust(&["c", "a~2"], None, FUNCTION, "pub fn c::a~2()"), + rust(&["c", "a"], None, FUNCTION, "pub fn c::a(x: u8)"), + rust(&["c", "a"], None, FUNCTION, "pub fn c::a(y: u16)"), + rust(&["c", "e\u{1b}#?@/%"], None, FUNCTION, "pub fn c::e()"), + rust( + &["c:x"], + None, + ApiKind::Item(ItemKind::Module), + "pub mod c:x", + ), + ]; + let facts = api_facts(&entries, &[item("rust:c::a")]); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + [ + "api:rust:c%3Ax", + "api:rust:c::a", + "api:rust:c::a%7E2", + "api:rust:c::a~2", + "api:rust:c::e%1B%23%3F%40%2F%25", + ] + ); + // The item is still looked up by the unencoded path; only the fact's own id is encoded. + assert_eq!(field(&facts[1], "item"), Some("rust:c::a")); + assert_eq!(field(&facts[2], "path"), Some("c::a~2")); +} + +#[test] +fn an_owner_keeps_its_spaces_and_encodes_its_other_text() { + let entries = [rust( + &["demo", "f"], + owner("&'a demo::S", Some("demo::Tr")), + METHOD, + "pub fn demo::f()", + )]; + let facts = api_facts(&entries, &[]); + assert_eq!(facts[0].id, "api:rust:demo::<&'a demo%3A%3AS as Tr>::f"); +} + +#[test] +fn a_reexported_path_or_an_ambiguous_crate_cites_nothing() { + // `demo::S` is defined in `demo::inner`: its public path names no served item. + let reexported = rust( + &["demo", "S"], + None, + ApiKind::Item(ItemKind::Struct), + "pub struct demo::S", + ); + let facts = api_facts(&[reexported], &[item("rust:demo::inner::S")]); + assert_eq!(facts[0].id, "api:rust:demo::S"); + assert_eq!(field(&facts[0], "item"), None); + // Two libs read as one crate: neither is cited. + let ambiguous = rust( + &["de_mo", "S"], + None, + ApiKind::Item(ItemKind::Struct), + "pub struct de_mo::S", + ); + let facts = api_facts( + &[ambiguous], + &[item("rust:de-mo::S"), item("rust:de_mo::S")], + ); + assert_eq!(field(&facts[0], "item"), None); +} + +#[test] +fn a_variant_reexport_or_crate_root_cites_no_item() { + let entries = [ + rust( + &["demo"], + None, + ApiKind::Item(ItemKind::Module), + "pub mod demo", + ), + rust( + &["demo", "E", "A"], + None, + ApiKind::Variant, + "pub demo::E::A", + ), + rust(&["demo", "E"], None, ApiKind::Reexport, "pub use demo::E"), + ]; + let served = [item("rust:demo::E::A"), item("rust:demo::E")]; + let facts = api_facts(&entries, &served); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + ["api:rust:demo", "api:rust:demo::E", "api:rust:demo::E::A"] + ); + assert!( + facts.iter().all(|f| field(f, "item").is_none()), + "{facts:?}" + ); +} + +/// A public JavaScript entry of the package `@demo/widget` at the name path `path`, written `signature`. +fn js(path: &[&str], kind: ApiKind, signature: &str) -> ApiEntry { + ApiEntry { + scheme: Scheme::Js, + container: "@demo/widget".to_string(), + path: strings(path), + owner: None, + kind, + visibility: Visibility::Public, + signature: signature.to_string(), + tag: Some("Public".to_string()), + } +} + +#[test] +fn a_js_entry_cites_the_one_served_item_of_its_package_with_its_name_path() { + let entries = [ + js(&["Widget", "render"], METHOD, "render(): string;"), + js( + &["VERSION"], + ApiKind::Item(ItemKind::Variable), + "VERSION: string", + ), + js( + &["util"], + ApiKind::Item(ItemKind::Namespace), + "namespace util", + ), + ]; + let served = [ + item("js:@demo/widget/src/widget.ts::Widget.render"), + item("js:@demo/widget/src/index.ts::VERSION"), + item("js:@demo/widget/src/version.ts::VERSION"), + item("js:@demo/widget-extra/src/util.ts::util"), + ]; + let facts = api_facts(&entries, &served); + let cited: Vec<(&str, Option<&str>)> = facts + .iter() + .map(|f| (f.id.as_str(), field(f, "item"))) + .collect(); + assert_eq!( + cited, + [ + ("api:js:%40demo%2Fwidget::VERSION", None), + ( + "api:js:%40demo%2Fwidget::Widget.render", + Some("js:@demo/widget/src/widget.ts::Widget.render") + ), + ("api:js:%40demo%2Fwidget::util", None), + ] + ); + assert_eq!(field(&facts[1], "path"), Some("Widget.render")); + assert_eq!(field(&facts[1], "tag"), Some("Public")); +} + +#[test] +fn a_js_overload_takes_a_suffix_and_a_name_cannot_forge_one() { + let entries = [ + js(&["parse"], FUNCTION, "parse(text: string): Widget;"), + js(&["parse"], FUNCTION, "parse(bytes: Uint8Array): Widget;"), + js(&["parse~2"], FUNCTION, "a name holding a tilde"), + ]; + let facts = api_facts(&entries, &[]); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + [ + "api:js:%40demo%2Fwidget::parse", + "api:js:%40demo%2Fwidget::parse%7E2", + "api:js:%40demo%2Fwidget::parse~2" + ] + ); +} + +#[test] +fn a_dotted_js_name_and_a_member_path_are_two_ids() { + let entries = [ + js(&["a.b"], FUNCTION, "\"a.b\": () => void"), + js(&["a", "b"], METHOD, "b(): void;"), + ]; + let facts = api_facts(&entries, &[]); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + [ + "api:js:%40demo%2Fwidget::a%2Eb", + "api:js:%40demo%2Fwidget::a.b" + ] + ); +} diff --git a/extensions/code/facts/src/tests/coverage.rs b/extensions/code/facts/src/tests/coverage.rs new file mode 100644 index 0000000000..e0da52efcd --- /dev/null +++ b/extensions/code/facts/src/tests/coverage.rs @@ -0,0 +1,220 @@ +//! The `coverage` facts minted from a coverage report's files and the served items. + +use crate::*; +use specforge_extension_sdk::prelude::{Fact, FactLocation}; + +fn item(id: &str, file: &str, start: usize, end: usize) -> Fact { + Fact::new("item", id).at(FactLocation { + file: file.to_string(), + start_line: start, + start_col: 1, + end_line: end, + end_col: 2, + }) +} + +/// `mod tests` at lines 10-30 holding `fn adds` at 12-16, and `fn add` at 1-5. +fn served() -> Vec { + vec![ + item("rust:demo::add", "src/lib.rs", 1, 5), + item("rust:demo::tests", "src/lib.rs", 10, 30), + item("rust:demo::tests::adds", "src/lib.rs", 12, 16), + ] +} + +fn function(line: usize, name: &str, hits: u64) -> Function { + Function { + line, + name: name.to_string(), + hits, + } +} + +fn branch(line: usize, branch: &str, taken: Option) -> Branch { + Branch { + line, + block: "0".to_string(), + branch: branch.to_string(), + taken, + } +} + +fn lib(functions: Vec, lines: Vec<(usize, u64)>, branches: Vec) -> CoverageFile { + CoverageFile { + file: "src/lib.rs".to_string(), + functions, + lines, + branches, + } +} + +/// The fact `id` of `facts`. +fn fact<'f>(facts: &'f [Fact], id: &str) -> &'f Fact { + facts + .iter() + .find(|f| f.id == id) + .unwrap_or_else(|| panic!("no fact {id} in {facts:?}")) +} + +/// The integer field `name` of `fact`. +fn count(fact: &Fact, name: &str) -> Option { + fact.fields.get(name).and_then(|v| v.as_u64()) +} + +#[test] +fn an_item_counts_its_functions_lines_and_branches() { + let files = [lib( + vec![function(1, "add", 3), function(1, "add_u8", 0)], + vec![(2, 3), (3, 0), (4, 1)], + vec![ + branch(3, "0", Some(2)), + branch(3, "1", Some(0)), + branch(4, "0", None), + ], + )]; + let facts = coverage_facts(&files, &served()); + assert_eq!(facts.len(), 1, "{facts:?}"); + let add = fact(&facts, "cov:rust:demo::add"); + assert_eq!(add.kind, "coverage"); + assert_eq!(add.fields["item"], "rust:demo::add"); + assert_eq!(add.fields["file"], "src/lib.rs"); + let counts: Vec> = [ + "functions_found", + "functions_hit", + "lines_found", + "lines_hit", + "branches_found", + "branches_hit", + ] + .iter() + .map(|name| count(add, name)) + .collect(); + assert_eq!( + counts, + [Some(2), Some(1), Some(3), Some(2), Some(3), Some(1)] + ); + assert!(add.at.is_empty()); +} + +#[test] +fn a_line_counts_for_the_innermost_item_holding_it() { + let files = [lib(vec![], vec![(13, 1), (20, 1), (21, 0)], vec![])]; + let facts = coverage_facts(&files, &served()); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!(ids, ["cov:rust:demo::tests", "cov:rust:demo::tests::adds"]); + let adds = fact(&facts, "cov:rust:demo::tests::adds"); + assert_eq!( + (count(adds, "lines_found"), count(adds, "lines_hit")), + (Some(1), Some(1)) + ); + let module = fact(&facts, "cov:rust:demo::tests"); + assert_eq!( + (count(module, "lines_found"), count(module, "lines_hit")), + (Some(2), Some(1)) + ); +} + +#[test] +fn what_no_item_holds_is_kept_per_file_with_no_item() { + let files = [ + lib(vec![function(0, "orphan", 1)], vec![(7, 1)], vec![]), + CoverageFile { + file: "src/bin/my tool.rs".to_string(), + lines: vec![(1, 0)], + ..CoverageFile::default() + }, + ]; + let facts = coverage_facts(&files, &served()); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!(ids, ["cov:@src%2Fbin%2Fmy%20tool.rs", "cov:@src%2Flib.rs"]); + let unheld = fact(&facts, "cov:@src%2Flib.rs"); + assert!(!unheld.fields.contains_key("item")); + assert_eq!(unheld.fields["file"], "src/lib.rs"); + assert_eq!( + (count(unheld, "functions_found"), count(unheld, "lines_hit")), + (Some(1), Some(1)) + ); + let tool = fact(&facts, "cov:@src%2Fbin%2Fmy%20tool.rs"); + assert_eq!(tool.fields["file"], "src/bin/my tool.rs"); + assert_eq!(count(tool, "lines_found"), Some(1)); + assert_eq!(count(tool, "functions_found"), None); +} + +#[test] +fn two_sections_of_one_file_merge() { + let files = [ + lib(vec![function(1, "add", 0)], vec![(2, 0), (3, 0)], vec![]), + lib( + vec![function(1, "add", 2)], + vec![(2, 1)], + vec![branch(2, "0", None)], + ), + lib(vec![], vec![], vec![branch(2, "0", Some(0))]), + ]; + let facts = coverage_facts(&files, &served()); + let add = fact(&facts, "cov:rust:demo::add"); + assert_eq!( + (count(add, "functions_found"), count(add, "functions_hit")), + (Some(1), Some(1)) + ); + assert_eq!( + (count(add, "lines_found"), count(add, "lines_hit")), + (Some(2), Some(1)) + ); + // `-` then `0`: evaluated, never taken. + assert_eq!( + (count(add, "branches_found"), count(add, "branches_hit")), + (Some(1), Some(0)) + ); +} + +#[test] +fn a_repeated_function_counts_once() { + let files = [lib( + vec![ + function(1, "add", 1), + function(1, "add", 1), + function(2, "add", 0), + ], + vec![], + vec![], + )]; + let facts = coverage_facts(&files, &served()); + assert_eq!(facts.len(), 1); + let add = fact(&facts, "cov:rust:demo::add"); + assert_eq!( + (count(add, "functions_found"), count(add, "functions_hit")), + (Some(2), Some(1)) + ); +} + +#[test] +fn a_file_with_no_branch_record_has_no_branch_fields() { + let files = [lib(vec![], vec![(2, 1)], vec![])]; + let facts = coverage_facts(&files, &served()); + let add = fact(&facts, "cov:rust:demo::add"); + let names: Vec<&str> = add.fields.keys().map(String::as_str).collect(); + assert_eq!(names, ["file", "item", "lines_found", "lines_hit"]); +} + +#[test] +fn a_family_the_file_holds_counts_zero_for_an_item_it_misses() { + // The file has branches, all in `add`; `adds` gets branch counts of zero, since the report measured branches there. + let files = [lib( + vec![], + vec![(2, 1), (13, 1)], + vec![branch(2, "0", Some(1))], + )]; + let facts = coverage_facts(&files, &served()); + let adds = fact(&facts, "cov:rust:demo::tests::adds"); + assert_eq!( + (count(adds, "branches_found"), count(adds, "branches_hit")), + (Some(0), Some(0)) + ); +} + +#[test] +fn no_record_mints_nothing() { + assert!(coverage_facts(&[], &served()).is_empty()); + assert!(coverage_facts(&[lib(vec![], vec![], vec![])], &served()).is_empty()); +} diff --git a/extensions/code/facts/src/tests/cvss.rs b/extensions/code/facts/src/tests/cvss.rs new file mode 100644 index 0000000000..eec5a1c82a --- /dev/null +++ b/extensions/code/facts/src/tests/cvss.rs @@ -0,0 +1,68 @@ +//! CVSS v3.x base scores, in tenths, and the severity they rate. + +use crate::*; + +#[test] +fn the_research_vectors_give_their_published_base_scores() { + for (vector, tenths) in [ + ("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", 98), + ("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H", 100), + ("CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:L/I:L/A:N", 38), + ("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", 75), + ("CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:L/I:L/A:N", 64), + ("CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", 78), + ("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N", 0), + ("CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", 61), + ] { + assert_eq!(cvss::base_score(vector), Some(tenths), "{vector}"); + } +} + +#[test] +fn order_the_v3_0_prefix_and_temporal_metrics_change_nothing() { + for vector in [ + "CVSS:3.1/A:H/I:H/C:H/S:U/UI:N/PR:N/AC:L/AV:N", + "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", + "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H/E:U/RL:O/RC:C", + "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H/CR:H/MAV:L/MS:C", + ] { + assert_eq!(cvss::base_score(vector), Some(98), "{vector}"); + } +} + +#[test] +fn a_vector_this_reader_cannot_rate_has_no_score() { + for vector in [ + "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H", + "CVSS:3.1/AV:N/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", + "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H/E:U/E:U", + "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H/XX:N", + "CVSS:3.1/AV:Q/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", + "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H/E:Z", + "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H/", + "CVSS:3.1/AVN/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", + "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N", + "AV:N/AC:L/Au:N/C:P/I:P/A:P", + "CVSS:2.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", + "", + ] { + assert_eq!(cvss::base_score(vector), None, "{vector:?}"); + } +} + +#[test] +fn a_rating_bands_the_tenths_and_none_reads_low() { + for (tenths, rating) in [ + (0, "low"), + (1, "low"), + (39, "low"), + (40, "medium"), + (69, "medium"), + (70, "high"), + (89, "high"), + (90, "critical"), + (100, "critical"), + ] { + assert_eq!(cvss::rating(tenths).as_str(), rating, "{tenths}"); + } +} diff --git a/extensions/code/facts/src/tests/dependency.rs b/extensions/code/facts/src/tests/dependency.rs new file mode 100644 index 0000000000..ea933498dd --- /dev/null +++ b/extensions/code/facts/src/tests/dependency.rs @@ -0,0 +1,223 @@ +//! The `dependency` facts minted from a CycloneDX reader's BOMs and the served packages. + +use crate::*; +use specforge_extension_sdk::prelude::Fact; + +fn package(id: &str) -> Fact { + Fact::new("package", id).field("path", "") +} + +fn component(bom_ref: Option<&str>, purl: Option<&str>, name: &str, scope: Scope) -> Component { + Component { + bom_ref: bom_ref.map(str::to_string), + purl: purl.map(str::to_string), + group: None, + name: name.to_string(), + version: Some("1.0.0".to_string()), + scope, + } +} + +fn bom(root_purl: &str, components: Vec, direct: Option<&[&str]>) -> Bom { + Bom { + root: component(Some("root"), Some(root_purl), "root", Scope::Required), + components, + direct: direct.map(|refs| refs.iter().map(|r| r.to_string()).collect()), + } +} + +fn field<'f>(fact: &'f Fact, name: &str) -> Option<&'f serde_json::Value> { + fact.fields.get(name) +} + +#[test] +fn a_bom_root_resolves_by_its_purl_without_version_or_qualifiers() { + let served = [package("pkg:cargo/demo"), package("pkg:npm/%40demo/board")]; + let serde = component( + None, + Some("pkg:cargo/serde@1.0.0"), + "serde", + Scope::Required, + ); + for (root, cited) in [ + ( + "pkg:cargo/demo@0.1.0?download_url=file://.", + "pkg:cargo/demo", + ), + ("pkg:cargo/demo#sub/path", "pkg:cargo/demo"), + ("pkg:npm/%40demo/board@1.0.0", "pkg:npm/%40demo/board"), + ("pkg:npm/@demo/board@1.0.0", "pkg:npm/%40demo/board"), + ] { + let facts = dependency_facts(&[bom(root, vec![serde.clone()], None)], &served) + .unwrap_or_else(|e| panic!("{root}: {e}")); + assert_eq!(facts.len(), 1, "{root}"); + assert_eq!( + field(&facts[0], "package").and_then(|v| v.as_str()), + Some(cited), + "{root}" + ); + assert_eq!( + facts[0].id, + format!("dep:{cited}/pkg%3Acargo%2Fserde%401.0.0"), + "{root}" + ); + } +} + +#[test] +fn a_root_naming_no_package_or_several_or_none_is_an_error() { + let served = [ + package("pkg:cargo/demo#crates/demo"), + package("pkg:cargo/demo#tools/demo"), + ]; + let several = dependency_facts(&[bom("pkg:cargo/demo@0.1.0", vec![], None)], &served) + .expect_err("two packages of one name, neither the plain id"); + assert!(several.contains("pkg:cargo/demo@0.1.0"), "{several}"); + assert!(several.contains("pkg:cargo/demo#crates/demo"), "{several}"); + let none = dependency_facts(&[bom("pkg:cargo/elsewhere@1.0.0", vec![], None)], &served) + .expect_err("no package"); + assert!(none.contains("pkg:cargo/elsewhere@1.0.0"), "{none}"); + let mut purl_less = bom("pkg:cargo/demo", vec![], None); + purl_less.root.purl = None; + let no_purl = dependency_facts(&[purl_less], &served).expect_err("no purl"); + assert!(no_purl.contains("'root'"), "{no_purl}"); +} + +#[test] +fn the_exact_package_id_wins_and_a_purl_subpath_selects_among_several() { + let serde = || { + component( + None, + Some("pkg:cargo/serde@1.0.0"), + "serde", + Scope::Required, + ) + }; + let cited = |root: &str, served: &[Fact]| -> String { + let facts = dependency_facts(&[bom(root, vec![serde()], None)], served) + .unwrap_or_else(|e| panic!("{root}: {e}")); + field(&facts[0], "package") + .and_then(|v| v.as_str()) + .unwrap_or_default() + .to_string() + }; + let twins = [ + package("pkg:cargo/demo"), + package("pkg:cargo/demo#crates/demo"), + ]; + assert_eq!(cited("pkg:cargo/demo@0.1.0", &twins), "pkg:cargo/demo"); + assert_eq!( + cited("pkg:cargo/demo@0.1.0#crates/demo", &twins), + "pkg:cargo/demo#crates/demo" + ); + assert_eq!( + cited("pkg:cargo/demo@0.1.0#/crates/demo/", &twins), + "pkg:cargo/demo#crates/demo" + ); + // A subpath no package has falls back to the plain id. + assert_eq!(cited("pkg:cargo/demo#sub/path", &twins), "pkg:cargo/demo"); + let spaced = [ + package("pkg:cargo/demo#a"), + package("pkg:cargo/demo#my%20dir"), + ]; + assert_eq!( + cited("pkg:cargo/demo@1#my%20dir", &spaced), + "pkg:cargo/demo#my%20dir" + ); + assert_eq!(cited("pkg:cargo/demo@1#a", &spaced), "pkg:cargo/demo#a"); +} + +#[test] +fn a_root_error_shows_its_purl_and_name_bounded_and_escaped() { + let served = [package("pkg:cargo/demo")]; + let hostile = format!("pkg:cargo/x\u{1b}]0;{}@1", "a".repeat(5_000)); + let error = dependency_facts(&[bom(&hostile, vec![], None)], &served).expect_err("unserved"); + assert!( + !error.contains('\u{1b}') && error.contains("\\u{1b}"), + "{error}" + ); + assert!(error.len() < 400, "{} bytes", error.len()); + let mut purl_less = bom("pkg:cargo/demo", vec![], None); + purl_less.root.purl = None; + purl_less.root.name = "r\u{7}".repeat(1_000); + let error = dependency_facts(&[purl_less], &served).expect_err("no purl"); + assert!(!error.contains('\u{7}') && error.len() < 400, "{error}"); +} + +#[test] +fn direct_is_true_false_or_absent_as_the_graph_states() { + let served = [package("pkg:cargo/demo")]; + let components = vec![ + component(Some("a"), Some("pkg:cargo/a@1"), "a", Scope::Required), + component(Some("b"), Some("pkg:cargo/b@1"), "b", Scope::Required), + component(None, Some("pkg:cargo/c@1"), "c", Scope::Required), + ]; + let directness = |direct: Option<&[&str]>| -> Vec> { + dependency_facts( + &[bom("pkg:cargo/demo", components.clone(), direct)], + &served, + ) + .unwrap() + .iter() + .map(|f| field(f, "direct").and_then(|v| v.as_bool())) + .collect() + }; + assert_eq!(directness(Some(&["a"])), [Some(true), Some(false), None]); + assert_eq!(directness(None), [None, None, None]); +} + +#[test] +fn a_purl_less_component_is_named_by_group_name_and_version() { + let served = [package("pkg:cargo/demo")]; + let mut lone = component(None, None, "tool", Scope::Optional); + lone.group = Some("acme".to_string()); + let facts = dependency_facts(&[bom("pkg:cargo/demo", vec![lone], None)], &served).unwrap(); + assert_eq!(facts[0].id, "dep:pkg:cargo/demo/@acme%2Ftool%401.0.0"); + assert_eq!( + field(&facts[0], "name").and_then(|v| v.as_str()), + Some("acme/tool") + ); + assert_eq!( + field(&facts[0], "scope").and_then(|v| v.as_str()), + Some("optional") + ); + assert!(field(&facts[0], "purl").is_none()); +} + +#[test] +fn a_repeated_purl_merges_into_one_fact_of_the_widest_scope() { + let served = [package("pkg:cargo/demo")]; + let components = vec![ + component(Some("x1"), Some("pkg:cargo/x@1"), "x", Scope::Excluded), + component( + Some("x2"), + Some("pkg:cargo/x@1?arch=y"), + "x", + Scope::Optional, + ), + component(Some("x3"), Some("pkg:cargo/x@1"), "x", Scope::Excluded), + ]; + let facts = + dependency_facts(&[bom("pkg:cargo/demo", components, Some(&["x2"]))], &served).unwrap(); + assert_eq!(facts.len(), 1, "{facts:?}"); + let fact = &facts[0]; + assert_eq!(fact.id, "dep:pkg:cargo/demo/pkg%3Acargo%2Fx%401"); + assert_eq!( + field(fact, "scope").and_then(|v| v.as_str()), + Some("optional") + ); + assert_eq!(field(fact, "direct").and_then(|v| v.as_bool()), Some(true)); + assert_eq!( + field(fact, "purl").and_then(|v| v.as_str()), + Some("pkg:cargo/x@1") + ); +} + +#[test] +fn the_scope_names_parse_back() { + assert_eq!(Scope::NAMES, ["required", "optional", "excluded"]); + for name in Scope::NAMES { + assert_eq!(Scope::parse(name).map(Scope::as_str), Some(name)); + } + assert_eq!(Scope::parse("mandatory"), None); +} diff --git a/extensions/code/facts/src/tests/finding.rs b/extensions/code/facts/src/tests/finding.rs new file mode 100644 index 0000000000..4d45e15b4a --- /dev/null +++ b/extensions/code/facts/src/tests/finding.rs @@ -0,0 +1,149 @@ +//! The `static_finding` facts minted from a SARIF reader's results and the served items and packages. + +use crate::*; +use specforge_extension_sdk::prelude::{Fact, FactLocation}; + +fn item(id: &str, file: &str, start: usize, end: usize) -> Fact { + Fact::new("item", id).at(FactLocation { + file: file.to_string(), + start_line: start, + start_col: 1, + end_line: end, + end_col: 2, + }) +} + +/// `fn add` at lines 1-5 of `src/lib.rs`, and the root package. +fn served() -> Vec { + vec![ + item("rust:demo::add", "src/lib.rs", 1, 5), + Fact::new("package", "pkg:cargo/demo").field("path", ""), + ] +} + +fn result(rule: &str, file: Option<&str>, line: Option) -> SarifResult { + SarifResult { + tool: "clippy".to_string(), + rule: rule.to_string(), + level: Level::Warning, + message: "a message".to_string(), + file: file.map(str::to_string), + line, + end_line: None, + } +} + +fn field<'f>(fact: &'f Fact, name: &str) -> Option<&'f str> { + fact.fields.get(name).and_then(|v| v.as_str()) +} + +#[test] +fn a_finding_cites_its_item_else_its_package_else_nothing() { + let results = [ + result("r", Some("src/lib.rs"), Some(3)), + result("r", Some("src/lib.rs"), Some(40)), + result("r", Some("src/lib.rs"), None), + result("r", None, None), + ]; + let facts = finding_facts(&results, &served()); + let cited: Vec<(&str, Option<&str>, Option<&str>)> = facts + .iter() + .map(|f| (f.id.as_str(), field(f, "item"), field(f, "package"))) + .collect(); + assert_eq!( + cited, + [ + ( + "sarif:clippy/r#src%2Flib.rs:3", + Some("rust:demo::add"), + None + ), + ( + "sarif:clippy/r#src%2Flib.rs:40", + None, + Some("pkg:cargo/demo") + ), + ("sarif:clippy/r#src%2Flib.rs", None, Some("pkg:cargo/demo")), + ("sarif:clippy/r", None, None), + ] + ); + assert!(facts.iter().all(|f| f.kind == "static_finding")); + assert!(!facts[3].fields.contains_key("file") && facts[3].at.is_empty()); +} + +#[test] +fn a_finding_holds_what_the_report_says_and_spans_whole_lines() { + let mut read = result("clippy::unwrap_used", Some("src/lib.rs"), Some(3)); + read.end_line = Some(4); + read.level = Level::Unknown; + let fact = &finding_facts(&[read], &served())[0]; + assert_eq!( + ["tool", "rule", "level", "message", "file"].map(|name| field(fact, name)), + [ + Some("clippy"), + Some("clippy::unwrap_used"), + Some("unknown"), + Some("a message"), + Some("src/lib.rs") + ] + ); + assert_eq!(fact.fields.get("line").and_then(|v| v.as_u64()), Some(3)); + assert_eq!( + fact.at, + [FactLocation { + file: "src/lib.rs".to_string(), + start_line: 3, + start_col: 1, + end_line: 5, + end_col: 1, + }] + ); +} + +#[test] +fn two_results_at_one_place_take_a_repeat_suffix_in_document_order() { + let at = result("r", Some("src/lib.rs"), Some(3)); + let ids: Vec = finding_facts(&[at.clone(), at.clone(), at], &[]) + .into_iter() + .map(|f| f.id) + .collect(); + assert_eq!( + ids, + [ + "sarif:clippy/r#src%2Flib.rs:3", + "sarif:clippy/r#src%2Flib.rs:3~2", + "sarif:clippy/r#src%2Flib.rs:3~3" + ] + ); +} + +#[test] +fn a_rule_holding_a_separator_cannot_forge_another_id() { + let forged = result("a#src/lib.rs:3", None, None); + let honest = result("a", Some("src/lib.rs"), Some(3)); + let ids: Vec = finding_facts(&[forged, honest], &[]) + .into_iter() + .map(|f| f.id) + .collect(); + assert_eq!( + ids, + [ + "sarif:clippy/a%23src%2Flib.rs%3A3", + "sarif:clippy/a#src%2Flib.rs:3" + ] + ); +} + +#[test] +fn a_level_reads_sarifs_four_values_only() { + assert_eq!( + Level::NAMES, + ["error", "warning", "note", "none", "unknown"] + ); + for name in &Level::NAMES[..4] { + assert_eq!(Level::parse(name).map(Level::as_str), Some(*name)); + } + assert_eq!(Level::parse("unknown"), None); + assert_eq!(Level::parse("Warning"), None); + assert_eq!(Level::Unknown.as_str(), UNKNOWN); +} diff --git a/extensions/code/facts/src/tests/mint.rs b/extensions/code/facts/src/tests/mint.rs index e0aaa06691..9b20b54e64 100644 --- a/extensions/code/facts/src/tests/mint.rs +++ b/extensions/code/facts/src/tests/mint.rs @@ -2,7 +2,7 @@ use super::{owner, strings}; use crate::*; -use specforge_code_junit::{cases, relative}; +use specforge_code_junit::cases; use specforge_extension_sdk::host::SyntaxPoint; use specforge_extension_sdk::prelude::{Fact, FactLocation, TestStatus}; use specforge_test::prelude::*; @@ -90,6 +90,30 @@ fn an_unrun_test_has_no_run() { assert_eq!(facts[0].fields["status"], "skipped"); } +#[test] +fn a_test_placed_at_its_item_takes_its_places_names_and_file() { + let item = Fact::new("item", "rust:toy::tests::adds") + .field("file", "src/lib.rs") + .at(place("src/lib.rs", 4)) + .name("names", "TR1", place("src/lib.rs", 3)) + .unplaced_name("names", "TR2"); + let id = TestId::rust("toy", "tests::adds"); + let placed = case(id.clone(), TestStatus::Passed, Some(0.5)).placed(&item); + assert_eq!(placed.file.as_deref(), Some("src/lib.rs")); + assert_eq!(placed.at, [place("src/lib.rs", 4)]); + assert_eq!(placed.names["TR1"], [place("src/lib.rs", 3)]); + assert_eq!(placed.names["TR2"], Vec::::new()); + assert_eq!( + (placed.status, placed.seconds, placed.ran), + (TestStatus::Passed, Some(0.5), true) + ); + let own = TestCase { + file: Some("tests/own.rs".to_string()), + ..case(id, TestStatus::Failed, None) + }; + assert_eq!(own.placed(&item).file.as_deref(), Some("tests/own.rs")); +} + #[test] fn a_rust_test_splits_its_path_into_suite_and_name() { let id = TestId::rust("specforge-ops::golden", "read::tests::adds"); diff --git a/extensions/code/facts/src/tests/paths.rs b/extensions/code/facts/src/tests/paths.rs new file mode 100644 index 0000000000..56e18f1ec2 --- /dev/null +++ b/extensions/code/facts/src/tests/paths.rs @@ -0,0 +1,196 @@ +//! A report's file path made project-relative, and a report's `file:` URI decoded to a path. + +use crate::*; + +#[test] +fn a_windows_file_under_a_verbatim_cwd_is_relative() { + let file = r"C:\work\app\test\a.test.js"; + assert_eq!( + relative(file, r"\\?\C:\work\app").as_deref(), + Some("test/a.test.js") + ); + assert_eq!( + relative(file, r"\\?\c:\work\app\").as_deref(), + Some("test/a.test.js") + ); + assert_eq!( + relative(r"\\server\share\app\t.js", r"\\?\UNC\server\share\app").as_deref(), + Some("t.js") + ); + assert_eq!(relative(file, r"\\?\D:\work\app"), None); +} + +#[test] +fn a_private_var_alias_is_relative() { + let file = "/var/folders/x/T/p/test/a.test.js"; + assert_eq!( + relative(file, "/private/var/folders/x/T/p").as_deref(), + Some("test/a.test.js") + ); + assert_eq!( + relative("/private/tmp/p/test/a.test.js", "/tmp/p").as_deref(), + Some("test/a.test.js") + ); + assert_eq!(relative("/variable/p/a.js", "/private/variable/p"), None); +} + +#[test] +fn a_file_outside_cwd_is_none() { + assert_eq!(relative("/elsewhere/test/a.test.js", "/project"), None); + assert_eq!(relative("/project-two/a.test.js", "/project"), None); + assert_eq!(relative("/project", "/project"), None); + assert_eq!( + relative("./test/a.test.js", "/project").as_deref(), + Some("test/a.test.js") + ); + assert_eq!( + relative("/project/a.js", "/").as_deref(), + Some("project/a.js") + ); +} + +#[test] +fn a_file_that_climbs_out_through_dot_dot_is_outside() { + for escaping in [ + "../x.test.js", + "./test/../../x.test.js", + r"..\x.test.js", + "/project/../x.test.js", + "/project/test/../../elsewhere/x.test.js", + ] { + assert_eq!(relative(escaping, "/project"), None, "{escaping}"); + } + for (inside, expected) in [ + ("test/../src/a.test.js", "src/a.test.js"), + ("/project/test/./unit/../a.test.js", "test/a.test.js"), + ] { + assert_eq!( + relative(inside, "/project").as_deref(), + Some(expected), + "{inside}" + ); + } +} + +#[test] +fn a_file_uri_decodes_to_its_path() { + for (uri, path) in [ + ("file:///project/src/a%20b.js", "/project/src/a b.js"), + ("file:///C:/work/app/x.ts", "C:/work/app/x.ts"), + ("file://localhost/p/x", "/p/x"), + ("FILE://LocalHost/p/x", "/p/x"), + ("file:/p/x", "/p/x"), + ("file://server/share/x.js", "//server/share/x.js"), + ("file:///p/x.js#L3", "/p/x.js"), + ("src/a.rs", "src/a.rs"), + ("src/a%3Ab.rs", "src/a:b.rs"), + ("C:/work/x.ts", "C:/work/x.ts"), + ] { + assert_eq!(file_uri_path(uri).as_deref(), Some(path), "{uri}"); + } + assert_eq!( + relative( + &file_uri_path("file:///C:/work/app/x.ts").unwrap(), + r"C:\work\app" + ) + .as_deref(), + Some("x.ts") + ); +} + +#[test] +fn a_uri_of_another_scheme_is_none() { + for uri in [ + "http://example.com/x", + "https://e.com/a.js", + "git+ssh://h/r", + "urn:x", + ] { + assert_eq!(file_uri_path(uri), None, "{uri}"); + } +} + +#[test] +fn only_two_hex_digits_decode_and_a_run_that_is_no_utf8_stays_as_written() { + for (uri, path) in [ + // `u8::from_str_radix` takes a sign: `%+f` is no escape. + ("src/a%+fb.rs", "src/a%+fb.rs"), + ("src/a%-1.rs", "src/a%-1.rs"), + ("src/a%2", "src/a%2"), + ("src/%%2e", "src/%."), + // One run that is no UTF-8 keeps its spelling; every other escape still decodes. + ("%ff/%2e%2e/a%20b", "%ff/../a b"), + ("%C3%A9%C3/x", "é%C3/x"), + ("%E2%82%AC%e2%82", "€%e2%82"), + ] { + assert_eq!(file_uri_path(uri).as_deref(), Some(path), "{uri}"); + } + assert_eq!( + relative(&file_uri_path("%FF/%2e%2e/%2e%2e/x").unwrap(), "/project"), + None + ); +} + +#[test] +fn the_outside_line_counts_the_paths_and_names_five() { + let r = ".specforge/reports/x.lcov"; + assert_eq!(outside_line(r, &[]), None); + assert_eq!( + outside_line(r, &super::strings(&["/elsewhere/a.rs", "../../etc/passwd"])).as_deref(), + Some( + ".specforge/reports/x.lcov: skipped 2 file(s) outside the project: /elsewhere/a.rs, \ + ../../etc/passwd" + ) + ); + let seven: Vec = (1..=7).map(|n| format!("/o/{n}")).collect(); + assert_eq!( + outside_line(r, &seven).as_deref(), + Some( + ".specforge/reports/x.lcov: skipped 7 file(s) outside the project: /o/1, /o/2, /o/3, /o/4, \ + /o/5, and 2 more" + ) + ); + let five = &seven[..5]; + assert!(!outside_line(r, five).unwrap().contains("more")); +} + +#[test] +fn a_path_resolving_to_the_root_or_a_pseudo_name_names_no_file_not_outside() { + for empty in [".", "./", "a/..", "/project", "/project/", "/project/a/.."] { + assert_eq!(place(empty, "/project"), Place::NoFile, "{empty}"); + assert_eq!(relative(empty, "/project"), None, "{empty}"); + } + for pseudo in ["", "", ""] { + assert_eq!(place(pseudo, "/project"), Place::NoFile, "{pseudo}"); + } + for outside in ["..", "../x.rs", "/elsewhere/x.rs", "/project-two/x.rs"] { + assert_eq!(place(outside, "/project"), Place::Outside, "{outside}"); + } + assert_eq!( + place("/project/src/lib.rs", "/project"), + Place::File("src/lib.rs".to_string()) + ); + assert_eq!( + place("/b.rs", "/project"), + Place::File("/b.rs".to_string()) + ); +} + +#[test] +fn the_no_file_line_counts_the_paths_like_the_outside_line() { + let r = ".specforge/reports/x.sarif"; + assert_eq!(no_file_line(r, &[]), None); + assert_eq!( + no_file_line(r, &super::strings(&["", "."])).as_deref(), + Some(".specforge/reports/x.sarif: skipped 2 path(s) naming no file: , .") + ); +} + +#[test] +fn a_decoded_dot_dot_is_judged_by_relative() { + let path = file_uri_path("%2E%2E/etc/passwd").expect("a relative reference"); + assert_eq!(path, "../etc/passwd"); + assert_eq!(relative(&path, "/project"), None); + let path = file_uri_path("file:///project/%2E%2E/etc/passwd").expect("a file URI"); + assert_eq!(relative(&path, "/project"), None); +} diff --git a/extensions/code/facts/src/tests/places.rs b/extensions/code/facts/src/tests/places.rs new file mode 100644 index 0000000000..8073eec8c6 --- /dev/null +++ b/extensions/code/facts/src/tests/places.rs @@ -0,0 +1,173 @@ +//! Where a report's location lies among the served item and package facts. + +use crate::*; +use specforge_extension_sdk::prelude::{Fact, FactLocation}; + +/// `file` from line `start` (column 1) to line `end`, column `end_col` (end exclusive). +fn span(file: &str, start: usize, end: usize, end_col: usize) -> FactLocation { + FactLocation { + file: file.to_string(), + start_line: start, + start_col: 1, + end_line: end, + end_col, + } +} + +fn item(id: &str, place: FactLocation) -> Fact { + Fact::new("item", id).at(place) +} + +fn package(id: &str, path: &str) -> Fact { + Fact::new("package", id).field("path", path) +} + +/// A Rust file with `mod tests` at lines 10-31 holding `fn adds` at 12-16, a method of an impl at 40-45, an item +/// whose place ends at column 1 of line 16, and two one-line items on line 50; the module is served as a collector +/// receives it, parsed from JSON. +fn served() -> Vec { + let module: Fact = serde_json::from_str( + r#"{"kind": "item", "id": "rust:demo::tests", "fields": {"kind": "mod"}, + "at": [{"file": "src/lib.rs", "start_line": 10, "start_col": 1, "end_line": 31, "end_col": 2}]}"#, + ) + .expect("a served item"); + vec![ + module, + item("rust:demo::tests::adds", span("src/lib.rs", 12, 16, 6)), + item( + "rust:demo::::fmt", + span("src/lib.rs", 40, 45, 6), + ), + item("rust:demo::ends_at_col_one", span("src/main.rs", 12, 16, 1)), + item("rust:demo::outer", span("src/main.rs", 1, 30, 2)), + item("rust:demo::b", span("src/lib.rs", 50, 50, 20)), + item("rust:demo::a", span("src/lib.rs", 50, 50, 30)), + ] +} + +#[test] +fn a_line_resolves_to_the_innermost_item_holding_it() { + let served = served(); + let places = Places::new(&served); + assert_eq!( + places.innermost("src/lib.rs", 13), + Some("rust:demo::tests::adds") + ); + assert_eq!(places.innermost("src/lib.rs", 20), Some("rust:demo::tests")); + assert_eq!( + places.innermost("src/lib.rs", 41), + Some("rust:demo::::fmt") + ); + assert_eq!(places.innermost("src/lib.rs", 46), None); +} + +#[test] +fn a_place_ending_at_column_one_does_not_hold_its_end_line() { + let served = served(); + let places = Places::new(&served); + assert_eq!( + places.innermost("src/main.rs", 15), + Some("rust:demo::ends_at_col_one") + ); + assert_eq!( + places.innermost("src/main.rs", 16), + Some("rust:demo::outer") + ); +} + +#[test] +fn two_items_on_one_line_resolve_to_the_smaller_id() { + let served = served(); + let places = Places::new(&served); + assert_eq!(places.innermost("src/lib.rs", 50), Some("rust:demo::a")); +} + +#[test] +fn an_unserved_file_has_no_item() { + let served = served(); + let places = Places::new(&served); + assert_eq!(places.innermost("src/other.rs", 13), None); + assert_eq!(Places::new(&[]).innermost("src/lib.rs", 13), None); +} + +#[test] +fn a_file_belongs_to_the_package_of_the_longest_directory_holding_it() { + let served = vec![ + package("pkg:cargo/root", ""), + package("pkg:cargo/a", "crates/a"), + Fact::new("package", "pkg:npm/no-path"), + ]; + let places = Places::new(&served); + assert_eq!(places.package_of("crates/a/src/x.rs"), Some("pkg:cargo/a")); + // `crates/a` does not hold `crates/ab`; of the two root packages (no `path` reads `""`) the file's ecosystem + // wins, and a file with no evidence of one names neither. + assert_eq!(places.package_of("crates/ab/x.rs"), Some("pkg:cargo/root")); + assert_eq!(places.package_of("crates/ab/x.js"), Some("pkg:npm/no-path")); + assert_eq!(places.package_of("crates/a"), None); + assert_eq!(Places::new(&[]).package_of("x.rs"), None); +} + +#[test] +fn a_directory_finds_its_packages_of_one_type_else_those_under_it() { + let served = vec![ + package("pkg:npm/web", ""), + package("pkg:cargo/b", "crates/b"), + package("pkg:cargo/a", "crates/a"), + package("pkg:cargo/a2", "crates/a/inner"), + package("pkg:cargo/x", "other/x"), + ]; + let places = Places::new(&served); + assert_eq!(places.packages_of_dir("crates/a", "cargo"), ["pkg:cargo/a"]); + assert_eq!( + places.packages_of_dir("crates", "cargo"), + ["pkg:cargo/a", "pkg:cargo/a2", "pkg:cargo/b"] + ); + assert_eq!( + places.packages_of_dir("", "cargo"), + ["pkg:cargo/a", "pkg:cargo/a2", "pkg:cargo/b", "pkg:cargo/x"] + ); + assert_eq!(places.packages_of_dir("", "npm"), ["pkg:npm/web"]); + assert!(places.packages_of_dir("crate", "cargo").is_empty()); +} + +#[test] +fn a_package_name_finds_its_second_packages_too() { + let served = vec![ + package("pkg:cargo/x#crates/y", "crates/y"), + package("pkg:cargo/x", "x"), + package("pkg:cargo/xy", "xy"), + ]; + let places = Places::new(&served); + assert_eq!( + places.packages_named("pkg:cargo/x"), + ["pkg:cargo/x", "pkg:cargo/x#crates/y"] + ); + assert!(places.packages_named("pkg:cargo/z").is_empty()); +} + +#[test] +fn a_tie_at_one_directory_goes_to_the_files_ecosystem_else_to_none() { + let served = vec![ + package("pkg:cargo/root", ""), + package("pkg:npm/web", "web"), + package("pkg:cargo/web", "web"), + item("rust:web::main", span("web/src/main.inc", 1, 9, 2)), + item("js:web/gen/x.inc::x", span("web/gen/x.inc", 1, 9, 2)), + ]; + let places = Places::new(&served); + for (file, package) in [ + ("web/src/index.ts", Some("pkg:npm/web")), + ("web/src/a.mjs", Some("pkg:npm/web")), + ("web/package.json", Some("pkg:npm/web")), + ("web/src/lib.rs", Some("pkg:cargo/web")), + ("web/Cargo.toml", Some("pkg:cargo/web")), + // A source pack's item on the file is the evidence first. + ("web/src/main.inc", Some("pkg:cargo/web")), + ("web/gen/x.inc", Some("pkg:npm/web")), + // No evidence: neither package, rather than the one whose id sorts first. + ("web/README.md", None), + ("src/main.rs", Some("pkg:cargo/root")), + ] { + assert_eq!(places.package_of(file), package, "{file}"); + } +} diff --git a/extensions/code/facts/src/tests/report.rs b/extensions/code/facts/src/tests/report.rs new file mode 100644 index 0000000000..cddff8b468 --- /dev/null +++ b/extensions/code/facts/src/tests/report.rs @@ -0,0 +1,185 @@ +//! The report kinds, safe id parts and repeat suffixes. + +use crate::*; + +#[test] +fn an_id_part_encodes_every_delimiter_whitespace_and_control() { + assert_eq!( + id_part("a/b#c:d~e@f?g h%\u{1b}"), + "a%2Fb%23c%3Ad%7Ee%40f%3Fg%20h%25%1B" + ); + assert_eq!(id_part("Az09.-_é"), "Az09.-_é"); + assert_eq!(id_part("tab\tnl\n\u{a0}"), "tab%09nl%0A%C2%A0"); +} + +#[test] +fn shown_text_is_bounded_and_escapes_control_characters() { + assert_eq!(shown("a\u{1b}]0;x\u{7}\"é"), "a\\u{1b}]0;x\\u{7}\\\"é"); + let long = "x".repeat(10_000); + assert_eq!(shown(&long), format!("{}…", "x".repeat(80))); + assert_eq!(shown(&"y".repeat(80)), "y".repeat(80)); + assert_eq!( + shown_json(&serde_json::json!("2.0\u{1b}")), + "\"2.0\\u{1b}\"" + ); + assert_eq!(shown_json(&serde_json::json!(2)), "2"); + assert!(shown_json(&serde_json::json!([long])).len() < 100); +} + +#[test] +fn a_repeated_id_gets_a_numbered_suffix() { + let mut repeats = Repeats::default(); + let ids: Vec = ["x", "x", "y", "x"] + .into_iter() + .map(|base| repeats.id(base.to_string())) + .collect(); + assert_eq!(ids, ["x", "x~2", "y", "x~3"]); +} + +/// Each vocabulary enum's name comes from an exhaustive match, usable in a const: a variant added without a name fails +/// to compile, never reads as a default name or the empty string. +const NAMED: [&str; 6] = [ + Scope::Excluded.as_str(), + Severity::Unknown.as_str(), + Level::None.as_str(), + ApiKind::ExternCrate.as_str(), + ApiKind::Item(ItemKind::Namespace).as_str(), + Visibility::Restricted.as_str(), +]; + +#[test] +fn every_vocabulary_variant_is_named_and_listed_once() { + assert_eq!( + NAMED, + [ + "excluded", + "unknown", + "none", + "extern_crate", + "namespace", + "restricted" + ] + ); + // The match lists each variant: a new one fails to compile here until it is checked as listed below. + let scope = |s: Scope| match s { + Scope::Required | Scope::Optional | Scope::Excluded => s.as_str(), + }; + let severity = |s: Severity| match s { + Severity::Critical + | Severity::High + | Severity::Medium + | Severity::Low + | Severity::Unknown => s.as_str(), + }; + let level = |l: Level| match l { + Level::Error | Level::Warning | Level::Note | Level::None | Level::Unknown => l.as_str(), + }; + let visibility = |v: Visibility| match v { + Visibility::Private | Visibility::Restricted | Visibility::Crate | Visibility::Public => { + v.as_str() + } + }; + for name in [Scope::Required, Scope::Optional, Scope::Excluded].map(scope) { + assert!(Scope::NAMES.contains(&name), "{name}"); + } + for name in [ + Severity::Critical, + Severity::High, + Severity::Medium, + Severity::Low, + Severity::Unknown, + ] + .map(severity) + { + assert!(Severity::NAMES.contains(&name), "{name}"); + } + for name in [ + Level::Error, + Level::Warning, + Level::Note, + Level::None, + Level::Unknown, + ] + .map(level) + { + assert!(Level::NAMES.contains(&name), "{name}"); + } + for name in [ + Visibility::Private, + Visibility::Restricted, + Visibility::Crate, + Visibility::Public, + ] + .map(visibility) + { + assert!(Visibility::NAMES.contains(&name), "{name}"); + } + let item = |k: ItemKind| match k { + ItemKind::Module + | ItemKind::Function + | ItemKind::Method + | ItemKind::Field + | ItemKind::Struct + | ItemKind::Enum + | ItemKind::Union + | ItemKind::Trait + | ItemKind::Type + | ItemKind::Const + | ItemKind::Static + | ItemKind::Macro + | ItemKind::Class + | ItemKind::Interface + | ItemKind::Variable + | ItemKind::Namespace => ItemKind::ALL.contains(&k), + }; + assert!(ItemKind::ALL.into_iter().all(item)); + for kind in ItemKind::ALL { + assert!(ApiKind::NAMES.contains(&ApiKind::Item(kind).as_str())); + } + for kind in [ + ApiKind::Variant, + ApiKind::Reexport, + ApiKind::ExternCrate, + ApiKind::Other, + ] { + assert!(ApiKind::NAMES.contains(&kind.as_str()), "{kind:?}"); + } + // No two variants share a name. + for names in [ + &Scope::NAMES[..], + &Severity::NAMES[..], + &Level::NAMES[..], + &Visibility::NAMES[..], + &ItemKind::NAMES[..], + &ApiKind::NAMES[..], + ] { + let unique: std::collections::BTreeSet<&str> = names.iter().copied().collect(); + assert_eq!(unique.len(), names.len(), "{names:?}"); + assert!(!unique.contains(""), "{names:?}"); + } +} + +#[test] +fn the_report_kinds_have_their_schemes() { + let named: Vec<(&str, &str)> = [ + COVERAGE, + API_ITEM, + STATIC_FINDING, + DEPENDENCY, + VULNERABILITY, + ] + .iter() + .map(|k| (k.kind, k.scheme)) + .collect(); + assert_eq!( + named, + [ + ("coverage", "cov"), + ("api_item", "api"), + ("static_finding", "sarif"), + ("dependency", "dep"), + ("vulnerability", "vuln"), + ] + ); + assert_eq!(UNKNOWN, "unknown"); +} diff --git a/extensions/code/facts/src/tests/vulnerability.rs b/extensions/code/facts/src/tests/vulnerability.rs new file mode 100644 index 0000000000..87027d762a --- /dev/null +++ b/extensions/code/facts/src/tests/vulnerability.rs @@ -0,0 +1,272 @@ +//! The `vulnerability` facts minted from an osv-scanner reader's report and the served packages. + +use crate::*; +use specforge_extension_sdk::prelude::Fact; + +fn package(id: &str, path: &str) -> Fact { + Fact::new("package", id).field("path", path) +} + +fn record(id: &str, label: Option<&str>) -> OsvRecord { + OsvRecord { + id: id.to_string(), + aliases: Vec::new(), + summary: None, + label: label.map(str::to_string), + scores: Vec::new(), + purl: None, + } +} + +fn dependency(name: &str, version: &str, ecosystem: &str, records: Vec) -> OsvPackage { + OsvPackage { + name: name.to_string(), + version: version.to_string(), + ecosystem: ecosystem.to_string(), + records, + } +} + +fn report(lockfile: &str, packages: Vec) -> OsvReport { + OsvReport { + sources: vec![OsvSource { + lockfile: lockfile.to_string(), + packages, + }], + } +} + +fn text<'f>(fact: &'f Fact, name: &str) -> Option<&'f str> { + fact.fields.get(name).and_then(|v| v.as_str()) +} + +fn list(fact: &Fact, name: &str) -> Vec { + serde_json::from_value(fact.fields[name].clone()).expect("a string list") +} + +#[test] +fn a_label_folds_to_a_severity_and_anything_else_is_unknown() { + for (label, severity) in [ + (Some("CRITICAL"), "critical"), + (Some("high"), "high"), + (Some("MODERATE"), "medium"), + (Some("Medium"), "medium"), + (Some("LOW"), "low"), + (Some("SEVERE"), "unknown"), + (None, "unknown"), + ] { + assert_eq!( + Severity::of(&record("X-1", label)).as_str(), + severity, + "{label:?}" + ); + } + assert_eq!( + Severity::NAMES, + ["critical", "high", "medium", "low", "unknown"] + ); +} + +#[test] +fn a_vulnerability_cites_the_package_at_the_lockfiles_directory_else_under_it() { + let served = [ + package("pkg:cargo/root", ""), + package("pkg:cargo/a", "crates/a"), + package("pkg:npm/web", "web"), + ]; + let cited = |lockfile: &str, ecosystem: &str| -> Vec { + let scan = report( + lockfile, + vec![dependency( + "x", + "1.0.0", + ecosystem, + vec![record("X-1", None)], + )], + ); + let minted = vulnerability_facts(&scan, &served); + assert!( + minted.skipped.is_empty(), + "{lockfile}: {:?}", + minted.skipped + ); + minted + .facts + .iter() + .map(|f| text(f, "package").unwrap_or_default().to_string()) + .collect() + }; + assert_eq!(cited("Cargo.lock", "crates.io"), ["pkg:cargo/root"]); + assert_eq!(cited("crates/a/Cargo.lock", "crates.io"), ["pkg:cargo/a"]); + assert_eq!(cited("crates/Cargo.lock", "crates.io"), ["pkg:cargo/a"]); + assert_eq!(cited("web/package-lock.json", "npm"), ["pkg:npm/web"]); + assert_eq!(cited("package-lock.json", "npm"), ["pkg:npm/web"]); +} + +#[test] +fn a_package_no_collected_package_or_ecosystem_holds_is_skipped_by_name_not_the_report() { + let served = [package("pkg:cargo/root", "")]; + let report = OsvReport { + sources: vec![ + OsvSource { + lockfile: "Cargo.lock".to_string(), + packages: vec![dependency( + "smallvec", + "1.6.0", + "crates.io", + vec![record("RUSTSEC-1", None)], + )], + }, + OsvSource { + lockfile: "requirements.txt".to_string(), + packages: vec![ + dependency("django", "4.0", "PyPI", vec![record("PYSEC-1", None)]), + // Nothing to mint, so nothing is skipped. + dependency("flask", "2.0", "PyPI", vec![]), + ], + }, + OsvSource { + lockfile: "web/package-lock.json".to_string(), + packages: vec![dependency( + "lodash", + "4.17.20", + "npm", + vec![record("GHSA-1", None), record("GHSA-2", None)], + )], + }, + ], + }; + let minted = vulnerability_facts(&report, &served); + let ids: Vec<&str> = minted.facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + ["vuln:pkg:cargo/root/RUSTSEC-1"], + "the cargo finding is kept" + ); + assert_eq!(minted.skipped.len(), 2, "{:?}", minted.skipped); + let (pypi, npm) = (&minted.skipped[0], &minted.skipped[1]); + for named in ["django", "4.0", "PyPI", "requirements.txt", "1 record"] { + assert!(pypi.contains(named), "{named}: {pypi}"); + } + for named in ["lodash", "web/package-lock.json", "pkg:npm", "2 records"] { + assert!(npm.contains(named), "{named}: {npm}"); + } +} + +#[test] +fn a_skipped_package_is_named_bounded_and_escaped() { + let served = [package("pkg:cargo/root", "")]; + let hostile = format!("\u{1b}]0;{}", "a".repeat(5_000)); + for (lockfile, ecosystem) in [ + (hostile.as_str(), "PyPI"), + ("requirements.txt", hostile.as_str()), + (hostile.as_str(), "npm"), + ] { + let scan = report( + lockfile, + vec![dependency( + &hostile, + "1", + ecosystem, + vec![record("X-1", None)], + )], + ); + let minted = vulnerability_facts(&scan, &served); + assert!(minted.facts.is_empty()); + let skipped = &minted.skipped[0]; + assert!( + !skipped.contains('\u{1b}') && skipped.contains("\\u{1b}"), + "{skipped}" + ); + assert!(skipped.len() < 600, "{} bytes", skipped.len()); + } +} + +#[test] +fn one_id_through_two_versions_is_one_fact_listing_both() { + let served = [package("pkg:npm/web", "")]; + let mut old = record("GHSA-aaaa", Some("LOW")); + old.aliases = vec!["CVE-2".to_string(), "CVE-1".to_string()]; + old.summary = Some("first".to_string()); + let mut new = record("GHSA-aaaa", Some("HIGH")); + new.aliases = vec!["CVE-1".to_string()]; + new.summary = Some("second".to_string()); + new.purl = Some("pkg:npm/%40scope/x".to_string()); + let scan = report( + "package-lock.json", + vec![ + dependency("@scope/x", "1.0.0", "npm", vec![old]), + dependency("@scope/x", "2.0.0", "npm", vec![new]), + ], + ); + let facts = vulnerability_facts(&scan, &served).facts; + assert_eq!(facts.len(), 1, "{facts:?}"); + let fact = &facts[0]; + assert_eq!(fact.id, "vuln:pkg:npm/web/GHSA-aaaa"); + assert_eq!(text(fact, "osv_id"), Some("GHSA-aaaa")); + assert_eq!(text(fact, "summary"), Some("first")); + assert_eq!(text(fact, "severity"), Some("high")); + assert_eq!(list(fact, "aliases"), ["CVE-1", "CVE-2"]); + assert_eq!(list(fact, "version"), ["1.0.0", "2.0.0"]); + assert_eq!( + list(fact, "purl"), + ["pkg:npm/%40scope/x@1.0.0", "pkg:npm/%40scope/x@2.0.0"] + ); +} + +#[test] +fn an_osv_id_is_made_safe_in_the_id() { + let served = [package("pkg:cargo/root", "")]; + let scan = report( + "Cargo.lock", + vec![dependency( + "x", + "1", + "crates.io", + vec![record("RUSTSEC-2024/0001#x", None)], + )], + ); + let facts = vulnerability_facts(&scan, &served).facts; + assert_eq!(facts[0].id, "vuln:pkg:cargo/root/RUSTSEC-2024%2F0001%23x"); + assert!(!facts[0].fields.contains_key("summary")); +} + +/// A record with no label and the `severity[]` entries `scores`, each a `(type, score)`. +fn scored(scores: &[(&str, &str)]) -> OsvRecord { + let mut scored = record("X-1", None); + scored.scores = scores + .iter() + .map(|(kind, score)| OsvScore { + kind: kind.to_string(), + score: score.to_string(), + }) + .collect(); + scored +} + +#[test] +fn an_unlabelled_record_reads_its_highest_cvss_v3_rating_and_a_label_wins() { + const HIGH: &str = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N"; + const CRITICAL: &str = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"; + const V4: &str = "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N"; + let cases: [(&[(&str, &str)], &str); 8] = [ + (&[("CVSS_V3", HIGH), ("CVSS_V3", CRITICAL)], "critical"), + (&[("CVSS_V3", CRITICAL), ("CVSS_V3", HIGH)], "critical"), + (&[("CVSS_V3", HIGH), ("CVSS_V3", "CVSS:3.1/AV:N")], "high"), + (&[("CVSS_V4", V4)], "unknown"), + (&[("CVSS_V2", "AV:N/AC:L/Au:N/C:P/I:P/A:P")], "unknown"), + (&[("CVSS_V3", V4)], "unknown"), + (&[("CVSS_V3", "CVSS:3.1/AV:N/AC:L")], "unknown"), + (&[("Ubuntu", "high")], "unknown"), + ]; + for (scores, severity) in cases { + assert_eq!( + Severity::of(&scored(scores)).as_str(), + severity, + "{scores:?}" + ); + } + let mut labelled = scored(&[("CVSS_V3", CRITICAL)]); + labelled.label = Some("LOW".to_string()); + assert_eq!(Severity::of(&labelled), Severity::Low); +} diff --git a/extensions/code/facts/src/vulnerability.rs b/extensions/code/facts/src/vulnerability.rs new file mode 100644 index 0000000000..2de96ed552 --- /dev/null +++ b/extensions/code/facts/src/vulnerability.rs @@ -0,0 +1,271 @@ +//! The `vulnerability` facts of an osv-scanner report (ADR 0388): what a reader (`specforge-code-osv`) read of a scan, +//! and the facts minted from it, each citing a served project `package` the scanned lockfile belongs to. A severity +//! is the OSV record's own label, else the rating of its CVSS v3 vector ([`cvss`]), and `unknown` when it states +//! neither in a form this library rates. + +use std::collections::{BTreeMap, BTreeSet}; + +use specforge_extension_sdk::prelude::Fact; + +use crate::cvss; +use crate::places::Places; +use crate::report::{id_part, shown, UNKNOWN, VULNERABILITY}; + +/// What a reader read of one osv-scanner report. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OsvReport { + pub sources: Vec, +} + +/// One scanned source: a lockfile (or an SBOM) and the vulnerable packages it lists. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OsvSource { + /// The lockfile's path, project-relative, with `/` separators. + pub lockfile: String, + pub packages: Vec, +} + +/// One dependency the lockfile pins, as osv-scanner names it, and the OSV records that affect it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OsvPackage { + pub name: String, + pub version: String, + /// The OSV ecosystem: `crates.io` or `npm` are minted. + pub ecosystem: String, + pub records: Vec, +} + +/// What one OSV record says. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OsvRecord { + pub id: String, + pub aliases: Vec, + pub summary: Option, + /// Its `database_specific.severity`, as written (GHSA writes `MODERATE`). + pub label: Option, + /// Its `severity[]` entries. + pub scores: Vec, + /// The `affected[].package.purl` of the entry naming this package, without version. + pub purl: Option, +} + +/// One `severity[]` entry of an OSV record: its `type` (`CVSS_V3`, `CVSS_V4`, …) and its `score`, a vector. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OsvScore { + pub kind: String, + pub score: String, +} + +/// A vulnerability's severity, highest first, [`UNKNOWN`] last and lowest. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Severity { + Critical, + High, + Medium, + Low, + Unknown, +} + +/// Every severity, highest first: the order [`Severity::NAMES`] reads. +const SEVERITIES: [Severity; 5] = [ + Severity::Critical, + Severity::High, + Severity::Medium, + Severity::Low, + Severity::Unknown, +]; + +impl Severity { + /// Every severity's name, highest first, `unknown` last: `@code/core`'s vocabulary of `vulnerability.severity`. + pub const NAMES: [&'static str; 5] = { + let mut names = [""; 5]; + let mut at = 0; + while at < names.len() { + names[at] = SEVERITIES[at].as_str(); + at += 1; + } + names + }; + + /// Its name: an exhaustive match, so a new severity names itself or fails to compile. + pub const fn as_str(self) -> &'static str { + match self { + Severity::Critical => "critical", + Severity::High => "high", + Severity::Medium => "medium", + Severity::Low => "low", + Severity::Unknown => UNKNOWN, + } + } + + /// The severity of `record`: its label uppercase-folded (`CRITICAL`, `HIGH`, `MODERATE` or `MEDIUM`, `LOW`), else + /// the rating of the highest [`base_score`](crate::cvss::base_score) of its `CVSS_V3` entries, else `Unknown` (a + /// record with only v4 or v2 entries, or only malformed vectors, included). + pub fn of(record: &OsvRecord) -> Severity { + record + .label + .as_deref() + .and_then(labelled) + .or_else(|| { + record + .scores + .iter() + .filter(|score| score.kind == "CVSS_V3") + .filter_map(|score| cvss::base_score(&score.score)) + .max() + .map(cvss::rating) + }) + .unwrap_or(Severity::Unknown) + } +} + +/// The severity an OSV database label names; `None` for any other text. +fn labelled(label: &str) -> Option { + match label.to_uppercase().as_str() { + "CRITICAL" => Some(Severity::Critical), + "HIGH" => Some(Severity::High), + "MODERATE" | "MEDIUM" => Some(Severity::Medium), + "LOW" => Some(Severity::Low), + _ => None, + } +} + +/// What [`vulnerability_facts`] minted of a report, and what it could not place. +#[derive(Debug, Clone, PartialEq)] +pub struct Vulnerabilities { + /// The `vulnerability` facts, sorted by id. + pub facts: Vec, + /// One line per report package with records that minted nothing, in report order, naming the package, its + /// version, its lockfile, how many records it held and why: an ecosystem other than `crates.io` and `npm`, or no + /// collected package of its type at or under the lockfile's directory. Report text in it is [`shown`]. + pub skipped: Vec, +} + +/// The `vulnerability` facts of `report`, each citing a served project `package`, and the packages skipped. +/// +/// A source's affected packages are [`Places::packages_of_dir`] of its lockfile's directory (`""` for a root file) +/// and the purl type of the package's ecosystem (`crates.io` is `cargo`, `npm` is `npm`): the packages of that type at +/// the directory, else under it. A package of another ecosystem, or one no such package holds, is skipped and named in +/// [`Vulnerabilities::skipped`]: one ecosystem a project does not collect (a `requirements.txt` beside a `Cargo.lock`) +/// never hides the findings of the others. +/// +/// The id is `vuln:/`. Fields: `package`, `osv_id`, `aliases` (sorted, deduplicated), +/// `summary` when stated, `purl` (the record's purl with `@`, else `pkg:/@` with an npm +/// scope's `@` written `%40`), `version`, and `severity` ([`Severity::of`]). One id met twice (two versions of one +/// dependency, one record in two sources) is one fact (F4): purls, versions and aliases united, the first summary, +/// the higher severity. +pub fn vulnerability_facts(report: &OsvReport, served: &[Fact]) -> Vulnerabilities { + let places = Places::new(served); + let mut merged: BTreeMap = BTreeMap::new(); + let mut skipped = Vec::new(); + for source in &report.sources { + let dir = source + .lockfile + .rfind('/') + .map_or("", |at| &source.lockfile[..at]); + for package in source.packages.iter().filter(|p| !p.records.is_empty()) { + let purl_type = match package.ecosystem.as_str() { + "crates.io" => "cargo", + "npm" => "npm", + other => { + let why = format!( + "the ecosystem '{}' is not read, only crates.io and npm", + shown(other) + ); + skipped.push(skip(package, &source.lockfile, &why)); + continue; + } + }; + let affected = places.packages_of_dir(dir, purl_type); + if affected.is_empty() { + let why = format!("no collected pkg:{purl_type} package lies at or under the lockfile's directory"); + skipped.push(skip(package, &source.lockfile, &why)); + continue; + } + for record in &package.records { + let purl = affected_purl(record, package, purl_type); + let severity = Severity::of(record); + for project in &affected { + let id = format!("{}:{project}/{}", VULNERABILITY.scheme, id_part(&record.id)); + let seen = merged.entry(id).or_insert_with(|| Merged { + package: project, + osv_id: &record.id, + summary: record.summary.as_deref(), + aliases: BTreeSet::new(), + purls: BTreeSet::new(), + versions: BTreeSet::new(), + severity, + }); + seen.aliases + .extend(record.aliases.iter().map(String::as_str)); + seen.purls.insert(purl.clone()); + seen.versions.insert(&package.version); + seen.severity = seen.severity.min(severity); + if seen.summary.is_none() { + seen.summary = record.summary.as_deref(); + } + } + } + } + } + Vulnerabilities { + facts: merged.into_iter().map(|(id, seen)| seen.fact(id)).collect(), + skipped, + } +} + +/// The line naming `package` of `lockfile`, skipped for `why`. +fn skip(package: &OsvPackage, lockfile: &str, why: &str) -> String { + let records = match package.records.len() { + 1 => "1 record".to_string(), + n => format!("{n} records"), + }; + format!( + "'{}' {} in '{}' ({records}) is skipped: {why}", + shown(&package.name), + shown(&package.version), + shown(lockfile) + ) +} + +/// The records of one id seen so far, merged. +struct Merged<'a> { + package: &'a str, + osv_id: &'a str, + summary: Option<&'a str>, + aliases: BTreeSet<&'a str>, + purls: BTreeSet, + versions: BTreeSet<&'a str>, + severity: Severity, +} + +impl Merged<'_> { + fn fact(self, id: String) -> Fact { + let list = |set: BTreeSet<&str>| set.into_iter().map(str::to_string).collect::>(); + let mut fact = Fact::new(VULNERABILITY.kind, id) + .field("package", self.package) + .field("osv_id", self.osv_id) + .field("aliases", list(self.aliases)); + if let Some(summary) = self.summary { + fact = fact.field("summary", summary); + } + fact.field("purl", self.purls.into_iter().collect::>()) + .field("version", list(self.versions)) + .field("severity", self.severity.as_str()) + } +} + +/// The versioned purl of `package` as `record` affects it: the record's own purl, else one built from the purl type, +/// the name (an npm scope's leading `@` written `%40`) and the version. +fn affected_purl(record: &OsvRecord, package: &OsvPackage, purl_type: &str) -> String { + match &record.purl { + Some(purl) => format!("{purl}@{}", package.version), + None => { + let name = match package.name.strip_prefix('@') { + Some(scoped) => format!("%40{scoped}"), + None => package.name.clone(), + }; + format!("pkg:{purl_type}/{name}@{}", package.version) + } + } +} diff --git a/extensions/code/junit/src/lib.rs b/extensions/code/junit/src/lib.rs index bff81017b1..0c62271ed9 100644 --- a/extensions/code/junit/src/lib.rs +++ b/extensions/code/junit/src/lib.rs @@ -7,7 +7,6 @@ //! - [`cases`] reads a report's ``s, each with the ``s around it and the [`names`] its name //! tags. //! - [`names`] reads the `[:]` tags in a test's name: the entities the test says it proves. -//! - [`relative`] makes a report's absolute file path project-relative, whatever spelling the host's root has. #[cfg(test)] mod tests; @@ -24,7 +23,8 @@ pub struct Case { pub suites: Vec, pub name: String, pub classname: String, - /// The `file` attribute as the report wrote it; a pack makes it project-relative with [`relative`]. + /// The `file` attribute as the report wrote it; a pack makes it project-relative with + /// `specforge_code_facts::relative`. pub file: Option, pub seconds: Option, /// `` or ``: failed; `` (a `todo` too): skipped; neither: passed. @@ -147,94 +147,3 @@ fn attr(attrs: &[(String, String)], key: &str) -> String { .map(|(_, v)| v.clone()) .unwrap_or_default() } - -/// `path` relative to the project root `cwd`, with `/` separators, or `None` when it lies outside it. Both are read -/// the same way first: a `\\?\` (or `\\?\UNC\`) verbatim prefix is stripped, `\` is folded to `/`, a drive letter -/// compares case-insensitively and a trailing `/` is dropped. The host's `cwd` is the canonical root, so the other -/// spelling of macOS's `/private` alias (`/private/var` and `/var`, `/private/tmp` and `/tmp`) is tried too. A -/// relative `path` is taken as project-relative already. Either way its `.` and `..` segments are resolved, and a -/// path that climbs out of the project through `..` lies outside it, as an absolute one elsewhere does. -pub fn relative(path: &str, cwd: &str) -> Option { - let path = normal(path); - if !is_absolute(&path) { - return contained(&path); - } - let cwd = normal(cwd); - aliases(&cwd) - .iter() - .find_map(|root| { - aliases(&path) - .iter() - .find_map(|spelling| under(spelling, root)) - }) - .and_then(|rest| contained(&rest)) -} - -/// The project-relative `path` with its `.` and `..` segments resolved, or `None` when a `..` climbs out of the -/// project or nothing is left. -fn contained(path: &str) -> Option { - let mut kept: Vec<&str> = Vec::new(); - for segment in path.split('/') { - match segment { - "" | "." => {} - ".." => { - kept.pop()?; - } - name => kept.push(name), - } - } - (!kept.is_empty()).then(|| kept.join("/")) -} - -/// `path` with no verbatim prefix, `/` separators and no trailing `/`. -fn normal(path: &str) -> String { - let path = match path.strip_prefix(r"\\?\UNC\") { - Some(share) => format!(r"\\{share}"), - None => path.strip_prefix(r"\\?\").unwrap_or(path).to_string(), - }; - let path = path.replace('\\', "/"); - match path.trim_end_matches('/') { - "" if path.starts_with('/') => "/".to_string(), - trimmed => trimmed.to_string(), - } -} - -/// Whether `path` (read by [`normal`]) is rooted: `/…` or a drive, `C:/…`. -fn is_absolute(path: &str) -> bool { - path.starts_with('/') || drive(path).is_some() -} - -/// The drive letter `path` starts with, `C:`, if any. -fn drive(path: &str) -> Option { - let mut chars = path.chars(); - let letter = chars.next().filter(char::is_ascii_alphabetic)?; - (chars.next() == Some(':')).then_some(letter) -} - -/// `path`, and its other spelling under macOS's `/private` alias. -fn aliases(path: &str) -> Vec { - let mut spellings = vec![path.to_string()]; - for (long, short) in [("/private/var", "/var"), ("/private/tmp", "/tmp")] { - for (from, to) in [(long, short), (short, long)] { - match path.strip_prefix(from) { - Some(rest) if rest.is_empty() || rest.starts_with('/') => { - spellings.push(format!("{to}{rest}")); - } - _ => {} - } - } - } - spellings -} - -/// `path` below `root`, both read by [`normal`]: what follows `root/`, or `None`. -fn under(path: &str, root: &str) -> Option { - let (path, root) = match (drive(path), drive(root)) { - (Some(a), Some(b)) if a.eq_ignore_ascii_case(&b) => (&path[2..], &root[2..]), - (None, None) => (path, root), - _ => return None, - }; - let rest = path.strip_prefix(root.trim_end_matches('/'))?; - let rest = rest.strip_prefix('/')?; - (!rest.is_empty()).then(|| rest.to_string()) -} diff --git a/extensions/code/junit/src/tests.rs b/extensions/code/junit/src/tests.rs index 9896c3185c..7fd731a041 100644 --- a/extensions/code/junit/src/tests.rs +++ b/extensions/code/junit/src/tests.rs @@ -85,10 +85,7 @@ fn nested_suites_make_the_path() { ("todo one".to_string(), TestStatus::Skipped), ] ); - assert_eq!( - relative(found[2].file.as_deref().unwrap(), "/project").as_deref(), - Some("test/a.test.js") - ); + assert_eq!(found[2].file.as_deref(), Some("/project/test/a.test.js")); } #[test] @@ -97,76 +94,6 @@ fn todo_is_skipped() { assert_eq!(cases(report).unwrap()[0].status, TestStatus::Skipped); } -#[test] -fn a_windows_file_under_a_verbatim_cwd_is_relative() { - let file = r"C:\work\app\test\a.test.js"; - assert_eq!( - relative(file, r"\\?\C:\work\app").as_deref(), - Some("test/a.test.js") - ); - assert_eq!( - relative(file, r"\\?\c:\work\app\").as_deref(), - Some("test/a.test.js") - ); - assert_eq!( - relative(r"\\server\share\app\t.js", r"\\?\UNC\server\share\app").as_deref(), - Some("t.js") - ); - assert_eq!(relative(file, r"\\?\D:\work\app"), None); -} - -#[test] -fn a_private_var_alias_is_relative() { - let file = "/var/folders/x/T/p/test/a.test.js"; - assert_eq!( - relative(file, "/private/var/folders/x/T/p").as_deref(), - Some("test/a.test.js") - ); - assert_eq!( - relative("/private/tmp/p/test/a.test.js", "/tmp/p").as_deref(), - Some("test/a.test.js") - ); - assert_eq!(relative("/variable/p/a.js", "/private/variable/p"), None); -} - -#[test] -fn a_file_outside_cwd_is_none() { - assert_eq!(relative("/elsewhere/test/a.test.js", "/project"), None); - assert_eq!(relative("/project-two/a.test.js", "/project"), None); - assert_eq!(relative("/project", "/project"), None); - assert_eq!( - relative("./test/a.test.js", "/project").as_deref(), - Some("test/a.test.js") - ); - assert_eq!( - relative("/project/a.js", "/").as_deref(), - Some("project/a.js") - ); -} - -#[test] -fn a_file_that_climbs_out_through_dot_dot_is_outside() { - for escaping in [ - "../x.test.js", - "./test/../../x.test.js", - r"..\x.test.js", - "/project/../x.test.js", - "/project/test/../../elsewhere/x.test.js", - ] { - assert_eq!(relative(escaping, "/project"), None, "{escaping}"); - } - for (inside, expected) in [ - ("test/../src/a.test.js", "src/a.test.js"), - ("/project/test/./unit/../a.test.js", "test/a.test.js"), - ] { - assert_eq!( - relative(inside, "/project").as_deref(), - Some(expected), - "{inside}" - ); - } -} - #[test] fn a_time_is_a_finite_non_negative_number() { for (time, seconds) in [ diff --git a/extensions/code/kani/Cargo.lock b/extensions/code/kani/Cargo.lock new file mode 100644 index 0000000000..1fa4adbbe2 --- /dev/null +++ b/extensions/code/kani/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "specforge-code-kani" +version = "1.0.0" diff --git a/extensions/code/kani/Cargo.toml b/extensions/code/kani/Cargo.toml new file mode 100644 index 0000000000..4f9e0a6023 --- /dev/null +++ b/extensions/code/kani/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "specforge-code-kani" +version = "1.0.0" +edition = "2021" +description = "The Kani regular-output reader @rust/proof links (ADR 0389 D10); no guest" +publish = false + +# An extension library (ADR 0328 D3): an rlib a builtin links, never embedded. +[lib] +crate-type = ["rlib"] diff --git a/extensions/code/kani/fixtures/README.md b/extensions/code/kani/fixtures/README.md new file mode 100644 index 0000000000..763c3fcdb9 --- /dev/null +++ b/extensions/code/kani/fixtures/README.md @@ -0,0 +1,15 @@ +# Kani reader fixtures + +Every fixture is hand-written to Kani's `--output-format regular` standard output as `kani-driver/src/harness_runner.rs` +prints it and Kani's own tests expect it (`tests/expected/*/expected`; the Phase 11 research, section B6). Kani was not +installable on the authoring host: it runs on Linux x86_64 and macOS only (ADR 0389 D12), and its compiler and CBMC +were not set up there. Each fixture is to be replaced by a recording of a real `cargo-kani --workspace +--output-format regular` run, its absolute paths replaced by `/project`. + +| Fixture | Source | +|---------|--------| +| `one-crate.txt` | hand-written: crate `demo` (`/project`), one harness `proofs::check_add` with two of its twelve checks shown, ` ** 0 of 12 failed`, `VERIFICATION:- SUCCESSFUL`, `Verification Time: 0.3897019s`, `Manual Harness Summary:` and `Complete - 1 successfully verified harnesses, 0 failures, 1 total.` | +| `workspace.txt` | hand-written: a two-crate workspace, so two runs: crate `ledger` (`crates/ledger`) with `proofs::balance_never_negative` and `proofs::transfer_conserves`, then `Complete - 2 ... 2 total.`; crate `vault` (`crates/vault`) with `checks::seal_roundtrip`, then `Complete - 1 ... 1 total.` | +| `failed.txt` | hand-written: crate `demo`, `proofs::check_add` SUCCESSFUL with a `Status: SATISFIED` cover check and the ` ** 1 of 1 cover properties satisfied` line, `proofs::check_bound` FAILED (` ** 1 of 7 failed`, `Failed Checks:`, an unwinding assertion check), `Verification failed for - proofs::check_bound` and `Complete - 1 successfully verified harnesses, 1 failures, 2 total.` | +| `none.txt` | hand-written: a crate with no harness, `No proof harnesses (functions with #[kani::proof]) were found to verify.` | +| `truncated.txt` | hand-written: `proofs::check_add`'s output cut off inside its checks, with no `VERIFICATION:-` line and no `Complete` line | diff --git a/extensions/code/kani/fixtures/failed.txt b/extensions/code/kani/fixtures/failed.txt new file mode 100644 index 0000000000..d787ed7f27 --- /dev/null +++ b/extensions/code/kani/fixtures/failed.txt @@ -0,0 +1,52 @@ +Kani Rust Verifier 0.68.0 (cargo plugin) + Compiling demo v0.1.0 (/project) + Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.40s +Checking harness proofs::check_add... +CBMC 6.8.0 (cbmc-6.8.0) + +RESULTS: +Check 1: proofs::check_add.assertion.1 + - Status: SUCCESS + - Description: "assertion failed: add(a, b) >= a" + - Location: src/lib.rs:11:9 in function proofs::check_add + +Check 2: proofs::check_add.cover.1 + - Status: SATISFIED + - Description: "cover condition: a > 0" + - Location: src/lib.rs:12:9 in function proofs::check_add + + +SUMMARY: + ** 0 of 5 failed + + ** 1 of 1 cover properties satisfied + +VERIFICATION:- SUCCESSFUL +Verification Time: 0.2s + +Checking harness proofs::check_bound... +CBMC 6.8.0 (cbmc-6.8.0) + +RESULTS: +Check 1: proofs::check_bound.assertion.1 + - Status: FAILURE + - Description: "assertion failed: x < 3" + - Location: src/lib.rs:20:9 in function proofs::check_bound + +Check 2: proofs::check_bound.unwind.0 + - Status: SUCCESS + - Description: "unwinding assertion loop 0" + - Location: src/lib.rs:18:5 in function proofs::check_bound + + +SUMMARY: + ** 1 of 7 failed +Failed Checks: assertion failed: x < 3 + File: "src/lib.rs", line 20, in proofs::check_bound + +VERIFICATION:- FAILED +Verification Time: 0.31s + +Manual Harness Summary: +Verification failed for - proofs::check_bound +Complete - 1 successfully verified harnesses, 1 failures, 2 total. diff --git a/extensions/code/kani/fixtures/none.txt b/extensions/code/kani/fixtures/none.txt new file mode 100644 index 0000000000..d1319d26a0 --- /dev/null +++ b/extensions/code/kani/fixtures/none.txt @@ -0,0 +1,4 @@ +Kani Rust Verifier 0.68.0 (cargo plugin) + Compiling demo v0.1.0 (/project) + Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.38s +No proof harnesses (functions with #[kani::proof]) were found to verify. diff --git a/extensions/code/kani/fixtures/one-crate.txt b/extensions/code/kani/fixtures/one-crate.txt new file mode 100644 index 0000000000..76dffb8cc6 --- /dev/null +++ b/extensions/code/kani/fixtures/one-crate.txt @@ -0,0 +1,33 @@ +Kani Rust Verifier 0.68.0 (cargo plugin) + Compiling demo v0.1.0 (/project) + Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s +Checking harness proofs::check_add... +CBMC 6.8.0 (cbmc-6.8.0) +CBMC version 6.8.0 (cbmc-6.8.0) 64-bit arm64 macos +Reading GOTO program from file /project/target/kani/aarch64-apple-darwin/debug/deps/demo-proofs_check_add.out +Generating GOTO Program +Running propositional reduction +Solving with CaDiCaL 2.0.0 +Runtime Solver: 0.0012s +Runtime decision procedure: 0.0013s + +RESULTS: +Check 1: demo::add.arithmetic_overflow.1 + - Status: SUCCESS + - Description: "attempt to add with overflow" + - Location: src/lib.rs:2:5 in function demo::add + +Check 2: proofs::check_add.assertion.1 + - Status: SUCCESS + - Description: "assertion failed: add(a, b) >= a" + - Location: src/lib.rs:11:9 in function proofs::check_add + + +SUMMARY: + ** 0 of 12 failed + +VERIFICATION:- SUCCESSFUL +Verification Time: 0.3897019s + +Manual Harness Summary: +Complete - 1 successfully verified harnesses, 0 failures, 1 total. diff --git a/extensions/code/kani/fixtures/truncated.txt b/extensions/code/kani/fixtures/truncated.txt new file mode 100644 index 0000000000..320602443e --- /dev/null +++ b/extensions/code/kani/fixtures/truncated.txt @@ -0,0 +1,14 @@ +Kani Rust Verifier 0.68.0 (cargo plugin) + Compiling demo v0.1.0 (/project) + Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.40s +Checking harness proofs::check_add... +CBMC 6.8.0 (cbmc-6.8.0) + +RESULTS: +Check 1: proofs::check_add.assertion.1 + - Status: SUCCESS + - Description: "assertion failed: add(a, b) >= a" + - Location: src/lib.rs:11:9 in function proofs::check_add + +Check 2: proofs::check_add.arithmetic_overflow.1 + - Status: FAILURE diff --git a/extensions/code/kani/fixtures/workspace.txt b/extensions/code/kani/fixtures/workspace.txt new file mode 100644 index 0000000000..acfe50f039 --- /dev/null +++ b/extensions/code/kani/fixtures/workspace.txt @@ -0,0 +1,56 @@ +Kani Rust Verifier 0.68.0 (cargo plugin) + Compiling ledger v0.1.0 (/project/crates/ledger) + Compiling vault v0.1.0 (/project/crates/vault) + Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.07s +Checking harness proofs::balance_never_negative... +CBMC 6.8.0 (cbmc-6.8.0) + +RESULTS: +Check 1: ledger::Ledger::debit.assertion.1 + - Status: SUCCESS + - Description: "assertion failed: self.balance >= amount" + - Location: crates/ledger/src/lib.rs:14:9 in function ledger::Ledger::debit + + +SUMMARY: + ** 0 of 4 failed + +VERIFICATION:- SUCCESSFUL +Verification Time: 0.211s + +Checking harness proofs::transfer_conserves... +CBMC 6.8.0 (cbmc-6.8.0) + +RESULTS: +Check 1: proofs::transfer_conserves.assertion.1 + - Status: SUCCESS + - Description: "assertion failed: a.balance + b.balance == total" + - Location: crates/ledger/src/lib.rs:41:9 in function proofs::transfer_conserves + + +SUMMARY: + ** 0 of 9 failed + +VERIFICATION:- SUCCESSFUL +Verification Time: 0.5s + +Manual Harness Summary: +Complete - 2 successfully verified harnesses, 0 failures, 2 total. +Checking harness checks::seal_roundtrip... +CBMC 6.8.0 (cbmc-6.8.0) + +RESULTS: +Check 1: checks::seal_roundtrip.assertion.1 + - Status: SUCCESS + - Description: "assertion failed: open(seal(x)) == x" + - Location: crates/vault/src/lib.rs:22:9 in function checks::seal_roundtrip + + +SUMMARY: + ** 0 of 3 failed + +VERIFICATION:- SUCCESSFUL +Verification Time: 1.25s + +Manual Harness Summary: +Complete - 1 successfully verified harnesses, 0 failures, 1 total. diff --git a/extensions/code/kani/src/lib.rs b/extensions/code/kani/src/lib.rs new file mode 100644 index 0000000000..eecd2b81dd --- /dev/null +++ b/extensions/code/kani/src/lib.rs @@ -0,0 +1,227 @@ +//! `specforge-code-kani`: the reader of Kani's regular output that `@rust/proof` links (ADR 0389 D10). +//! +//! An extension library (ADR 0328 D3): an rlib a builtin links, never a component of its own. It parses text and +//! depends on nothing; `@rust/proof` names each harness and mints its `test` facts. +//! +//! The format is Kani's `--output-format regular` standard output, as `kani-driver/src/harness_runner.rs` prints it +//! and Kani's own tests expect it: per harness a `Checking harness ...` line, its checks, `SUMMARY:` followed by +//! ` ** of failed`, `VERIFICATION:- SUCCESSFUL` or `VERIFICATION:- FAILED` and +//! `Verification Time: s`; after a crate's harnesses `Manual Harness Summary:`, a `Verification failed for - +//! ` line per failure, then `Complete - successfully verified harnesses, failures, total.` + +#[cfg(test)] +mod tests; + +/// One `Complete` line's harnesses: one crate's run. +#[derive(Debug, Clone, PartialEq)] +pub struct Run { + /// The harnesses in output order. + pub harnesses: Vec, + /// The `Complete` line's numbers. + pub successes: usize, + pub failures: usize, + pub total: usize, +} + +/// One proof harness and Kani's verdict on it. +#[derive(Debug, Clone, PartialEq)] +pub struct Harness { + /// Kani's name for it, the harness path without its crate (`proofs::check_add`). + pub name: String, + pub verdict: Verdict, + /// From ` ** of failed`, when printed. + pub failed_checks: Option, + pub checks: Option, + /// From `Verification Time: s`, when printed. + pub seconds: Option, +} + +/// The `VERIFICATION:-` line's word. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + Successful, + Failed, +} + +/// A harness whose `VERIFICATION:-` line is not read yet. +struct Open { + name: String, + /// Its `Checking harness` line, 1-based. + at: usize, + failed_checks: Option, + checks: Option, +} + +/// Kani's regular output `text` read into its runs, in output order, in one pass over its lines (a trailing `\r` +/// dropped, every line not named in the crate doc ignored). Only the `VERIFICATION:-` line sets a verdict: a check's +/// status (a cover's `SATISFIED`, an unwinding assertion's `FAILURE`) never does, as Kani itself decides what a +/// harness's checks mean (`#[kani::should_panic]` inverts them). No harness (`No proof harnesses ... were found`, or +/// empty text) is no run and no error: the text cannot tell "no harness" from "Kani never reached one", so the caller +/// says which it cannot tell (`@rust/proof` warns). +/// +/// An output that stops early is an Err naming its 1-based line, never a shorter list: a harness with no verdict, a +/// harness started before the last one's verdict, harnesses after the last `Complete` line, a `Complete` line whose +/// numbers differ from the harnesses read since the one before, or a number that does not parse. +pub fn read(text: &str) -> Result, String> { + let mut runs = Vec::new(); + let mut done: Vec = Vec::new(); + let mut open: Option = None; + // The line opening the first harness since the last `Complete`, while any is read. + let mut run_from: Option = None; + let mut after_summary = false; + for (index, raw) in text.lines().enumerate() { + let at = index + 1; + let line = raw.strip_suffix('\r').unwrap_or(raw).trim(); + if after_summary && !line.is_empty() { + after_summary = false; + if let Some(counts) = line.strip_prefix("** ") { + let (failed, checks) = + summary(counts).map_err(|why| format!("line {at}: {why}"))?; + if let Some(open) = open.as_mut() { + open.failed_checks = Some(failed); + open.checks = Some(checks); + } + continue; + } + } + if let Some(name) = line.strip_prefix("Checking harness ") { + let name = name.strip_suffix("...").unwrap_or(name).trim(); + if name.is_empty() { + return Err(format!( + "line {at}: a 'Checking harness' line names no harness" + )); + } + if let Some(before) = &open { + return Err(format!( + "line {at}: the harness '{name}' starts before the harness '{}' (line {}) has its \ + VERIFICATION line", + before.name, before.at + )); + } + open = Some(Open { + name: name.to_string(), + at, + failed_checks: None, + checks: None, + }); + } else if line == "SUMMARY:" { + after_summary = true; + } else if let Some(word) = line.strip_prefix("VERIFICATION:- ") { + let verdict = match word { + "SUCCESSFUL" => Verdict::Successful, + "FAILED" => Verdict::Failed, + other => return Err(format!("line {at}: '{other}' is no Kani verdict")), + }; + let Some(open) = open.take() else { + return Err(format!( + "line {at}: a VERIFICATION line with no 'Checking harness' line before it" + )); + }; + run_from.get_or_insert(open.at); + done.push(Harness { + name: open.name, + verdict, + failed_checks: open.failed_checks, + checks: open.checks, + seconds: None, + }); + } else if let Some(time) = line.strip_prefix("Verification Time: ") { + let seconds = time + .strip_suffix('s') + .and_then(|s| s.parse::().ok()) + .filter(|s| s.is_finite() && *s >= 0.0) + .ok_or_else(|| format!("line {at}: '{time}' is no verification time"))?; + if let Some(last) = done.last_mut().filter(|h| h.seconds.is_none()) { + last.seconds = Some(seconds); + } + } else if let Some(totals) = line.strip_prefix("Complete - ") { + if let Some(open) = &open { + return Err(format!( + "line {at}: Complete comes before the harness '{}' (line {}) has its VERIFICATION line", + open.name, open.at + )); + } + let (successes, failures, total) = + complete(totals).map_err(|why| format!("line {at}: {why}"))?; + let passed = done + .iter() + .filter(|h| h.verdict == Verdict::Successful) + .count(); + let read = (passed, done.len() - passed, done.len()); + if (successes, failures, total) != read { + return Err(format!( + "line {at}: Complete says {successes} successful, {failures} failed, {total} total; the \ + harnesses read since the last Complete are {} successful, {} failed, {} total", + read.0, read.1, read.2 + )); + } + run_from = None; + runs.push(Run { + harnesses: std::mem::take(&mut done), + successes, + failures, + total, + }); + } + } + if let Some(open) = open { + return Err(format!( + "the harness '{}' (line {}) has no VERIFICATION line: {CUT_OFF}", + open.name, open.at + )); + } + if let Some(from) = run_from { + return Err(format!( + "{} harnesses from line {from} have no Complete line: {CUT_OFF}", + done.len() + )); + } + Ok(runs) +} + +/// Why an output with an unfinished run is refused rather than read. +const CUT_OFF: &str = + "the output stops before Kani's Complete line: a cut-off run would drop a proof"; + +/// ` of failed[ trailing text]`. +fn summary(counts: &str) -> Result<(usize, usize), String> { + let bad = || format!("'** {counts}' is no '** of failed' summary"); + let (failed, rest) = counts.split_once(" of ").ok_or_else(bad)?; + let (checks, _) = rest.split_once(" failed").ok_or_else(bad)?; + Ok(( + number(failed).ok_or_else(bad)?, + number(checks).ok_or_else(bad)?, + )) +} + +/// ` successfully verified harnesses, failures, total.` +fn complete(totals: &str) -> Result<(usize, usize, usize), String> { + let bad = || { + format!( + "'Complete - {totals}' is no ' successfully verified harnesses, failures, total.' line" + ) + }; + let mut parts = totals.split(", "); + let mut part = |suffix: &str| { + parts + .next() + .and_then(|p| p.strip_suffix(suffix)) + .and_then(number) + .ok_or_else(bad) + }; + let successes = part(" successfully verified harnesses")?; + let failures = part(" failures")?; + let total = part(" total.")?; + match parts.next() { + None => Ok((successes, failures, total)), + Some(_) => Err(bad()), + } +} + +/// A count written in decimal digits only. +fn number(text: &str) -> Option { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse().ok() +} diff --git a/extensions/code/kani/src/tests.rs b/extensions/code/kani/src/tests.rs new file mode 100644 index 0000000000..4231e2adf9 --- /dev/null +++ b/extensions/code/kani/src/tests.rs @@ -0,0 +1,237 @@ +use super::*; + +const ONE_CRATE: &str = include_str!("../fixtures/one-crate.txt"); +const WORKSPACE: &str = include_str!("../fixtures/workspace.txt"); +const FAILED: &str = include_str!("../fixtures/failed.txt"); +const NONE: &str = include_str!("../fixtures/none.txt"); +const TRUNCATED: &str = include_str!("../fixtures/truncated.txt"); + +/// A harness block: its `Checking harness` line, the summary and the verdict (six lines). +fn block(name: &str, verdict: &str) -> String { + format!( + "Checking harness {name}...\n\nSUMMARY:\n ** 0 of 1 failed\n\nVERIFICATION:- {verdict}\n" + ) +} + +/// Each harness's `(name, verdict)`, run by run. +fn verdicts(runs: &[Run]) -> Vec> { + runs.iter() + .map(|run| { + run.harnesses + .iter() + .map(|h| (h.name.as_str(), h.verdict)) + .collect() + }) + .collect() +} + +#[test] +fn one_crates_harness_is_one_run() { + let runs = read(ONE_CRATE).unwrap(); + assert_eq!( + runs, + [Run { + harnesses: vec![Harness { + name: "proofs::check_add".to_string(), + verdict: Verdict::Successful, + failed_checks: Some(0), + checks: Some(12), + seconds: Some(0.3897019), + }], + successes: 1, + failures: 0, + total: 1, + }] + ); +} + +#[test] +fn a_workspace_is_one_run_per_complete_line_in_order() { + let runs = read(WORKSPACE).unwrap(); + assert_eq!( + verdicts(&runs), + [ + vec![ + ("proofs::balance_never_negative", Verdict::Successful), + ("proofs::transfer_conserves", Verdict::Successful), + ], + vec![("checks::seal_roundtrip", Verdict::Successful)], + ] + ); + assert_eq!( + runs.iter() + .map(|r| (r.successes, r.failures, r.total)) + .collect::>(), + [(2, 0, 2), (1, 0, 1)] + ); + assert_eq!(runs[1].harnesses[0].seconds, Some(1.25)); +} + +#[test] +fn a_failed_harness_is_failed_and_counts_its_failed_checks() { + let runs = read(FAILED).unwrap(); + assert_eq!( + verdicts(&runs), + [vec![ + ("proofs::check_add", Verdict::Successful), + ("proofs::check_bound", Verdict::Failed), + ]] + ); + let [add, bound] = &runs[0].harnesses[..] else { + panic!("two harnesses: {runs:?}"); + }; + assert_eq!((add.failed_checks, add.checks), (Some(0), Some(5))); + assert_eq!((bound.failed_checks, bound.checks), (Some(1), Some(7))); + assert_eq!(bound.seconds, Some(0.31)); + assert_eq!( + (runs[0].successes, runs[0].failures, runs[0].total), + (1, 1, 2) + ); +} + +#[test] +fn only_the_verification_line_sets_a_verdict() { + let checks = |status: &str, verdict: &str| { + format!( + "Checking harness p...\nCheck 1: p.cover.1\n\t - Status: {status}\n\t - Description: \"unwinding \ + assertion loop 0\"\n\nSUMMARY:\n ** 0 of 1 failed\n\nVERIFICATION:- {verdict}\nComplete - {} \ + successfully verified harnesses, {} failures, 1 total.\n", + usize::from(verdict == "SUCCESSFUL"), + usize::from(verdict == "FAILED"), + ) + }; + for (status, verdict, expected) in [ + ("FAILURE", "SUCCESSFUL", Verdict::Successful), + ("SATISFIED", "FAILED", Verdict::Failed), + ("UNSATISFIABLE", "SUCCESSFUL", Verdict::Successful), + ("SUCCESS", "FAILED", Verdict::Failed), + ] { + let runs = read(&checks(status, verdict)).unwrap(); + assert_eq!( + verdicts(&runs), + [vec![("p", expected)]], + "{status} {verdict}" + ); + } +} + +#[test] +fn a_harness_without_a_summary_or_a_time_keeps_them_unknown() { + let text = "Checking harness p...\nVERIFICATION:- SUCCESSFUL\n\nComplete - 1 successfully verified harnesses, \ + 0 failures, 1 total.\n"; + let harness = &read(text).unwrap()[0].harnesses[0]; + assert_eq!( + (harness.failed_checks, harness.checks, harness.seconds), + (None, None, None) + ); +} + +#[test] +fn no_harness_is_no_run_and_no_error() { + for text in [NONE, "", "\n\n"] { + assert_eq!(read(text), Ok(Vec::new()), "{text:?}"); + } +} + +#[test] +fn a_cut_off_or_inconsistent_output_is_an_error_naming_its_line() { + let one = block("a", "SUCCESSFUL"); + let complete = |s: usize, f: usize, t: usize| { + format!("Complete - {s} successfully verified harnesses, {f} failures, {t} total.\n") + }; + let after_one_crate = format!( + "1 harnesses from line {} have no Complete line", + ONE_CRATE.lines().count() + 1 + ); + let rows: Vec<(String, &str)> = vec![ + (TRUNCATED.to_string(), "(line 4) has no VERIFICATION line"), + ( + format!("{ONE_CRATE}{}", block("b", "FAILED")), + &after_one_crate, + ), + ( + format!("{one}{}", complete(1, 0, 2)), + "line 7: Complete says", + ), + ( + format!("{one}{}", complete(0, 1, 1)), + "line 7: Complete says", + ), + ( + format!("{}{}", block("a", "FAILED"), complete(1, 0, 1)), + "line 7: Complete says", + ), + ( + format!("Checking harness a...\n{one}"), + "line 2: the harness 'a' starts before the harness 'a' (line 1)", + ), + ( + format!("Checking harness a...\n{}", complete(0, 0, 0)), + "line 2: Complete comes before the harness 'a' (line 1)", + ), + ( + format!("{one}Complete - x successfully verified harnesses, 0 failures, 1 total.\n"), + "line 7: 'Complete - x", + ), + ( + format!( + "{one}Complete - 1 successfully verified harnesses, 0 failures, 1 total, 2 more.\n" + ), + "line 7: 'Complete - 1", + ), + ( + "Checking harness a...\nSUMMARY:\n ** 1x of 3 failed\n".to_string(), + "line 3: '** 1x of 3 failed'", + ), + ( + format!("{one}Verification Time: NaNs\n{}", complete(1, 0, 1)), + "line 7: 'NaNs' is no verification time", + ), + ( + "VERIFICATION:- SUCCESSFUL\n".to_string(), + "line 1: a VERIFICATION line", + ), + ( + "Checking harness a...\nVERIFICATION:- UNDETERMINED\n".to_string(), + "line 2: 'UNDETERMINED' is no Kani verdict", + ), + ( + "Checking harness ...\n".to_string(), + "line 1: a 'Checking harness' line", + ), + ]; + for (text, expected) in &rows { + let why = read(text).unwrap_err(); + assert!( + why.contains(expected), + "{expected:?} not in {why:?} for {text:?}" + ); + assert!(why.contains("line") || why.contains("Complete"), "{why}"); + } +} + +#[test] +fn crlf_text_reads_like_lf() { + for text in [ONE_CRATE, WORKSPACE, FAILED] { + assert_eq!(read(&text.replace('\n', "\r\n")), read(text)); + } +} + +#[test] +fn a_200000_line_output_reads_in_one_pass() { + let harnesses = 200_000usize.div_ceil(6); + let mut text = String::with_capacity(harnesses * 64); + for at in 0..harnesses { + text.push_str(&block(&format!("proofs::p{at}"), "SUCCESSFUL")); + } + text.push_str(&format!( + "Complete - {harnesses} successfully verified harnesses, 0 failures, {harnesses} total.\n" + )); + assert!(text.lines().count() >= 200_000); + let runs = read(&text).unwrap(); + assert_eq!(runs[0].harnesses.len(), harnesses); + assert_eq!( + runs[0].harnesses[harnesses - 1].name, + format!("proofs::p{}", harnesses - 1) + ); +} diff --git a/extensions/code/lcov/Cargo.lock b/extensions/code/lcov/Cargo.lock new file mode 100644 index 0000000000..c2ec163c31 --- /dev/null +++ b/extensions/code/lcov/Cargo.lock @@ -0,0 +1,646 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "windows-sys", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "insta" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67d3d2e287e4b86c10b3f3b641033d1f89b74bdb39d05f34952e2b9a6fe21cd" +dependencies = [ + "console", + "once_cell", + "serde", + "similar", + "tempfile", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-lcov" +version = "1.0.0" +dependencies = [ + "insta", + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/code/lcov/Cargo.toml b/extensions/code/lcov/Cargo.toml new file mode 100644 index 0000000000..83e51ff68d --- /dev/null +++ b/extensions/code/lcov/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "specforge-code-lcov" +version = "1.0.0" +edition = "2021" +description = "The LCOV reader the coverage packs link (ADR 0388); no guest" +publish = false + +# An extension library (ADR 0328 D3): an rlib a builtin links, never embedded. +[lib] +crate-type = ["rlib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-facts = { path = "../facts" } + +[dev-dependencies] +serde_json = "1.0" +insta = { version = "1.46.3", features = ["json"] } diff --git a/extensions/code/lcov/fixtures/README.md b/extensions/code/lcov/fixtures/README.md new file mode 100644 index 0000000000..11ffde7be9 --- /dev/null +++ b/extensions/code/lcov/fixtures/README.md @@ -0,0 +1,13 @@ +# LCOV reader fixtures + +Each fixture is hand-written to the grammar or source named below, except the one marked recorded, which a real tool +wrote. A hand-written fixture is replaced by a recording when its tool can be run. + +| Fixture | Source | +|---------|--------| +| `llvm-cov.info` | hand-written to llvm-cov's `CoverageExporterLcov` output (`cargo llvm-cov --lcov`): absolute `SF`, `FN:,` with no end line, `FNDA`, `DA`, `BRDA`, the file totals and `end_of_record`. Crate `demo` at `/project`: `add` (lines 3-5), `Board::len` in an impl (12-14), `tests::adds` in `mod tests` (21-24), `helper` with two monomorphizations (27-34), and line 37 in no item | +| `c8.info` | hand-written to istanbul-reports lcovonly (`c8 --reporter=lcovonly`): an empty `TN`, relative `SF:src/board.js`, `FN:,`, the totals after each family. Package `board`: `createBoard` (lines 2-8), class `Board` (10-18) with `constructor` (11-13) and `add` (14-17), and a top-level call on line 20 in no item | +| `c8-12.0.0.info` | recorded with c8 12.0.0 (`--reporter=lcovonly`) around `npm test` (node:test) on a one-file project, package `board`, unchanged: it holds no absolute path. V8 names the class constructor after the class (`FN:5,Board`). Its served facts are `c8-12.0.0.items.json` | +| `c8-12.0.0.items.json` | hand-written served facts for that project: `src/board.js`'s `createBoard` (lines 1-3), class `Board` (4-7) with its constructor (5) and `add` (6), and the package `board`, where the recorded file writes them | +| `lcov2.info` | hand-written to geninfo(1) LCOV 2.2: `#` comment, `TN`, `VER`, function groups `FNL:,,` with their aliases `FNA:,,` (one name holding a comma), `MCDC`/`MCF`/`MCH`. The same counts as `llvm-cov.info`, in group form | +| `items.json` | hand-written served facts: the `item` facts (with their places) and the root `package` a coverage collector receives, for the crate `demo` (`src/lib.rs`) and the npm package `board` (`src/board.js`) | diff --git a/extensions/code/lcov/fixtures/c8-12.0.0.info b/extensions/code/lcov/fixtures/c8-12.0.0.info new file mode 100644 index 0000000000..0c0cb44a7d --- /dev/null +++ b/extensions/code/lcov/fixtures/c8-12.0.0.info @@ -0,0 +1,26 @@ +TN: +SF:src/board.js +FN:1,createBoard +FN:5,Board +FN:6,add +FNF:3 +FNH:3 +FNDA:2,createBoard +FNDA:2,Board +FNDA:2,add +DA:1,2 +DA:2,2 +DA:3,2 +DA:4,2 +DA:5,2 +DA:6,2 +DA:7,2 +LF:7 +LH:7 +BRDA:1,0,0,2 +BRDA:1,1,0,2 +BRDA:5,2,0,2 +BRDA:6,3,0,2 +BRF:4 +BRH:4 +end_of_record diff --git a/extensions/code/lcov/fixtures/c8-12.0.0.items.json b/extensions/code/lcov/fixtures/c8-12.0.0.items.json new file mode 100644 index 0000000000..9d163ccc38 --- /dev/null +++ b/extensions/code/lcov/fixtures/c8-12.0.0.items.json @@ -0,0 +1,18 @@ +[ + {"kind": "item", "id": "js:board/src/board.js::createBoard", + "fields": {"kind": ["function"], "package": "pkg:npm/board", "file": "src/board.js", "visibility": "public", + "attrs": ["export"]}, + "at": [{"file": "src/board.js", "start_line": 1, "start_col": 8, "end_line": 3, "end_col": 2}]}, + {"kind": "item", "id": "js:board/src/board.js::Board", + "fields": {"kind": ["class"], "package": "pkg:npm/board", "file": "src/board.js", "visibility": "public", + "attrs": ["export"]}, + "at": [{"file": "src/board.js", "start_line": 4, "start_col": 8, "end_line": 7, "end_col": 2}]}, + {"kind": "item", "id": "js:board/src/board.js::Board.constructor", + "fields": {"kind": ["method"], "package": "pkg:npm/board", "file": "src/board.js", "visibility": "public"}, + "at": [{"file": "src/board.js", "start_line": 5, "start_col": 3, "end_line": 5, "end_col": 37}]}, + {"kind": "item", "id": "js:board/src/board.js::Board.add", + "fields": {"kind": ["method"], "package": "pkg:npm/board", "file": "src/board.js", "visibility": "public"}, + "at": [{"file": "src/board.js", "start_line": 6, "start_col": 3, "end_line": 6, "end_col": 46}]}, + {"kind": "package", "id": "pkg:npm/board", + "fields": {"name": "board", "version": "1.0.0", "path": ""}} +] diff --git a/extensions/code/lcov/fixtures/c8.info b/extensions/code/lcov/fixtures/c8.info new file mode 100644 index 0000000000..e0dc778e11 --- /dev/null +++ b/extensions/code/lcov/fixtures/c8.info @@ -0,0 +1,25 @@ +TN: +SF:src/board.js +FN:2,createBoard +FN:11,constructor +FN:14,add +FNF:3 +FNH:2 +FNDA:2,createBoard +FNDA:2,constructor +FNDA:0,add +DA:3,2 +DA:4,2 +DA:5,1 +DA:7,2 +DA:12,2 +DA:15,0 +DA:16,0 +DA:20,1 +LF:8 +LH:6 +BRDA:4,0,0,1 +BRDA:4,0,1,1 +BRF:2 +BRH:2 +end_of_record diff --git a/extensions/code/lcov/fixtures/items.json b/extensions/code/lcov/fixtures/items.json new file mode 100644 index 0000000000..f55a0fd3dc --- /dev/null +++ b/extensions/code/lcov/fixtures/items.json @@ -0,0 +1,40 @@ +[ + {"kind": "item", "id": "rust:demo::add", + "fields": {"kind": ["fn"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "public"}, + "at": [{"file": "src/lib.rs", "start_line": 3, "start_col": 1, "end_line": 5, "end_col": 2}]}, + {"kind": "item", "id": "rust:demo::Board", + "fields": {"kind": ["struct"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "public"}, + "at": [{"file": "src/lib.rs", "start_line": 7, "start_col": 1, "end_line": 9, "end_col": 2}]}, + {"kind": "item", "id": "rust:demo::Board::len", + "fields": {"kind": ["fn"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "public"}, + "at": [{"file": "src/lib.rs", "start_line": 12, "start_col": 5, "end_line": 14, "end_col": 6}]}, + {"kind": "item", "id": "rust:demo::tests", + "fields": {"kind": ["mod"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "private", + "attrs": ["cfg(test)"]}, + "at": [{"file": "src/lib.rs", "start_line": 17, "start_col": 1, "end_line": 25, "end_col": 2}]}, + {"kind": "item", "id": "rust:demo::tests::adds", + "fields": {"kind": ["fn"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "private", + "attrs": ["test"], "test_id": "rust:demo#tests::adds"}, + "at": [{"file": "src/lib.rs", "start_line": 21, "start_col": 5, "end_line": 24, "end_col": 6}]}, + {"kind": "item", "id": "rust:demo::helper", + "fields": {"kind": ["fn"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "public"}, + "at": [{"file": "src/lib.rs", "start_line": 27, "start_col": 1, "end_line": 34, "end_col": 2}]}, + {"kind": "package", "id": "pkg:cargo/demo", + "fields": {"name": "demo", "version": "0.1.0", "path": ""}}, + {"kind": "item", "id": "js:board/src/board.js::createBoard", + "fields": {"kind": ["function"], "package": "pkg:npm/board", "file": "src/board.js", "visibility": "public", + "attrs": ["export"]}, + "at": [{"file": "src/board.js", "start_line": 2, "start_col": 8, "end_line": 8, "end_col": 2}]}, + {"kind": "item", "id": "js:board/src/board.js::Board", + "fields": {"kind": ["class"], "package": "pkg:npm/board", "file": "src/board.js", "visibility": "public", + "attrs": ["export"]}, + "at": [{"file": "src/board.js", "start_line": 10, "start_col": 8, "end_line": 18, "end_col": 2}]}, + {"kind": "item", "id": "js:board/src/board.js::Board.constructor", + "fields": {"kind": ["method"], "package": "pkg:npm/board", "file": "src/board.js", "visibility": "public"}, + "at": [{"file": "src/board.js", "start_line": 11, "start_col": 3, "end_line": 13, "end_col": 4}]}, + {"kind": "item", "id": "js:board/src/board.js::Board.add", + "fields": {"kind": ["method"], "package": "pkg:npm/board", "file": "src/board.js", "visibility": "public"}, + "at": [{"file": "src/board.js", "start_line": 14, "start_col": 3, "end_line": 17, "end_col": 4}]}, + {"kind": "package", "id": "pkg:npm/board", + "fields": {"name": "board", "version": "1.0.0", "path": ""}} +] diff --git a/extensions/code/lcov/fixtures/lcov2.info b/extensions/code/lcov/fixtures/lcov2.info new file mode 100644 index 0000000000..c4b561914d --- /dev/null +++ b/extensions/code/lcov/fixtures/lcov2.info @@ -0,0 +1,41 @@ +# The demo crate of llvm-cov.info as geninfo 2.2 writes it: function groups and demangled names. +TN:demo +SF:/project/src/lib.rs +VER:2a4c9e1f +FNL:0,3,5 +FNA:0,4,demo::add +FNL:1,12,14 +FNA:1,2,::len +FNL:2,22,24 +FNA:2,1,demo::tests::adds +FNL:3,27,34 +FNA:3,3,demo::helper:: +FNA:3,0,demo::helper::<(u8, u16)> +FNF:4 +FNH:4 +DA:3,4 +DA:4,4 +DA:5,4 +DA:12,2 +DA:13,2 +DA:14,2 +DA:22,1 +DA:23,1 +DA:24,1 +DA:27,3 +DA:28,3 +DA:29,3 +DA:30,0 +DA:32,3 +DA:34,3 +DA:37,1 +BRDA:29,0,0,0 +BRDA:29,0,1,3 +BRF:2 +BRH:1 +MCDC:29,2,t,1,0,x > 2 +MCF:2 +MCH:1 +LF:16 +LH:15 +end_of_record diff --git a/extensions/code/lcov/fixtures/llvm-cov.info b/extensions/code/lcov/fixtures/llvm-cov.info new file mode 100644 index 0000000000..deead6b531 --- /dev/null +++ b/extensions/code/lcov/fixtures/llvm-cov.info @@ -0,0 +1,36 @@ +SF:/project/src/lib.rs +FN:3,_RNvCs4fqI2P2rA04_4demo3add +FN:12,_RNvMCs4fqI2P2rA04_4demoNtB2_5Board3len +FN:22,_RNvNtCs4fqI2P2rA04_4demo5tests4adds +FN:27,_RINvCs4fqI2P2rA04_4demo6helperhEB2_ +FN:27,_RINvCs4fqI2P2rA04_4demo6helpertEB2_ +FNDA:4,_RNvCs4fqI2P2rA04_4demo3add +FNDA:2,_RNvMCs4fqI2P2rA04_4demoNtB2_5Board3len +FNDA:1,_RNvNtCs4fqI2P2rA04_4demo5tests4adds +FNDA:3,_RINvCs4fqI2P2rA04_4demo6helperhEB2_ +FNDA:0,_RINvCs4fqI2P2rA04_4demo6helpertEB2_ +FNF:5 +FNH:4 +DA:3,4 +DA:4,4 +DA:5,4 +DA:12,2 +DA:13,2 +DA:14,2 +DA:22,1 +DA:23,1 +DA:24,1 +DA:27,3 +DA:28,3 +DA:29,3 +DA:30,0 +DA:32,3 +DA:34,3 +DA:37,1 +BRDA:29,0,0,0 +BRDA:29,0,1,3 +BRF:2 +BRH:1 +LF:16 +LH:15 +end_of_record diff --git a/extensions/code/lcov/src/lib.rs b/extensions/code/lcov/src/lib.rs new file mode 100644 index 0000000000..f81cc9db7d --- /dev/null +++ b/extensions/code/lcov/src/lib.rs @@ -0,0 +1,284 @@ +//! `specforge-code-lcov`: the LCOV reader the coverage packs link (ADR 0388). +//! +//! An extension library (ADR 0328 D3): an rlib a builtin links, never a component of its own. The wire has no +//! guest-to-guest call, so a coverage pack reads its tracefile here; `specforge-code-facts` mints the `coverage` facts +//! from what it reads ([`specforge_code_facts::coverage_facts`]). +//! +//! - [`read`] reads a tracefile (geninfo(1) LCOV, `cargo llvm-cov --lcov`, c8/istanbul `lcovonly`) into a +//! [`Tracefile`]: one [`CoverageFile`] per file section, its path made project-relative, and the paths outside the +//! project it skipped and counted (ADR 0389 D7). A path is only text here: the reader never opens a file. + +#[cfg(test)] +mod tests; + +use std::collections::{HashMap, HashSet}; + +use specforge_code_facts::{place, shown, Branch, CoverageFile, Function, Place}; + +/// What a tracefile says: its file sections in the project, and the paths outside it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Tracefile { + /// The file sections whose `SF` lies in the project, in document order. + pub files: Vec, + /// Each `SF` path outside the project, once, in document order, as [`shown`] writes it: its sections mint nothing. + pub outside: Vec, +} + +/// The LCOV tracefile `text` read against the project root `cwd`: its file sections in document order, each `SF:` +/// path made project-relative. Read: `SF`, `FN`, `FNDA`, the LCOV 2.2 group form `FNL`/`FNA`, `DA`, `BRDA` and +/// `end_of_record`; ignored: `TN`, `VER`, the file +/// totals (`FNF`, `FNH`, `LF`, `LH`, `BRF`, `BRH`), `MCDC`/`MCF`/`MCH`, `#` comments, blank lines and any other +/// all-capitals `KEY:`. An `SF` path is trimmed. A section whose `SF` lies outside the project (a path dependency +/// beside the workspace) is skipped: its path is counted in [`Tracefile::outside`] and its records still read for +/// syntax (ADR 0389 D7). An error names the 1-based line: a line that is no `KEY:value`, a record outside a file +/// section, a malformed number, an `SF` naming no file (empty, resolving to the project root itself, or a pseudo name +/// like ``: no section's file, and no path outside), and a text ending inside a file section, which must not drop +/// its last file. An empty text has no file. +pub fn read(text: &str, cwd: &str) -> Result { + let mut tracefile = Tracefile::default(); + let mut seen = HashSet::new(); + let mut open: Option
= None; + for (n, line) in text.lines().enumerate() { + let at = n + 1; + let line = line.strip_suffix('\r').unwrap_or(line); + if line.trim().is_empty() || line.starts_with('#') { + continue; + } + if line.trim_end() == "end_of_record" { + let section = open + .take() + .ok_or_else(|| format!("line {at}: end_of_record outside a file section"))?; + if !section.outside { + tracefile.files.push(section.file); + } + continue; + } + let (key, value) = line + .split_once(':') + .filter(|(key, _)| !key.is_empty() && key.bytes().all(|b| b.is_ascii_uppercase())) + .ok_or_else(|| format!("line {at}: `{}` is no LCOV record (KEY:value)", shown(line)))?; + if key == "SF" { + if let Some(section) = &open { + return Err(format!( + "line {at}: a new file section opens before `{}` (line {}) ends with end_of_record", + shown(§ion.file.file), + section.opened + )); + } + let value = value.trim(); + if value.is_empty() { + return Err(format!("line {at}: SF names no file")); + } + open = Some(match place(value, cwd) { + Place::File(file) => Section::new(file, at, false), + Place::NoFile => { + return Err(format!("line {at}: SF `{}` names no file", shown(value))) + } + Place::Outside => { + let path = shown(value); + if seen.insert(path.clone()) { + tracefile.outside.push(path); + } + Section::new(value.to_string(), at, true) + } + }); + continue; + } + if !matches!(key, "FN" | "FNDA" | "FNL" | "FNA" | "DA" | "BRDA") { + continue; + } + let section = open.as_mut().ok_or_else(|| { + format!("line {at}: the record {key} lies outside a file section (no SF before it)") + })?; + section + .record(key, value) + .map_err(|why| format!("line {at}: {key}:{} {why}", shown(value)))?; + } + match open { + Some(section) => Err(format!( + "line {}: the report ends inside the file `{}` opened here, with no end_of_record", + section.opened, + shown(§ion.file.file) + )), + None => Ok(tracefile), + } +} + +/// An open file section: what it has read so far, the line its `SF` was on, whether that path lies outside the +/// project, its functions by name and the start lines of its function groups. +struct Section { + file: CoverageFile, + opened: usize, + outside: bool, + /// Name → the functions of that name and the `FN` and `FNDA` records of it read so far. + named: HashMap, + /// `FNL` index → the group's start line. + groups: HashMap, +} + +/// The functions of one name, in the order their first record met them, and how many `FN` and `FNDA` records of the +/// name have been read: the n-th `FN` and the n-th `FNDA` of a name are one function's (two impls' `new`, `fmt`). +#[derive(Default)] +struct Named { + /// Indexes in `file.functions`. + functions: Vec, + fns: usize, + fndas: usize, +} + +impl Section { + fn new(file: String, opened: usize, outside: bool) -> Section { + Section { + file: CoverageFile { + file, + ..CoverageFile::default() + }, + opened, + outside, + named: HashMap::new(), + groups: HashMap::new(), + } + } + + /// Reads the record `key:value` of this section; the error says what is wrong with it. + fn record(&mut self, key: &str, value: &str) -> Result<(), String> { + match key { + // FN:[,],: the second field is an end line only when it is a number and a name + // follows, since a C++ name holds commas. + "FN" => { + let (line, rest) = value.split_once(',').ok_or("has no name")?; + let line = number(line)?; + let name = match rest.split_once(',') { + Some((end, name)) if end.trim().parse::().is_ok() => name, + _ => rest, + }; + self.function(line, name) + } + // FNDA:,: paired with the FN of that name and rank, else kept at line 0, which no item holds. + "FNDA" => { + let (hits, name) = value.split_once(',').ok_or("has no name")?; + let hits = count(hits)?; + if name.is_empty() { + return Err("has no name".to_string()); + } + let index = self.pair(name, Record::Fnda); + if let Some(function) = self.file.functions.get_mut(index) { + function.hits = function.hits.saturating_add(hits); + } + Ok(()) + } + // FNL:,[,]: a function group (LCOV 2.2), its aliases named by FNA. + "FNL" => { + let (index, lines) = value.split_once(',').ok_or("has no start line")?; + let (start, end) = match lines.split_once(',') { + Some((start, end)) => (start, Some(end)), + None => (lines, None), + }; + let start = number(start)?; + end.map(number).transpose()?; + self.groups.insert(index.trim().to_string(), start); + Ok(()) + } + // FNA:,,: one alias of a group, a function at its start line (0 with no FNL). + "FNA" => { + let mut fields = value.splitn(3, ','); + let index = fields.next().unwrap_or_default().trim(); + let hits = count(fields.next().ok_or("has no hit count")?)?; + let name = fields + .next() + .filter(|name| !name.is_empty()) + .ok_or("has no name")?; + self.file.functions.push(Function { + line: self.groups.get(index).copied().unwrap_or(0), + name: name.to_string(), + hits, + }); + Ok(()) + } + // DA:,[,] + "DA" => { + let mut fields = value.splitn(3, ','); + let line = number(fields.next().unwrap_or_default())?; + let hits = count(fields.next().ok_or("has no hit count")?)?; + self.file.lines.push((line, hits)); + Ok(()) + } + // BRDA:,,,: the branch may be an expression holding commas. + "BRDA" => { + let (line, rest) = value.split_once(',').ok_or("has no block")?; + let (rest, taken) = rest.rsplit_once(',').ok_or("has no taken count")?; + let (block, branch) = rest.split_once(',').ok_or("has no branch")?; + let taken = match taken.trim() { + "-" => None, + taken => Some(count(taken)?), + }; + self.file.branches.push(Branch { + line: number(line)?, + block: block.to_string(), + branch: branch.to_string(), + taken, + }); + Ok(()) + } + _ => Ok(()), + } + } + + /// A function starting at `line`: an `FNDA` of its name and rank read before it, kept at line 0, takes its line. + fn function(&mut self, line: usize, name: &str) -> Result<(), String> { + if name.is_empty() { + return Err("has no name".to_string()); + } + let index = self.pair(name, Record::Fn); + if let Some(function) = self.file.functions.get_mut(index) { + function.line = line; + } + Ok(()) + } + + /// The index of the function the next `record` of `name` belongs to: the n-th of its kind pairs with the n-th + /// function of that name, one no record has met yet appended at line 0 with no hit. + fn pair(&mut self, name: &str, record: Record) -> usize { + let named = self.named.entry(name.to_string()).or_default(); + let rank = match record { + Record::Fn => &mut named.fns, + Record::Fnda => &mut named.fndas, + }; + let at = *rank; + *rank += 1; + match named.functions.get(at) { + Some(&index) => index, + None => { + let index = self.file.functions.len(); + self.file.functions.push(Function { + line: 0, + name: name.to_string(), + hits: 0, + }); + named.functions.push(index); + index + } + } + } +} + +/// The two records that pair by name. +#[derive(Clone, Copy)] +enum Record { + Fn, + Fnda, +} + +/// A 1-based line number. +fn number(text: &str) -> Result { + text.trim() + .parse() + .map_err(|_| format!("has `{}` where a line number belongs", shown(text))) +} + +/// A hit or taken count. +fn count(text: &str) -> Result { + text.trim() + .parse() + .map_err(|_| format!("has `{}` where a count belongs", shown(text))) +} diff --git a/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__c8.snap b/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__c8.snap new file mode 100644 index 0000000000..260fa1d6d3 --- /dev/null +++ b/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__c8.snap @@ -0,0 +1,61 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "coverage", + "id": "cov:@src%2Fboard.js", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/board.js", + "functions_found": 0, + "functions_hit": 0, + "lines_found": 1, + "lines_hit": 1 + } + }, + { + "kind": "coverage", + "id": "cov:js:board/src/board.js::Board.add", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/board.js", + "functions_found": 1, + "functions_hit": 0, + "item": "js:board/src/board.js::Board.add", + "lines_found": 2, + "lines_hit": 0 + } + }, + { + "kind": "coverage", + "id": "cov:js:board/src/board.js::Board.constructor", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/board.js", + "functions_found": 1, + "functions_hit": 1, + "item": "js:board/src/board.js::Board.constructor", + "lines_found": 1, + "lines_hit": 1 + } + }, + { + "kind": "coverage", + "id": "cov:js:board/src/board.js::createBoard", + "fields": { + "branches_found": 2, + "branches_hit": 2, + "file": "src/board.js", + "functions_found": 1, + "functions_hit": 1, + "item": "js:board/src/board.js::createBoard", + "lines_found": 4, + "lines_hit": 4 + } + } +] diff --git a/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__c8_12.snap b/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__c8_12.snap new file mode 100644 index 0000000000..21d03f0728 --- /dev/null +++ b/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__c8_12.snap @@ -0,0 +1,62 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "coverage", + "id": "cov:js:board/src/board.js::Board", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/board.js", + "functions_found": 0, + "functions_hit": 0, + "item": "js:board/src/board.js::Board", + "lines_found": 2, + "lines_hit": 2 + } + }, + { + "kind": "coverage", + "id": "cov:js:board/src/board.js::Board.add", + "fields": { + "branches_found": 1, + "branches_hit": 1, + "file": "src/board.js", + "functions_found": 1, + "functions_hit": 1, + "item": "js:board/src/board.js::Board.add", + "lines_found": 1, + "lines_hit": 1 + } + }, + { + "kind": "coverage", + "id": "cov:js:board/src/board.js::Board.constructor", + "fields": { + "branches_found": 1, + "branches_hit": 1, + "file": "src/board.js", + "functions_found": 1, + "functions_hit": 1, + "item": "js:board/src/board.js::Board.constructor", + "lines_found": 1, + "lines_hit": 1 + } + }, + { + "kind": "coverage", + "id": "cov:js:board/src/board.js::createBoard", + "fields": { + "branches_found": 2, + "branches_hit": 2, + "file": "src/board.js", + "functions_found": 1, + "functions_hit": 1, + "item": "js:board/src/board.js::createBoard", + "lines_found": 3, + "lines_hit": 3 + } + } +] diff --git a/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__lcov2.snap b/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__lcov2.snap new file mode 100644 index 0000000000..4d3c45861c --- /dev/null +++ b/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__lcov2.snap @@ -0,0 +1,75 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "coverage", + "id": "cov:@src%2Flib.rs", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/lib.rs", + "functions_found": 0, + "functions_hit": 0, + "lines_found": 1, + "lines_hit": 1 + } + }, + { + "kind": "coverage", + "id": "cov:rust:demo::Board::len", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/lib.rs", + "functions_found": 1, + "functions_hit": 1, + "item": "rust:demo::Board::len", + "lines_found": 3, + "lines_hit": 3 + } + }, + { + "kind": "coverage", + "id": "cov:rust:demo::add", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/lib.rs", + "functions_found": 1, + "functions_hit": 1, + "item": "rust:demo::add", + "lines_found": 3, + "lines_hit": 3 + } + }, + { + "kind": "coverage", + "id": "cov:rust:demo::helper", + "fields": { + "branches_found": 2, + "branches_hit": 1, + "file": "src/lib.rs", + "functions_found": 2, + "functions_hit": 1, + "item": "rust:demo::helper", + "lines_found": 6, + "lines_hit": 5 + } + }, + { + "kind": "coverage", + "id": "cov:rust:demo::tests::adds", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/lib.rs", + "functions_found": 1, + "functions_hit": 1, + "item": "rust:demo::tests::adds", + "lines_found": 3, + "lines_hit": 3 + } + } +] diff --git a/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__llvm_cov.snap b/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__llvm_cov.snap new file mode 100644 index 0000000000..f138499238 --- /dev/null +++ b/extensions/code/lcov/src/snapshots/specforge_code_lcov__tests__llvm_cov.snap @@ -0,0 +1,75 @@ +--- +source: src/tests.rs +expression: "coverage_facts(&files, &served())" +--- +[ + { + "kind": "coverage", + "id": "cov:@src%2Flib.rs", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/lib.rs", + "functions_found": 0, + "functions_hit": 0, + "lines_found": 1, + "lines_hit": 1 + } + }, + { + "kind": "coverage", + "id": "cov:rust:demo::Board::len", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/lib.rs", + "functions_found": 1, + "functions_hit": 1, + "item": "rust:demo::Board::len", + "lines_found": 3, + "lines_hit": 3 + } + }, + { + "kind": "coverage", + "id": "cov:rust:demo::add", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/lib.rs", + "functions_found": 1, + "functions_hit": 1, + "item": "rust:demo::add", + "lines_found": 3, + "lines_hit": 3 + } + }, + { + "kind": "coverage", + "id": "cov:rust:demo::helper", + "fields": { + "branches_found": 2, + "branches_hit": 1, + "file": "src/lib.rs", + "functions_found": 2, + "functions_hit": 1, + "item": "rust:demo::helper", + "lines_found": 6, + "lines_hit": 5 + } + }, + { + "kind": "coverage", + "id": "cov:rust:demo::tests::adds", + "fields": { + "branches_found": 0, + "branches_hit": 0, + "file": "src/lib.rs", + "functions_found": 1, + "functions_hit": 1, + "item": "rust:demo::tests::adds", + "lines_found": 3, + "lines_hit": 3 + } + } +] diff --git a/extensions/code/lcov/src/tests.rs b/extensions/code/lcov/src/tests.rs new file mode 100644 index 0000000000..901dcd168b --- /dev/null +++ b/extensions/code/lcov/src/tests.rs @@ -0,0 +1,313 @@ +use specforge_code_facts::coverage_facts; +use specforge_extension_sdk::prelude::Fact; + +use super::*; + +/// `cargo llvm-cov --lcov` form, hand-written to llvm-cov's `CoverageExporterLcov`: crate `demo` at `/project`. +const LLVM_COV: &str = include_str!("../fixtures/llvm-cov.info"); +/// c8 (istanbul lcovonly) form, hand-written: relative `SF`, package `board` at `/project`. +const C8: &str = include_str!("../fixtures/c8.info"); +/// geninfo(1) LCOV 2.2 form, hand-written: `llvm-cov.info`'s counts with `FNL`/`FNA` groups, `TN`, `VER`, `#`. +const LCOV2: &str = include_str!("../fixtures/lcov2.info"); +/// The served `item` and `package` facts a coverage collector receives, as JSON. +const ITEMS: &str = include_str!("../fixtures/items.json"); +/// Recorded with c8 12.0.0 (`--reporter=lcovonly`) on a one-file project, unchanged. +const C8_12: &str = include_str!("../fixtures/c8-12.0.0.info"); +/// The served facts of the recorded project: `src/board.js`'s items where the file writes them. +const C8_12_ITEMS: &str = include_str!("../fixtures/c8-12.0.0.items.json"); + +fn served() -> Vec { + serde_json::from_str(ITEMS).expect("the served facts parse") +} + +#[test] +fn a_recorded_c8_12_report_mints_coverage_counting_each_line_once() { + let files = read(C8_12, "/project").expect("the report reads").files; + assert_eq!(files.len(), 1); + assert_eq!(files[0].file, "src/board.js"); + let served: Vec = serde_json::from_str(C8_12_ITEMS).expect("the served facts parse"); + let facts = coverage_facts(&files, &served); + let recorded = C8_12.lines().filter(|l| l.starts_with("DA:")).count() as u64; + let counted: u64 = facts + .iter() + .map(|f| f.fields["lines_found"].as_u64().expect("lines_found")) + .sum(); + assert_eq!(counted, recorded); + assert!( + facts.iter().all(|f| f.fields.contains_key("item")), + "{facts:?}" + ); + insta::assert_json_snapshot!("c8_12", facts); +} + +#[test] +fn an_llvm_cov_report_mints_coverage_citing_its_items() { + let Tracefile { files, outside } = read(LLVM_COV, "/project").expect("the report reads"); + assert_eq!(files.len(), 1); + assert_eq!(files[0].file, "src/lib.rs"); + assert_eq!(outside, Vec::::new()); + insta::assert_json_snapshot!("llvm_cov", coverage_facts(&files, &served())); +} + +#[test] +fn an_llvm_cov_report_reads_every_record() { + let files = read(LLVM_COV, "/project").expect("the report reads").files; + let file = &files[0]; + assert_eq!(file.functions.len(), 5); + assert_eq!( + file.functions[0], + Function { + line: 3, + name: "_RNvCs4fqI2P2rA04_4demo3add".to_string(), + hits: 4 + } + ); + assert_eq!(file.lines.len(), 16); + assert_eq!( + file.branches, + [ + Branch { + line: 29, + block: "0".to_string(), + branch: "0".to_string(), + taken: Some(0) + }, + Branch { + line: 29, + block: "0".to_string(), + branch: "1".to_string(), + taken: Some(3) + }, + ] + ); +} + +#[test] +fn a_c8_report_mints_coverage_citing_its_js_items() { + let files = read(C8, "/project").expect("the report reads").files; + assert_eq!(files.len(), 1); + assert_eq!(files[0].file, "src/board.js"); + let facts = coverage_facts(&files, &served()); + assert!(facts + .iter() + .any(|f| f.id == "cov:js:board/src/board.js::createBoard")); + insta::assert_json_snapshot!("c8", facts); +} + +#[test] +fn an_lcov2_report_reads_the_counts_of_its_fn_twin() { + let files = read(LCOV2, "/project").expect("the report reads").files; + let groups: Vec<(usize, &str, u64)> = files[0] + .functions + .iter() + .map(|f| (f.line, f.name.as_str(), f.hits)) + .collect(); + assert_eq!( + groups, + [ + (3, "demo::add", 4), + (12, "::len", 2), + (22, "demo::tests::adds", 1), + (27, "demo::helper::", 3), + (27, "demo::helper::<(u8, u16)>", 0), + ] + ); + let facts = coverage_facts(&files, &served()); + let twin = coverage_facts( + &read(LLVM_COV, "/project").expect("the twin reads").files, + &served(), + ); + assert_eq!(facts, twin); + insta::assert_json_snapshot!("lcov2", facts); +} + +#[test] +fn an_fna_with_no_fnl_and_an_fnda_with_no_fn_are_kept_at_line_0() { + let text = "SF:src/a.rs\nFNA:7,1,lost\nFNDA:2,orphan\nFN:4,late\nFNDA:1,late\nend_of_record\n"; + let files = read(text, "/project").expect("the report reads").files; + let functions: Vec<(usize, &str, u64)> = files[0] + .functions + .iter() + .map(|f| (f.line, f.name.as_str(), f.hits)) + .collect(); + assert_eq!( + functions, + [(0, "lost", 1), (0, "orphan", 2), (4, "late", 1)] + ); +} + +#[test] +fn the_nth_fnda_of_a_repeated_name_pairs_with_its_nth_fn() { + let functions = |text: &str| -> Vec<(usize, String, u64)> { + read(text, "/project").expect("the report reads").files[0] + .functions + .iter() + .map(|f| (f.line, f.name.clone(), f.hits)) + .collect() + }; + let owned = |rows: &[(usize, &str, u64)]| -> Vec<(usize, String, u64)> { + rows.iter() + .map(|(l, n, h)| (*l, n.to_string(), *h)) + .collect() + }; + // Two impls' `new`: the second FNDA is the second function's, whatever the first one's count. + let text = "SF:src/a.rs\nFN:3,new\nFN:10,new\nFN:20,other\nFNDA:0,new\nFNDA:5,new\nFNDA:1,other\nend_of_record\n"; + assert_eq!( + functions(text), + owned(&[(3, "new", 0), (10, "new", 5), (20, "other", 1)]) + ); + // FNDA first: each takes the line of the FN of its rank; one FNDA more than FNs stays at line 0. + let text = + "SF:src/a.rs\nFNDA:2,new\nFNDA:7,new\nFNDA:9,new\nFN:3,new\nFN:10,new\nend_of_record\n"; + assert_eq!( + functions(text), + owned(&[(3, "new", 2), (10, "new", 7), (0, "new", 9)]) + ); +} + +#[test] +fn a_bad_report_is_an_error_naming_its_line() { + // (report, what the error names) + let bad: [(&str, &str); 13] = [ + ("garbage", "line 1:"), + ("TN:\nDA:1,1\n", "line 2:"), + ("SF:src/a.rs\nDA:x,1\nend_of_record\n", "line 2:"), + ("SF:src/a.rs\nBRDA:3,0,0\nend_of_record\n", "line 2:"), + ("SF:src/a.rs\nDA:1,1\n", "line 1:"), + ("SF:/elsewhere/a.rs\nDA:x,1\nend_of_record\n", "line 2:"), + ("SF:src/a.rs\nSF:src/b.rs\nend_of_record\n", "line 2:"), + ("end_of_record\n", "line 1:"), + ("SF:src/a.rs\nFN:x,add\nend_of_record\n", "line 2:"), + ("SF:src/a.rs\nFNDA:1\nend_of_record\n", "line 2:"), + ("SF:src/a.rs\n\nFNA:0,1\nend_of_record\n", "line 3:"), + ("SF:src/a.rs\nDA:1,-1\nend_of_record\n", "line 2:"), + ( + "SF:src/a.rs\nDA:1,18446744073709551616\nend_of_record\n", + "line 2:", + ), + ]; + for (text, named) in bad { + match read(text, "/project") { + Err(error) => assert!(error.contains(named), "{text:?}: {error}"), + Ok(files) => panic!("{text:?} read as {files:?}"), + } + } + assert!(read("lower:case", "/project").is_err()); +} + +#[test] +fn an_error_naming_an_open_file_shows_it_bounded_and_escaped() { + let file = format!("src/\u{1b}]0;{}.rs", "a".repeat(5_000)); + for text in [ + format!("SF:{file}\nDA:1,1\n"), + format!("SF:{file}\nSF:src/b.rs\nend_of_record\n"), + ] { + let error = read(&text, "/project").expect_err("refused"); + assert!( + !error.contains('\u{1b}') && error.contains("\\u{1b}"), + "{error}" + ); + assert!(error.len() < 400, "{} bytes", error.len()); + } +} + +#[test] +fn an_sf_path_is_trimmed_and_an_empty_one_has_its_own_error() { + for text in [ + "SF:src/a.rs \nend_of_record\n", + "SF: src/a.rs\r\t\nend_of_record\n", + ] { + let files = read(text, "/project").expect("the report reads").files; + assert_eq!(files[0].file, "src/a.rs", "{text:?}"); + } + // Empty, resolving to the root itself, or a pseudo name: no file, never "outside the project". + for text in [ + "SF:\nend_of_record\n", + "SF: \t\nend_of_record\n", + "SF:.\nend_of_record\n", + "SF:/project\nend_of_record\n", + "SF:src/..\nend_of_record\n", + "SF:\nend_of_record\n", + ] { + let error = read(text, "/project").expect_err("no path"); + assert!( + error.contains("line 1:") && error.contains("names no file"), + "{text:?}: {error}" + ); + assert!(!error.contains("outside"), "{error}"); + } +} + +#[test] +fn crlf_line_endings_read_like_lf() { + let crlf = LLVM_COV.replace('\n', "\r\n"); + assert_eq!(read(&crlf, "/project"), read(LLVM_COV, "/project")); +} + +#[test] +fn a_huge_report_reads_in_linear_time_and_keeps_every_count_exactly() { + let mut text = String::from("SF:src/a.rs\n"); + for n in 1..=50_000 { + text.push_str(&format!("FN:{n},f{n}\n")); + } + for n in 1..=50_000 { + text.push_str(&format!("FNDA:{n},f{n}\n")); + } + text.push_str("DA:1,18446744073709551615\nend_of_record\n"); + let started = std::time::Instant::now(); + let files = read(&text, "/project").expect("the report reads"); + // Linear pairing reads it in milliseconds; an FNDA scan over the FN list takes minutes. + assert!(started.elapsed().as_secs() < 5, "{:?}", started.elapsed()); + let files = files.files; + assert_eq!(files[0].functions.len(), 50_000); + assert_eq!(files[0].functions[49_999].hits, 50_000); + assert_eq!(files[0].lines, [(1, u64::MAX)]); +} + +#[test] +fn an_empty_text_has_no_file() { + assert_eq!(read("", "/project"), Ok(Tracefile::default())); + assert_eq!(read("\n\n", "/project"), Ok(Tracefile::default())); +} + +#[test] +fn an_outside_path_is_skipped_counted_once_and_mints_nothing() { + let text = "SF:src/lib.rs\nDA:1,1\nend_of_record\n\ + SF:/elsewhere/a.rs\nDA:1,4\nend_of_record\n\ + SF:../../etc/passwd\nFN:1,f\nFNDA:1,f\nend_of_record\n\ + SF:/elsewhere/a.rs\nDA:2,4\nend_of_record\n"; + let read = read(text, "/project").expect("the report reads"); + assert_eq!( + read.files, + [CoverageFile { + file: "src/lib.rs".to_string(), + lines: vec![(1, 1)], + ..CoverageFile::default() + }] + ); + assert_eq!(read.outside, ["/elsewhere/a.rs", "../../etc/passwd"]); + let only = read_outside("SF:/elsewhere/a.rs\nend_of_record\n"); + assert_eq!( + (only.files.len(), &only.outside[..]), + (0, &["/elsewhere/a.rs".to_string()][..]) + ); +} + +#[test] +fn an_outside_path_is_counted_escaped_and_bounded() { + let path = format!("/elsewhere/\u{1b}]0;{}.rs", "a".repeat(5_000)); + let read = read_outside(&format!("SF:{path}\nend_of_record\n")); + let [shown] = &read.outside[..] else { + panic!("one outside path: {:?}", read.outside); + }; + assert!( + !shown.contains('\u{1b}') && shown.contains("\\u{1b}"), + "{shown}" + ); + assert!(shown.len() < 200, "{} bytes", shown.len()); +} + +/// `text` read at `/project`, which must succeed. +fn read_outside(text: &str) -> Tracefile { + read(text, "/project").expect("the report reads") +} diff --git a/extensions/code/osv/Cargo.lock b/extensions/code/osv/Cargo.lock new file mode 100644 index 0000000000..9a05859d6e --- /dev/null +++ b/extensions/code/osv/Cargo.lock @@ -0,0 +1,646 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "windows-sys", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "insta" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67d3d2e287e4b86c10b3f3b641033d1f89b74bdb39d05f34952e2b9a6fe21cd" +dependencies = [ + "console", + "once_cell", + "serde", + "similar", + "tempfile", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-osv" +version = "1.0.0" +dependencies = [ + "insta", + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/code/osv/Cargo.toml b/extensions/code/osv/Cargo.toml new file mode 100644 index 0000000000..9be1706309 --- /dev/null +++ b/extensions/code/osv/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "specforge-code-osv" +version = "1.0.0" +edition = "2021" +description = "The osv-scanner JSON reader the vulnerability packs link (ADR 0388); no guest" +publish = false + +# An extension library (ADR 0328 D3): an rlib a builtin links, never embedded. +[lib] +crate-type = ["rlib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-facts = { path = "../facts" } +serde_json = "1.0" + +[dev-dependencies] +insta = { version = "1.46.3", features = ["json"] } diff --git a/extensions/code/osv/fixtures/README.md b/extensions/code/osv/fixtures/README.md new file mode 100644 index 0000000000..bbd57dcacb --- /dev/null +++ b/extensions/code/osv/fixtures/README.md @@ -0,0 +1,13 @@ +# osv-scanner reader fixtures + +The first fixtures were written where osv-scanner was not installed, so each is hand-written to the osv-scanner JSON +output (`osv-scanner --format json`: `results[]` of `source` and `packages[]`, each package with its full OSV records +and `groups`) and the OSV schema. The advisories in them are invented (`example.invalid` references, `2099` ids): +they exercise the reader, not a real vulnerability. The first row below is a real recording. + +| Fixture | Source | +|---------|--------| +| `osv-scanner-2.7.1.json` | recorded with osv-scanner 2.7.1 by the Phase 11 research (`osv-scanner scan source -r --format json`) against a project at `/project` whose `Cargo.lock` holds `smallvec` 1.6.0 and whose `web/package-lock.json` holds `lodash` 4.17.15; committed as recorded, its paths already `/project`. The advisories are real OSV records: the GitHub Advisory Database ones (`GHSA-…`) under CC-BY 4.0 and the RustSec ones (`RUSTSEC-…`) under CC0 1.0 | +| `osv-scanner.json` | hand-written to the osv-scanner JSON output and the OSV schema: one source `/project/Cargo.lock` of type `lockfile`; `smallvec` 1.6.0 (`crates.io`) with a GHSA-shaped record labelled `MODERATE` (`database_specific.severity`), two aliases and an `affected[]` entry for another crate before its own; `time` 0.1.45 with a RustSec-shaped record with no label and no `severity[]` entry | +| `workspace.json` | hand-written: a virtual workspace and a nested npm lockfile. A root `/project/Cargo.lock` with `smallvec` 1.6.0 (one unlabelled `CVSS_V3` vector, 7.5) and `time` 0.1.45 (only a `CVSS_V4` vector), and `/project/web/package-lock.json` with `@babel/traverse` 7.22.0 (two unlabelled `CVSS_V3` vectors, 6.1 and 9.8, and no purl in `affected[]`) | +| `packages.json` | hand-written served facts: the `package` facts a vulnerability collector receives. `pkg:cargo/demo` and `pkg:npm/site` at the project root, the cargo members `pkg:cargo/ledger` and `pkg:cargo/vault` under `crates/`, and `pkg:npm/%40demo/web` at `web`. The workspace test serves them without `pkg:cargo/demo`: a virtual workspace has no root package | diff --git a/extensions/code/osv/fixtures/osv-scanner-2.7.1.json b/extensions/code/osv/fixtures/osv-scanner-2.7.1.json new file mode 100644 index 0000000000..50ee7d0021 --- /dev/null +++ b/extensions/code/osv/fixtures/osv-scanner-2.7.1.json @@ -0,0 +1,1774 @@ +{ + "results": [ + { + "source": { + "path": "/project/Cargo.lock", + "type": "lockfile" + }, + "packages": [ + { + "package": { + "name": "smallvec", + "version": "1.6.0", + "ecosystem": "crates.io", + "purl": "pkg:cargo/smallvec@1.6.0" + }, + "groups": [ + { + "ids": [ + "RUSTSEC-2021-0003", + "GHSA-43w2-9j62-hq99" + ], + "aliases": [ + "CVE-2021-25900", + "GHSA-43w2-9j62-hq99", + "RUSTSEC-2021-0003" + ], + "max_severity": "9.8" + } + ], + "vulnerabilities": [ + { + "affected": [ + { + "database_specific": { + "categories": [ + "memory-corruption" + ], + "cvss": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", + "informational": null, + "source": "https://github.com/rustsec/advisory-db/blob/osv/crates/RUSTSEC-2021-0003.json" + }, + "ecosystem_specific": { + "affected_functions": null, + "affects": { + "arch": [], + "functions": [ + "smallvec::SmallVec::insert_many" + ], + "os": [] + } + }, + "package": { + "ecosystem": "crates.io", + "name": "smallvec", + "purl": "pkg:cargo/smallvec" + }, + "ranges": [ + { + "events": [ + { + "introduced": "0.6.3" + }, + { + "fixed": "0.6.14" + }, + { + "introduced": "1.0.0" + }, + { + "fixed": "1.6.1" + } + ], + "type": "SEMVER" + } + ] + } + ], + "aliases": [ + "CVE-2021-25900", + "GHSA-43w2-9j62-hq99" + ], + "database_specific": { + "license": "CC0-1.0" + }, + "details": "A bug in the `SmallVec::insert_many` method caused it to allocate a buffer that was smaller than needed. It then wrote past the end of the buffer, causing a buffer overflow and memory corruption on the heap.\n\nThis bug was only triggered if the iterator passed to `insert_many` yielded more items than the lower bound returned from its `size_hint` method.\n \nThe flaw was corrected in smallvec 0.6.14 and 1.6.1, by ensuring that additional space is always reserved for each item inserted. The fix also simplified the implementation of `insert_many` to use less unsafe code, so it is easier to verify its correctness.\n\nThank you to Yechan Bae ([@Qwaz](https://github.com/Qwaz)) and the Rust group at Georgia Tech’s SSLab for finding and reporting this bug.", + "id": "RUSTSEC-2021-0003", + "modified": "2026-07-17T16:00:03.208176448Z", + "published": "2021-01-08T12:00:00Z", + "references": [ + { + "type": "PACKAGE", + "url": "https://crates.io/crates/smallvec" + }, + { + "type": "ADVISORY", + "url": "https://rustsec.org/advisories/RUSTSEC-2021-0003.html" + }, + { + "type": "REPORT", + "url": "https://github.com/servo/rust-smallvec/issues/252" + } + ], + "schema_version": "1.7.5", + "severity": [ + { + "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", + "type": "CVSS_V3" + } + ], + "summary": "Buffer overflow in SmallVec::insert_many" + }, + { + "affected": [ + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2022/05/GHSA-43w2-9j62-hq99/GHSA-43w2-9j62-hq99.json" + }, + "package": { + "ecosystem": "crates.io", + "name": "smallvec", + "purl": "pkg:cargo/smallvec" + }, + "ranges": [ + { + "events": [ + { + "introduced": "0.6.3" + }, + { + "fixed": "0.6.14" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2022/05/GHSA-43w2-9j62-hq99/GHSA-43w2-9j62-hq99.json" + }, + "package": { + "ecosystem": "crates.io", + "name": "smallvec", + "purl": "pkg:cargo/smallvec" + }, + "ranges": [ + { + "events": [ + { + "introduced": "1.0.0" + }, + { + "fixed": "1.6.1" + } + ], + "type": "SEMVER" + } + ] + } + ], + "aliases": [ + "CVE-2021-25900", + "RUSTSEC-2021-0003" + ], + "database_specific": { + "cwe_ids": [ + "CWE-787" + ], + "github_reviewed": true, + "github_reviewed_at": "2022-06-17T00:20:48Z", + "nvd_published_at": "2021-01-26T18:16:00Z", + "severity": "CRITICAL" + }, + "details": "A bug in the SmallVec::insert_many method caused it to allocate a buffer that was smaller than needed. It then wrote past the end of the buffer, causing a buffer overflow and memory corruption on the heap. This bug was only triggered if the iterator passed to insert_many yielded more items than the lower bound returned from its size_hint method.\n\nThe flaw was corrected in smallvec 0.6.14 and 1.6.1, by ensuring that additional space is always reserved for each item inserted. The fix also simplified the implementation of insert_many to use less unsafe code, so it is easier to verify its correctness.", + "id": "GHSA-43w2-9j62-hq99", + "modified": "2023-11-08T04:05:16.493284Z", + "published": "2022-05-24T17:40:21Z", + "references": [ + { + "type": "ADVISORY", + "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-25900" + }, + { + "type": "WEB", + "url": "https://github.com/servo/rust-smallvec/issues/252" + }, + { + "type": "WEB", + "url": "https://github.com/servo/rust-smallvec/commit/5757ac500d4e544485d796b542e4e589749c291b" + }, + { + "type": "WEB", + "url": "https://github.com/servo/rust-smallvec/commit/9998ba0694a6b51aa6604748b00b6a98f0a0039e" + }, + { + "type": "PACKAGE", + "url": "https://github.com/servo/rust-smallvec" + }, + { + "type": "WEB", + "url": "https://rustsec.org/advisories/RUSTSEC-2021-0003.html" + } + ], + "schema_version": "1.9.0", + "severity": [ + { + "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", + "type": "CVSS_V3" + } + ], + "summary": "Buffer overflow in SmallVec::insert_many" + } + ] + } + ] + }, + { + "source": { + "path": "/project/web/package-lock.json", + "type": "lockfile" + }, + "packages": [ + { + "package": { + "name": "lodash", + "version": "4.17.15", + "ecosystem": "npm", + "purl": "pkg:npm/lodash@4.17.15?source=PUBLIC_REGISTRY" + }, + "groups": [ + { + "ids": [ + "GHSA-29mw-wpgm-hmr9" + ], + "aliases": [ + "CVE-2020-28500", + "GHSA-29mw-wpgm-hmr9" + ], + "max_severity": "5.3" + }, + { + "ids": [ + "GHSA-35jh-r3h4-6jhm" + ], + "aliases": [ + "CVE-2021-23337", + "GHSA-35jh-r3h4-6jhm" + ], + "max_severity": "7.2" + }, + { + "ids": [ + "GHSA-p6mc-m468-83gw" + ], + "aliases": [ + "CVE-2020-8203", + "GHSA-p6mc-m468-83gw" + ], + "max_severity": "7.4" + }, + { + "ids": [ + "GHSA-r5fr-rjxr-66jc" + ], + "aliases": [ + "CVE-2026-4800", + "GHSA-r5fr-rjxr-66jc" + ], + "max_severity": "8.1" + }, + { + "ids": [ + "GHSA-xxjr-mmjv-4gpg" + ], + "aliases": [ + "CVE-2025-13465", + "GHSA-xxjr-mmjv-4gpg" + ], + "max_severity": "6.9" + } + ], + "vulnerabilities": [ + { + "affected": [ + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2022/01/GHSA-29mw-wpgm-hmr9/GHSA-29mw-wpgm-hmr9.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash", + "purl": "pkg:npm/lodash" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.17.21" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2022/01/GHSA-29mw-wpgm-hmr9/GHSA-29mw-wpgm-hmr9.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash-es", + "purl": "pkg:npm/lodash-es" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.17.21" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2022/01/GHSA-29mw-wpgm-hmr9/GHSA-29mw-wpgm-hmr9.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.trimend", + "purl": "pkg:npm/lodash.trimend" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "last_affected": "4.5.1" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2022/01/GHSA-29mw-wpgm-hmr9/GHSA-29mw-wpgm-hmr9.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.trim", + "purl": "pkg:npm/lodash.trim" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "last_affected": "4.5.1" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2022/01/GHSA-29mw-wpgm-hmr9/GHSA-29mw-wpgm-hmr9.json" + }, + "package": { + "ecosystem": "RubyGems", + "name": "lodash-rails", + "purl": "pkg:gem/lodash-rails" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.17.21" + } + ], + "type": "ECOSYSTEM" + } + ], + "versions": [ + "4.0.0", + "4.11.2", + "4.12.0", + "4.13.1", + "4.14.1", + "4.15.0", + "4.16.1", + "4.16.3", + "4.16.4", + "4.16.6", + "4.17.10", + "4.17.11", + "4.17.14", + "4.17.15", + "4.17.2", + "4.17.4", + "4.17.5", + "4.3.0", + "4.5.1", + "4.6.1" + ] + } + ], + "aliases": [ + "CVE-2020-28500" + ], + "database_specific": { + "cwe_ids": [ + "CWE-1333", + "CWE-400" + ], + "github_reviewed": true, + "github_reviewed_at": "2021-03-19T22:45:28Z", + "nvd_published_at": "2021-02-15T11:15:00Z", + "severity": "MODERATE" + }, + "details": "All versions of package lodash prior to 4.17.21 are vulnerable to Regular Expression Denial of Service (ReDoS) via the `toNumber`, `trim` and `trimEnd` functions. \n\nSteps to reproduce (provided by reporter Liyuan Chen):\n```js\nvar lo = require('lodash');\n\nfunction build_blank(n) {\n var ret = \"1\"\n for (var i = 0; i \u003c n; i++) {\n ret += \" \"\n }\n return ret + \"1\";\n}\nvar s = build_blank(50000) var time0 = Date.now();\nlo.trim(s) \nvar time_cost0 = Date.now() - time0;\nconsole.log(\"time_cost0: \" + time_cost0);\nvar time1 = Date.now();\nlo.toNumber(s) var time_cost1 = Date.now() - time1;\nconsole.log(\"time_cost1: \" + time_cost1);\nvar time2 = Date.now();\nlo.trimEnd(s);\nvar time_cost2 = Date.now() - time2;\nconsole.log(\"time_cost2: \" + time_cost2);\n```", + "id": "GHSA-29mw-wpgm-hmr9", + "modified": "2025-09-29T21:12:31.102523Z", + "published": "2022-01-06T20:30:46Z", + "references": [ + { + "type": "ADVISORY", + "url": "https://nvd.nist.gov/vuln/detail/CVE-2020-28500" + }, + { + "type": "WEB", + "url": "https://github.com/github/advisory-database/pull/6139" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/pull/5065" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/pull/5065/commits/02906b8191d3c100c193fe6f7b27d1c40f200bb7" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/commit/c4847ebe7d14540bb28a8b932a9ce1b9ecbfee1a" + }, + { + "type": "WEB", + "url": "https://www.oracle.com/security-alerts/cpuoct2021.html" + }, + { + "type": "WEB", + "url": "https://www.oracle.com/security-alerts/cpujul2022.html" + }, + { + "type": "WEB", + "url": "https://www.oracle.com/security-alerts/cpujan2022.html" + }, + { + "type": "WEB", + "url": "https://www.oracle.com//security-alerts/cpujul2021.html" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JS-LODASH-1018905" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSNPM-1074893" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSBOWERGITHUBLODASH-1074895" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSBOWER-1074892" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARS-1074894" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JAVA-ORGFUJIONWEBJARS-1074896" + }, + { + "type": "WEB", + "url": "https://security.netapp.com/advisory/ntap-20210312-0006" + }, + { + "type": "WEB", + "url": "https://github.com/rubysec/ruby-advisory-db/blob/master/gems/lodash-rails/CVE-2020-28500.yml" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/blob/npm/trimEnd.js%23L8" + }, + { + "type": "PACKAGE", + "url": "https://github.com/lodash/lodash" + }, + { + "type": "WEB", + "url": "https://cert-portal.siemens.com/productcert/pdf/ssa-637483.pdf" + } + ], + "schema_version": "1.9.0", + "severity": [ + { + "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L", + "type": "CVSS_V3" + } + ], + "summary": "Regular Expression Denial of Service (ReDoS) in lodash" + }, + { + "affected": [ + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2021/05/GHSA-35jh-r3h4-6jhm/GHSA-35jh-r3h4-6jhm.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash", + "purl": "pkg:npm/lodash" + }, + "ranges": [ + { + "events": [ + { + "introduced": "0" + }, + { + "fixed": "4.17.21" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2021/05/GHSA-35jh-r3h4-6jhm/GHSA-35jh-r3h4-6jhm.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash-es", + "purl": "pkg:npm/lodash-es" + }, + "ranges": [ + { + "events": [ + { + "introduced": "0" + }, + { + "fixed": "4.17.21" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2021/05/GHSA-35jh-r3h4-6jhm/GHSA-35jh-r3h4-6jhm.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.template", + "purl": "pkg:npm/lodash.template" + }, + "ranges": [ + { + "events": [ + { + "introduced": "0" + }, + { + "last_affected": "4.5.0" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2021/05/GHSA-35jh-r3h4-6jhm/GHSA-35jh-r3h4-6jhm.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash-template", + "purl": "pkg:npm/lodash-template" + }, + "ranges": [ + { + "events": [ + { + "introduced": "0" + }, + { + "last_affected": "1.0.0" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2021/05/GHSA-35jh-r3h4-6jhm/GHSA-35jh-r3h4-6jhm.json" + }, + "package": { + "ecosystem": "RubyGems", + "name": "lodash-rails", + "purl": "pkg:gem/lodash-rails" + }, + "ranges": [ + { + "events": [ + { + "introduced": "0" + }, + { + "fixed": "4.17.21" + } + ], + "type": "ECOSYSTEM" + } + ], + "versions": [ + "0.10.0", + "0.7.0", + "0.8.1", + "0.8.2", + "0.9.0", + "0.9.1", + "0.9.2", + "1.0.0.rc.1", + "1.0.0.rc.2", + "1.0.0.rc.3", + "1.0.1", + "1.1.0", + "1.1.1", + "1.2.0", + "1.2.1", + "1.3.1", + "2.0.0", + "2.1.0", + "2.2.0", + "2.2.1", + "2.3.0", + "2.4.0", + "2.4.1", + "3.1.0", + "3.10.0", + "3.10.1", + "3.2.0", + "3.3.0", + "3.3.1", + "3.3.1.1", + "3.4.0", + "3.5.0", + "3.6.0", + "3.7.0", + "3.9.3", + "4.0.0", + "4.11.2", + "4.12.0", + "4.13.1", + "4.14.1", + "4.15.0", + "4.16.1", + "4.16.3", + "4.16.4", + "4.16.6", + "4.17.10", + "4.17.11", + "4.17.14", + "4.17.15", + "4.17.2", + "4.17.4", + "4.17.5", + "4.3.0", + "4.5.1", + "4.6.1" + ] + } + ], + "aliases": [ + "CVE-2021-23337" + ], + "database_specific": { + "cwe_ids": [ + "CWE-77", + "CWE-94" + ], + "github_reviewed": true, + "github_reviewed_at": "2021-03-31T23:59:26Z", + "nvd_published_at": "2021-02-15T13:15:00Z", + "severity": "HIGH" + }, + "details": "`lodash` versions prior to 4.17.21 are vulnerable to Command Injection via the template function.", + "id": "GHSA-35jh-r3h4-6jhm", + "modified": "2026-10-17T02:55:38.085813876Z", + "published": "2021-05-06T16:05:51Z", + "references": [ + { + "type": "ADVISORY", + "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-23337" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/commit/3469357cff396a26c363f8c1b5a91dde28ba4b1c" + }, + { + "type": "WEB", + "url": "https://www.oracle.com/security-alerts/cpuoct2021.html" + }, + { + "type": "WEB", + "url": "https://www.oracle.com/security-alerts/cpujul2022.html" + }, + { + "type": "WEB", + "url": "https://www.oracle.com/security-alerts/cpujan2022.html" + }, + { + "type": "WEB", + "url": "https://www.oracle.com//security-alerts/cpujul2021.html" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JS-LODASH-1040724" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSNPM-1074929" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSBOWERGITHUBLODASH-1074931" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSBOWER-1074928" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARS-1074930" + }, + { + "type": "WEB", + "url": "https://snyk.io/vuln/SNYK-JAVA-ORGFUJIONWEBJARS-1074932" + }, + { + "type": "WEB", + "url": "https://security.netapp.com/advisory/ntap-20210312-0006" + }, + { + "type": "WEB", + "url": "https://github.com/rubysec/ruby-advisory-db/blob/master/gems/lodash-rails/CVE-2021-23337.yml" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/blob/ddfd9b11a0126db2302cb70ec9973b66baec0975/lodash.js#L14851" + }, + { + "type": "PACKAGE", + "url": "https://github.com/lodash/lodash" + }, + { + "type": "WEB", + "url": "https://cert-portal.siemens.com/productcert/pdf/ssa-637483.pdf" + } + ], + "schema_version": "1.9.0", + "severity": [ + { + "score": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H", + "type": "CVSS_V3" + } + ], + "summary": "Command Injection in lodash" + }, + { + "affected": [ + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2020/07/GHSA-p6mc-m468-83gw/GHSA-p6mc-m468-83gw.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash", + "purl": "pkg:npm/lodash" + }, + "ranges": [ + { + "events": [ + { + "introduced": "3.7.0" + }, + { + "fixed": "4.17.19" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2020/07/GHSA-p6mc-m468-83gw/GHSA-p6mc-m468-83gw.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash-es", + "purl": "pkg:npm/lodash-es" + }, + "ranges": [ + { + "events": [ + { + "introduced": "3.7.0" + }, + { + "fixed": "4.17.20" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2020/07/GHSA-p6mc-m468-83gw/GHSA-p6mc-m468-83gw.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.pick", + "purl": "pkg:npm/lodash.pick" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "last_affected": "4.4.0" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2020/07/GHSA-p6mc-m468-83gw/GHSA-p6mc-m468-83gw.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.set", + "purl": "pkg:npm/lodash.set" + }, + "ranges": [ + { + "events": [ + { + "introduced": "3.7.0" + }, + { + "last_affected": "4.3.2" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2020/07/GHSA-p6mc-m468-83gw/GHSA-p6mc-m468-83gw.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.setwith", + "purl": "pkg:npm/lodash.setwith" + }, + "ranges": [ + { + "events": [ + { + "introduced": "0" + }, + { + "last_affected": "4.3.2" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2020/07/GHSA-p6mc-m468-83gw/GHSA-p6mc-m468-83gw.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.update", + "purl": "pkg:npm/lodash.update" + }, + "ranges": [ + { + "events": [ + { + "introduced": "0" + }, + { + "last_affected": "4.10.2" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2020/07/GHSA-p6mc-m468-83gw/GHSA-p6mc-m468-83gw.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.updatewith", + "purl": "pkg:npm/lodash.updatewith" + }, + "ranges": [ + { + "events": [ + { + "introduced": "0" + }, + { + "last_affected": "4.10.2" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2020/07/GHSA-p6mc-m468-83gw/GHSA-p6mc-m468-83gw.json" + }, + "package": { + "ecosystem": "RubyGems", + "name": "lodash-rails", + "purl": "pkg:gem/lodash-rails" + }, + "ranges": [ + { + "events": [ + { + "introduced": "3.7.0" + }, + { + "fixed": "4.17.19" + } + ], + "type": "ECOSYSTEM" + } + ], + "versions": [ + "3.10.0", + "3.10.1", + "3.7.0", + "3.9.3", + "4.0.0", + "4.11.2", + "4.12.0", + "4.13.1", + "4.14.1", + "4.15.0", + "4.16.1", + "4.16.3", + "4.16.4", + "4.16.6", + "4.17.10", + "4.17.11", + "4.17.14", + "4.17.15", + "4.17.2", + "4.17.4", + "4.17.5", + "4.3.0", + "4.5.1", + "4.6.1" + ] + } + ], + "aliases": [ + "CVE-2020-8203" + ], + "database_specific": { + "cwe_ids": [ + "CWE-1321", + "CWE-770" + ], + "github_reviewed": true, + "github_reviewed_at": "2020-07-15T19:14:58Z", + "nvd_published_at": "2020-07-15T17:15:00Z", + "severity": "HIGH" + }, + "details": "Versions of lodash prior to 4.17.19 are vulnerable to Prototype Pollution. The functions `pick`, `set`, `setWith`, `update`, `updateWith`, and `zipObjectDeep` allow a malicious user to modify the prototype of Object if the property identifiers are user-supplied. Being affected by this issue requires manipulating objects based on user-provided property values or arrays.\n\nThis vulnerability causes the addition or modification of an existing property that will exist on all objects and may lead to Denial of Service or Code Execution under specific circumstances.", + "id": "GHSA-p6mc-m468-83gw", + "modified": "2025-08-12T21:56:17.174859Z", + "published": "2020-07-15T19:15:48Z", + "references": [ + { + "type": "ADVISORY", + "url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8203" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/issues/4744" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/issues/4874" + }, + { + "type": "WEB", + "url": "https://github.com/github/advisory-database/pull/2884" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/commit/c84fe82760fb2d3e03a63379b297a1cc1a2fce12" + }, + { + "type": "WEB", + "url": "https://hackerone.com/reports/712065" + }, + { + "type": "WEB", + "url": "https://hackerone.com/reports/864701" + }, + { + "type": "PACKAGE", + "url": "https://github.com/lodash/lodash" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/wiki/Changelog#v41719" + }, + { + "type": "WEB", + "url": "https://github.com/rubysec/ruby-advisory-db/blob/master/gems/lodash-rails/CVE-2020-8203.yml" + }, + { + "type": "WEB", + "url": "https://security.netapp.com/advisory/ntap-20200724-0006" + }, + { + "type": "WEB", + "url": "https://web.archive.org/web/20210914001339/https://github.com/lodash/lodash/issues/4744" + } + ], + "schema_version": "1.9.0", + "severity": [ + { + "score": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:H", + "type": "CVSS_V3" + } + ], + "summary": "Prototype Pollution in lodash" + }, + { + "affected": [ + { + "database_specific": { + "last_known_affected_version_range": "\u003c= 4.17.23", + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/04/GHSA-r5fr-rjxr-66jc/GHSA-r5fr-rjxr-66jc.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash", + "purl": "pkg:npm/lodash" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.18.0" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "last_known_affected_version_range": "\u003c= 4.17.23", + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/04/GHSA-r5fr-rjxr-66jc/GHSA-r5fr-rjxr-66jc.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash-es", + "purl": "pkg:npm/lodash-es" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.18.0" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "last_known_affected_version_range": "\u003c= 4.17.23", + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/04/GHSA-r5fr-rjxr-66jc/GHSA-r5fr-rjxr-66jc.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash-amd", + "purl": "pkg:npm/lodash-amd" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.18.0" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/04/GHSA-r5fr-rjxr-66jc/GHSA-r5fr-rjxr-66jc.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.template", + "purl": "pkg:npm/lodash.template" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.18.0" + } + ], + "type": "SEMVER" + } + ] + } + ], + "aliases": [ + "CVE-2026-4800" + ], + "database_specific": { + "cwe_ids": [ + "CWE-94" + ], + "github_reviewed": true, + "github_reviewed_at": "2026-04-01T23:51:12Z", + "nvd_published_at": "2026-03-31T20:16:29Z", + "severity": "HIGH" + }, + "details": "### Impact\n\nThe fix for [CVE-2021-23337](https://github.com/advisories/GHSA-35jh-r3h4-6jhm) added validation for the `variable` option in `_.template` but did not apply the same validation to `options.imports` key names. Both paths flow into the same `Function()` constructor sink.\n\nWhen an application passes untrusted input as `options.imports` key names, an attacker can inject default-parameter expressions that execute arbitrary code at template compilation time.\n\nAdditionally, `_.template` uses `assignInWith` to merge imports, which enumerates inherited properties via `for..in`. If `Object.prototype` has been polluted by any other vector, the polluted keys are copied into the imports object and passed to `Function()`.\n\n### Patches\n\nUsers should upgrade to version 4.18.0.\n\nThe fix applies two changes:\n1. Validate `importsKeys` against the existing `reForbiddenIdentifierChars` regex (same check already used for the `variable` option)\n2. Replace `assignInWith` with `assignWith` when merging imports, so only own properties are enumerated\n\n### Workarounds\n\nDo not pass untrusted input as key names in `options.imports`. Only use developer-controlled, static key names.", + "id": "GHSA-r5fr-rjxr-66jc", + "modified": "2026-10-17T02:56:15.633068434Z", + "published": "2026-04-01T23:51:12Z", + "references": [ + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/security/advisories/GHSA-r5fr-rjxr-66jc" + }, + { + "type": "ADVISORY", + "url": "https://nvd.nist.gov/vuln/detail/CVE-2026-4800" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/commit/3469357cff396a26c363f8c1b5a91dde28ba4b1c" + }, + { + "type": "WEB", + "url": "https://cna.openjsf.org/security-advisories.html" + }, + { + "type": "ADVISORY", + "url": "https://github.com/advisories/GHSA-35jh-r3h4-6jhm" + }, + { + "type": "PACKAGE", + "url": "https://github.com/lodash/lodash" + } + ], + "schema_version": "1.9.0", + "severity": [ + { + "score": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", + "type": "CVSS_V3" + } + ], + "summary": "lodash vulnerable to Code Injection via `_.template` imports key names" + }, + { + "affected": [ + { + "database_specific": { + "last_known_affected_version_range": "\u003c= 4.17.22", + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/01/GHSA-xxjr-mmjv-4gpg/GHSA-xxjr-mmjv-4gpg.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash", + "purl": "pkg:npm/lodash" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.17.23" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "last_known_affected_version_range": "\u003c= 4.17.22", + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/01/GHSA-xxjr-mmjv-4gpg/GHSA-xxjr-mmjv-4gpg.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash-amd", + "purl": "pkg:npm/lodash-amd" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.17.23" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/01/GHSA-xxjr-mmjv-4gpg/GHSA-xxjr-mmjv-4gpg.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash-es", + "purl": "pkg:npm/lodash-es" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.17.23" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/01/GHSA-xxjr-mmjv-4gpg/GHSA-xxjr-mmjv-4gpg.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.omit", + "purl": "pkg:npm/lodash.omit" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.18.0" + } + ], + "type": "SEMVER" + } + ] + }, + { + "database_specific": { + "source": "https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/01/GHSA-xxjr-mmjv-4gpg/GHSA-xxjr-mmjv-4gpg.json" + }, + "package": { + "ecosystem": "npm", + "name": "lodash.unset", + "purl": "pkg:npm/lodash.unset" + }, + "ranges": [ + { + "events": [ + { + "introduced": "4.0.0" + }, + { + "fixed": "4.18.0" + } + ], + "type": "SEMVER" + } + ] + } + ], + "aliases": [ + "CVE-2025-13465" + ], + "database_specific": { + "cwe_ids": [ + "CWE-1321" + ], + "github_reviewed": true, + "github_reviewed_at": "2026-01-21T23:01:22Z", + "nvd_published_at": "2026-01-21T20:16:05Z", + "severity": "MODERATE" + }, + "details": "### Impact\n\nThe `_.unset`, `_.omit`, and `_.pullAt` functions are vulnerable to prototype pollution. An attacker can pass crafted paths which cause Lodash to delete methods from global prototypes.\n\nThe issue permits deletion of properties but does not allow overwriting their original behavior.\n\n### Patches\n\nThe issue is patched from 4.17.23 to 4.18.0 depending on the package: `lodash`, `lodash-es`, and `lodash-amd` in 4.17.23, and the standalone `lodash.unset` and `lodash.omit` packages in 4.18.0.\n\n### Workarounds\n\nNone. Upgrade to the patched version.", + "id": "GHSA-xxjr-mmjv-4gpg", + "modified": "2026-11-04T03:15:10.832238351Z", + "published": "2026-01-21T23:01:22Z", + "references": [ + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/security/advisories/GHSA-xxjr-mmjv-4gpg" + }, + { + "type": "ADVISORY", + "url": "https://nvd.nist.gov/vuln/detail/CVE-2025-13465" + }, + { + "type": "WEB", + "url": "https://github.com/lodash/lodash/commit/edadd452146f7e4bad4ea684e955708931d84d81" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:41941" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:41928" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:41064" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:40984" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:40945" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:40138" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:40118" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3962" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3960" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3958" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3884" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3874" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3870" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3869" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3825" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3782" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3710" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:36882" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:36651" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:34608" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3422" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:34100" + }, + { + "type": "WEB", + "url": "https://security.access.redhat.com/data/csaf/v2/vex/2025/cve-2025-13465.json" + }, + { + "type": "PACKAGE", + "url": "https://github.com/lodash/lodash" + }, + { + "type": "WEB", + "url": "https://cna.openjsf.org/security-advisories.html" + }, + { + "type": "WEB", + "url": "https://cert-portal.siemens.com/productcert/html/ssa-253495.html" + }, + { + "type": "WEB", + "url": "https://bugzilla.redhat.com/show_bug.cgi?id=2431740" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/security/cve/CVE-2025-13465" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:9848" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:8229" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:8218" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:6567" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:6497" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:6288" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:6192" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:57487" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:5636" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:5633" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:4782" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:4630" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:4467" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:4466" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:4423" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:41944" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:24331" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:21658" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2149" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2148" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2147" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2145" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2119" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2078" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:20088" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:20042" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:19712" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:18868" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:18480" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:1845" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:17469" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:15091" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:14871" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:14870" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:14774" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:13829" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:13548" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:13542" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:11414" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:33371" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:33154" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:3087" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2990" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2984" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2926" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2900" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2819" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2818" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2817" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2816" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2694" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2675" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2672" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2661" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2651" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:25089" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2484" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2469" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2465" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2462" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2452" + }, + { + "type": "WEB", + "url": "https://access.redhat.com/errata/RHSA-2026:2438" + } + ], + "schema_version": "1.9.2", + "severity": [ + { + "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:L", + "type": "CVSS_V3" + }, + { + "score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:L/VA:L/SC:H/SI:H/SA:H/E:P", + "type": "CVSS_V4" + } + ], + "summary": "Lodash has Prototype Pollution Vulnerability in `_.unset`, `_.omit`, and `_.pullAt` functions" + } + ] + } + ] + } + ], + "experimental_config": { + "licenses": { + "summary": false, + "allowlist": null + } + } +} diff --git a/extensions/code/osv/fixtures/osv-scanner.json b/extensions/code/osv/fixtures/osv-scanner.json new file mode 100644 index 0000000000..3fdabe1f9d --- /dev/null +++ b/extensions/code/osv/fixtures/osv-scanner.json @@ -0,0 +1,91 @@ +{ + "results": [ + { + "source": { + "path": "/project/Cargo.lock", + "type": "lockfile" + }, + "packages": [ + { + "package": { + "name": "smallvec", + "version": "1.6.0", + "ecosystem": "crates.io" + }, + "vulnerabilities": [ + { + "modified": "2024-03-01T12:00:00Z", + "published": "2021-08-25T20:50:00Z", + "schema_version": "1.6.0", + "id": "GHSA-7v4m-2x9q-3h8c", + "aliases": ["RUSTSEC-2099-0001", "CVE-2099-0001"], + "summary": "Buffer overflow in SmallVec::insert_many", + "details": "An invented advisory for this fixture: insert_many can write past the end of the buffer.", + "affected": [ + { + "package": { + "ecosystem": "crates.io", + "name": "smallvec-derive", + "purl": "pkg:cargo/smallvec-derive" + }, + "ranges": [{"type": "SEMVER", "events": [{"introduced": "0"}, {"fixed": "0.2.0"}]}] + }, + { + "package": { + "ecosystem": "crates.io", + "name": "smallvec", + "purl": "pkg:cargo/smallvec" + }, + "ranges": [{"type": "SEMVER", "events": [{"introduced": "1.0.0"}, {"fixed": "1.6.1"}]}] + } + ], + "references": [ + {"type": "ADVISORY", "url": "https://example.invalid/advisories/GHSA-7v4m-2x9q-3h8c"} + ], + "database_specific": { + "cwe_ids": ["CWE-787"], + "severity": "MODERATE", + "github_reviewed": true + } + } + ], + "groups": [ + {"ids": ["GHSA-7v4m-2x9q-3h8c", "RUSTSEC-2099-0001"]} + ] + }, + { + "package": { + "name": "time", + "version": "0.1.45", + "ecosystem": "crates.io" + }, + "vulnerabilities": [ + { + "modified": "2024-02-10T08:00:00Z", + "published": "2020-11-18T12:00:00Z", + "schema_version": "1.6.0", + "id": "RUSTSEC-2099-0002", + "summary": "Potential segfault in the time crate", + "details": "An invented advisory for this fixture, with no severity label and no severity entry.", + "affected": [ + { + "package": { + "ecosystem": "crates.io", + "name": "time" + }, + "ranges": [{"type": "SEMVER", "events": [{"introduced": "0"}, {"fixed": "0.2.23"}]}] + } + ], + "database_specific": { + "license": "CC0-1.0" + } + } + ], + "groups": [ + {"ids": ["RUSTSEC-2099-0002"]} + ] + } + ] + } + ] +} diff --git a/extensions/code/osv/fixtures/packages.json b/extensions/code/osv/fixtures/packages.json new file mode 100644 index 0000000000..1a66cb53d2 --- /dev/null +++ b/extensions/code/osv/fixtures/packages.json @@ -0,0 +1,12 @@ +[ + {"kind": "package", "id": "pkg:cargo/demo", + "fields": {"name": "demo", "version": "0.1.0", "path": ""}}, + {"kind": "package", "id": "pkg:cargo/ledger", + "fields": {"name": "ledger", "version": "0.1.0", "path": "crates/ledger"}}, + {"kind": "package", "id": "pkg:cargo/vault", + "fields": {"name": "vault", "version": "0.1.0", "path": "crates/vault"}}, + {"kind": "package", "id": "pkg:npm/site", + "fields": {"name": "site", "version": "1.0.0", "path": ""}}, + {"kind": "package", "id": "pkg:npm/%40demo/web", + "fields": {"name": "@demo/web", "version": "1.0.0", "path": "web"}} +] diff --git a/extensions/code/osv/fixtures/workspace.json b/extensions/code/osv/fixtures/workspace.json new file mode 100644 index 0000000000..5ccf5970eb --- /dev/null +++ b/extensions/code/osv/fixtures/workspace.json @@ -0,0 +1,109 @@ +{ + "results": [ + { + "source": { + "path": "/project/Cargo.lock", + "type": "lockfile" + }, + "packages": [ + { + "package": { + "name": "smallvec", + "version": "1.6.0", + "ecosystem": "crates.io" + }, + "vulnerabilities": [ + { + "modified": "2024-03-01T12:00:00Z", + "schema_version": "1.6.0", + "id": "RUSTSEC-2099-0003", + "aliases": ["CVE-2099-0003"], + "summary": "Out-of-bounds read in SmallVec::drain", + "affected": [ + { + "package": { + "ecosystem": "crates.io", + "name": "smallvec", + "purl": "pkg:cargo/smallvec" + } + } + ], + "severity": [ + {"type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N"} + ] + } + ], + "groups": [{"ids": ["RUSTSEC-2099-0003"]}] + }, + { + "package": { + "name": "time", + "version": "0.1.45", + "ecosystem": "crates.io" + }, + "vulnerabilities": [ + { + "modified": "2024-02-10T08:00:00Z", + "schema_version": "1.6.0", + "id": "RUSTSEC-2099-0004", + "summary": "Unsound localtime in the time crate", + "affected": [ + { + "package": { + "ecosystem": "crates.io", + "name": "time", + "purl": "pkg:cargo/time" + } + } + ], + "severity": [ + {"type": "CVSS_V4", "score": "CVSS:4.0/AV:L/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:H/SC:N/SI:N/SA:N"} + ] + } + ], + "groups": [{"ids": ["RUSTSEC-2099-0004"]}] + } + ] + }, + { + "source": { + "path": "/project/web/package-lock.json", + "type": "lockfile" + }, + "packages": [ + { + "package": { + "name": "@babel/traverse", + "version": "7.22.0", + "ecosystem": "npm" + }, + "vulnerabilities": [ + { + "modified": "2024-01-15T09:00:00Z", + "schema_version": "1.6.0", + "id": "GHSA-m3p6-8x4q-2c7v", + "aliases": ["CVE-2099-0005"], + "summary": "Arbitrary code execution when compiling crafted code", + "affected": [ + { + "package": { + "ecosystem": "npm", + "name": "@babel/traverse" + } + } + ], + "severity": [ + {"type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"}, + {"type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"} + ], + "database_specific": { + "github_reviewed": true + } + } + ], + "groups": [{"ids": ["GHSA-m3p6-8x4q-2c7v"]}] + } + ] + } + ] +} diff --git a/extensions/code/osv/src/lib.rs b/extensions/code/osv/src/lib.rs new file mode 100644 index 0000000000..f7aa5be80b --- /dev/null +++ b/extensions/code/osv/src/lib.rs @@ -0,0 +1,140 @@ +//! `specforge-code-osv`: the osv-scanner JSON reader the vulnerability packs link (ADR 0388). +//! +//! An extension library (ADR 0328 D3): an rlib a builtin links, never a component of its own. The wire has no +//! guest-to-guest call, so a vulnerability pack reads its scan here; `specforge-code-facts` mints the `vulnerability` +//! facts from what it reads ([`specforge_code_facts::vulnerability_facts`]). +//! +//! - [`read`] reads an `osv-scanner --format json` report into an [`OsvReport`]: each scanned lockfile, project-relative, +//! and the OSV records of each package it lists. + +#[cfg(test)] +mod tests; + +use serde_json::Value; +use specforge_code_facts::{relative, shown, OsvPackage, OsvRecord, OsvScore, OsvSource}; + +pub use specforge_code_facts::OsvReport; + +/// The `source.type`s read: a scan of a lockfile or an SBOM names the project's dependencies; a scanned image or +/// commit holds no project package. +const SOURCE_TYPES: [&str; 2] = ["lockfile", "sbom"]; + +/// The report in the osv-scanner JSON `text`, its lockfile paths made relative to the project root `cwd`. +/// +/// Per `results[]` entry: `source.path` and `source.type`, then per `packages[]` entry its `package.name`, +/// `package.version` and `package.ecosystem`, and every record of its `vulnerabilities`: `id`, `aliases`, `summary`, +/// `database_specific.severity` when it is a string, the `severity[]` entries with a `type` and a `score`, and the +/// `package.purl` of the `affected[]` entry whose name and ecosystem are the package's. `groups` is not read. +/// +/// An error, naming the JSON path or the value, and nothing is read: text that is no JSON (nesting deeper than +/// serde_json's limit included), no `results` array, a result with no `source.path` or `source.type`, a `source.type` +/// other than `lockfile` or `sbom`, a `source.path` outside the project, a `packages` or `vulnerabilities` that is no +/// array, a package with no `package.name`, `package.version` or `package.ecosystem`, and a vulnerability with no `id`. +pub fn read(text: &str, cwd: &str) -> Result { + let report: Value = serde_json::from_str(text).map_err(|e| format!("no JSON: {e}"))?; + let Some(Value::Array(results)) = report.get("results") else { + return Err("results: absent or no array".to_string()); + }; + let mut sources = Vec::new(); + for (i, result) in results.iter().enumerate() { + let at = format!("results[{i}]"); + let path = string(result, "/source/path", &format!("{at}.source.path"))?; + let kind = string(result, "/source/type", &format!("{at}.source.type"))?; + if !SOURCE_TYPES.contains(&kind) { + return Err(format!( + "{at}.source.type: '{}' of '{}' is not read, only {}", + shown(kind), + shown(path), + SOURCE_TYPES.join(" and ") + )); + } + let lockfile = relative(path, cwd).ok_or_else(|| { + format!( + "{at}.source.path: '{}' lies outside the project", + shown(path) + ) + })?; + let mut packages = Vec::new(); + for (j, entry) in array(result, "packages", &at)?.iter().enumerate() { + packages.push(package(entry, &format!("{at}.packages[{j}]"))?); + } + sources.push(OsvSource { lockfile, packages }); + } + Ok(OsvReport { sources }) +} + +/// The package `entry` at the JSON path `at`, with its records. +fn package(entry: &Value, at: &str) -> Result { + let name = string(entry, "/package/name", &format!("{at}.package.name"))?; + let ecosystem = string( + entry, + "/package/ecosystem", + &format!("{at}.package.ecosystem"), + )?; + let version = string(entry, "/package/version", &format!("{at}.package.version"))?; + let mut records = Vec::new(); + for (k, value) in array(entry, "vulnerabilities", at)?.iter().enumerate() { + let id = string(value, "/id", &format!("{at}.vulnerabilities[{k}].id"))?; + let text = |pointer: &str| value.pointer(pointer).and_then(Value::as_str); + let strings = |key: &str| { + value + .get(key) + .and_then(Value::as_array) + .map_or(&[][..], Vec::as_slice) + }; + records.push(OsvRecord { + id: id.to_string(), + aliases: strings("aliases") + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect(), + summary: text("/summary").map(str::to_string), + label: text("/database_specific/severity").map(str::to_string), + scores: strings("severity") + .iter() + .filter_map(|score| { + Some(OsvScore { + kind: score.get("type")?.as_str()?.to_string(), + score: score.get("score")?.as_str()?.to_string(), + }) + }) + .collect(), + purl: strings("affected") + .iter() + .find(|affected| { + affected.pointer("/package/name").and_then(Value::as_str) == Some(name) + && affected + .pointer("/package/ecosystem") + .and_then(Value::as_str) + == Some(ecosystem) + }) + .and_then(|affected| affected.pointer("/package/purl")) + .and_then(Value::as_str) + .map(str::to_string), + }); + } + Ok(OsvPackage { + name: name.to_string(), + version: version.to_string(), + ecosystem: ecosystem.to_string(), + records, + }) +} + +/// The string at `pointer` in `value`, else an error naming the JSON path `at`. +fn string<'v>(value: &'v Value, pointer: &str, at: &str) -> Result<&'v str, String> { + value + .pointer(pointer) + .and_then(Value::as_str) + .ok_or_else(|| format!("{at}: absent or no string")) +} + +/// The array at `key` of `value` (none when absent), else an error naming `.`. +fn array<'v>(value: &'v Value, key: &str, at: &str) -> Result<&'v [Value], String> { + match value.get(key) { + None => Ok(&[]), + Some(Value::Array(list)) => Ok(list), + Some(_) => Err(format!("{at}.{key}: no array")), + } +} diff --git a/extensions/code/osv/src/snapshots/specforge_code_osv__tests__osv_scanner.snap b/extensions/code/osv/src/snapshots/specforge_code_osv__tests__osv_scanner.snap new file mode 100644 index 0000000000..3c3faeee75 --- /dev/null +++ b/extensions/code/osv/src/snapshots/specforge_code_osv__tests__osv_scanner.snap @@ -0,0 +1,43 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "vulnerability", + "id": "vuln:pkg:cargo/demo/GHSA-7v4m-2x9q-3h8c", + "fields": { + "aliases": [ + "CVE-2099-0001", + "RUSTSEC-2099-0001" + ], + "osv_id": "GHSA-7v4m-2x9q-3h8c", + "package": "pkg:cargo/demo", + "purl": [ + "pkg:cargo/smallvec@1.6.0" + ], + "severity": "medium", + "summary": "Buffer overflow in SmallVec::insert_many", + "version": [ + "1.6.0" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:cargo/demo/RUSTSEC-2099-0002", + "fields": { + "aliases": [], + "osv_id": "RUSTSEC-2099-0002", + "package": "pkg:cargo/demo", + "purl": [ + "pkg:cargo/time@0.1.45" + ], + "severity": "unknown", + "summary": "Potential segfault in the time crate", + "version": [ + "0.1.45" + ] + } + } +] diff --git a/extensions/code/osv/src/snapshots/specforge_code_osv__tests__osv_scanner_2_7_1.snap b/extensions/code/osv/src/snapshots/specforge_code_osv__tests__osv_scanner_2_7_1.snap new file mode 100644 index 0000000000..5df370f742 --- /dev/null +++ b/extensions/code/osv/src/snapshots/specforge_code_osv__tests__osv_scanner_2_7_1.snap @@ -0,0 +1,141 @@ +--- +source: src/tests.rs +expression: minted.facts +--- +[ + { + "kind": "vulnerability", + "id": "vuln:pkg:cargo/demo/GHSA-43w2-9j62-hq99", + "fields": { + "aliases": [ + "CVE-2021-25900", + "RUSTSEC-2021-0003" + ], + "osv_id": "GHSA-43w2-9j62-hq99", + "package": "pkg:cargo/demo", + "purl": [ + "pkg:cargo/smallvec@1.6.0" + ], + "severity": "critical", + "summary": "Buffer overflow in SmallVec::insert_many", + "version": [ + "1.6.0" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:cargo/demo/RUSTSEC-2021-0003", + "fields": { + "aliases": [ + "CVE-2021-25900", + "GHSA-43w2-9j62-hq99" + ], + "osv_id": "RUSTSEC-2021-0003", + "package": "pkg:cargo/demo", + "purl": [ + "pkg:cargo/smallvec@1.6.0" + ], + "severity": "critical", + "summary": "Buffer overflow in SmallVec::insert_many", + "version": [ + "1.6.0" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:npm/%40demo/web/GHSA-29mw-wpgm-hmr9", + "fields": { + "aliases": [ + "CVE-2020-28500" + ], + "osv_id": "GHSA-29mw-wpgm-hmr9", + "package": "pkg:npm/%40demo/web", + "purl": [ + "pkg:npm/lodash@4.17.15" + ], + "severity": "medium", + "summary": "Regular Expression Denial of Service (ReDoS) in lodash", + "version": [ + "4.17.15" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:npm/%40demo/web/GHSA-35jh-r3h4-6jhm", + "fields": { + "aliases": [ + "CVE-2021-23337" + ], + "osv_id": "GHSA-35jh-r3h4-6jhm", + "package": "pkg:npm/%40demo/web", + "purl": [ + "pkg:npm/lodash@4.17.15" + ], + "severity": "high", + "summary": "Command Injection in lodash", + "version": [ + "4.17.15" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:npm/%40demo/web/GHSA-p6mc-m468-83gw", + "fields": { + "aliases": [ + "CVE-2020-8203" + ], + "osv_id": "GHSA-p6mc-m468-83gw", + "package": "pkg:npm/%40demo/web", + "purl": [ + "pkg:npm/lodash@4.17.15" + ], + "severity": "high", + "summary": "Prototype Pollution in lodash", + "version": [ + "4.17.15" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:npm/%40demo/web/GHSA-r5fr-rjxr-66jc", + "fields": { + "aliases": [ + "CVE-2026-4800" + ], + "osv_id": "GHSA-r5fr-rjxr-66jc", + "package": "pkg:npm/%40demo/web", + "purl": [ + "pkg:npm/lodash@4.17.15" + ], + "severity": "high", + "summary": "lodash vulnerable to Code Injection via `_.template` imports key names", + "version": [ + "4.17.15" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:npm/%40demo/web/GHSA-xxjr-mmjv-4gpg", + "fields": { + "aliases": [ + "CVE-2025-13465" + ], + "osv_id": "GHSA-xxjr-mmjv-4gpg", + "package": "pkg:npm/%40demo/web", + "purl": [ + "pkg:npm/lodash@4.17.15" + ], + "severity": "medium", + "summary": "Lodash has Prototype Pollution Vulnerability in `_.unset`, `_.omit`, and `_.pullAt` functions", + "version": [ + "4.17.15" + ] + } + } +] diff --git a/extensions/code/osv/src/snapshots/specforge_code_osv__tests__workspace.snap b/extensions/code/osv/src/snapshots/specforge_code_osv__tests__workspace.snap new file mode 100644 index 0000000000..fafd6fd47b --- /dev/null +++ b/extensions/code/osv/src/snapshots/specforge_code_osv__tests__workspace.snap @@ -0,0 +1,97 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "vulnerability", + "id": "vuln:pkg:cargo/ledger/RUSTSEC-2099-0003", + "fields": { + "aliases": [ + "CVE-2099-0003" + ], + "osv_id": "RUSTSEC-2099-0003", + "package": "pkg:cargo/ledger", + "purl": [ + "pkg:cargo/smallvec@1.6.0" + ], + "severity": "high", + "summary": "Out-of-bounds read in SmallVec::drain", + "version": [ + "1.6.0" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:cargo/ledger/RUSTSEC-2099-0004", + "fields": { + "aliases": [], + "osv_id": "RUSTSEC-2099-0004", + "package": "pkg:cargo/ledger", + "purl": [ + "pkg:cargo/time@0.1.45" + ], + "severity": "unknown", + "summary": "Unsound localtime in the time crate", + "version": [ + "0.1.45" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:cargo/vault/RUSTSEC-2099-0003", + "fields": { + "aliases": [ + "CVE-2099-0003" + ], + "osv_id": "RUSTSEC-2099-0003", + "package": "pkg:cargo/vault", + "purl": [ + "pkg:cargo/smallvec@1.6.0" + ], + "severity": "high", + "summary": "Out-of-bounds read in SmallVec::drain", + "version": [ + "1.6.0" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:cargo/vault/RUSTSEC-2099-0004", + "fields": { + "aliases": [], + "osv_id": "RUSTSEC-2099-0004", + "package": "pkg:cargo/vault", + "purl": [ + "pkg:cargo/time@0.1.45" + ], + "severity": "unknown", + "summary": "Unsound localtime in the time crate", + "version": [ + "0.1.45" + ] + } + }, + { + "kind": "vulnerability", + "id": "vuln:pkg:npm/%40demo/web/GHSA-m3p6-8x4q-2c7v", + "fields": { + "aliases": [ + "CVE-2099-0005" + ], + "osv_id": "GHSA-m3p6-8x4q-2c7v", + "package": "pkg:npm/%40demo/web", + "purl": [ + "pkg:npm/%40babel/traverse@7.22.0" + ], + "severity": "critical", + "summary": "Arbitrary code execution when compiling crafted code", + "version": [ + "7.22.0" + ] + } + } +] diff --git a/extensions/code/osv/src/tests.rs b/extensions/code/osv/src/tests.rs new file mode 100644 index 0000000000..ee03fc5884 --- /dev/null +++ b/extensions/code/osv/src/tests.rs @@ -0,0 +1,259 @@ +use specforge_code_facts::vulnerability_facts; +use specforge_extension_sdk::prelude::Fact; + +use super::*; + +/// An osv-scanner report, hand-written to its JSON output and the OSV schema: a root `Cargo.lock` of `/project`. +const SCAN: &str = include_str!("../fixtures/osv-scanner.json"); +/// A scan of a virtual workspace's root `Cargo.lock` and of a nested npm `web/package-lock.json`, hand-written. +const WORKSPACE: &str = include_str!("../fixtures/workspace.json"); +/// osv-scanner 2.7.1's report of `/project`'s `Cargo.lock` and `web/package-lock.json`, recorded with real records. +const OSV_SCANNER_2_7_1: &str = include_str!("../fixtures/osv-scanner-2.7.1.json"); +/// The served `package` facts a vulnerability collector receives, as JSON. +const PACKAGES: &str = include_str!("../fixtures/packages.json"); + +fn served() -> Vec { + serde_json::from_str(PACKAGES).expect("the served facts parse") +} + +fn text<'f>(fact: &'f Fact, name: &str) -> Option<&'f str> { + fact.fields.get(name).and_then(Value::as_str) +} + +#[test] +fn a_scan_mints_vulnerabilities_citing_the_lockfiles_package() { + let report = read(SCAN, "/project").expect("the scan reads"); + let minted = vulnerability_facts(&report, &served()); + assert!(minted.skipped.is_empty(), "{:?}", minted.skipped); + let facts = minted.facts; + let read_out: Vec<(&str, Option<&str>, Option<&str>)> = facts + .iter() + .map(|f| { + assert!(f.id.starts_with("vuln:pkg:cargo/demo/"), "{}", f.id); + ( + text(f, "package").unwrap_or_default(), + text(f, "osv_id"), + text(f, "severity"), + ) + }) + .collect(); + assert_eq!( + read_out, + [ + ( + "pkg:cargo/demo", + Some("GHSA-7v4m-2x9q-3h8c"), + Some("medium") + ), + ("pkg:cargo/demo", Some("RUSTSEC-2099-0002"), Some("unknown")), + ] + ); + insta::assert_json_snapshot!("osv_scanner", facts); +} + +#[test] +fn a_scan_reads_its_lockfile_relative_and_each_records_purl_for_its_package() { + let report = read(SCAN, "/project").expect("the scan reads"); + assert_eq!(report.sources.len(), 1); + let source = &report.sources[0]; + assert_eq!(source.lockfile, "Cargo.lock"); + let smallvec = &source.packages[0].records[0]; + assert_eq!(smallvec.purl.as_deref(), Some("pkg:cargo/smallvec")); + assert_eq!(smallvec.label.as_deref(), Some("MODERATE")); + assert_eq!(smallvec.aliases, ["RUSTSEC-2099-0001", "CVE-2099-0001"]); + let time = &source.packages[1].records[0]; + assert_eq!((time.purl.as_deref(), time.label.as_deref()), (None, None)); + assert!(time.scores.is_empty()); +} + +#[test] +fn a_workspace_lockfile_reaches_every_member_and_a_nested_one_its_own_package() { + let report = read(WORKSPACE, "/project").expect("the scan reads"); + let lockfiles: Vec<&str> = report.sources.iter().map(|s| s.lockfile.as_str()).collect(); + assert_eq!(lockfiles, ["Cargo.lock", "web/package-lock.json"]); + // A virtual workspace has no root package. + let served: Vec = served() + .into_iter() + .filter(|f| f.id != "pkg:cargo/demo") + .collect(); + let minted = vulnerability_facts(&report, &served); + assert!(minted.skipped.is_empty(), "{:?}", minted.skipped); + let facts = minted.facts; + let read_out: Vec<(&str, &str, &str)> = facts + .iter() + .map(|f| { + ( + text(f, "package").unwrap_or_default(), + text(f, "osv_id").unwrap_or_default(), + text(f, "severity").unwrap_or_default(), + ) + }) + .collect(); + assert_eq!( + read_out, + [ + ("pkg:cargo/ledger", "RUSTSEC-2099-0003", "high"), + ("pkg:cargo/ledger", "RUSTSEC-2099-0004", "unknown"), + ("pkg:cargo/vault", "RUSTSEC-2099-0003", "high"), + ("pkg:cargo/vault", "RUSTSEC-2099-0004", "unknown"), + ("pkg:npm/%40demo/web", "GHSA-m3p6-8x4q-2c7v", "critical"), + ] + ); + let web = &facts[4]; + assert_eq!( + web.fields["purl"], + serde_json::json!(["pkg:npm/%40babel/traverse@7.22.0"]) + ); + insta::assert_json_snapshot!("workspace", facts); +} + +#[test] +fn a_recorded_osv_scanner_2_7_1_report_mints_real_records_of_both_lockfiles() { + let report = read(OSV_SCANNER_2_7_1, "/project").expect("the recording reads"); + let lockfiles: Vec<&str> = report.sources.iter().map(|s| s.lockfile.as_str()).collect(); + assert_eq!(lockfiles, ["Cargo.lock", "web/package-lock.json"]); + let minted = vulnerability_facts(&report, &served()); + assert!(minted.skipped.is_empty(), "{:?}", minted.skipped); + let packages: std::collections::BTreeSet<&str> = minted + .facts + .iter() + .map(|f| text(f, "package").unwrap_or_default()) + .collect(); + assert_eq!( + packages, + ["pkg:cargo/demo", "pkg:npm/%40demo/web"] + .into_iter() + .collect() + ); + insta::assert_json_snapshot!("osv_scanner_2_7_1", minted.facts); +} + +#[test] +fn an_error_shows_the_reports_text_bounded_and_escaped() { + let hostile = format!("\u{1b}]0;{}", "a".repeat(5_000)); + let smallvec = + || serde_json::json!({"name": "smallvec", "version": "1.6.0", "ecosystem": "crates.io"}); + let record = || serde_json::json!({"id": "RUSTSEC-2099-0001"}); + for source in [ + serde_json::json!({"path": hostile, "type": "docker"}), + serde_json::json!({"path": "/project/Cargo.lock", "type": hostile}), + serde_json::json!({"path": format!("/elsewhere/{hostile}"), "type": "lockfile"}), + ] { + let error = read(&scan(source, smallvec(), record()), "/project").expect_err("refused"); + assert!( + !error.contains('\u{1b}') && error.contains("\\u{1b}"), + "{error}" + ); + assert!(error.len() < 400, "{} bytes", error.len()); + } +} + +#[test] +fn a_polyglot_scan_keeps_its_cargo_findings_and_names_what_it_skips() { + let text = serde_json::json!({"results": [ + {"source": {"path": "/project/Cargo.lock", "type": "lockfile"}, "packages": [ + {"package": {"name": "smallvec", "version": "1.6.0", "ecosystem": "crates.io"}, + "vulnerabilities": [{"id": "RUSTSEC-2099-0001"}]}]}, + {"source": {"path": "/project/requirements.txt", "type": "lockfile"}, "packages": [ + {"package": {"name": "django", "version": "4.0", "ecosystem": "PyPI"}, + "vulnerabilities": [{"id": "PYSEC-2099-1"}]}]}, + {"source": {"path": "/project/api/package-lock.json", "type": "lockfile"}, "packages": [ + {"package": {"name": "lodash", "version": "4.17.20", "ecosystem": "npm"}, + "vulnerabilities": [{"id": "GHSA-0000-0000-0000"}]}]} + ]}) + .to_string(); + // Only the cargo package at the root: no npm package lies at or under `api`. + let served: Vec = served() + .into_iter() + .filter(|f| f.id == "pkg:cargo/demo") + .collect(); + let minted = vulnerability_facts(&read(&text, "/project").expect("the scan reads"), &served); + let ids: Vec<&str> = minted.facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!(ids, ["vuln:pkg:cargo/demo/RUSTSEC-2099-0001"]); + assert_eq!(minted.skipped.len(), 2, "{:?}", minted.skipped); + assert!( + minted.skipped[0].contains("PyPI") && minted.skipped[0].contains("requirements.txt"), + "{}", + minted.skipped[0] + ); + assert!( + minted.skipped[1].contains("api/package-lock.json"), + "{}", + minted.skipped[1] + ); +} + +/// A minimal scan of one `source` holding one `package` of `ecosystem`, its record `vulnerability`. +fn scan(source: Value, package: Value, vulnerability: Value) -> String { + serde_json::json!({ + "results": [{ + "source": source, + "packages": [{"package": package, "vulnerabilities": [vulnerability]}] + }] + }) + .to_string() +} + +#[test] +fn a_bad_scan_is_an_error_naming_its_value_or_key_and_mints_nothing() { + let lockfile = || serde_json::json!({"path": "/project/Cargo.lock", "type": "lockfile"}); + let smallvec = + || serde_json::json!({"name": "smallvec", "version": "1.6.0", "ecosystem": "crates.io"}); + let record = || serde_json::json!({"id": "RUSTSEC-2099-0001"}); + let rows: [(&str, String, &[&str]); 8] = [ + ("no results", "{}".to_string(), &["results"]), + ( + "results no array", + "{\"results\": {}}".to_string(), + &["results"], + ), + ( + "source type docker", + scan( + serde_json::json!({"path": "/project/Dockerfile", "type": "docker"}), + smallvec(), + record(), + ), + &["docker", "/project/Dockerfile"], + ), + ( + "a path outside the project", + scan( + serde_json::json!({"path": "/elsewhere/Cargo.lock", "type": "lockfile"}), + smallvec(), + record(), + ), + &["/elsewhere/Cargo.lock"], + ), + ( + "no source.path", + scan( + serde_json::json!({"type": "lockfile"}), + smallvec(), + record(), + ), + &["results[0].source.path"], + ), + ( + "a package with no version", + scan( + lockfile(), + serde_json::json!({"name": "smallvec", "ecosystem": "crates.io"}), + record(), + ), + &["results[0].packages[0].package.version"], + ), + ( + "a vulnerability with no id", + scan(lockfile(), smallvec(), serde_json::json!({"summary": "x"})), + &["results[0].packages[0].vulnerabilities[0].id"], + ), + ("no JSON", "{\"results\":".to_string(), &["no JSON"]), + ]; + for (case, text, named) in rows { + let error = read(&text, "/project").expect_err(case); + for name in named { + assert!(error.contains(name), "{case}: {error}"); + } + } +} diff --git a/extensions/code/sarif/Cargo.lock b/extensions/code/sarif/Cargo.lock new file mode 100644 index 0000000000..2f8f022e9e --- /dev/null +++ b/extensions/code/sarif/Cargo.lock @@ -0,0 +1,646 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "windows-sys", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "insta" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67d3d2e287e4b86c10b3f3b641033d1f89b74bdb39d05f34952e2b9a6fe21cd" +dependencies = [ + "console", + "once_cell", + "serde", + "similar", + "tempfile", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-sarif" +version = "1.0.0" +dependencies = [ + "insta", + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/code/sarif/Cargo.toml b/extensions/code/sarif/Cargo.toml new file mode 100644 index 0000000000..414a5e2cdb --- /dev/null +++ b/extensions/code/sarif/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "specforge-code-sarif" +version = "1.0.0" +edition = "2021" +description = "The SARIF 2.1.0 reader the lint packs link (ADR 0388); no guest" +publish = false + +# An extension library (ADR 0328 D3): an rlib a builtin links, never embedded. +[lib] +crate-type = ["rlib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-facts = { path = "../facts" } +serde_json = "1.0" + +[dev-dependencies] +insta = { version = "1.46.3", features = ["json"] } diff --git a/extensions/code/sarif/fixtures/README.md b/extensions/code/sarif/fixtures/README.md new file mode 100644 index 0000000000..213856a556 --- /dev/null +++ b/extensions/code/sarif/fixtures/README.md @@ -0,0 +1,15 @@ +# SARIF reader fixtures + +Neither clippy-sarif nor ESLint was installed where the first fixtures were written, so those are hand-written to the +SARIF 2.1.0 specification and the tool shape named below. `eslint-10.15.0.sarif` is a real recording; its absolute +paths were replaced with one command: +`sed -E 's#/private/tmp/[^"<> ]*/research-tools/[^/"<> ]*#/project#g' > eslint-10.15.0.sarif`. + +| Fixture | Source | +|---------|--------| +| `clippy.sarif` | hand-written to SARIF 2.1.0 and the clippy-sarif shape (`cargo clippy --message-format=json \| clippy-sarif`): driver `clippy` with the rules `clippy::needless_return` and `clippy::unwrap_used`, results with `ruleId`, `ruleIndex` and level `warning`, `uri` `src/lib.rs` relative to `%SRCROOT%`. One result in the method `Board::len` (line 7), one in the test fn `tests::reads` (lines 16-17), one on line 24, which no item holds | +| `eslint.sarif` | hand-written to the @microsoft/eslint-formatter-sarif shape: driver `ESLint` with rule metadata and no `ruleIndex` on any result, `artifacts[]` holding the absolute percent-encoded `file:///project/src/board%20view.js`, levels `error` and `warning`. One result giving its file by `uri`, one by `artifactLocation.index` alone, one of a rule with no metadata (`local/no-raw-dom`), one suppressed in source | +| `rule-less.sarif` | hand-written to SARIF 2.1.0 §3.27.10: driver `demo-lint` with rule `R1` (no `defaultConfiguration`) and `R2` (default `note`). A result naming no rule, a result of `R1` stating no level, a `kind` `pass` with no level, `R2` by `ruleIndex` alone and by `rule.id` with no location, and two results of `R1` at one line | +| `eslint-10.15.0.sarif` | recorded with ESLint 10.15.0 and @microsoft/eslint-formatter-sarif 3.1.0 by the Phase 11 research (`eslint --format @microsoft/eslint-formatter-sarif --output-file .` over the package `board`, `js.configs.recommended` with `no-console` warn and `eqeqeq` error), absolute paths replaced by `/project`. Four results in `src/board view.js` (percent-encoded `board%20view.js`), each by `uri` and `index`, with `ruleIndex` | +| `eslint-10.15.0.items.json` | hand-written served facts for that recording: the function `view` (lines 1-5 of the recorded `src/board view.js`) and the package `board`. Its own file: `view` would overlap the hand-written `render` of `items.json` in the same file and change the `eslint` snapshot | +| `items.json` | hand-written served facts: the `item` facts (with their places) and the root `package` a lint collector receives, for the crate `demo` (`src/lib.rs`) and the npm package `board` (`src/board view.js`) | diff --git a/extensions/code/sarif/fixtures/clippy.sarif b/extensions/code/sarif/fixtures/clippy.sarif new file mode 100644 index 0000000000..a89ad413ca --- /dev/null +++ b/extensions/code/sarif/fixtures/clippy.sarif @@ -0,0 +1,107 @@ +{ + "$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json", + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "clippy", + "informationUri": "https://rust-lang.github.io/rust-clippy/", + "rules": [ + { + "id": "clippy::needless_return", + "fullDescription": { + "text": "for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_return" + } + }, + { + "id": "clippy::unwrap_used", + "fullDescription": { + "text": "for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used" + } + } + ] + } + }, + "originalUriBaseIds": { + "%SRCROOT%": { + "uri": "file:///project/" + } + }, + "results": [ + { + "ruleId": "clippy::needless_return", + "ruleIndex": 0, + "level": "warning", + "message": { + "text": "unneeded `return` statement" + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "src/lib.rs", + "uriBaseId": "%SRCROOT%" + }, + "region": { + "startLine": 7, + "startColumn": 9, + "endLine": 7, + "endColumn": 30 + } + } + } + ] + }, + { + "ruleId": "clippy::unwrap_used", + "ruleIndex": 1, + "level": "warning", + "message": { + "text": "used `unwrap()` on a `Result` value" + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "src/lib.rs", + "uriBaseId": "%SRCROOT%" + }, + "region": { + "startLine": 16, + "startColumn": 17, + "endLine": 17, + "endColumn": 22 + } + } + } + ] + }, + { + "ruleId": "clippy::unwrap_used", + "ruleIndex": 1, + "level": "warning", + "message": { + "text": "used `unwrap()` on an `Option` value" + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "src/lib.rs", + "uriBaseId": "%SRCROOT%" + }, + "region": { + "startLine": 24, + "startColumn": 5, + "endLine": 24, + "endColumn": 40 + } + } + } + ] + } + ] + } + ] +} diff --git a/extensions/code/sarif/fixtures/eslint-10.15.0.items.json b/extensions/code/sarif/fixtures/eslint-10.15.0.items.json new file mode 100644 index 0000000000..cf759b61c3 --- /dev/null +++ b/extensions/code/sarif/fixtures/eslint-10.15.0.items.json @@ -0,0 +1,8 @@ +[ + {"kind": "item", "id": "js:board/src/board%20view.js::view", + "fields": {"kind": ["function"], "package": "pkg:npm/board", "file": "src/board view.js", "visibility": "public", + "attrs": ["export"]}, + "at": [{"file": "src/board view.js", "start_line": 1, "start_col": 8, "end_line": 5, "end_col": 2}]}, + {"kind": "package", "id": "pkg:npm/board", + "fields": {"name": "board", "version": "1.0.0", "path": ""}} +] diff --git a/extensions/code/sarif/fixtures/eslint-10.15.0.sarif b/extensions/code/sarif/fixtures/eslint-10.15.0.sarif new file mode 100644 index 0000000000..bb760effee --- /dev/null +++ b/extensions/code/sarif/fixtures/eslint-10.15.0.sarif @@ -0,0 +1,159 @@ +{ + "version": "2.1.0", + "$schema": "http://json.schemastore.org/sarif-2.1.0-rtm.5", + "runs": [ + { + "tool": { + "driver": { + "name": "ESLint", + "informationUri": "https://eslint.org", + "rules": [ + { + "id": "no-unused-vars", + "helpUri": "https://eslint.org/docs/latest/rules/no-unused-vars", + "properties": {}, + "shortDescription": { + "text": "Disallow unused variables" + } + }, + { + "id": "no-undef", + "helpUri": "https://eslint.org/docs/latest/rules/no-undef", + "properties": {}, + "shortDescription": { + "text": "Disallow the use of undeclared variables unless mentioned in `/*global */` comments" + } + }, + { + "id": "no-console", + "helpUri": "https://eslint.org/docs/latest/rules/no-console", + "properties": {}, + "shortDescription": { + "text": "Disallow the use of `console`" + } + }, + { + "id": "eqeqeq", + "helpUri": "https://eslint.org/docs/latest/rules/eqeqeq", + "properties": {}, + "shortDescription": { + "text": "Require the use of `===` and `!==`" + } + } + ], + "version": "10.15.0" + } + }, + "artifacts": [ + { + "location": { + "uri": "file:///project/eslint.config.js" + } + }, + { + "location": { + "uri": "file:///project/src/board%20view.js" + } + } + ], + "results": [ + { + "level": "error", + "message": { + "text": "'unused' is assigned a value but never used." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "file:///project/src/board%20view.js", + "index": 1 + }, + "region": { + "startLine": 2, + "startColumn": 7, + "endLine": 2, + "endColumn": 13 + } + } + } + ], + "ruleId": "no-unused-vars", + "ruleIndex": 0 + }, + { + "level": "error", + "message": { + "text": "'console' is not defined." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "file:///project/src/board%20view.js", + "index": 1 + }, + "region": { + "startLine": 3, + "startColumn": 3, + "endLine": 3, + "endColumn": 10 + } + } + } + ], + "ruleId": "no-undef", + "ruleIndex": 1 + }, + { + "level": "warning", + "message": { + "text": "Unexpected console statement." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "file:///project/src/board%20view.js", + "index": 1 + }, + "region": { + "startLine": 3, + "startColumn": 3, + "endLine": 3, + "endColumn": 14 + } + } + } + ], + "ruleId": "no-console", + "ruleIndex": 2 + }, + { + "level": "error", + "message": { + "text": "Expected '===' and instead saw '=='." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "file:///project/src/board%20view.js", + "index": 1 + }, + "region": { + "startLine": 4, + "startColumn": 9, + "endLine": 4, + "endColumn": 11 + } + } + } + ], + "ruleId": "eqeqeq", + "ruleIndex": 3 + } + ] + } + ] +} \ No newline at end of file diff --git a/extensions/code/sarif/fixtures/eslint.sarif b/extensions/code/sarif/fixtures/eslint.sarif new file mode 100644 index 0000000000..377ce207b0 --- /dev/null +++ b/extensions/code/sarif/fixtures/eslint.sarif @@ -0,0 +1,153 @@ +{ + "version": "2.1.0", + "$schema": "http://json.schemastore.org/sarif-2.1.0-rtm.5", + "runs": [ + { + "tool": { + "driver": { + "name": "ESLint", + "informationUri": "https://eslint.org", + "rules": [ + { + "id": "no-unused-vars", + "helpUri": "https://eslint.org/docs/latest/rules/no-unused-vars", + "properties": { + "category": "Variables" + }, + "shortDescription": { + "text": "Disallow unused variables" + } + }, + { + "id": "eqeqeq", + "helpUri": "https://eslint.org/docs/latest/rules/eqeqeq", + "properties": { + "category": "Best Practices" + }, + "shortDescription": { + "text": "Require the use of `===` and `!==`" + } + }, + { + "id": "no-console", + "helpUri": "https://eslint.org/docs/latest/rules/no-console", + "properties": { + "category": "Suggestions" + }, + "shortDescription": { + "text": "Disallow the use of `console`" + } + } + ], + "version": "9.14.0" + } + }, + "artifacts": [ + { + "location": { + "uri": "file:///project/src/board%20view.js" + } + } + ], + "results": [ + { + "level": "error", + "message": { + "text": "'size' is assigned a value but never used." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "file:///project/src/board%20view.js", + "index": 0 + }, + "region": { + "startLine": 3, + "startColumn": 9, + "endLine": 3, + "endColumn": 13 + } + } + } + ], + "ruleId": "no-unused-vars" + }, + { + "level": "warning", + "message": { + "text": "Expected '===' and instead saw '=='." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "index": 0 + }, + "region": { + "startLine": 12, + "startColumn": 14, + "endLine": 12, + "endColumn": 16 + } + } + } + ], + "ruleId": "eqeqeq" + }, + { + "level": "warning", + "message": { + "text": "Direct DOM access is not allowed in views." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "file:///project/src/board%20view.js", + "index": 0 + }, + "region": { + "startLine": 18, + "startColumn": 5, + "endLine": 18, + "endColumn": 33 + } + } + } + ], + "ruleId": "local/no-raw-dom" + }, + { + "level": "warning", + "message": { + "text": "Unexpected console statement." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "file:///project/src/board%20view.js", + "index": 0 + }, + "region": { + "startLine": 4, + "startColumn": 3, + "endLine": 4, + "endColumn": 14 + } + } + } + ], + "suppressions": [ + { + "kind": "inSource", + "justification": "debug output kept on purpose" + } + ], + "ruleId": "no-console" + } + ] + } + ] +} diff --git a/extensions/code/sarif/fixtures/items.json b/extensions/code/sarif/fixtures/items.json new file mode 100644 index 0000000000..30dea2ab15 --- /dev/null +++ b/extensions/code/sarif/fixtures/items.json @@ -0,0 +1,31 @@ +[ + {"kind": "item", "id": "rust:demo::Board", + "fields": {"kind": ["struct"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "public"}, + "at": [{"file": "src/lib.rs", "start_line": 1, "start_col": 1, "end_line": 3, "end_col": 2}]}, + {"kind": "item", "id": "rust:demo::Board::len", + "fields": {"kind": ["fn"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "public"}, + "at": [{"file": "src/lib.rs", "start_line": 6, "start_col": 5, "end_line": 8, "end_col": 6}]}, + {"kind": "item", "id": "rust:demo::tests", + "fields": {"kind": ["mod"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "private", + "attrs": ["cfg(test)"]}, + "at": [{"file": "src/lib.rs", "start_line": 11, "start_col": 1, "end_line": 20, "end_col": 2}]}, + {"kind": "item", "id": "rust:demo::tests::reads", + "fields": {"kind": ["fn"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "private", + "attrs": ["test"], "test_id": "rust:demo#tests::reads"}, + "at": [{"file": "src/lib.rs", "start_line": 14, "start_col": 5, "end_line": 18, "end_col": 6}]}, + {"kind": "package", "id": "pkg:cargo/demo", + "fields": {"name": "demo", "version": "0.1.0", "path": ""}}, + {"kind": "item", "id": "js:board/src/board%20view.js::render", + "fields": {"kind": ["function"], "package": "pkg:npm/board", "file": "src/board view.js", "visibility": "public", + "attrs": ["export"]}, + "at": [{"file": "src/board view.js", "start_line": 1, "start_col": 8, "end_line": 6, "end_col": 2}]}, + {"kind": "item", "id": "js:board/src/board%20view.js::View", + "fields": {"kind": ["class"], "package": "pkg:npm/board", "file": "src/board view.js", "visibility": "public", + "attrs": ["export"]}, + "at": [{"file": "src/board view.js", "start_line": 8, "start_col": 8, "end_line": 20, "end_col": 2}]}, + {"kind": "item", "id": "js:board/src/board%20view.js::View.draw", + "fields": {"kind": ["method"], "package": "pkg:npm/board", "file": "src/board view.js", "visibility": "public"}, + "at": [{"file": "src/board view.js", "start_line": 10, "start_col": 3, "end_line": 14, "end_col": 4}]}, + {"kind": "package", "id": "pkg:npm/board", + "fields": {"name": "board", "version": "1.0.0", "path": ""}} +] diff --git a/extensions/code/sarif/fixtures/rule-less.sarif b/extensions/code/sarif/fixtures/rule-less.sarif new file mode 100644 index 0000000000..c0bbfa1c91 --- /dev/null +++ b/extensions/code/sarif/fixtures/rule-less.sarif @@ -0,0 +1,146 @@ +{ + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "demo-lint", + "rules": [ + { + "id": "R1" + }, + { + "id": "R2", + "defaultConfiguration": { + "level": "note" + } + } + ] + } + }, + "results": [ + { + "level": "error", + "message": { + "text": "a result naming no rule" + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "src/lib.rs" + }, + "region": { + "startLine": 2 + } + } + } + ] + }, + { + "ruleId": "R1", + "message": { + "text": "a rule with no defaultConfiguration and no level" + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "src/lib.rs" + }, + "region": { + "startLine": 7 + } + } + } + ] + }, + { + "ruleId": "R1", + "kind": "pass", + "message": { + "text": "a pass with no level" + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "src/lib.rs" + }, + "region": { + "startLine": 15 + } + } + } + ] + }, + { + "ruleIndex": 1, + "message": { + "text": "a rule given by index alone, its default note" + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "src/lib.rs" + }, + "region": { + "startLine": 16 + } + } + } + ] + }, + { + "rule": { + "id": "R2" + }, + "message": { + "text": "a rule given by its reference id, its default note" + } + }, + { + "ruleId": "R1", + "level": "warning", + "message": { + "text": "the first of two results at one place" + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "src/lib.rs" + }, + "region": { + "startLine": 24, + "startColumn": 5 + } + } + } + ] + }, + { + "ruleId": "R1", + "level": "warning", + "message": { + "text": "the second of two results at one place" + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "src/lib.rs" + }, + "region": { + "startLine": 24, + "startColumn": 20 + } + } + } + ] + } + ] + } + ] +} diff --git a/extensions/code/sarif/src/lib.rs b/extensions/code/sarif/src/lib.rs new file mode 100644 index 0000000000..7b96528edc --- /dev/null +++ b/extensions/code/sarif/src/lib.rs @@ -0,0 +1,253 @@ +//! `specforge-code-sarif`: the SARIF 2.1.0 reader the lint packs link (ADR 0388). +//! +//! An extension library (ADR 0328 D3): an rlib a builtin links, never a component of its own. The wire has no +//! guest-to-guest call, so a lint pack reads its report here; `specforge-code-facts` mints the `static_finding` facts +//! from what it reads ([`specforge_code_facts::finding_facts`]). +//! +//! - [`read`] reads a SARIF 2.1.0 log into a [`Sarif`]: one [`SarifResult`] per result of each run, in document +//! order, and the files outside the project its results named and the paths naming no file, which it skips and +//! counts (ADR 0389 D7). + +#[cfg(test)] +mod tests; + +use std::collections::HashSet; + +use serde_json::Value; +use specforge_code_facts::{file_uri_path, place, shown, shown_json, Level, Place, UNKNOWN}; + +pub use specforge_code_facts::SarifResult; + +/// What a SARIF log says: its results in the project, the files outside it, and the paths naming no file. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Sarif { + /// The results whose file lies in the project, or that name no file, in document order. + pub results: Vec, + /// Each `file:` path outside the project, once, in document order, as [`shown`] writes it: its results mint + /// nothing. + pub outside: Vec, + /// Each path naming no file (the project root itself, a pseudo name like ``), once, in document order, as + /// [`shown`] writes it: its results mint nothing. + pub no_file: Vec, +} + +/// The results of the SARIF 2.1.0 log `text`, every run's in document order, their files relative to the project +/// root `cwd`. +/// +/// Per result: the rule is `ruleId`, else `rule.id`, else the id of the driver rule at `ruleIndex` (or +/// `rule.index`), else `unknown`. The level is the result's `level`, else `none` when its `kind` is stated and is +/// not `fail`, else its rule's `defaultConfiguration.level` (the rule found by index, else by id), else `unknown`: +/// what the log states, never SARIF's own `warning` default (F5). The message is `message.text`, empty when absent. +/// The file is the first location's `artifactLocation.uri`, else the `uri` of the run artifact at its `index`: a +/// `file:` URI decoded to its path, any other (with a `uriBaseId`, or no scheme) taken as project-relative, either +/// way through [`place`]. The lines are its `region`'s `startLine` and `endLine`. A result with no physical +/// location has no file and no line; a suppressed result is read like any other. +/// +/// A result whose path lies outside the project (a `file:` URI elsewhere, or a relative one climbing out through +/// `..`) is skipped: its path is counted once in [`Sarif::outside`], never opened (ADR 0389 D7). A result whose path +/// names no file (`.`, the root's own path, ``) is skipped the same way and counted in [`Sarif::no_file`]. +/// +/// An error, naming the JSON path or the value, and nothing is read: text that is no JSON (nesting deeper than +/// serde_json's limit included), a `version` other than `"2.1.0"`, no `runs` array, a run with no +/// `tool.driver.name`, a run with no `results` (absent means the tool did not run, SARIF §3.14.23; an empty array is +/// a run that found nothing), an index naming no rule or artifact, and a URI of a scheme other than `file:`. +pub fn read(text: &str, cwd: &str) -> Result { + let log: Value = serde_json::from_str(text).map_err(|e| format!("no JSON: {e}"))?; + match log.get("version") { + Some(Value::String(version)) if version == "2.1.0" => {} + Some(version) => { + return Err(format!( + "version: {} is not read, only \"2.1.0\"", + shown_json(version) + )) + } + None => return Err("version: absent, only \"2.1.0\" is read".to_string()), + } + let runs = log + .get("runs") + .and_then(Value::as_array) + .ok_or("runs: absent or no array")?; + let mut read = Sarif::default(); + let mut seen = HashSet::new(); + for (r, run) in runs.iter().enumerate() { + let at = format!("runs[{r}]"); + let Run { + tool, + rules, + artifacts, + } = Run::of(run, &at)?; + let results = match run.get("results") { + Some(Value::Array(results)) => results, + Some(_) => return Err(format!("{at}.results: no array")), + None => { + return Err(format!( + "{at}.results: absent, so the tool did not run (SARIF §3.14.23)" + )) + } + }; + for (i, result) in results.iter().enumerate() { + let here = format!("{at}.results[{i}]"); + let rule = rule_of(result, rules, &here)?; + let (file, line, end_line) = match place_of(result, artifacts, cwd, &here)? { + Located::In(lines) => lines, + Located::Outside(path) => { + if seen.insert(path.clone()) { + read.outside.push(path); + } + continue; + } + Located::NoFile(path) => { + if seen.insert(path.clone()) { + read.no_file.push(path); + } + continue; + } + }; + read.results.push(SarifResult { + tool: tool.to_string(), + rule: rule.and_then(|(id, _)| id).unwrap_or(UNKNOWN).to_string(), + level: level_of(result, rule.and_then(|(_, descriptor)| descriptor)), + message: text_at(result, "/message/text") + .unwrap_or_default() + .to_string(), + file, + line, + end_line, + }); + } + } + Ok(read) +} + +/// What a result of a run reads from its run. +struct Run<'v> { + tool: &'v str, + rules: &'v [Value], + artifacts: &'v [Value], +} + +impl<'v> Run<'v> { + fn of(run: &'v Value, at: &str) -> Result, String> { + Ok(Run { + tool: text_at(run, "/tool/driver/name") + .ok_or_else(|| format!("{at}.tool.driver.name: absent"))?, + rules: array_at(run, "/tool/driver/rules"), + artifacts: array_at(run, "/artifacts"), + }) + } +} + +/// The rule a result names, its id and its driver descriptor, each when known; `None` when it names none. +type Rule<'v> = Option<(Option<&'v str>, Option<&'v Value>)>; + +/// The rule of `result` (at the JSON path `at`): by `ruleIndex` or `rule.index` into `rules` first, then by `ruleId` +/// or `rule.id`. An index naming no rule is an error. +fn rule_of<'v>(result: &'v Value, rules: &'v [Value], at: &str) -> Result, String> { + let id = text_at(result, "/ruleId").or_else(|| text_at(result, "/rule/id")); + // A negative index (SARIF's -1) reads as none. + let index = result + .get("ruleIndex") + .or_else(|| result.pointer("/rule/index")) + .and_then(Value::as_u64); + let descriptor = match index { + Some(index) => Some( + usize::try_from(index) + .ok() + .and_then(|index| rules.get(index)) + .ok_or_else(|| format!("{at}: rule index {index} names no rule of the driver"))?, + ), + None => id.and_then(|id| rules.iter().find(|rule| text_at(rule, "/id") == Some(id))), + }; + let id = id.or_else(|| descriptor.and_then(|rule| text_at(rule, "/id"))); + Ok((id.is_some() || descriptor.is_some()).then_some((id, descriptor))) +} + +/// The level `result` states, else `none` for a stated `kind` other than `fail`, else its rule's default, else +/// `unknown` (F5). +fn level_of(result: &Value, rule: Option<&Value>) -> Level { + if let Some(level) = text_at(result, "/level").and_then(Level::parse) { + return level; + } + if text_at(result, "/kind").is_some_and(|kind| kind != "fail") { + return Level::None; + } + rule.and_then(|rule| text_at(rule, "/defaultConfiguration/level")) + .and_then(Level::parse) + .unwrap_or(Level::Unknown) +} + +/// The file and the start and end lines of `result`'s first physical location, each when stated. +type Lines = (Option, Option, Option); + +/// Where a result lies: its place in the project, or the path outside it or naming no file, [`shown`]. +enum Located { + In(Lines), + Outside(String), + NoFile(String), +} + +/// The place of `result` (at the JSON path `at`); a URI of another scheme than `file:`, or an artifact index naming +/// no artifact, is an error. +fn place_of(result: &Value, artifacts: &[Value], cwd: &str, at: &str) -> Result { + let Some(physical) = result.pointer("/locations/0/physicalLocation") else { + return Ok(Located::In((None, None, None))); + }; + let artifact = physical.get("artifactLocation"); + let uri = match artifact.and_then(|a| text_at(a, "/uri")) { + Some(uri) => Some(uri), + None => match artifact + .and_then(|a| a.get("index")) + .and_then(Value::as_u64) + { + Some(index) => Some( + usize::try_from(index) + .ok() + .and_then(|index| artifacts.get(index)) + .and_then(|artifact| text_at(artifact, "/location/uri")) + .ok_or_else(|| { + format!("{at}: artifact index {index} names no artifact with a uri") + })?, + ), + None => None, + }, + }; + let file = match uri { + // shortcut: a `uriBaseId` is taken as the project root, whatever `originalUriBaseIds` maps it to; read the + // map when a tool writes a base below the root. + Some(uri) => { + let path = file_uri_path(uri).ok_or_else(|| { + format!( + "{at}: the uri `{}` is no file: uri, so it names no file of the project `{cwd}`", + shown(uri) + ) + })?; + match place(&path, cwd) { + Place::File(file) => Some(file), + Place::Outside => return Ok(Located::Outside(shown(&path))), + Place::NoFile => return Ok(Located::NoFile(shown(&path))), + } + } + None => None, + }; + let line = |name: &str| { + physical + .pointer(&format!("/region/{name}")) + .and_then(Value::as_u64) + .and_then(|line| usize::try_from(line).ok()) + .filter(|&line| line >= 1) + }; + Ok(Located::In((file, line("startLine"), line("endLine")))) +} + +/// The string at the JSON pointer `pointer` of `value`, if it is one. +fn text_at<'v>(value: &'v Value, pointer: &str) -> Option<&'v str> { + value.pointer(pointer).and_then(Value::as_str) +} + +/// The array at the JSON pointer `pointer` of `value`; empty when absent or not an array. +fn array_at<'v>(value: &'v Value, pointer: &str) -> &'v [Value] { + value + .pointer(pointer) + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice) +} diff --git a/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__clippy.snap b/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__clippy.snap new file mode 100644 index 0000000000..5ac43d4b06 --- /dev/null +++ b/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__clippy.snap @@ -0,0 +1,72 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "static_finding", + "id": "sarif:clippy/clippy%3A%3Aneedless_return#src%2Flib.rs:7", + "fields": { + "file": "src/lib.rs", + "item": "rust:demo::Board::len", + "level": "warning", + "line": 7, + "message": "unneeded `return` statement", + "rule": "clippy::needless_return", + "tool": "clippy" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 7, + "start_col": 1, + "end_line": 8, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:clippy/clippy%3A%3Aunwrap_used#src%2Flib.rs:16", + "fields": { + "file": "src/lib.rs", + "item": "rust:demo::tests::reads", + "level": "warning", + "line": 16, + "message": "used `unwrap()` on a `Result` value", + "rule": "clippy::unwrap_used", + "tool": "clippy" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 16, + "start_col": 1, + "end_line": 18, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:clippy/clippy%3A%3Aunwrap_used#src%2Flib.rs:24", + "fields": { + "file": "src/lib.rs", + "level": "warning", + "line": 24, + "message": "used `unwrap()` on an `Option` value", + "package": "pkg:cargo/demo", + "rule": "clippy::unwrap_used", + "tool": "clippy" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 24, + "start_col": 1, + "end_line": 25, + "end_col": 1 + } + ] + } +] diff --git a/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__eslint.snap b/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__eslint.snap new file mode 100644 index 0000000000..b543c559f2 --- /dev/null +++ b/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__eslint.snap @@ -0,0 +1,94 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "static_finding", + "id": "sarif:ESLint/no-unused-vars#src%2Fboard%20view.js:3", + "fields": { + "file": "src/board view.js", + "item": "js:board/src/board%20view.js::render", + "level": "error", + "line": 3, + "message": "'size' is assigned a value but never used.", + "rule": "no-unused-vars", + "tool": "ESLint" + }, + "at": [ + { + "file": "src/board view.js", + "start_line": 3, + "start_col": 1, + "end_line": 4, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:ESLint/eqeqeq#src%2Fboard%20view.js:12", + "fields": { + "file": "src/board view.js", + "item": "js:board/src/board%20view.js::View.draw", + "level": "warning", + "line": 12, + "message": "Expected '===' and instead saw '=='.", + "rule": "eqeqeq", + "tool": "ESLint" + }, + "at": [ + { + "file": "src/board view.js", + "start_line": 12, + "start_col": 1, + "end_line": 13, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:ESLint/local%2Fno-raw-dom#src%2Fboard%20view.js:18", + "fields": { + "file": "src/board view.js", + "item": "js:board/src/board%20view.js::View", + "level": "warning", + "line": 18, + "message": "Direct DOM access is not allowed in views.", + "rule": "local/no-raw-dom", + "tool": "ESLint" + }, + "at": [ + { + "file": "src/board view.js", + "start_line": 18, + "start_col": 1, + "end_line": 19, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:ESLint/no-console#src%2Fboard%20view.js:4", + "fields": { + "file": "src/board view.js", + "item": "js:board/src/board%20view.js::render", + "level": "warning", + "line": 4, + "message": "Unexpected console statement.", + "rule": "no-console", + "tool": "ESLint" + }, + "at": [ + { + "file": "src/board view.js", + "start_line": 4, + "start_col": 1, + "end_line": 5, + "end_col": 1 + } + ] + } +] diff --git a/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__eslint_10_15.snap b/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__eslint_10_15.snap new file mode 100644 index 0000000000..32331e90ad --- /dev/null +++ b/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__eslint_10_15.snap @@ -0,0 +1,94 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "static_finding", + "id": "sarif:ESLint/no-unused-vars#src%2Fboard%20view.js:2", + "fields": { + "file": "src/board view.js", + "item": "js:board/src/board%20view.js::view", + "level": "error", + "line": 2, + "message": "'unused' is assigned a value but never used.", + "rule": "no-unused-vars", + "tool": "ESLint" + }, + "at": [ + { + "file": "src/board view.js", + "start_line": 2, + "start_col": 1, + "end_line": 3, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:ESLint/no-undef#src%2Fboard%20view.js:3", + "fields": { + "file": "src/board view.js", + "item": "js:board/src/board%20view.js::view", + "level": "error", + "line": 3, + "message": "'console' is not defined.", + "rule": "no-undef", + "tool": "ESLint" + }, + "at": [ + { + "file": "src/board view.js", + "start_line": 3, + "start_col": 1, + "end_line": 4, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:ESLint/no-console#src%2Fboard%20view.js:3", + "fields": { + "file": "src/board view.js", + "item": "js:board/src/board%20view.js::view", + "level": "warning", + "line": 3, + "message": "Unexpected console statement.", + "rule": "no-console", + "tool": "ESLint" + }, + "at": [ + { + "file": "src/board view.js", + "start_line": 3, + "start_col": 1, + "end_line": 4, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:ESLint/eqeqeq#src%2Fboard%20view.js:4", + "fields": { + "file": "src/board view.js", + "item": "js:board/src/board%20view.js::view", + "level": "error", + "line": 4, + "message": "Expected '===' and instead saw '=='.", + "rule": "eqeqeq", + "tool": "ESLint" + }, + "at": [ + { + "file": "src/board view.js", + "start_line": 4, + "start_col": 1, + "end_line": 5, + "end_col": 1 + } + ] + } +] diff --git a/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__rule_less.snap b/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__rule_less.snap new file mode 100644 index 0000000000..3ff2b5164b --- /dev/null +++ b/extensions/code/sarif/src/snapshots/specforge_code_sarif__tests__rule_less.snap @@ -0,0 +1,148 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "static_finding", + "id": "sarif:demo-lint/unknown#src%2Flib.rs:2", + "fields": { + "file": "src/lib.rs", + "item": "rust:demo::Board", + "level": "error", + "line": 2, + "message": "a result naming no rule", + "rule": "unknown", + "tool": "demo-lint" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 2, + "start_col": 1, + "end_line": 3, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:demo-lint/R1#src%2Flib.rs:7", + "fields": { + "file": "src/lib.rs", + "item": "rust:demo::Board::len", + "level": "unknown", + "line": 7, + "message": "a rule with no defaultConfiguration and no level", + "rule": "R1", + "tool": "demo-lint" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 7, + "start_col": 1, + "end_line": 8, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:demo-lint/R1#src%2Flib.rs:15", + "fields": { + "file": "src/lib.rs", + "item": "rust:demo::tests::reads", + "level": "none", + "line": 15, + "message": "a pass with no level", + "rule": "R1", + "tool": "demo-lint" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 15, + "start_col": 1, + "end_line": 16, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:demo-lint/R2#src%2Flib.rs:16", + "fields": { + "file": "src/lib.rs", + "item": "rust:demo::tests::reads", + "level": "note", + "line": 16, + "message": "a rule given by index alone, its default note", + "rule": "R2", + "tool": "demo-lint" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 16, + "start_col": 1, + "end_line": 17, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:demo-lint/R2", + "fields": { + "level": "note", + "message": "a rule given by its reference id, its default note", + "rule": "R2", + "tool": "demo-lint" + } + }, + { + "kind": "static_finding", + "id": "sarif:demo-lint/R1#src%2Flib.rs:24", + "fields": { + "file": "src/lib.rs", + "level": "warning", + "line": 24, + "message": "the first of two results at one place", + "package": "pkg:cargo/demo", + "rule": "R1", + "tool": "demo-lint" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 24, + "start_col": 1, + "end_line": 25, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:demo-lint/R1#src%2Flib.rs:24~2", + "fields": { + "file": "src/lib.rs", + "level": "warning", + "line": 24, + "message": "the second of two results at one place", + "package": "pkg:cargo/demo", + "rule": "R1", + "tool": "demo-lint" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 24, + "start_col": 1, + "end_line": 25, + "end_col": 1 + } + ] + } +] diff --git a/extensions/code/sarif/src/tests.rs b/extensions/code/sarif/src/tests.rs new file mode 100644 index 0000000000..9b2db76d7a --- /dev/null +++ b/extensions/code/sarif/src/tests.rs @@ -0,0 +1,296 @@ +use specforge_code_facts::{finding_facts, Level}; +use specforge_extension_sdk::prelude::Fact; + +use super::*; + +/// A clippy-sarif log, hand-written to SARIF 2.1.0 and the tool's shape: crate `demo` at `/project`. +const CLIPPY: &str = include_str!("../fixtures/clippy.sarif"); +/// An @microsoft/eslint-formatter-sarif log, hand-written: package `board` at `/project`. +const ESLINT: &str = include_str!("../fixtures/eslint.sarif"); +/// Results stating no rule or no level, hand-written to SARIF 2.1.0 §3.27.10. +const RULE_LESS: &str = include_str!("../fixtures/rule-less.sarif"); +/// The served `item` and `package` facts a lint collector receives, as JSON. +const ITEMS: &str = include_str!("../fixtures/items.json"); + +fn served() -> Vec { + serde_json::from_str(ITEMS).expect("the served facts parse") +} + +#[test] +fn a_clippy_report_mints_static_findings_citing_their_items() { + let results = read(CLIPPY, "/project").expect("the report reads").results; + let facts = finding_facts(&results, &served()); + let cited: Vec<(Option<&str>, Option<&str>)> = facts + .iter() + .map(|f| { + let field = |name: &str| f.fields.get(name).and_then(|v| v.as_str()); + (field("item"), field("package")) + }) + .collect(); + assert_eq!( + cited, + [ + (Some("rust:demo::Board::len"), None), + (Some("rust:demo::tests::reads"), None), + (None, Some("pkg:cargo/demo")), + ] + ); + insta::assert_json_snapshot!("clippy", facts); +} + +#[test] +fn a_clippy_result_reads_its_rule_level_message_and_lines() { + let results = read(CLIPPY, "/project").expect("the report reads").results; + assert_eq!( + results[1], + SarifResult { + tool: "clippy".to_string(), + rule: "clippy::unwrap_used".to_string(), + level: Level::Warning, + message: "used `unwrap()` on a `Result` value".to_string(), + file: Some("src/lib.rs".to_string()), + line: Some(16), + end_line: Some(17), + } + ); +} + +fn field<'f>(fact: &'f Fact, name: &str) -> Option<&'f str> { + fact.fields.get(name).and_then(|v| v.as_str()) +} + +#[test] +fn an_eslint_report_mints_static_findings_citing_their_js_items() { + let results = read(ESLINT, "/project").expect("the report reads").results; + assert!(results + .iter() + .all(|r| r.file.as_deref() == Some("src/board view.js"))); + let facts = finding_facts(&results, &served()); + let cited: Vec<(&str, Option<&str>)> = facts + .iter() + .map(|f| (field(f, "rule").unwrap_or_default(), field(f, "item"))) + .collect(); + let item = |name: &str| Some(format!("js:board/src/board%20view.js::{name}")); + let expected = [ + ("no-unused-vars", item("render")), + ("eqeqeq", item("View.draw")), + ("local/no-raw-dom", item("View")), + ("no-console", item("render")), + ]; + let expected: Vec<(&str, Option<&str>)> = expected + .iter() + .map(|(rule, item)| (*rule, item.as_deref())) + .collect(); + assert_eq!(cited, expected); + assert_eq!( + facts[2].id, + "sarif:ESLint/local%2Fno-raw-dom#src%2Fboard%20view.js:18" + ); + insta::assert_json_snapshot!("eslint", facts); +} + +#[test] +fn a_result_stating_no_rule_or_level_is_read_as_unknown() { + let results = read(RULE_LESS, "/project") + .expect("the report reads") + .results; + let read: Vec<(&str, Level)> = results.iter().map(|r| (r.rule.as_str(), r.level)).collect(); + assert_eq!( + read, + [ + ("unknown", Level::Error), + ("R1", Level::Unknown), + ("R1", Level::None), + ("R2", Level::Note), + ("R2", Level::Note), + ("R1", Level::Warning), + ("R1", Level::Warning), + ] + ); + assert_eq!((results[4].file.as_deref(), results[4].line), (None, None)); + let facts = finding_facts(&results, &served()); + let ids: Vec<&str> = facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids[4..], + [ + "sarif:demo-lint/R2", + "sarif:demo-lint/R1#src%2Flib.rs:24", + "sarif:demo-lint/R1#src%2Flib.rs:24~2" + ] + ); + insta::assert_json_snapshot!("rule_less", facts); +} + +#[test] +fn a_file_uri_loses_its_fragment_and_a_relative_one_reads_from_the_root() { + let log = |uri: &str| { + format!( + r#"{{"version": "2.1.0", "runs": [{{"tool": {{"driver": {{"name": "t"}}}}, "results": [{{ + "locations": [{{"physicalLocation": {{"artifactLocation": {{"uri": "{uri}"}}}}}}]}}]}}]}}"# + ) + }; + for uri in [ + "file:///project/src/lib.rs#L3", + "file://localhost/project/src/lib.rs", + "./src/lib.rs", + ] { + let results = read(&log(uri), "/project").expect(uri).results; + assert_eq!(results[0].file.as_deref(), Some("src/lib.rs"), "{uri}"); + } +} + +#[test] +fn a_bad_report_is_an_error_naming_its_value_or_path_and_reads_nothing() { + let run = |run: &str| format!(r#"{{"version": "2.1.0", "runs": [{run}]}}"#); + let at = |uri: &str| { + run(&format!( + r#"{{"tool": {{"driver": {{"name": "t"}}}}, "results": [{{"locations": [{{"physicalLocation": + {{"artifactLocation": {{"uri": "{uri}"}}}}}}]}}]}}"# + )) + }; + let deep = format!("{}{}", "[".repeat(10_000), "]".repeat(10_000)); + let rows: Vec<(String, &str)> = vec![ + ("no json at all".to_string(), "no JSON"), + (deep, "no JSON"), + (r#"{"version": "2.0.0", "runs": []}"#.to_string(), "2.0.0"), + (r#"{"runs": []}"#.to_string(), "version"), + (r#"{"version": "2.1.0"}"#.to_string(), "runs"), + (run(r#"{"results": []}"#), "runs[0].tool.driver.name"), + ( + run(r#"{"tool": {"driver": {"name": "t"}}}"#), + "runs[0].results", + ), + ( + run(r#"{"tool": {"driver": {"name": "t"}}, "results": {}}"#), + "runs[0].results", + ), + ( + run(r#"{"tool": {"driver": {"name": "t"}}, "results": [{"ruleIndex": 5}]}"#), + "rule index 5", + ), + ( + run( + r#"{"tool": {"driver": {"name": "t"}}, "results": [{"locations": [{"physicalLocation": + {"artifactLocation": {"index": 3}}}]}]}"#, + ), + "artifact index 3", + ), + (at("https://example.com/a.js"), "https://example.com/a.js"), + ]; + for (text, named) in &rows { + let error = read(text, "/project").expect_err(named); + assert!(error.contains(named), "{error} should name {named}"); + } +} + +/// A log of one run of the tool `t` whose results each lie at one of `uris`, in order. +fn at_uris(uris: &[&str]) -> String { + let results: Vec = uris + .iter() + .map(|uri| { + format!( + r#"{{"ruleId": "R", "locations": [{{"physicalLocation": {{"artifactLocation": {{"uri": "{uri}"}}}}}}]}}"# + ) + }) + .collect(); + format!( + r#"{{"version": "2.1.0", "runs": [{{"tool": {{"driver": {{"name": "t"}}}}, "results": [{}]}}]}}"#, + results.join(", ") + ) +} + +#[test] +fn a_result_outside_the_project_is_skipped_and_its_path_counted_once() { + let log = at_uris(&[ + "file:///elsewhere/a.js", + "file:///project/src/lib.rs", + "%2E%2E/%2E%2E/etc/passwd", + "file://server/share/a.js", + "file:///elsewhere/a.js", + ]); + let read = read(&log, "/project").expect("an outside file is no error"); + let files: Vec> = read.results.iter().map(|r| r.file.as_deref()).collect(); + assert_eq!(files, [Some("src/lib.rs")]); + assert_eq!( + read.outside, + ["/elsewhere/a.js", "../../etc/passwd", "//server/share/a.js"] + ); +} + +#[test] +fn a_result_naming_no_file_is_skipped_and_counted_apart_from_outside() { + let log = at_uris(&[ + ".", + "file:///project", + "src/..", + "%3Canon%3E", + "file:///project/src/lib.rs", + ".", + ]); + let read = read(&log, "/project").expect("a path naming no file is no error"); + let files: Vec> = read.results.iter().map(|r| r.file.as_deref()).collect(); + assert_eq!(files, [Some("src/lib.rs")]); + assert_eq!(read.no_file, [".", "/project", "src/..", ""]); + assert_eq!(read.outside, Vec::::new()); +} + +#[test] +fn an_error_or_an_outside_path_shows_the_reports_text_bounded_and_escaped() { + let hostile = + |scheme: &str| format!("{scheme}/elsewhere/\\u001b]0;{}\\u0007", "a".repeat(5_000)); + let error = read(&at_uris(&[&hostile("https://")]), "/project").expect_err("no file: uri"); + assert!( + !error.contains(['\u{1b}', '\u{7}']) && error.contains("\\u{1b}"), + "{error}" + ); + assert!(error.len() < 400, "{} bytes", error.len()); + let read_outside = read(&at_uris(&[&hostile("file://")]), "/project").expect("outside"); + let [outside] = &read_outside.outside[..] else { + panic!("one outside path: {:?}", read_outside.outside); + }; + assert!( + !outside.contains(['\u{1b}', '\u{7}']) && outside.contains("\\u{1b}"), + "{outside}" + ); + assert!(outside.len() < 200, "{} bytes", outside.len()); + let version = format!(r#"{{"version": "{}", "runs": []}}"#, "9".repeat(5_000)); + assert!(read(&version, "/project").expect_err("version").len() < 400); +} + +#[test] +fn an_empty_results_array_is_a_run_that_found_nothing() { + let log = + r#"{"version": "2.1.0", "runs": [{"tool": {"driver": {"name": "t"}}, "results": []}]}"#; + assert_eq!(read(log, "/project"), Ok(Sarif::default())); +} + +/// ESLint 10.15.0's recording (see `fixtures/README.md`): the package `board` at `/project`. +const ESLINT_10_15: &str = include_str!("../fixtures/eslint-10.15.0.sarif"); +/// The served facts of that recording's package. +const ESLINT_10_15_ITEMS: &str = include_str!("../fixtures/eslint-10.15.0.items.json"); + +#[test] +fn a_recorded_eslint_10_15_report_mints_static_findings_in_its_function() { + let read = read(ESLINT_10_15, "/project").expect("the recording reads"); + assert_eq!(read.outside, Vec::::new()); + let placed: Vec<(&str, Option<&str>, Option)> = read + .results + .iter() + .map(|r| (r.rule.as_str(), r.file.as_deref(), r.line)) + .collect(); + assert_eq!( + placed, + [ + ("no-unused-vars", Some("src/board view.js"), Some(2)), + ("no-undef", Some("src/board view.js"), Some(3)), + ("no-console", Some("src/board view.js"), Some(3)), + ("eqeqeq", Some("src/board view.js"), Some(4)), + ] + ); + let served: Vec = serde_json::from_str(ESLINT_10_15_ITEMS).expect("the items parse"); + let facts = finding_facts(&read.results, &served); + assert!(facts + .iter() + .all(|f| field(f, "item") == Some("js:board/src/board%20view.js::view"))); + insta::assert_json_snapshot!("eslint_10_15", facts); +} diff --git a/extensions/formal/wasm/inputs.json b/extensions/formal/wasm/inputs.json index 4266582627..8de115cc83 100644 --- a/extensions/formal/wasm/inputs.json +++ b/extensions/formal/wasm/inputs.json @@ -1,6 +1,6 @@ { "artifact": "specforge_ext_formal.wasm", - "artifact_sha256": "950fa380cce952d7adb5ac98873cb37eae84d830a062fef098a166822e679fbc", + "artifact_sha256": "396bbbf497157b477281cfa38d2996d8637eb2e94449c65cccf9e5345126275e", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", @@ -10,12 +10,12 @@ "crates/leaf/cycles/src/lib.rs": "18b6d9b085c507c2f0e52c1011d2d92526ac2e0e3f459d282d086ed5f497a920", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -25,29 +25,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -59,14 +59,14 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", diff --git a/extensions/formal/wasm/specforge_ext_formal.wasm b/extensions/formal/wasm/specforge_ext_formal.wasm index 3d806856fc..7090b88095 100755 Binary files a/extensions/formal/wasm/specforge_ext_formal.wasm and b/extensions/formal/wasm/specforge_ext_formal.wasm differ diff --git a/extensions/governance/wasm/inputs.json b/extensions/governance/wasm/inputs.json index 1e1bb7e397..afa8646414 100644 --- a/extensions/governance/wasm/inputs.json +++ b/extensions/governance/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "specforge_ext_governance.wasm", - "artifact_sha256": "ba345adf2ecb68271be942c289b198532a0c58fc5f031f207c05d79b68178b6b", + "artifact_sha256": "d44ee07304979b8b682089fe3d652bc14a97687fca73301b82fb052ac684b51b", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,14 +55,14 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", diff --git a/extensions/governance/wasm/specforge_ext_governance.wasm b/extensions/governance/wasm/specforge_ext_governance.wasm index 67720bd861..ad51c1d43a 100755 Binary files a/extensions/governance/wasm/specforge_ext_governance.wasm and b/extensions/governance/wasm/specforge_ext_governance.wasm differ diff --git a/extensions/javascript/api/Cargo.lock b/extensions/javascript/api/Cargo.lock new file mode 100644 index 0000000000..e58a70eaa4 --- /dev/null +++ b/extensions/javascript/api/Cargo.lock @@ -0,0 +1,575 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-api" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-javascript-api" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-api", + "specforge-code-facts", + "specforge-extension-sdk", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/javascript/api/Cargo.toml b/extensions/javascript/api/Cargo.toml new file mode 100644 index 0000000000..e8c2ce69eb --- /dev/null +++ b/extensions/javascript/api/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "specforge-ext-javascript-api" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-api = { path = "../../code/api" } +specforge-code-facts = { path = "../../code/facts" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" diff --git a/extensions/javascript/api/fixtures/README.md b/extensions/javascript/api/fixtures/README.md new file mode 100644 index 0000000000..607cd554a7 --- /dev/null +++ b/extensions/javascript/api/fixtures/README.md @@ -0,0 +1,8 @@ +# @javascript/api fixtures + +| Fixture | Source | +|---------|--------| +| `items.json` | hand-written served `item` facts (ids only) of `@demo/widget`'s `src/index.ts`: every member of the recorded model an item can be, except `Id`, which only another package (`@demo/other`) holds, so its `api_item` cites nothing | + +The tests read the API reader's recorded doc model, `../../code/api/fixtures/api-extractor-7.60.1.widget.api.json` +(api-extractor 7.60.1, `@demo/widget`; see that directory's README). diff --git a/extensions/javascript/api/fixtures/items.json b/extensions/javascript/api/fixtures/items.json new file mode 100644 index 0000000000..dbb2911097 --- /dev/null +++ b/extensions/javascript/api/fixtures/items.json @@ -0,0 +1,11 @@ +[ + {"kind": "item", "id": "js:@demo/widget/src/index.ts::Widget"}, + {"kind": "item", "id": "js:@demo/widget/src/index.ts::Widget.render"}, + {"kind": "item", "id": "js:@demo/widget/src/index.ts::Widget.size"}, + {"kind": "item", "id": "js:@demo/widget/src/index.ts::Options"}, + {"kind": "item", "id": "js:@demo/widget/src/index.ts::Options.mode"}, + {"kind": "item", "id": "js:@demo/widget/src/index.ts::Mode"}, + {"kind": "item", "id": "js:@demo/widget/src/index.ts::create"}, + {"kind": "item", "id": "js:@demo/widget/src/index.ts::VERSION"}, + {"kind": "item", "id": "js:@demo/other/src/index.ts::Id"} +] diff --git a/extensions/javascript/api/src/lib.rs b/extensions/javascript/api/src/lib.rs new file mode 100644 index 0000000000..88441f9b9f --- /dev/null +++ b/extensions/javascript/api/src/lib.rs @@ -0,0 +1,202 @@ +//! @javascript/api — runs api-extractor and records the package's public API as `@code/core`'s `api_item` facts +//! (ADR 0389). +//! +//! The collector `javascript-api` is selected by a `tsconfig.json` at the project root. The host writes the pack's +//! config file at `.specforge/reports/javascript-api.api-extractor.json` and runs, with consent, `npx --no -- +//! api-extractor run --local --config {config}`. `npx --no` never downloads anything: api-extractor and TypeScript must +//! be dev dependencies of the project. api-extractor resolves `projectFolder` against the config's own folder, so +//! `../..` is the project root. +//! +//! api-extractor reads built declarations, never `.ts` sources, and its config names the entry as a literal path: the +//! pack's entry is `/dist/index.d.ts`, so the project builds its declarations there first (the pack +//! runs no build). Only the doc model is written, to `{report}`: `apiReport`, `dtsRollup` and `tsdocMetadata` stay +//! off, so no `.api.md`, rollup or metadata file is written into the project (ADR 0389 D8), and every message reports +//! at `logLevel` `none`, so only a config or compile failure fails the run. `--local` keeps an API report diff from +//! failing it. +//! +//! The doc model is read by `specforge-code-api` and minted by `specforge-code-facts` against `@javascript/source`'s +//! items: one `api_item` per member, `api:js:::[.…]`, citing the one served item of the package +//! with that name path. +//! +//! The accepted API (ADR 0390 D3) is the API report the project commits for review, read beside the run (files up to +//! 4 MiB): api-extractor's `etc/.api.md` (the read `accepted`, glob `**/etc/*.api.md`) or rush's +//! `common/reviews/api/.api.md` (the read `reviews`). Never `**/*.api.md`: api-extractor's `temp/` holds the +//! fresh run's own copy, which would hide every break; the `.alpha`, `.beta` and `.public` report variants are not read +//! either. The report's title names its package: only a report of the package the run read is judged, and each +//! `api_item` then carries `change` (`added`, `unchanged`, `changed`, `narrowed`, `removed`) against it; without one the +//! facts carry none. A report of the package that does not parse (a merge-conflict marker, a broken fence) is the +//! collector's error naming it, as are two reports of the package (the accepted side is one file); a file the host did +//! not serve (over 4 MiB, not UTF-8), with no report title (prose in an `etc/` folder) or of another package, broken or +//! not, is one warning naming it, which the host shows as W203, and the collect goes on. +//! +//! Accepting a break is committing the updated report: enable `apiReport` in your own `api-extractor.json` (the same +//! entry, `dist/index.d.ts`), run `api-extractor run --local` (it copies `temp/.api.md` to `etc/`), commit +//! `etc/.api.md`, then `specforge collect`. Your config and the pack's are two configs: they must agree on the +//! entry, `includeForgottenExports` and `bundledPackages`, or the report differs from the run in content, which the +//! comparison does not forgive (it forgives only the report's spelling). The pack's own run never writes a report. + +use std::collections::BTreeSet; + +use specforge_code_api::{js_report_package, read_js_model, read_js_report}; +use specforge_code_facts::{api_facts, api_facts_against, ApiEntry}; +use specforge_extension_sdk::prelude::*; + +const COLLECTOR: &str = "javascript-api"; +/// The reads of the committed accepted reports, and their globs: api-extractor's report folder, then rush's. +const ACCEPTED: [(&str, &str); 2] = [ + ("accepted", "**/etc/*.api.md"), + ("reviews", "common/reviews/api/*.api.md"), +]; +/// The report variants (`reportVariants`), never the accepted side. +const VARIANTS: [&str; 3] = [".alpha.api.md", ".beta.api.md", ".public.api.md"]; +/// The doc model api-extractor writes, relative to the project root. +const REPORT: &str = ".specforge/reports/javascript-api.api.json"; +/// The config file the host writes before the run, `{report}` the report's absolute path (ADR 0348 D2). +const CONFIG: &str = "api-extractor.json"; +const TEMPLATE: &str = r#"{ + "projectFolder": "../..", + "mainEntryPointFilePath": "/dist/index.d.ts", + "apiReport": { "enabled": false }, + "docModel": { "enabled": true, "apiJsonFilePath": "{report}" }, + "dtsRollup": { "enabled": false }, + "tsdocMetadata": { "enabled": false }, + "messages": { + "compilerMessageReporting": { "default": { "logLevel": "none" } }, + "extractorMessageReporting": { "default": { "logLevel": "none" } }, + "tsdocMessageReporting": { "default": { "logLevel": "none" } } + } +} +"#; + +#[specforge_extension_sdk::extension( + name = "@javascript/api", + version = "1.0.0", + description = "Runs api-extractor and records the package's public API as api_item facts (@code/core)" +)] +struct JavascriptApi; + +impl Contributions for JavascriptApi { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.4"); + // Its items are what an api_item cites; without them an entry cites nothing. + c.peer("@javascript/source", "^1.0"); + c.collector(COLLECTOR, |k| { + k.input_format("api-extractor-json") + .detect_files(&["tsconfig.json"]) + .run(&[ + "npx", + "--no", + "--", + "api-extractor", + "run", + "--local", + "--config", + "{config}", + ]) + .config(CONFIG, TEMPLATE) + .env(&["NODE_*", "CI"]) + .install("npm install --save-dev @microsoft/api-extractor typescript") + .report(REPORT) + .input(Input::facts(&["item"])); + for (name, glob) in ACCEPTED { + k.input(Input::files( + name, + FileReadSpec::glob(glob).text_up_to(TEXT_MAX_CEILING_BYTES), + )); + } + k.answers(&["api_item"]).collect(collect); + }); + } +} + +/// Map api-extractor's doc model to `api_item` facts. +fn collect(input: &CollectInput) -> Result { + let [report] = &input.reports[..] else { + return Err(format!( + "{COLLECTOR} reads one report, {REPORT}; it was given {}", + input.reports.len() + )); + }; + let entries = + read_js_model(&report.content).map_err(|why| format!("{}: {why}", report.path))?; + let mut warnings = Vec::new(); + let facts = match accepted(input, &entries, &mut warnings)? { + Some(accepted) => api_facts_against(&entries, &accepted, &input.facts), + None => api_facts(&entries, &input.facts), + }; + Ok(CollectOutput { + facts, + warnings, + ..CollectOutput::default() + }) +} + +/// The entries of the one served accepted report of the run's package (the doc model's); a warning for each file not +/// served, not a report or of another package, and for a read that matched more files than were served. A report of +/// the package that does not parse, and two reports of it, are the collector's error. +fn accepted( + input: &CollectInput, + entries: &[ApiEntry], + warnings: &mut Vec, +) -> Result>, String> { + let packages: BTreeSet<&str> = entries.iter().map(|e| e.container.as_str()).collect(); + let mut found: Option<(&str, Vec)> = None; + for (name, glob) in ACCEPTED { + let Some(read) = input.files.get(name) else { + continue; + }; + if read.truncated { + warnings.push(format!( + "the read '{name}' ({glob}) stopped early: the host's walk reached its cap of {GLOB_VISITS_MAX} \ + entries, or more than {FILE_READ_MAX} files matched; no break was judged against a file not read" + )); + } + for file in &read.facts { + if VARIANTS.iter().any(|variant| file.path.ends_with(variant)) { + continue; + } + let Some(text) = file.text.as_deref().filter(|_| file.error.is_none()) else { + let error = file.error.as_deref().unwrap_or("no text"); + warnings.push(format!( + "{}: the accepted API was not read ({error}); no break was judged for it", + file.path + )); + continue; + }; + let mut report = match read_js_report(text) { + Ok(report) => report, + Err(why) if js_report_package(text).is_some_and(|name| packages.contains(name)) => { + return Err(format!("{}: {why}", file.path)); + } + Err(why) => { + warnings.push(format!( + "{}: not an API report of a package this run read ({why}); no break was judged \ + for it", + file.path + )); + continue; + } + }; + report.retain(|e| packages.contains(e.container.as_str())); + if report.is_empty() { + warnings.push(format!( + "{}: names no package this run read; no break was judged for it", + file.path + )); + } else if let Some((first, _)) = &found { + return Err(format!( + "{first} and {}: two accepted API reports of the package; keep the one api-extractor writes", + file.path + )); + } else { + found = Some((&file.path, report)); + } + } + } + Ok(found.map(|(_, report)| report)) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/javascript/api/src/tests.rs b/extensions/javascript/api/src/tests.rs new file mode 100644 index 0000000000..1dfa0778c8 --- /dev/null +++ b/extensions/javascript/api/src/tests.rs @@ -0,0 +1,330 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_test::prelude::*; + +/// The API reader's api-extractor 7.60.1 recording: package `@demo/widget`. +const RECORDED: &str = + include_str!("../../../code/api/fixtures/api-extractor-7.60.1.widget.api.json"); +/// The served items of `@demo/widget`, as JSON (see `fixtures/README.md`). +const ITEMS: &str = include_str!("../fixtures/items.json"); +/// The doc model of a run that breaks the API `TAGGED` accepted (the API reader's recordings). +const CHANGED: &str = + include_str!("../../../code/api/fixtures/api-extractor-7.60.1.widget-changed.api.json"); +/// The committed API report of `@demo/widget` before the break. +const TAGGED: &str = + include_str!("../../../code/api/fixtures/api-extractor-7.60.1.widget-tagged.api.md"); + +/// The input of a run writing `model`, the host serving `files` (each read by its name). +fn against(model: &str, files: Value) -> CollectInput { + CollectInput { + files: serde_json::from_value(files).expect("the reads parse"), + ..input(&[model]) + } +} + +/// One read serving `text` at `path`. +fn served(path: &str, text: &str) -> Value { + json!({"facts": [{"path": path, "exists": true, "text": text}]}) +} + +/// Each fact's name path (its id after `::`) and its `change`. +fn changes(out: &CollectOutput) -> Vec<(&str, Option<&str>)> { + out.facts + .iter() + .map(|f| { + let name = f.id.split_once("::").map_or("", |(_, name)| name); + (name, f.fields.get("change").and_then(Value::as_str)) + }) + .collect() +} + +/// The input the host sends for these reports, the package's items served. +fn input(reports: &[&str]) -> CollectInput { + CollectInput { + reports: reports + .iter() + .map(|content| CollectReportFile { + path: REPORT.to_string(), + content: content.to_string(), + }) + .collect(), + facts: serde_json::from_str(ITEMS).expect("the served facts parse"), + ..CollectInput::default() + } +} + +#[specforge_test(requirement = "FEATURE-149")] +fn javascript_api_declares_api_extractor_its_config_and_its_peers() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.4", false), + ("@javascript/source", "^1.0", false) + ] + ); + let [collector] = &declaration.collectors[..] else { + panic!("one collector: {:?}", declaration.collectors); + }; + assert_eq!(collector.name, COLLECTOR); + assert_eq!(collector.input_formats, ["api-extractor-json"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["tsconfig.json".to_string()][..]) + ); + assert_eq!(collector.answers, ["api_item"]); + // Never `**/*.api.md`: api-extractor's `temp/` holds the fresh run's own report. + assert_eq!( + collector.inputs, + [ + Input::facts(&["item"]), + Input::files( + "accepted", + FileReadSpec::glob("**/etc/*.api.md").text_up_to(TEXT_MAX_CEILING_BYTES) + ), + Input::files( + "reviews", + FileReadSpec::glob("common/reviews/api/*.api.md") + .text_up_to(TEXT_MAX_CEILING_BYTES) + ) + ] + ); + assert_eq!(collector.report.as_deref(), Some(REPORT)); + assert_eq!( + collector.install.as_deref(), + Some("npm install --save-dev @microsoft/api-extractor typescript") + ); + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + assert_eq!(capabilities[0]["name"], COLLECTOR); + assert_eq!(capabilities[0]["port"], "process"); + assert_eq!( + capabilities[0]["argv"], + json!([ + "npx", + "--no", + "--", + "api-extractor", + "run", + "--local", + "--config", + "{config}" + ]), + "{capabilities}" + ); + assert_eq!( + capabilities[0]["config"], + json!({"name": "api-extractor.json", "template": TEMPLATE}) + ); + assert_eq!(capabilities[0]["env"], json!(["NODE_*", "CI"])); + assert!(capabilities[0].get("filter").is_none_or(Value::is_null)); +} + +#[specforge_test(requirement = "FEATURE-149")] +fn the_config_writes_only_the_doc_model_to_the_report_path_from_dist() { + assert!(TEMPLATE.len() < 16 * 1024); + // The host escapes the absolute report path for a quoted string (ADR 0348 D2): `\` and `"` take a backslash. + let report = r#"C:\work\my "board"\.specforge\reports\javascript-api.api.json"#; + let escaped = report.replace('\\', "\\\\").replace('"', "\\\""); + let config: Value = serde_json::from_str(&TEMPLATE.replace("{report}", &escaped)) + .expect("the config parses as JSON"); + assert_eq!(config["projectFolder"], "../.."); + assert_eq!( + config["mainEntryPointFilePath"], + "/dist/index.d.ts" + ); + assert_eq!( + config["docModel"], + json!({"enabled": true, "apiJsonFilePath": report}) + ); + for off in ["apiReport", "dtsRollup", "tsdocMetadata"] { + assert_eq!(config[off], json!({"enabled": false}), "{off}"); + } + let messages = config["messages"] + .as_object() + .expect("the message settings"); + let reporting: Vec<&str> = messages.keys().map(String::as_str).collect(); + assert_eq!( + reporting, + [ + "compilerMessageReporting", + "extractorMessageReporting", + "tsdocMessageReporting" + ] + ); + assert!( + messages + .values() + .all(|m| m == &json!({"default": {"logLevel": "none"}})), + "{messages:?}" + ); +} + +#[specforge_test(requirement = "FEATURE-149")] +fn a_recorded_api_extractor_model_mints_api_items_citing_the_served_items() { + let out = collect(&input(&[RECORDED])).unwrap(); + let cited: Vec<(&str, Option<&str>)> = out + .facts + .iter() + .map(|f| (f.id.as_str(), f.fields.get("item").and_then(Value::as_str))) + .collect(); + let at = |name: &str| format!("js:@demo/widget/src/index.ts::{name}"); + let expected = [ + ("Id", None), + ("Mode", Some(at("Mode"))), + ("Mode.Fast", None), + ("Mode.Slow", None), + ("Options", Some(at("Options"))), + ("Options.mode", Some(at("Options.mode"))), + ("VERSION", Some(at("VERSION"))), + ("Widget", Some(at("Widget"))), + ("Widget.render", Some(at("Widget.render"))), + ("Widget.size", Some(at("Widget.size"))), + ("create", Some(at("create"))), + ]; + let expected: Vec<(String, Option)> = expected + .into_iter() + .map(|(name, item)| (format!("api:js:%40demo%2Fwidget::{name}"), item)) + .collect(); + let expected: Vec<(&str, Option<&str>)> = expected + .iter() + .map(|(id, item)| (id.as_str(), item.as_deref())) + .collect(); + assert_eq!(cited, expected); + assert!(out.facts.iter().all(|f| f.kind == "api_item")); + assert_eq!(out.warnings, Vec::::new()); +} + +#[specforge_test(requirement = "FEATURE-149")] +fn zero_or_two_reports_or_a_bad_one_is_the_collectors_error() { + for reports in [&[][..], &[RECORDED, RECORDED][..]] { + let why = collect(&input(reports)).unwrap_err(); + assert!(why.contains(COLLECTOR) && why.contains(REPORT), "{why}"); + } + let why = collect(&input(&["garbage"])).unwrap_err(); + assert!(why.starts_with(&format!("{REPORT}: no JSON")), "{why}"); +} + +#[specforge_test(requirement = "FEATURE-149")] +fn a_committed_report_in_etc_or_in_rushs_reviews_marks_each_items_change() { + let mut seen = Vec::new(); + for files in [ + json!({"accepted": served("etc/widget.api.md", TAGGED)}), + json!({"reviews": served("common/reviews/api/widget.api.md", TAGGED)}), + ] { + let out = collect(&against(CHANGED, files)).unwrap(); + assert_eq!(out.warnings, Vec::::new()); + let changes = changes(&out); + for (name, change) in [ + ("create", "changed"), + ("Widget.render", "narrowed"), + ("Widget.size", "narrowed"), + ("trial", "removed"), + ("added", "added"), + ] { + assert!( + changes.contains(&(name, Some(change))), + "{name} {change}: {changes:?}" + ); + } + seen.push(serde_json::to_value(&out.facts).unwrap()); + } + assert_eq!(seen[0], seen[1]); +} + +#[specforge_test(requirement = "FEATURE-149")] +fn a_report_variant_is_not_read() { + let today = collect(&input(&[CHANGED])).unwrap(); + let files = json!({"accepted": served("etc/widget.beta.api.md", TAGGED)}); + let out = collect(&against(CHANGED, files)).unwrap(); + assert_eq!(out.facts, today.facts); + assert_eq!(out.warnings, Vec::::new()); +} + +#[specforge_test(requirement = "FEATURE-149")] +fn two_reports_of_the_package_or_a_bad_one_is_the_collectors_error_naming_them() { + let files = json!({ + "accepted": served("etc/widget.api.md", TAGGED), + "reviews": served("common/reviews/api/widget.api.md", TAGGED), + }); + let why = collect(&against(CHANGED, files)).unwrap_err(); + assert!( + why.contains("etc/widget.api.md") && why.contains("common/reviews/api/widget.api.md"), + "{why}" + ); + let conflicted = format!("<<<<<<< HEAD\n{TAGGED}"); + let files = json!({"accepted": served("etc/widget.api.md", &conflicted)}); + let why = collect(&against(CHANGED, files)).unwrap_err(); + assert!(why.starts_with("etc/widget.api.md: "), "{why}"); +} + +#[specforge_test(requirement = "FEATURE-149")] +fn prose_or_a_broken_report_of_another_package_is_one_warning_and_the_collect_goes_on() { + let today = collect(&input(&[CHANGED])).unwrap(); + let other = TAGGED.replace("\"@demo/widget\"", "\"@demo/other\""); + for (path, text) in [ + ( + "etc/notes.api.md", + "# Notes\n\nThe users API, in prose.\n".to_string(), + ), + ("other/etc/other.api.md", format!("{other}\n<<<<<<< HEAD\n")), + ] { + let out = collect(&against(CHANGED, json!({"accepted": served(path, &text)}))).unwrap(); + assert_eq!(out.facts, today.facts); + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + assert!( + out.warnings[0].starts_with(&format!( + "{path}: not an API report of a package this run read (" + )), + "{:?}", + out.warnings + ); + } +} + +#[specforge_test(requirement = "FEATURE-149")] +fn a_report_not_served_or_of_another_package_is_one_warning_and_no_change() { + let today = collect(&input(&[CHANGED])).unwrap(); + let other = TAGGED.replace("\"@demo/widget\"", "\"@demo/other\""); + let unserved = + json!({"facts": [{"path": "etc/widget.api.md", "exists": true, "error": "too_large"}]}); + for (read, path, says) in [ + ( + served("etc/other.api.md", &other), + "etc/other.api.md", + "names no package this run read", + ), + ( + unserved, + "etc/widget.api.md", + "the accepted API was not read (too_large)", + ), + ] { + let out = collect(&against(CHANGED, json!({ "accepted": read }))).unwrap(); + assert_eq!(out.facts, today.facts); + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + assert!( + out.warnings[0].starts_with(&format!("{path}: ")) && out.warnings[0].contains(says), + "{:?}", + out.warnings + ); + } +} + +#[specforge_test(requirement = "FEATURE-149")] +fn a_truncated_read_names_the_walks_entry_cap_and_the_file_cap() { + let mut read = served("etc/widget.api.md", TAGGED); + read["truncated"] = json!(true); + let out = collect(&against(CHANGED, json!({ "accepted": read }))).unwrap(); + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + assert_eq!( + out.warnings[0], + "the read 'accepted' (**/etc/*.api.md) stopped early: the host's walk reached its cap of 20000 entries, \ + or more than 2000 files matched; no break was judged against a file not read" + ); +} diff --git a/extensions/javascript/api/wasm/inputs.json b/extensions/javascript/api/wasm/inputs.json new file mode 100644 index 0000000000..ded465bf0b --- /dev/null +++ b/extensions/javascript/api/wasm/inputs.json @@ -0,0 +1,96 @@ +{ + "artifact": "specforge_ext_javascript_api.wasm", + "artifact_sha256": "e59776a07e0ef9602eae70eda8b56c6f6ae921566c19b98d2d7df84bca54d952", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/api/Cargo.toml": "0ec7e09fd08c471d405b140f2f4ba08a827759ef2d43ed4285b1b2a0b3240f07", + "extensions/code/api/src/js_model.rs": "287c3fd4d4feb64a934f2a3d724dee672b0ed778fcf9ff6b9396dab545210221", + "extensions/code/api/src/js_report.rs": "028ffa203f1e122d9e429afc4a467a2ac5b34bf82f5cebe2f4b391c0a30e7370", + "extensions/code/api/src/lib.rs": "24cfeed2f5f84c8a68e9e3900f4580ea754e23e3293a0cb0374edb249f77e0bb", + "extensions/code/api/src/rust_text.rs": "158bfe14aca8f178b5e623ba6acd58eb75f483328c9be5186498ec7d5cd55ebd", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/javascript/api/Cargo.lock": "58cf10a0dab88a87d1b84497882872d64e4a3893ee8e3c8db522d603dda2d65b", + "extensions/javascript/api/Cargo.toml": "634ebbc40c37fac8eba9dfaf261a8d85cf0a3dd0c30222ff1c9c92882faeac1a", + "extensions/javascript/api/src/lib.rs": "6d256f3b317d215af10be2abb77c9d7809bf5eff9c5b5c278de5a56c45c04266" + } +} diff --git a/extensions/javascript/api/wasm/specforge_ext_javascript_api.wasm b/extensions/javascript/api/wasm/specforge_ext_javascript_api.wasm new file mode 100644 index 0000000000..c37e119441 Binary files /dev/null and b/extensions/javascript/api/wasm/specforge_ext_javascript_api.wasm differ diff --git a/extensions/javascript/coverage/Cargo.lock b/extensions/javascript/coverage/Cargo.lock new file mode 100644 index 0000000000..2a106550bc --- /dev/null +++ b/extensions/javascript/coverage/Cargo.lock @@ -0,0 +1,574 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-lcov" +version = "1.0.0" +dependencies = [ + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-javascript-coverage" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-code-lcov", + "specforge-extension-sdk", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/javascript/coverage/Cargo.toml b/extensions/javascript/coverage/Cargo.toml new file mode 100644 index 0000000000..ee64556724 --- /dev/null +++ b/extensions/javascript/coverage/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "specforge-ext-javascript-coverage" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-lcov = { path = "../../code/lcov" } +specforge-code-facts = { path = "../../code/facts" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" diff --git a/extensions/javascript/coverage/src/lib.rs b/extensions/javascript/coverage/src/lib.rs new file mode 100644 index 0000000000..36d8e28a44 --- /dev/null +++ b/extensions/javascript/coverage/src/lib.rs @@ -0,0 +1,86 @@ +//! @javascript/coverage — runs the project's own `npm test` under c8 and records its LCOV coverage as `@code/core`'s +//! `coverage` facts (ADR 0389). +//! +//! The collector `javascript-coverage` is selected by a `package.json` at the project root. The host runs, with +//! consent, `npx --no -- c8 --reporter=lcovonly --reports-dir=.specforge/reports/javascript-coverage npm test`. c8 +//! wraps the project's own `test` script, so the project's test command decides what runs, whichever runner it uses; +//! the project's own tests run (ADR 0389 D9). `npx --no` never downloads c8: it must be a dev dependency of the +//! project. c8 writes into a directory, always `lcov.info`, so the argv names the directory and the report is the file +//! in it; c8 also leaves its raw V8 data under `tmp/` there, cleared on its next run. c8 exits with the test command's +//! code and still writes the report, so a failing test still records coverage. +//! +//! The LCOV is read by `specforge-code-lcov` and minted by `specforge-code-facts` against `@javascript/source`'s +//! items: a `coverage` fact per item a line reaches, one per file for what no item holds. A file outside the project +//! is skipped and counted, and the pack returns one warning naming the report and the paths, which the host shows as +//! W203 (ADR 0389 D7). + +use specforge_code_facts::{coverage_facts, outside_line}; +use specforge_extension_sdk::prelude::*; + +const COLLECTOR: &str = "javascript-coverage"; +/// The LCOV c8 writes in the directory its argv names, relative to the project root. +const REPORT: &str = ".specforge/reports/javascript-coverage/lcov.info"; + +#[specforge_extension_sdk::extension( + name = "@javascript/coverage", + version = "1.0.0", + description = "Runs c8 around npm test and records its LCOV coverage as coverage facts (@code/core)" +)] +struct JavascriptCoverage; + +impl Contributions for JavascriptCoverage { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.2"); + // Its items place each line; without them every line is its file's. + c.peer("@javascript/source", "^1.0"); + c.collector(COLLECTOR, |k| { + k.input_format("lcov") + .detect_files(&["package.json"]) + // No filter: `npm test -- ` is the runner's, and a filtered run is partial coverage. + .run(&[ + "npx", + "--no", + "--", + "c8", + "--reporter=lcovonly", + "--reports-dir=.specforge/reports/javascript-coverage", + "npm", + "test", + ]) + .env(&["NODE_*", "NPM_CONFIG_*", "npm_config_*", "CI"]) + .install("npm install --save-dev c8") + .report(REPORT) + .input(Input::facts(&["item"])) + .answers(&["coverage"]) + .collect(collect); + }); + } +} + +/// Map c8's LCOV to `coverage` facts, and the files it skipped as outside the project to one warning. +fn collect(input: &CollectInput) -> Result { + let [report] = &input.reports[..] else { + return Err(format!( + "{COLLECTOR} reads one report, {REPORT}; it was given {}", + input.reports.len() + )); + }; + let cwd = input + .cwd + .as_deref() + .ok_or("the host sent no cwd: an LCOV file path is read against the project root")?; + let read = specforge_code_lcov::read(&report.content, cwd) + .map_err(|why| format!("{}: {why}", report.path))?; + Ok(CollectOutput { + facts: coverage_facts(&read.files, &input.facts), + warnings: outside_line(&report.path, &read.outside) + .into_iter() + .collect(), + ..CollectOutput::default() + }) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/javascript/coverage/src/tests.rs b/extensions/javascript/coverage/src/tests.rs new file mode 100644 index 0000000000..757841201e --- /dev/null +++ b/extensions/javascript/coverage/src/tests.rs @@ -0,0 +1,134 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_test::prelude::*; + +/// The LCOV reader's c8 12.0.0 recording: `src/board.js` of the package `board`, relative `SF`. +const C8_12: &str = include_str!("../../../code/lcov/fixtures/c8-12.0.0.info"); +/// The LCOV reader's served facts for that recording, as JSON. +const ITEMS: &str = include_str!("../../../code/lcov/fixtures/c8-12.0.0.items.json"); +/// The LCOV reader's accepted snapshot of the facts `C8_12` mints with `ITEMS` served. +const C8_12_FACTS: &str = + include_str!("../../../code/lcov/src/snapshots/specforge_code_lcov__tests__c8_12.snap"); + +/// The input the host sends for these reports at `/project`, the reader's items served. +fn input(reports: &[&str]) -> CollectInput { + CollectInput { + reports: reports + .iter() + .map(|content| CollectReportFile { + path: REPORT.to_string(), + content: content.to_string(), + }) + .collect(), + cwd: Some("/project".to_string()), + facts: serde_json::from_str(ITEMS).expect("the served facts parse"), + ..CollectInput::default() + } +} + +/// The JSON body of an insta snapshot, after its `---` header. +fn snapshot(text: &str) -> Value { + let body = text.splitn(3, "---\n").nth(2).expect("a snapshot body"); + serde_json::from_str(body).expect("the snapshot parses") +} + +#[specforge_test(requirement = "FEATURE-144")] +fn javascript_coverage_declares_c8_around_npm_test_and_its_peers() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.2", false), + ("@javascript/source", "^1.0", false) + ] + ); + let [collector] = &declaration.collectors[..] else { + panic!("one collector: {:?}", declaration.collectors); + }; + assert_eq!(collector.name, COLLECTOR); + assert_eq!(collector.input_formats, ["lcov"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["package.json".to_string()][..]) + ); + assert_eq!(collector.answers, ["coverage"]); + assert_eq!(collector.inputs, [Input::facts(&["item"])]); + assert_eq!(collector.report.as_deref(), Some(REPORT)); + assert_eq!( + collector.install.as_deref(), + Some("npm install --save-dev c8") + ); + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + assert_eq!(capabilities[0]["name"], COLLECTOR); + assert_eq!(capabilities[0]["port"], "process"); + assert_eq!( + capabilities[0]["argv"], + json!([ + "npx", + "--no", + "--", + "c8", + "--reporter=lcovonly", + "--reports-dir=.specforge/reports/javascript-coverage", + "npm", + "test" + ]), + "{capabilities}" + ); + assert_eq!( + capabilities[0]["env"], + json!(["NODE_*", "NPM_CONFIG_*", "npm_config_*", "CI"]) + ); + assert!(capabilities[0].get("filter").is_none_or(Value::is_null)); + // c8 writes `lcov.info` in the directory the argv names. + assert!(REPORT.ends_with("/lcov.info")); + assert!(capabilities[0]["argv"] + .as_array() + .unwrap() + .contains(&json!(format!( + "--reports-dir={}", + REPORT.trim_end_matches("/lcov.info") + )))); +} + +#[specforge_test(requirement = "FEATURE-144")] +fn a_c8_report_mints_the_readers_coverage_facts_and_no_warning() { + let out = collect(&input(&[C8_12])).unwrap(); + assert_eq!( + serde_json::to_value(&out.facts).unwrap(), + snapshot(C8_12_FACTS) + ); + assert_eq!(out.warnings, Vec::::new()); +} + +#[specforge_test(requirement = "FEATURE-144")] +fn a_file_outside_the_project_is_skipped_with_one_warning() { + let report = format!("{C8_12}SF:../shared/util.js\nDA:1,1\nend_of_record\n"); + let out = collect(&input(&[&report])).unwrap(); + assert_eq!( + serde_json::to_value(&out.facts).unwrap(), + snapshot(C8_12_FACTS) + ); + assert_eq!( + out.warnings, + [format!( + "{REPORT}: skipped 1 file(s) outside the project: ../shared/util.js" + )] + ); +} + +#[specforge_test(requirement = "FEATURE-144")] +fn zero_or_two_reports_or_a_bad_one_is_the_collectors_error() { + for reports in [&[][..], &[C8_12, C8_12][..]] { + let why = collect(&input(reports)).unwrap_err(); + assert!(why.contains(COLLECTOR) && why.contains(REPORT), "{why}"); + } + let why = collect(&input(&["garbage"])).unwrap_err(); + assert!(why.starts_with(&format!("{REPORT}: line 1:")), "{why}"); +} diff --git a/extensions/javascript/coverage/wasm/inputs.json b/extensions/javascript/coverage/wasm/inputs.json new file mode 100644 index 0000000000..4aac1a86c5 --- /dev/null +++ b/extensions/javascript/coverage/wasm/inputs.json @@ -0,0 +1,93 @@ +{ + "artifact": "specforge_ext_javascript_coverage.wasm", + "artifact_sha256": "e216cd8a440702cbf4fda8449bd7d5b9b10b1ba5536602f5613082f8649d88d2", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/code/lcov/Cargo.toml": "4beea7242b208263bcd13a5144693e9d16def91f0f05cd836be84a251f1a17c0", + "extensions/code/lcov/src/lib.rs": "48f980fd4ec553a09ae2cec049a524046de13a66d81a534e07271baae1130c87", + "extensions/javascript/coverage/Cargo.lock": "5707d40d7f15d4519c56921dedcbfd5141130354a1f3a12063f8266e959dab7b", + "extensions/javascript/coverage/Cargo.toml": "7b931aa2a7223c537cea3875e19d4f6a8e830848ead280458d21897e48b57b13", + "extensions/javascript/coverage/src/lib.rs": "b77790874d9e15f4d2875b64c9e8da035caa25618ccbc2dcb23119cf23e9d567" + } +} diff --git a/extensions/javascript/coverage/wasm/specforge_ext_javascript_coverage.wasm b/extensions/javascript/coverage/wasm/specforge_ext_javascript_coverage.wasm new file mode 100644 index 0000000000..2b08f26dd5 Binary files /dev/null and b/extensions/javascript/coverage/wasm/specforge_ext_javascript_coverage.wasm differ diff --git a/extensions/javascript/deps/Cargo.lock b/extensions/javascript/deps/Cargo.lock new file mode 100644 index 0000000000..6d42806266 --- /dev/null +++ b/extensions/javascript/deps/Cargo.lock @@ -0,0 +1,586 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-cyclonedx" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-osv" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-javascript-deps" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-cyclonedx", + "specforge-code-facts", + "specforge-code-osv", + "specforge-extension-sdk", + "specforge-protocol-types", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/javascript/deps/Cargo.toml b/extensions/javascript/deps/Cargo.toml new file mode 100644 index 0000000000..ec0ecbe7c1 --- /dev/null +++ b/extensions/javascript/deps/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "specforge-ext-javascript-deps" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-cyclonedx = { path = "../../code/cyclonedx" } +specforge-code-osv = { path = "../../code/osv" } +specforge-code-facts = { path = "../../code/facts" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" +# is_install_line: the host's rule for a collector's install line. +specforge-protocol-types = { path = "../../../crates/leaf/protocol-types" } diff --git a/extensions/javascript/deps/fixtures/README.md b/extensions/javascript/deps/fixtures/README.md new file mode 100644 index 0000000000..b2b18381ed --- /dev/null +++ b/extensions/javascript/deps/fixtures/README.md @@ -0,0 +1,8 @@ +# @javascript/deps fixtures + +| Fixture | Source | +|---------|--------| +| `cyclonedx-npm-7.0.1.cdx.json` | recorded by the Phase 11 research with cyclonedx-npm 7.0.1 (npm 11.20.0): `cyclonedx-npm --output-format JSON --spec-version 1.6 --package-lock-only` over a project whose root package is `board` 1.0.0 (`pkg:npm/board@1.0.0`); committed as recorded. It names no absolute path | +| `packages.json` | hand-written served facts: the `package` facts the collectors receive, `pkg:npm/board` at the project root and `pkg:npm/web` at `web` (the npm package the OSV reader's recorded `web/package-lock.json` belongs to) | + +The `javascript-osv` tests read the OSV reader's recorded report, `../../code/osv/fixtures/osv-scanner-2.7.1.json`. diff --git a/extensions/javascript/deps/fixtures/cyclonedx-npm-7.0.1.cdx.json b/extensions/javascript/deps/fixtures/cyclonedx-npm-7.0.1.cdx.json new file mode 100644 index 0000000000..b3964fc8cc --- /dev/null +++ b/extensions/javascript/deps/fixtures/cyclonedx-npm-7.0.1.cdx.json @@ -0,0 +1,3088 @@ +{ + "$schema": "http://cyclonedx.org/schema/bom-1.6.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.6", + "version": 1, + "serialNumber": "urn:uuid:1a3bed51-42a3-470c-b056-d96e16403c7a", + "metadata": { + "timestamp": "2026-11-22T22:49:26.829Z", + "tools": { + "components": [ + { + "type": "application", + "name": "npm", + "version": "11.20.0" + }, + { + "type": "application", + "name": "cyclonedx-npm", + "group": "@cyclonedx", + "version": "7.0.1", + "author": "Jan Kowalleck", + "description": "Create CycloneDX Software Bill of Materials (SBOM) from NPM projects.", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "externalReferences": [ + { + "url": "git+https://github.com/CycloneDX/cyclonedx-node-npm.git", + "type": "vcs", + "comment": "as detected from PackageJson property \"repository.url\"" + }, + { + "url": "https://github.com/CycloneDX/cyclonedx-node-npm#readme", + "type": "website", + "comment": "as detected from PackageJson property \"homepage\"" + }, + { + "url": "https://github.com/CycloneDX/cyclonedx-node-npm/issues", + "type": "issue-tracker", + "comment": "as detected from PackageJson property \"bugs.url\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:constraint:engine:node", + "value": ">=20.18.0" + }, + { + "name": "cdx:npm:package:constraint:engine:npm", + "value": ">=9" + } + ] + }, + { + "type": "library", + "name": "cyclonedx-library", + "group": "@cyclonedx", + "version": "10.5.1", + "author": "Jan Kowalleck", + "description": "Core functionality of CycloneDX for JavaScript (Node.js or WebBrowser).", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "externalReferences": [ + { + "url": "git+https://github.com/CycloneDX/cyclonedx-javascript-library.git", + "type": "vcs", + "comment": "as detected from PackageJson property \"repository.url\"" + }, + { + "url": "https://github.com/CycloneDX/cyclonedx-javascript-library#readme", + "type": "website", + "comment": "as detected from PackageJson property \"homepage\"" + }, + { + "url": "https://github.com/CycloneDX/cyclonedx-javascript-library/issues", + "type": "issue-tracker", + "comment": "as detected from PackageJson property \"bugs.url\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:constraint:engine:node", + "value": ">=20.18.0" + } + ] + } + ] + }, + "component": { + "type": "application", + "name": "board", + "version": "1.0.0", + "bom-ref": "board@1.0.0", + "purl": "pkg:npm/board@1.0.0", + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "" + } + ] + } + }, + "components": [ + { + "type": "library", + "name": "cyclonedx-npm", + "group": "@cyclonedx", + "version": "7.0.1", + "bom-ref": "board@1.0.0|@cyclonedx/cyclonedx-npm@7.0.1", + "licenses": [ + { + "license": { + "id": "Apache-2.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/%40cyclonedx/cyclonedx-npm@7.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@cyclonedx/cyclonedx-npm/-/cyclonedx-npm-7.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "69df53c73f63f1c0eb77396a9ea88d12eddac470f2fe9bf74639ee698938b17bed65d97418cb6cdd39ca384f64b60fa80c7422623ac8799823c646910ead67b8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@cyclonedx/cyclonedx-npm" + } + ] + }, + { + "type": "library", + "name": "c8", + "version": "12.0.0", + "bom-ref": "board@1.0.0|c8@12.0.0", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/c8@12.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/c8/-/c8-12.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e33a49beb7759ca5aeb679ca0b6a5790599bea233597e7df37ffe8d42ce54cdc16ec648eb3d6b5c6b2ea902e3c9d4f281248e63d92cf8b032c21a3afa05e0faa" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/c8" + } + ] + }, + { + "type": "library", + "name": "cyclonedx-library", + "group": "@cyclonedx", + "version": "10.5.1", + "bom-ref": "board@1.0.0|@cyclonedx/cyclonedx-library@10.5.1", + "licenses": [ + { + "license": { + "id": "Apache-2.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/%40cyclonedx/cyclonedx-library@10.5.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@cyclonedx/cyclonedx-library/-/cyclonedx-library-10.5.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a88f523f7b343a611a45d35b75cbf02773ce297b4a5fc10925d994aa18a5d93ad4340df1376d1873cb0cef72dc9f34477e215c255118d163a67cd8fd664b5eb0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@cyclonedx/cyclonedx-library" + } + ] + }, + { + "type": "library", + "name": "commander", + "version": "14.0.3", + "bom-ref": "board@1.0.0|commander@14.0.3", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/commander@14.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1fecb4268fd3d5167da8f3f8121d6991c41c2d1825ada25a48ba323ad1f1bba01aa648d6542cb64a2b75410e31dc39e0f2a0e54ac6447adee0e4fab4e8cbd383" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/commander" + } + ] + }, + { + "type": "library", + "name": "normalize-package-data", + "version": "8.0.0", + "bom-ref": "board@1.0.0|normalize-package-data@8.0.0", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/normalize-package-data@8.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-8.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "45693e3c8e37dde11243ba2e9d8c48a7aec262e56c4b5b984a89d7de403aa6cff72d67e35506bfa6d120e98dd3eae00cab5996a57f4f43eab1f90687a6c73b81" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/normalize-package-data" + } + ] + }, + { + "type": "library", + "name": "packageurl-js", + "version": "2.0.1", + "bom-ref": "board@1.0.0|packageurl-js@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/packageurl-js@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/packageurl-js/-/packageurl-js-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3798b15e3cd3cb8403407d10f58163a8859deb31faf77e838e99769bd40d1660efe45ba6f2af018e4a4070734ccce144d08c10ac584959ec7700dea44b4392c2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/packageurl-js" + } + ] + }, + { + "type": "library", + "name": "spdx-expression-parse", + "version": "4.0.0", + "bom-ref": "board@1.0.0|spdx-expression-parse@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/spdx-expression-parse@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0a5c9ae492228ffec2e9b451db6fad9c65db73854a9626ca4958f6887bd5797e62316eecd5221096abbaf7d26438324922187fa54bbc2f4fd52e1f317e50fe2d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/spdx-expression-parse" + } + ] + }, + { + "type": "library", + "name": "v8-coverage", + "group": "@bcoe", + "version": "1.0.2", + "bom-ref": "board@1.0.0|@bcoe/v8-coverage@1.0.2", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/%40bcoe/v8-coverage@1.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "eb300193f10203f418482435346895c306d07ab50267e4d06e9eb843702099f36fbab1c7d23f13b576b5a9b4a15c0eaaaa4a408f85795bca4fea62ded6670ca8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@bcoe/v8-coverage" + } + ] + }, + { + "type": "library", + "name": "schema", + "group": "@istanbuljs", + "version": "0.1.6", + "bom-ref": "board@1.0.0|@istanbuljs/schema@0.1.6", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/%40istanbuljs/schema@0.1.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f9283a18247fc32d684a640316ae0b4030219b71132a7a2bc4dfb2e676cb50b391dcfd1cd787f65aeaf38f7ff1a8f5ed6ac2c57c7779891150ec026de0a1f673" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@istanbuljs/schema" + } + ] + }, + { + "type": "library", + "name": "find-up", + "version": "5.0.0", + "bom-ref": "board@1.0.0|find-up@5.0.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/find-up@5.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "efcfcf5d3d7094b2c3813cc3b3bb23abd873cf4bd70fece7fbbc32a447b87d74310a6766a9f1ac10f4319a2092408dda8c557dd5b552b2f36dac94625ba9c69e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/find-up" + } + ] + }, + { + "type": "library", + "name": "foreground-child", + "version": "3.3.1", + "bom-ref": "board@1.0.0|foreground-child@3.3.1", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/foreground-child@3.3.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8085e32aab45b96120cc544903d58241e4892d90e380950e302333c6dbc5abfdfb2a88ccd41146b9faac0b2d2be2a4909982ec65831ec91ab321638cba9d37b3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/foreground-child" + } + ] + }, + { + "type": "library", + "name": "istanbul-lib-coverage", + "version": "3.2.2", + "bom-ref": "board@1.0.0|istanbul-lib-coverage@3.2.2", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/istanbul-lib-coverage@3.2.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3bc769b05fabd1657ff0c35129f9e6aed09686e2a3c6bab6c3e8e9cc12f95192938b62de5569d63a6591c4595eb0938d99cfb02c01af29064439a9e4a342c54e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/istanbul-lib-coverage" + } + ] + }, + { + "type": "library", + "name": "istanbul-lib-report", + "version": "3.0.1", + "bom-ref": "board@1.0.0|istanbul-lib-report@3.0.1", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/istanbul-lib-report@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1827c4d66b6c1c63842c253c7bf67b616ce99b26ebc7ff9d4937cbaef63ca9199a63acd74ca5a7e964088da005c34ebd89c9ba19530d920bb437323888f65437" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/istanbul-lib-report" + } + ] + }, + { + "type": "library", + "name": "istanbul-reports", + "version": "3.2.0", + "bom-ref": "board@1.0.0|istanbul-reports@3.2.0", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/istanbul-reports@3.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1c6616592fde86a4d5df1375d22db7b643e4a47e3a30b08830534269a28d6af0174c5d5192ac5ac043ed9e39c667a5ca4889c12a488e03904a4be699898dc0bc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/istanbul-reports" + } + ] + }, + { + "type": "library", + "name": "test-exclude", + "version": "8.0.0", + "bom-ref": "board@1.0.0|test-exclude@8.0.0", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/test-exclude@8.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/test-exclude/-/test-exclude-8.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "64e7dfb0dad762082f535983187939e08f7aaf6e8ff12c8c8cee6c94c29273bf885a6b41fcc40a9c40b67cfe758a6077fe94fa60ae5c4f913c7fe0ddf4a77239" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/test-exclude" + } + ] + }, + { + "type": "library", + "name": "v8-to-istanbul", + "version": "9.3.0", + "bom-ref": "board@1.0.0|v8-to-istanbul@9.3.0", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/v8-to-istanbul@9.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9221946a558dfab80127fd4e1d9b01b54e2b5d939f8ffeeb290c542ca948cf0cd04af3095143603f0244121ee053ac445710b46a1a0e06f376608f061fa14d80" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/v8-to-istanbul" + } + ] + }, + { + "type": "library", + "name": "yargs-parser", + "version": "21.1.1", + "bom-ref": "board@1.0.0|yargs-parser@21.1.1", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/yargs-parser@21.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b55a6c256ec376379c0221696c80757b7ab1210b04e8da0f739fde4ddadb6c80b88742d5b16867a1ade0fa6d87725048ba31f3b31678549540f8652e736fcb07" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/yargs-parser" + } + ] + }, + { + "type": "library", + "name": "yargs", + "version": "18.2.0", + "bom-ref": "board@1.0.0|yargs@18.2.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/yargs@18.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f4ea4a38b79aa0d15e704a7b3fa8986f3cdeff90aa5a81fb37748cb3feb2d571789ccbc532ca44199cc9eae162f4c990c17872cea62848428ededbc0dd9fe8db" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/yargs" + } + ], + "components": [ + { + "type": "library", + "name": "yargs-parser", + "version": "22.0.0", + "bom-ref": "board@1.0.0|yargs@18.2.0|yargs-parser@22.0.0", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/yargs-parser@22.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "af0bbf0a535d48ca644ab51bf9de8146c4a42d4ab57e67ec63a4cea58cd3c2fc24835fcd446f39281cb792afbe03c2ca4305fa96cbbe69669dfb6921bee5ebab" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/yargs/node_modules/yargs-parser" + } + ] + } + ] + }, + { + "type": "library", + "name": "hosted-git-info", + "version": "9.0.3", + "bom-ref": "board@1.0.0|hosted-git-info@9.0.3", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/hosted-git-info@9.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1dcfa084ba12b7a41a61952fd1606222f98c0d9b9967ba1a0ef747f0c6df38ee253acc5d5cb12fb82e9e3e81acf47d57f6808bcaaebe35537430aa83fb2771ca" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/hosted-git-info" + } + ] + }, + { + "type": "library", + "name": "semver", + "version": "7.8.6", + "bom-ref": "board@1.0.0|semver@7.8.6", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/semver@7.8.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f65a52494e0c972de6aedaeec0bb3578b2bafa0cdbcea78117044d8c88c4fbd2ee0e959d61cb6b4254377a3d489608bb8249e9b134673e82cff03a421ea1c827" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/semver" + } + ] + }, + { + "type": "library", + "name": "validate-npm-package-license", + "version": "3.0.4", + "bom-ref": "board@1.0.0|validate-npm-package-license@3.0.4", + "licenses": [ + { + "license": { + "id": "Apache-2.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/validate-npm-package-license@3.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0e92a6d948bfc4deff1d0282b69671a11581859f59d24aadca01bc5c280d43c6650e7c6e4265a18f9eba8fc7cde02bb7fc999b86c0e8edf70026ae2cf61dbb13" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/validate-npm-package-license" + } + ], + "components": [ + { + "type": "library", + "name": "spdx-expression-parse", + "version": "3.0.1", + "bom-ref": "board@1.0.0|validate-npm-package-license@3.0.4|spdx-expression-parse@3.0.1", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/spdx-expression-parse@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "71ba87ba7b105a724d13a2a155232c31e1f91ff2fd129ca66f3a93437b8bc0d08b675438f35a166a87ea1fb9cee95d3bc655f063a3e141d43621e756c7f64ae1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/validate-npm-package-license/node_modules/spdx-expression-parse" + } + ] + } + ] + }, + { + "type": "library", + "name": "spdx-exceptions", + "version": "2.5.0", + "bom-ref": "board@1.0.0|spdx-exceptions@2.5.0", + "licenses": [ + { + "license": { + "id": "CC-BY-3.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/spdx-exceptions@2.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3e2538dabfb13b851b512d5bba8dcb3c992394eef8df45e7e5254085da73cec3c7b236d855f9679c57404e069b9cbb9d7be0aabb6e69e8dfa0da5c3f3c5b1ae3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/spdx-exceptions" + } + ] + }, + { + "type": "library", + "name": "spdx-license-ids", + "version": "3.0.24", + "bom-ref": "board@1.0.0|spdx-license-ids@3.0.24", + "licenses": [ + { + "license": { + "id": "CC0-1.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/spdx-license-ids@3.0.24", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.24.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "70b4bd4ed5a42101722e4277ff968540038739229394eb3fed60eeb7f5cf49d8e89b57c98547647a978900a5daf58d39f8569b1ddd2cb62f84b79e7dbc3b64a5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/spdx-license-ids" + } + ] + }, + { + "type": "library", + "name": "locate-path", + "version": "6.0.0", + "bom-ref": "board@1.0.0|locate-path@6.0.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/locate-path@6.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "88f64ae9e6236f146edee078fd667712c10830914ca80a28a65dd1fb3baad148dc026fcc3ba282c1e0e03df3f77a54f3b6828fdcab67547c539f63470520d553" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/locate-path" + } + ] + }, + { + "type": "library", + "name": "path-exists", + "version": "4.0.0", + "bom-ref": "board@1.0.0|path-exists@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/path-exists@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6a4f50cb943b8d86f65b071ecb9169be0d8aa0073f64884b48b392066466ca03ec1b091556dd1f65ad2aaed333fa6ead2530077d943c167981e0c1b82d6cbbff" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/path-exists" + } + ] + }, + { + "type": "library", + "name": "cross-spawn", + "version": "7.0.6", + "bom-ref": "board@1.0.0|cross-spawn@7.0.6", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/cross-spawn@7.0.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b95d903963f69d6ceccb668ca7c69189b862f5d9731791e0879487681f4e893184c834e2249cb1d2ecb9d505ddc966ed00736e6b85c9cd429c6b73b3294777bc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/cross-spawn" + } + ] + }, + { + "type": "library", + "name": "signal-exit", + "version": "4.1.0", + "bom-ref": "board@1.0.0|signal-exit@4.1.0", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/signal-exit@4.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6f3c99d5ef3cc3d3b588d25b2a73a5bd84eb58f0e5e3a3b56c6d03dd7227bfef6d90faf1acdf235144e21650e4926296827d4ce827c8035dd2b86a8e6bd2a8af" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/signal-exit" + } + ] + }, + { + "type": "library", + "name": "make-dir", + "version": "4.0.0", + "bom-ref": "board@1.0.0|make-dir@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/make-dir@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8577544d960854eb75131fff8c0422fb04d9669529c018ffd10b0ecea7a06f7ac630c78989212ee712c79d87c1ad1578447dbe38248e3bde48b3fef1d562786f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/make-dir" + } + ] + }, + { + "type": "library", + "name": "supports-color", + "version": "7.2.0", + "bom-ref": "board@1.0.0|supports-color@7.2.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/supports-color@7.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "aa9080bd197db2db8e1ef78ab27ec79dc251befe74d6a21a70acd094effe2f0c5cf7ed2adb02f2bf80dfbedf34fc33e7da9a8e06c25d0e2a205c647df8ebf047" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/supports-color" + } + ] + }, + { + "type": "library", + "name": "html-escaper", + "version": "2.0.2", + "bom-ref": "board@1.0.0|html-escaper@2.0.2", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/html-escaper@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1f688cb5dd08e0cb7979889aa517480e3a7e5f37a55d0d2d144e094bb605c057af5d73263a9f66c8dad4bc28340fac2cf22aa444f05f28781bc228354a694b7e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/html-escaper" + } + ] + }, + { + "type": "library", + "name": "glob", + "version": "13.0.7", + "bom-ref": "board@1.0.0|glob@13.0.7", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/glob@13.0.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/glob/-/glob-13.0.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c1fb0581743c03748423d5c67fb365dd8f65edf7d2ac687b494093eef53fd82cd83dea7d923c409f54b8d05f4e3cac4030609597b1ed365261ac2254794abcde" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/glob" + } + ] + }, + { + "type": "library", + "name": "minimatch", + "version": "10.2.6", + "bom-ref": "board@1.0.0|minimatch@10.2.6", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/minimatch@10.2.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "be92d012cf952c2af59d4d015d2d3b99a628170943007d209e042ebadb71230bad0c510c1ead9b957fbcbe98310dd2b72753f08c22627a9efb3a2b536782e5d4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/minimatch" + } + ] + }, + { + "type": "library", + "name": "trace-mapping", + "group": "@jridgewell", + "version": "0.3.31", + "bom-ref": "board@1.0.0|@jridgewell/trace-mapping@0.3.31", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/%40jridgewell/trace-mapping@0.3.31", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cf3351f9275048327373c8e869e3fc410a0242bf0db98c76748232b65d507811191c9f6e5ba85e6ecad881bcfc849c1441aa374d608cb667d5f0dbb5b7038b03" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@jridgewell/trace-mapping" + } + ] + }, + { + "type": "library", + "name": "istanbul-lib-coverage", + "group": "@types", + "version": "2.0.6", + "bom-ref": "board@1.0.0|@types/istanbul-lib-coverage@2.0.6", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/%40types/istanbul-lib-coverage@2.0.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d9017fb7f6ae5a6d25b32f17b4a54f1b5f6fdec48e42525efd81d981f8dbfca0411ce19257e276abf4baef5adcabdb9306b2c05e6669a8989a41b313fb3354d7" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/istanbul-lib-coverage" + } + ] + }, + { + "type": "library", + "name": "convert-source-map", + "version": "2.0.0", + "bom-ref": "board@1.0.0|convert-source-map@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/convert-source-map@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2afa78e7d1eb576144275080b22d4abbe318de46ac1f5f53172913cf6c5698c7aae9b936354dd75ef7c9f90eb59b4c64b56c2dfb51d261fdc966c4e6b3769126" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/convert-source-map" + } + ] + }, + { + "type": "library", + "name": "cliui", + "version": "9.0.1", + "bom-ref": "board@1.0.0|cliui@9.0.1", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/cliui@9.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "93b9dd80a870a10bde04bfbfd6da86258373d3dec8ed63afc1b9a6536011e7e99a82d6e33d64134b50b9bf31a4042f189bc5164737ca533514a852f2a58e10fb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/cliui" + } + ], + "components": [ + { + "type": "library", + "name": "string-width", + "version": "7.2.0", + "bom-ref": "board@1.0.0|cliui@9.0.1|string-width@7.2.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/string-width@7.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b6c693224296f5be0df80123f92540f96849cd5effccc85c4aeefc98b2964a4edc5cc3921ec04a15652cd1f5b0abc4322b73202414115fa19b8b89186ddbc691" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/cliui/node_modules/string-width" + } + ] + } + ] + }, + { + "type": "library", + "name": "escalade", + "version": "3.2.0", + "bom-ref": "board@1.0.0|escalade@3.2.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/escalade@3.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5948f6aa5c5a42d3b883a3eae5cdbd193716183c9df22b4bf334e58a98040b3dc97ac02288e2a8b5df0953aa2d0773c00a01bac64254c9585ba0c4be6e37bf8c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/escalade" + } + ] + }, + { + "type": "library", + "name": "get-caller-file", + "version": "2.0.5", + "bom-ref": "board@1.0.0|get-caller-file@2.0.5", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/get-caller-file@2.0.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0f214fdc133fdd81d340e0942ffc343991d1d25a4a786af1a2d70759ca8d11d9e5b6a1705d57e110143de1e228df801f429a34ac6922e1cc8889fb58d3a87616" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/get-caller-file" + } + ] + }, + { + "type": "library", + "name": "string-width", + "version": "8.3.0", + "bom-ref": "board@1.0.0|string-width@8.3.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/string-width@8.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "65b9993342428a140df757569f1a22a53d8a384c87a84c9f4575328ee4615bc6ffc67a8f0e8ab88161150294d56bd75bdb037c9a6a229201416e387bd7e70679" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/string-width" + } + ] + }, + { + "type": "library", + "name": "y18n", + "version": "5.0.8", + "bom-ref": "board@1.0.0|y18n@5.0.8", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/y18n@5.0.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d297c5cde81e0d62472480264cb44fd83c078dd179b3b8e8f6dbb3b5d43102120d09dbd2fb79c620da8f774d00a61a8947fd0b8403544baffeed209bf7c60e7c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/y18n" + } + ] + }, + { + "type": "library", + "name": "lru-cache", + "version": "11.5.3", + "bom-ref": "board@1.0.0|lru-cache@11.5.3", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/lru-cache@11.5.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "53837c160ce65b173c935547f0aafa950835f14ec58ef6f2eb05c75515ff659ec8c166d1320ad16cfd16adbe6ae4d5629ebca9e1241a9a91ca76fb5e708b7152" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lru-cache" + } + ] + }, + { + "type": "library", + "name": "spdx-correct", + "version": "3.2.0", + "bom-ref": "board@1.0.0|spdx-correct@3.2.0", + "licenses": [ + { + "license": { + "id": "Apache-2.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/spdx-correct@3.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "90df5d25bbe7c921d42c896e0c7cb7d961d152edce83b07db1b63bb6c14b72d42422a9cc877844ad881d3234d8baa99c5d7fa52b94f596752ddc6ef336cc2664" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/spdx-correct" + } + ], + "components": [ + { + "type": "library", + "name": "spdx-expression-parse", + "version": "3.0.1", + "bom-ref": "board@1.0.0|spdx-correct@3.2.0|spdx-expression-parse@3.0.1", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/spdx-expression-parse@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "71ba87ba7b105a724d13a2a155232c31e1f91ff2fd129ca66f3a93437b8bc0d08b675438f35a166a87ea1fb9cee95d3bc655f063a3e141d43621e756c7f64ae1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/spdx-correct/node_modules/spdx-expression-parse" + } + ] + } + ] + }, + { + "type": "library", + "name": "p-locate", + "version": "5.0.0", + "bom-ref": "board@1.0.0|p-locate@5.0.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/p-locate@5.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2da363b51594058fbecc1e6713f37071aa0cca548f93e4be647341d53cdd6cc24c9f2e9dca7a401aded7fed97f418ab74c8784ea7c47a696e8d8b1b29ab1b93f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/p-locate" + } + ] + }, + { + "type": "library", + "name": "path-key", + "version": "3.1.1", + "bom-ref": "board@1.0.0|path-key@3.1.1", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/path-key@3.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a2399e374a9dfb2d23b3312da18e3caf43deab97703049089423aee90e5fe3595f92cc17b8ab58ae18284e92e7c887079b6e1486ac7ee53aa6d889d2c0b844e9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/path-key" + } + ] + }, + { + "type": "library", + "name": "shebang-command", + "version": "2.0.0", + "bom-ref": "board@1.0.0|shebang-command@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/shebang-command@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "907c6bdb366962d766acdd6a0e3aeb5ff675ad1d641bc0f1fa09292b51b87979af5ecc26704d614d6056614ce5ada630d7fc99a7a62e0d8efb62dbdb3747660c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/shebang-command" + } + ] + }, + { + "type": "library", + "name": "which", + "version": "2.0.2", + "bom-ref": "board@1.0.0|which@2.0.2", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/which@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "04b2374e5d535b73ef97bd25df2ab763ae22f9ac29c17aac181616924a8cb676d782b303fb28fbae15b492e103c7325a6171a3116e6881aa4a34c10a34c8e26c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/which" + } + ] + }, + { + "type": "library", + "name": "has-flag", + "version": "4.0.0", + "bom-ref": "board@1.0.0|has-flag@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/has-flag@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1329094ff4352a34d672da698080207d23b4b4a56e6548e180caf5ee4a93ba6325e807efdc421295e53ba99533a170c54c01d30c2e0d3a81bf67153712f94c3d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/has-flag" + } + ] + }, + { + "type": "library", + "name": "minipass", + "version": "7.1.3", + "bom-ref": "board@1.0.0|minipass@7.1.3", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/minipass@7.1.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b44047a839c8a0cff5ad7304d738246bd83a43695ca029311cbb9cece0c9e41c5b3f977873667970682d5c092ee7ddb4d02c7b762b874ce61f4810fc9fa9a6f0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/minipass" + } + ] + }, + { + "type": "library", + "name": "path-scurry", + "version": "2.0.2", + "bom-ref": "board@1.0.0|path-scurry@2.0.2", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/path-scurry@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "dcefe2555b0900fb0e9e9c1621e0fe77acffecf9aa029c9078f52d0a77636ad8fff48e4bca51efb79aa5b856814f7239877af57a37d1d39e9cf850aff8d9cd5e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/path-scurry" + } + ] + }, + { + "type": "library", + "name": "brace-expansion", + "version": "5.0.13", + "bom-ref": "board@1.0.0|brace-expansion@5.0.13", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/brace-expansion@5.0.13", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "561ddd9856dce3065ea31eccf48ff42fd19f15df374aee3ec82724fce17d1a2fcffdd0079f4453ed7e0af51ee030d3210dc9370ef851e905ec9d07638e0c0dbd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/brace-expansion" + } + ] + }, + { + "type": "library", + "name": "resolve-uri", + "group": "@jridgewell", + "version": "3.1.3", + "bom-ref": "board@1.0.0|@jridgewell/resolve-uri@3.1.3", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/%40jridgewell/resolve-uri@3.1.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9614ed8eda0402b5818e2b26b5f4bbeb54bd1e5ca7fa7219a8e6556286755e7f363cc34c56793e8e3fcd842e1f017193b3bc9d38d709891e6fc90053303bb6ee" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@jridgewell/resolve-uri" + } + ] + }, + { + "type": "library", + "name": "sourcemap-codec", + "group": "@jridgewell", + "version": "1.6.0", + "bom-ref": "board@1.0.0|@jridgewell/sourcemap-codec@1.6.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/%40jridgewell/sourcemap-codec@1.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4fb8dffb9ce0b191f0349e25bd0eff69ecdbca4d27357fb32555a998703b558b04c7b6bbaabe5183921bb4916a920cdee58dacaeeab545463c43cdfb39dee217" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@jridgewell/sourcemap-codec" + } + ] + }, + { + "type": "library", + "name": "strip-ansi", + "version": "7.2.0", + "bom-ref": "board@1.0.0|strip-ansi@7.2.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/strip-ansi@7.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c833cc363a785b27d80641e78c844b7dc6b58ba28cc860adb1582829eff3d7eeafba481a10d76018166df9998a3dce206afbc46793a01df1ddadace180dc86ef" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/strip-ansi" + } + ] + }, + { + "type": "library", + "name": "wrap-ansi", + "version": "9.0.2", + "bom-ref": "board@1.0.0|wrap-ansi@9.0.2", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/wrap-ansi@9.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e3602d9a0aa357e5f556974e7f24c6398462d3fceca0baad5d07244e6a937b26d3f810c86ccfc6bb1a3bc77a44dafb69af5a24eb146a33d3a905ef89ca8ab2c3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/wrap-ansi" + } + ], + "components": [ + { + "type": "library", + "name": "string-width", + "version": "7.2.0", + "bom-ref": "board@1.0.0|wrap-ansi@9.0.2|string-width@7.2.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/string-width@7.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b6c693224296f5be0df80123f92540f96849cd5effccc85c4aeefc98b2964a4edc5cc3921ec04a15652cd1f5b0abc4322b73202414115fa19b8b89186ddbc691" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/wrap-ansi/node_modules/string-width" + } + ] + } + ] + }, + { + "type": "library", + "name": "get-east-asian-width", + "version": "1.7.0", + "bom-ref": "board@1.0.0|get-east-asian-width@1.7.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/get-east-asian-width@1.7.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5e31f50040b17f48222f6575694f2f2b2451da9a5151be5cd04bd3ef3b894e8910ef86cda39db33ad821a9d588aab8540fbf5fa37c7459f29974eab117a2c6d5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/get-east-asian-width" + } + ] + }, + { + "type": "library", + "name": "p-limit", + "version": "3.1.0", + "bom-ref": "board@1.0.0|p-limit@3.1.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/p-limit@3.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4d839a9ccdf01b0346b193767154d83c0af0e39e319d78f9aa6585d5b12801ce3e714fe897b19587ba1d7af8e9d4534776e1dcdca64c70576ec54e5773ab8945" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/p-limit" + } + ] + }, + { + "type": "library", + "name": "shebang-regex", + "version": "3.0.0", + "bom-ref": "board@1.0.0|shebang-regex@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/shebang-regex@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "efef9d161b5cc77df9dee05aabc0c347836ec417ad0730bb6503a19934089c711de9b4ab5dd884cb30af1b4ed9e3851874b4a1594c97b7933fca1cfc7a471bd4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/shebang-regex" + } + ] + }, + { + "type": "library", + "name": "isexe", + "version": "2.0.0", + "bom-ref": "board@1.0.0|isexe@2.0.0", + "licenses": [ + { + "license": { + "id": "ISC", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/isexe@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "447c4c2e9f659ca1c61d19e0f5016144231b600715a67ebdb2648672addfdfac638155564e18f8aaa2db4cb96aed2b23f01f9f210d44b8210623694ab3241e23" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/isexe" + } + ] + }, + { + "type": "library", + "name": "balanced-match", + "version": "4.0.4", + "bom-ref": "board@1.0.0|balanced-match@4.0.4", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/balanced-match@4.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "04bae011c453c17da8ea01b118e08dc8cbc64a9df96287ee633c3d87520c4d198aaadb40659554ebb6dd6fd3ebdaf50703cfa3de2dad25f8cee82ebee26c864c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/balanced-match" + } + ] + }, + { + "type": "library", + "name": "emoji-regex", + "version": "10.6.0", + "bom-ref": "board@1.0.0|emoji-regex@10.6.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/emoji-regex@10.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b68508f38612e589b15b6d7d7ab9e2583d022153a8e3ac46282a2578d41180ecc3a2b8018b5bf80fbd7f385ce00fd18ed9418a22fd42dd2a7c0c09f4fa3e70ec" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/emoji-regex" + } + ] + }, + { + "type": "library", + "name": "ansi-regex", + "version": "6.6.0", + "bom-ref": "board@1.0.0|ansi-regex@6.6.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/ansi-regex@6.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5d9e5aa5bceb7826d748ac0f8c9b2dbbc474cce8b6e3bc375d8c16c6dc015e0a59ac2c9cd4a6bba7dff163403dfdd88c7b09876c42b3f8522b6966845a394de6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/ansi-regex" + } + ] + }, + { + "type": "library", + "name": "ansi-styles", + "version": "6.2.3", + "bom-ref": "board@1.0.0|ansi-styles@6.2.3", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/ansi-styles@6.2.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e038fa336f0907ea001fc9059132d4a3e6b68f038592ea9bdf2b9c53408035c45151bc52d1c3f49d96021a371cdc1357c1122c5159831a0cdac267bbcef247be" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/ansi-styles" + } + ] + }, + { + "type": "library", + "name": "yocto-queue", + "version": "0.1.0", + "bom-ref": "board@1.0.0|yocto-queue@0.1.0", + "licenses": [ + { + "license": { + "id": "MIT", + "acknowledgement": "declared" + } + } + ], + "purl": "pkg:npm/yocto-queue@0.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ad592cbec9cd09d27fa2119ceb180fc3237c7a1782c6c88b33c9b1b84fedfe6395a897b03ee3b59a22e94c74224604ca08b7b12f831e00555a82db3b1e6359d9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/yocto-queue" + } + ] + } + ], + "dependencies": [ + { + "ref": "board@1.0.0", + "dependsOn": [ + "board@1.0.0|@cyclonedx/cyclonedx-npm@7.0.1", + "board@1.0.0|c8@12.0.0" + ] + }, + { + "ref": "board@1.0.0|@cyclonedx/cyclonedx-npm@7.0.1", + "dependsOn": [ + "board@1.0.0|@cyclonedx/cyclonedx-library@10.5.1", + "board@1.0.0|commander@14.0.3", + "board@1.0.0|normalize-package-data@8.0.0", + "board@1.0.0|packageurl-js@2.0.1", + "board@1.0.0|spdx-expression-parse@4.0.0" + ] + }, + { + "ref": "board@1.0.0|c8@12.0.0", + "dependsOn": [ + "board@1.0.0|@bcoe/v8-coverage@1.0.2", + "board@1.0.0|@istanbuljs/schema@0.1.6", + "board@1.0.0|find-up@5.0.0", + "board@1.0.0|foreground-child@3.3.1", + "board@1.0.0|istanbul-lib-coverage@3.2.2", + "board@1.0.0|istanbul-lib-report@3.0.1", + "board@1.0.0|istanbul-reports@3.2.0", + "board@1.0.0|test-exclude@8.0.0", + "board@1.0.0|v8-to-istanbul@9.3.0", + "board@1.0.0|yargs-parser@21.1.1", + "board@1.0.0|yargs@18.2.0" + ] + }, + { + "ref": "board@1.0.0|@cyclonedx/cyclonedx-library@10.5.1", + "dependsOn": [ + "board@1.0.0|packageurl-js@2.0.1", + "board@1.0.0|spdx-expression-parse@4.0.0" + ] + }, + { + "ref": "board@1.0.0|commander@14.0.3" + }, + { + "ref": "board@1.0.0|normalize-package-data@8.0.0", + "dependsOn": [ + "board@1.0.0|hosted-git-info@9.0.3", + "board@1.0.0|semver@7.8.6", + "board@1.0.0|validate-npm-package-license@3.0.4" + ] + }, + { + "ref": "board@1.0.0|packageurl-js@2.0.1" + }, + { + "ref": "board@1.0.0|spdx-expression-parse@4.0.0", + "dependsOn": [ + "board@1.0.0|spdx-exceptions@2.5.0", + "board@1.0.0|spdx-license-ids@3.0.24" + ] + }, + { + "ref": "board@1.0.0|@bcoe/v8-coverage@1.0.2" + }, + { + "ref": "board@1.0.0|@istanbuljs/schema@0.1.6" + }, + { + "ref": "board@1.0.0|find-up@5.0.0", + "dependsOn": [ + "board@1.0.0|locate-path@6.0.0", + "board@1.0.0|path-exists@4.0.0" + ] + }, + { + "ref": "board@1.0.0|foreground-child@3.3.1", + "dependsOn": [ + "board@1.0.0|cross-spawn@7.0.6", + "board@1.0.0|signal-exit@4.1.0" + ] + }, + { + "ref": "board@1.0.0|istanbul-lib-coverage@3.2.2" + }, + { + "ref": "board@1.0.0|istanbul-lib-report@3.0.1", + "dependsOn": [ + "board@1.0.0|istanbul-lib-coverage@3.2.2", + "board@1.0.0|make-dir@4.0.0", + "board@1.0.0|supports-color@7.2.0" + ] + }, + { + "ref": "board@1.0.0|istanbul-reports@3.2.0", + "dependsOn": [ + "board@1.0.0|html-escaper@2.0.2", + "board@1.0.0|istanbul-lib-report@3.0.1" + ] + }, + { + "ref": "board@1.0.0|test-exclude@8.0.0", + "dependsOn": [ + "board@1.0.0|@istanbuljs/schema@0.1.6", + "board@1.0.0|glob@13.0.7", + "board@1.0.0|minimatch@10.2.6" + ] + }, + { + "ref": "board@1.0.0|v8-to-istanbul@9.3.0", + "dependsOn": [ + "board@1.0.0|@jridgewell/trace-mapping@0.3.31", + "board@1.0.0|@types/istanbul-lib-coverage@2.0.6", + "board@1.0.0|convert-source-map@2.0.0" + ] + }, + { + "ref": "board@1.0.0|yargs-parser@21.1.1" + }, + { + "ref": "board@1.0.0|yargs@18.2.0", + "dependsOn": [ + "board@1.0.0|cliui@9.0.1", + "board@1.0.0|escalade@3.2.0", + "board@1.0.0|get-caller-file@2.0.5", + "board@1.0.0|string-width@8.3.0", + "board@1.0.0|y18n@5.0.8", + "board@1.0.0|yargs@18.2.0|yargs-parser@22.0.0" + ] + }, + { + "ref": "board@1.0.0|yargs@18.2.0|yargs-parser@22.0.0" + }, + { + "ref": "board@1.0.0|hosted-git-info@9.0.3", + "dependsOn": [ + "board@1.0.0|lru-cache@11.5.3" + ] + }, + { + "ref": "board@1.0.0|semver@7.8.6" + }, + { + "ref": "board@1.0.0|validate-npm-package-license@3.0.4", + "dependsOn": [ + "board@1.0.0|spdx-correct@3.2.0", + "board@1.0.0|validate-npm-package-license@3.0.4|spdx-expression-parse@3.0.1" + ] + }, + { + "ref": "board@1.0.0|validate-npm-package-license@3.0.4|spdx-expression-parse@3.0.1", + "dependsOn": [ + "board@1.0.0|spdx-exceptions@2.5.0", + "board@1.0.0|spdx-license-ids@3.0.24" + ] + }, + { + "ref": "board@1.0.0|spdx-exceptions@2.5.0" + }, + { + "ref": "board@1.0.0|spdx-license-ids@3.0.24" + }, + { + "ref": "board@1.0.0|locate-path@6.0.0", + "dependsOn": [ + "board@1.0.0|p-locate@5.0.0" + ] + }, + { + "ref": "board@1.0.0|path-exists@4.0.0" + }, + { + "ref": "board@1.0.0|cross-spawn@7.0.6", + "dependsOn": [ + "board@1.0.0|path-key@3.1.1", + "board@1.0.0|shebang-command@2.0.0", + "board@1.0.0|which@2.0.2" + ] + }, + { + "ref": "board@1.0.0|signal-exit@4.1.0" + }, + { + "ref": "board@1.0.0|make-dir@4.0.0", + "dependsOn": [ + "board@1.0.0|semver@7.8.6" + ] + }, + { + "ref": "board@1.0.0|supports-color@7.2.0", + "dependsOn": [ + "board@1.0.0|has-flag@4.0.0" + ] + }, + { + "ref": "board@1.0.0|html-escaper@2.0.2" + }, + { + "ref": "board@1.0.0|glob@13.0.7", + "dependsOn": [ + "board@1.0.0|minimatch@10.2.6", + "board@1.0.0|minipass@7.1.3", + "board@1.0.0|path-scurry@2.0.2" + ] + }, + { + "ref": "board@1.0.0|minimatch@10.2.6", + "dependsOn": [ + "board@1.0.0|brace-expansion@5.0.13" + ] + }, + { + "ref": "board@1.0.0|@jridgewell/trace-mapping@0.3.31", + "dependsOn": [ + "board@1.0.0|@jridgewell/resolve-uri@3.1.3", + "board@1.0.0|@jridgewell/sourcemap-codec@1.6.0" + ] + }, + { + "ref": "board@1.0.0|@types/istanbul-lib-coverage@2.0.6" + }, + { + "ref": "board@1.0.0|convert-source-map@2.0.0" + }, + { + "ref": "board@1.0.0|cliui@9.0.1", + "dependsOn": [ + "board@1.0.0|cliui@9.0.1|string-width@7.2.0", + "board@1.0.0|strip-ansi@7.2.0", + "board@1.0.0|wrap-ansi@9.0.2" + ] + }, + { + "ref": "board@1.0.0|cliui@9.0.1|string-width@7.2.0", + "dependsOn": [ + "board@1.0.0|emoji-regex@10.6.0", + "board@1.0.0|get-east-asian-width@1.7.0", + "board@1.0.0|strip-ansi@7.2.0" + ] + }, + { + "ref": "board@1.0.0|escalade@3.2.0" + }, + { + "ref": "board@1.0.0|get-caller-file@2.0.5" + }, + { + "ref": "board@1.0.0|string-width@8.3.0", + "dependsOn": [ + "board@1.0.0|get-east-asian-width@1.7.0", + "board@1.0.0|strip-ansi@7.2.0" + ] + }, + { + "ref": "board@1.0.0|y18n@5.0.8" + }, + { + "ref": "board@1.0.0|lru-cache@11.5.3" + }, + { + "ref": "board@1.0.0|spdx-correct@3.2.0", + "dependsOn": [ + "board@1.0.0|spdx-correct@3.2.0|spdx-expression-parse@3.0.1", + "board@1.0.0|spdx-license-ids@3.0.24" + ] + }, + { + "ref": "board@1.0.0|spdx-correct@3.2.0|spdx-expression-parse@3.0.1", + "dependsOn": [ + "board@1.0.0|spdx-exceptions@2.5.0", + "board@1.0.0|spdx-license-ids@3.0.24" + ] + }, + { + "ref": "board@1.0.0|p-locate@5.0.0", + "dependsOn": [ + "board@1.0.0|p-limit@3.1.0" + ] + }, + { + "ref": "board@1.0.0|path-key@3.1.1" + }, + { + "ref": "board@1.0.0|shebang-command@2.0.0", + "dependsOn": [ + "board@1.0.0|shebang-regex@3.0.0" + ] + }, + { + "ref": "board@1.0.0|which@2.0.2", + "dependsOn": [ + "board@1.0.0|isexe@2.0.0" + ] + }, + { + "ref": "board@1.0.0|has-flag@4.0.0" + }, + { + "ref": "board@1.0.0|minipass@7.1.3" + }, + { + "ref": "board@1.0.0|path-scurry@2.0.2", + "dependsOn": [ + "board@1.0.0|lru-cache@11.5.3", + "board@1.0.0|minipass@7.1.3" + ] + }, + { + "ref": "board@1.0.0|brace-expansion@5.0.13", + "dependsOn": [ + "board@1.0.0|balanced-match@4.0.4" + ] + }, + { + "ref": "board@1.0.0|@jridgewell/resolve-uri@3.1.3" + }, + { + "ref": "board@1.0.0|@jridgewell/sourcemap-codec@1.6.0" + }, + { + "ref": "board@1.0.0|strip-ansi@7.2.0", + "dependsOn": [ + "board@1.0.0|ansi-regex@6.6.0" + ] + }, + { + "ref": "board@1.0.0|wrap-ansi@9.0.2", + "dependsOn": [ + "board@1.0.0|ansi-styles@6.2.3", + "board@1.0.0|wrap-ansi@9.0.2|string-width@7.2.0", + "board@1.0.0|strip-ansi@7.2.0" + ] + }, + { + "ref": "board@1.0.0|wrap-ansi@9.0.2|string-width@7.2.0", + "dependsOn": [ + "board@1.0.0|emoji-regex@10.6.0", + "board@1.0.0|get-east-asian-width@1.7.0", + "board@1.0.0|strip-ansi@7.2.0" + ] + }, + { + "ref": "board@1.0.0|get-east-asian-width@1.7.0" + }, + { + "ref": "board@1.0.0|p-limit@3.1.0", + "dependsOn": [ + "board@1.0.0|yocto-queue@0.1.0" + ] + }, + { + "ref": "board@1.0.0|shebang-regex@3.0.0" + }, + { + "ref": "board@1.0.0|isexe@2.0.0" + }, + { + "ref": "board@1.0.0|balanced-match@4.0.4" + }, + { + "ref": "board@1.0.0|emoji-regex@10.6.0" + }, + { + "ref": "board@1.0.0|ansi-regex@6.6.0" + }, + { + "ref": "board@1.0.0|ansi-styles@6.2.3" + }, + { + "ref": "board@1.0.0|yocto-queue@0.1.0" + } + ] +} \ No newline at end of file diff --git a/extensions/javascript/deps/fixtures/packages.json b/extensions/javascript/deps/fixtures/packages.json new file mode 100644 index 0000000000..50ece84cc5 --- /dev/null +++ b/extensions/javascript/deps/fixtures/packages.json @@ -0,0 +1,6 @@ +[ + {"kind": "package", "id": "pkg:npm/board", + "fields": {"name": "board", "version": "1.0.0", "path": ""}}, + {"kind": "package", "id": "pkg:npm/web", + "fields": {"name": "web", "version": "0.1.0", "path": "web"}} +] diff --git a/extensions/javascript/deps/src/lib.rs b/extensions/javascript/deps/src/lib.rs new file mode 100644 index 0000000000..8fbd37feef --- /dev/null +++ b/extensions/javascript/deps/src/lib.rs @@ -0,0 +1,140 @@ +//! @javascript/deps — runs cyclonedx-npm and osv-scanner and records a JavaScript project's dependencies and their +//! known vulnerabilities as `@code/core`'s `dependency` and `vulnerability` facts (ADR 0389). A collector runs one +//! command, so the pack holds two. +//! +//! The collector `javascript-sbom` is selected by a `package-lock.json` at the project root. The host runs, with +//! consent, `npx --no -- cyclonedx-npm --output-format JSON --spec-version 1.6 --package-lock-only --output-file +//! {report}`. `npx --no` never downloads anything: cyclonedx-npm must be a dev dependency of the project. +//! `--package-lock-only` reads the lockfile alone, so no `node_modules` is needed and no install script runs. +//! The BOM is read by `specforge-code-cyclonedx` and minted by `specforge-code-facts` against `@javascript/source`'s +//! packages: one `dependency` fact per component, citing the served package the BOM's root names. A BOM whose root +//! names no served package is an error: it is no report about this project. +//! +//! The collector `javascript-osv` is selected by the same lockfile. The host runs, with consent, `osv-scanner scan +//! source --lockfile package-lock.json --format json --output-file {report}`. The scan sends the lockfile's package +//! names and versions to the OSV API over the network, which the approval shows (ADR 0389 D9). osv-scanner exits 1 +//! when it finds vulnerabilities and 128 when it finds no lockfile (then it writes no report: E045); the host judges +//! neither exit code (ADR 0348 D4), it reads the report. Each record becomes a `vulnerability` fact citing the +//! served npm package at or under the lockfile's directory; every package the scan lists that no served package +//! holds is returned as one warning line, which the host shows as W203 (ADR 0389 D7), never dropped. + +use specforge_code_facts::{dependency_facts, vulnerability_facts}; +use specforge_extension_sdk::prelude::*; + +const SBOM: &str = "javascript-sbom"; +/// The BOM cyclonedx-npm writes, relative to the project root. +const SBOM_REPORT: &str = ".specforge/reports/javascript-sbom.cdx.json"; +const OSV: &str = "javascript-osv"; +/// The report osv-scanner writes, relative to the project root. +const OSV_REPORT: &str = ".specforge/reports/javascript-osv.json"; + +#[specforge_extension_sdk::extension( + name = "@javascript/deps", + version = "1.0.0", + description = "Runs cyclonedx-npm and osv-scanner and records dependencies and vulnerabilities as facts (@code/core)" +)] +struct JavascriptDeps; + +impl Contributions for JavascriptDeps { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.2"); + // Its packages are what a BOM's root names; without them a dependency cites nothing. + c.peer("@javascript/source", "^1.0"); + c.collector(SBOM, |k| { + k.input_format("cyclonedx-json") + .detect_files(&["package-lock.json"]) + .run(&[ + "npx", + "--no", + "--", + "cyclonedx-npm", + "--output-format", + "JSON", + "--spec-version", + "1.6", + "--package-lock-only", + "--output-file", + "{report}", + ]) + .env(&["NODE_*", "NPM_CONFIG_*", "npm_config_*", "CI"]) + .install("npm install --save-dev @cyclonedx/cyclonedx-npm") + .report(SBOM_REPORT) + .input(Input::facts(&["package"])) + .answers(&["dependency"]) + .collect(collect_sbom); + }); + c.collector(OSV, |k| { + k.input_format("osv-json") + .detect_files(&["package-lock.json"]) + .run(&[ + "osv-scanner", + "scan", + "source", + "--lockfile", + "package-lock.json", + "--format", + "json", + "--output-file", + "{report}", + ]) + .env(&[ + "HTTPS_PROXY", + "HTTP_PROXY", + "NO_PROXY", + "https_proxy", + "http_proxy", + "no_proxy", + "OSV_*", + ]) + .install("go install github.com/google/osv-scanner/v2/cmd/osv-scanner@latest (or: brew install osv-scanner)") + .report(OSV_REPORT) + .input(Input::facts(&["package"])) + .answers(&["vulnerability"]) + .collect(collect_osv); + }); + } +} + +/// Map osv-scanner's report to `vulnerability` facts, and every package it lists that no served package holds to a +/// warning line. +fn collect_osv(input: &CollectInput) -> Result { + let [report] = &input.reports[..] else { + return Err(format!( + "{OSV} reads one report, {OSV_REPORT}; it was given {}", + input.reports.len() + )); + }; + let cwd = input.cwd.as_deref().ok_or( + "the host sent no cwd: osv-scanner's report names absolute lockfile paths, read against the project root", + )?; + let scan = specforge_code_osv::read(&report.content, cwd) + .map_err(|why| format!("{}: {why}", report.path))?; + let minted = vulnerability_facts(&scan, &input.facts); + Ok(CollectOutput { + facts: minted.facts, + warnings: minted.skipped, + ..CollectOutput::default() + }) +} + +/// Map cyclonedx-npm's BOM to `dependency` facts of the served package its root names. +fn collect_sbom(input: &CollectInput) -> Result { + let [report] = &input.reports[..] else { + return Err(format!( + "{SBOM} reads one report, {SBOM_REPORT}; it was given {}", + input.reports.len() + )); + }; + let bom = specforge_code_cyclonedx::read(&report.content) + .map_err(|why| format!("{}: {why}", report.path))?; + Ok(CollectOutput { + facts: dependency_facts(&[bom], &input.facts) + .map_err(|why| format!("{}: {why}", report.path))?, + ..CollectOutput::default() + }) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/javascript/deps/src/tests.rs b/extensions/javascript/deps/src/tests.rs new file mode 100644 index 0000000000..8fc5fdd2fa --- /dev/null +++ b/extensions/javascript/deps/src/tests.rs @@ -0,0 +1,228 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_extension_sdk::ExtensionDeclaration; +use specforge_test::prelude::*; + +/// cyclonedx-npm 7.0.1's BOM of the project `board`, recorded by the Phase 11 research. +const CYCLONEDX_NPM_7_0_1: &str = include_str!("../fixtures/cyclonedx-npm-7.0.1.cdx.json"); +/// The OSV reader's osv-scanner 2.7.1 recording: `Cargo.lock` (smallvec 1.6.0) and `web/package-lock.json` (lodash +/// 4.17.15) of `/project`. +const OSV_SCANNER_2_7_1: &str = include_str!("../../../code/osv/fixtures/osv-scanner-2.7.1.json"); +/// The served `package` facts: `pkg:npm/board` at the root, `pkg:npm/web` at `web`. +const PACKAGES: &str = include_str!("../fixtures/packages.json"); + +/// The input the host sends for these reports, each at `path`, at `/project` with the pack's packages served. +fn input(path: &str, reports: &[&str]) -> CollectInput { + CollectInput { + reports: reports + .iter() + .map(|content| CollectReportFile { + path: path.to_string(), + content: content.to_string(), + }) + .collect(), + cwd: Some("/project".to_string()), + facts: serde_json::from_str(PACKAGES).expect("the served facts parse"), + ..CollectInput::default() + } +} + +/// The process capability of the collector `name`, with no filter. +fn capability(declaration: &ExtensionDeclaration, name: &str) -> Value { + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + let capability = capabilities + .as_array() + .unwrap() + .iter() + .find(|c| c["name"] == name) + .unwrap_or_else(|| panic!("a capability {name}: {capabilities}")) + .clone(); + assert_eq!(capability["port"], "process"); + assert!(capability.get("filter").is_none_or(Value::is_null)); + capability +} + +#[specforge_test(requirement = "FEATURE-147")] +fn javascript_deps_declares_cyclonedx_npm_over_the_lockfile_and_its_peers() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.2", false), + ("@javascript/source", "^1.0", false) + ] + ); + let collector = declaration.collectors.iter().find(|c| c.name == SBOM); + let collector = collector.expect("a collector javascript-sbom"); + let capability = capability(&declaration, SBOM); + assert_eq!(collector.input_formats, ["cyclonedx-json"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["package-lock.json".to_string()][..]) + ); + assert_eq!(collector.answers, ["dependency"]); + assert_eq!(collector.inputs, [Input::facts(&["package"])]); + assert_eq!(collector.report.as_deref(), Some(SBOM_REPORT)); + assert_eq!( + collector.install.as_deref(), + Some("npm install --save-dev @cyclonedx/cyclonedx-npm") + ); + assert_eq!( + capability["argv"], + json!([ + "npx", + "--no", + "--", + "cyclonedx-npm", + "--output-format", + "JSON", + "--spec-version", + "1.6", + "--package-lock-only", + "--output-file", + "{report}" + ]) + ); + assert_eq!( + capability["env"], + json!(["NODE_*", "NPM_CONFIG_*", "npm_config_*", "CI"]) + ); +} + +#[specforge_test(requirement = "FEATURE-147")] +fn a_recorded_cyclonedx_npm_bom_mints_one_dependency_per_component_of_the_root_package() { + let bom = specforge_code_cyclonedx::read(CYCLONEDX_NPM_7_0_1).expect("the recording reads"); + // npm installs `spdx-expression-parse` 3.0.1 and `string-width` 7.2.0 twice, at two paths: one fact each. + let purls: std::collections::BTreeSet<_> = + bom.components.iter().map(|c| c.purl.as_deref()).collect(); + assert_eq!((bom.components.len(), purls.len()), (68, 66)); + let out = collect_sbom(&input(SBOM_REPORT, &[CYCLONEDX_NPM_7_0_1])).unwrap(); + assert_eq!(out.facts.len(), purls.len()); + for fact in &out.facts { + assert_eq!(fact.kind, "dependency"); + assert!(fact.id.starts_with("dep:pkg:npm/board/"), "{}", fact.id); + assert_eq!(fact.fields["package"], "pkg:npm/board"); + } + assert_eq!(out.warnings, Vec::::new()); +} + +#[specforge_test(requirement = "FEATURE-147")] +fn a_bom_about_no_served_package_is_an_error_naming_the_report() { + let other = CYCLONEDX_NPM_7_0_1.replacen( + "\"purl\": \"pkg:npm/board@1.0.0\"", + "\"purl\": \"pkg:npm/elsewhere@1.0.0\"", + 1, + ); + assert_ne!(other, CYCLONEDX_NPM_7_0_1, "the recording names its root"); + let why = collect_sbom(&input(SBOM_REPORT, &[&other])).unwrap_err(); + assert!( + why.starts_with(&format!("{SBOM_REPORT}: ")) && why.contains("names no collected package"), + "{why}" + ); +} + +#[specforge_test(requirement = "FEATURE-147")] +fn zero_or_two_boms_or_a_bad_one_is_the_sbom_collectors_error() { + for reports in [&[][..], &[CYCLONEDX_NPM_7_0_1, CYCLONEDX_NPM_7_0_1][..]] { + let why = collect_sbom(&input(SBOM_REPORT, reports)).unwrap_err(); + assert!(why.contains(SBOM) && why.contains(SBOM_REPORT), "{why}"); + } + let why = collect_sbom(&input(SBOM_REPORT, &["garbage"])).unwrap_err(); + assert!(why.starts_with(&format!("{SBOM_REPORT}: no JSON")), "{why}"); +} + +#[specforge_test(requirement = "FEATURE-147")] +fn javascript_deps_declares_osv_scanner_over_the_lockfile() { + let declaration = crate::specforge_extension_build().declaration(); + let names: Vec<&str> = declaration + .collectors + .iter() + .map(|c| c.name.as_str()) + .collect(); + assert_eq!(names, [SBOM, OSV]); + let collector = &declaration.collectors[1]; + let capability = capability(&declaration, OSV); + assert_eq!(collector.input_formats, ["osv-json"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["package-lock.json".to_string()][..]) + ); + assert_eq!(collector.answers, ["vulnerability"]); + assert_eq!(collector.inputs, [Input::facts(&["package"])]); + assert_eq!(collector.report.as_deref(), Some(OSV_REPORT)); + let install = collector.install.as_deref().expect("an install line"); + assert_eq!( + install, + "go install github.com/google/osv-scanner/v2/cmd/osv-scanner@latest (or: brew install osv-scanner)" + ); + assert!(specforge_protocol_types::is_install_line(install)); + assert_eq!( + capability["argv"], + json!([ + "osv-scanner", + "scan", + "source", + "--lockfile", + "package-lock.json", + "--format", + "json", + "--output-file", + "{report}" + ]) + ); + assert_eq!( + capability["env"], + json!([ + "HTTPS_PROXY", + "HTTP_PROXY", + "NO_PROXY", + "https_proxy", + "http_proxy", + "no_proxy", + "OSV_*" + ]) + ); +} + +#[specforge_test(requirement = "FEATURE-147")] +fn a_recorded_osv_scan_cites_the_npm_package_and_warns_of_each_package_it_skips() { + let out = collect_osv(&input(OSV_REPORT, &[OSV_SCANNER_2_7_1])).unwrap(); + let ids: Vec<&str> = out.facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + [ + "vuln:pkg:npm/web/GHSA-29mw-wpgm-hmr9", + "vuln:pkg:npm/web/GHSA-35jh-r3h4-6jhm", + "vuln:pkg:npm/web/GHSA-p6mc-m468-83gw", + "vuln:pkg:npm/web/GHSA-r5fr-rjxr-66jc", + "vuln:pkg:npm/web/GHSA-xxjr-mmjv-4gpg" + ] + ); + // smallvec of the root Cargo.lock: this pack serves no cargo package, so it is named, not dropped. + assert_eq!( + out.warnings, + ["'smallvec' 1.6.0 in 'Cargo.lock' (2 records) is skipped: no collected pkg:cargo package lies at or \ + under the lockfile's directory"] + ); +} + +#[specforge_test(requirement = "FEATURE-147")] +fn zero_or_two_scans_or_a_bad_one_is_the_osv_collectors_error() { + for reports in [&[][..], &[OSV_SCANNER_2_7_1, OSV_SCANNER_2_7_1][..]] { + let why = collect_osv(&input(OSV_REPORT, reports)).unwrap_err(); + assert!(why.contains(OSV) && why.contains(OSV_REPORT), "{why}"); + } + let why = collect_osv(&input(OSV_REPORT, &["garbage"])).unwrap_err(); + assert!(why.starts_with(&format!("{OSV_REPORT}: no JSON")), "{why}"); + let no_cwd = CollectInput { + cwd: None, + ..input(OSV_REPORT, &[OSV_SCANNER_2_7_1]) + }; + assert!(collect_osv(&no_cwd).unwrap_err().contains("no cwd")); +} diff --git a/extensions/javascript/deps/wasm/inputs.json b/extensions/javascript/deps/wasm/inputs.json new file mode 100644 index 0000000000..9c5ffec64e --- /dev/null +++ b/extensions/javascript/deps/wasm/inputs.json @@ -0,0 +1,95 @@ +{ + "artifact": "specforge_ext_javascript_deps.wasm", + "artifact_sha256": "41f02cb3f267bf5dc7c03daa315aacef52d6dea485f0eeb8d3efd6d91a828363", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/cyclonedx/Cargo.toml": "26066b84a4d10419509350276717b316340d2a60e5c4a75752b2439afa6ea46d", + "extensions/code/cyclonedx/src/lib.rs": "7123dc3e319e203cfa0594bad454f9ca6605b5258163fa63d6a3de643d9a3909", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/code/osv/Cargo.toml": "60be7012d312638636f64a736ead96529b134fc08f3b5aa9f0b481af8eadca17", + "extensions/code/osv/src/lib.rs": "47c587bd88b2fc3d1aa4885aa4d4c3666f59ddbb6a4aff1408a5e06618e0cff9", + "extensions/javascript/deps/Cargo.lock": "4b54c6de4f204c135b08f0b8daa05d0160614a207a8b8f7c16fb655d511991e9", + "extensions/javascript/deps/Cargo.toml": "30dbfd0d94b4e7c183350e94e579f01eb3ea4ef02a279ef0f431aeb6ff208688", + "extensions/javascript/deps/src/lib.rs": "7ae8054e2219effe5644f02f0744b2201f1ad7e2ad4598d84486d4497dfb154f" + } +} diff --git a/extensions/javascript/deps/wasm/specforge_ext_javascript_deps.wasm b/extensions/javascript/deps/wasm/specforge_ext_javascript_deps.wasm new file mode 100644 index 0000000000..a782e9c244 Binary files /dev/null and b/extensions/javascript/deps/wasm/specforge_ext_javascript_deps.wasm differ diff --git a/extensions/javascript/jest/Cargo.lock b/extensions/javascript/jest/Cargo.lock new file mode 100644 index 0000000000..cc04d2eb00 --- /dev/null +++ b/extensions/javascript/jest/Cargo.lock @@ -0,0 +1,576 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-javascript-jest" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-code-junit", + "specforge-extension-sdk", + "specforge-javascript-workspace", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-javascript-workspace" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/javascript/jest/Cargo.toml b/extensions/javascript/jest/Cargo.toml new file mode 100644 index 0000000000..c0e6187924 --- /dev/null +++ b/extensions/javascript/jest/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "specforge-ext-javascript-jest" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-junit = { path = "../../code/junit" } +specforge-code-facts = { path = "../../code/facts" } +specforge-javascript-workspace = { path = "../workspace" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" diff --git a/extensions/javascript/jest/fixtures/README.md b/extensions/javascript/jest/fixtures/README.md new file mode 100644 index 0000000000..6b31b415c6 --- /dev/null +++ b/extensions/javascript/jest/fixtures/README.md @@ -0,0 +1,5 @@ +# @javascript/jest fixtures + +| Fixture | Source | +|---------|--------| +| `jest-30.5.2-jest-junit-17.0.0.junit.xml` | recorded with jest 30.5.2 and jest-junit 17.0.0 by the Phase 11 research through the pack's env file: `node --env-file=jest-junit.env.toml node_modules/jest/bin/jest.js --reporters=default --reporters=jest-junit`, the file holding the pack's six `JEST_JUNIT_*` lines. One file, `test/board.test.js` (the tests serve a root `package.json` named `board`): `describe("board")` holding `describe("inner")` with a passing and a failing test, and a skipped test, then a top-level test. The research directory in the failure's stack trace is replaced by `/project` | diff --git a/extensions/javascript/jest/fixtures/jest-30.5.2-jest-junit-17.0.0.junit.xml b/extensions/javascript/jest/fixtures/jest-30.5.2-jest-junit-17.0.0.junit.xml new file mode 100644 index 0000000000..32e25bdcd4 --- /dev/null +++ b/extensions/javascript/jest/fixtures/jest-30.5.2-jest-junit-17.0.0.junit.xml @@ -0,0 +1,36 @@ + + + + + + + Error: expect(received).toBe(expected) // Object.is equality + +Expected: 2 +Received: 1 + at Object.toBe (/project/test/board.test.js:5:37) + at Promise.finally.completed (/project/node_modules/jest-circus/build/jestAdapterInit.js:1834:28) + at new Promise (<anonymous>) + at callAsyncCircusFn (/project/node_modules/jest-circus/build/jestAdapterInit.js:1774:10) + at _callCircusTest (/project/node_modules/jest-circus/build/jestAdapterInit.js:1167:40) + at _runTestInContext (/project/node_modules/jest-circus/build/jestAdapterInit.js:1103:3) + at runTestWithContext (/project/node_modules/jest-circus/build/jestAdapterInit.js:996:5) + at _runTestsForDescribeBlockOnce (/project/node_modules/jest-circus/build/jestAdapterInit.js:1008:11) + at _runTestsForDescribeBlock (/project/node_modules/jest-circus/build/jestAdapterInit.js:824:5) + at _runTestsForDescribeBlockOnce (/project/node_modules/jest-circus/build/jestAdapterInit.js:1003:11) + at _runTestsForDescribeBlock (/project/node_modules/jest-circus/build/jestAdapterInit.js:824:5) + at _runTestsForDescribeBlockOnce (/project/node_modules/jest-circus/build/jestAdapterInit.js:1003:11) + at _runTestsForDescribeBlock (/project/node_modules/jest-circus/build/jestAdapterInit.js:824:5) + at run (/project/node_modules/jest-circus/build/jestAdapterInit.js:789:3) + at runAndTransformResultsToJestFormat (/project/node_modules/jest-circus/build/jestAdapterInit.js:2300:21) + at jestAdapter (/project/node_modules/jest-circus/build/runner.js:111:19) + at runTestInternal (/project/node_modules/jest-runner/build/index.js:247:16) + at runTest (/project/node_modules/jest-runner/build/index.js:315:7) + + + + + + + + \ No newline at end of file diff --git a/extensions/javascript/jest/src/lib.rs b/extensions/javascript/jest/src/lib.rs new file mode 100644 index 0000000000..93a673d18e --- /dev/null +++ b/extensions/javascript/jest/src/lib.rs @@ -0,0 +1,140 @@ +//! @javascript/jest — runs jest with jest-junit and records its tests as `@code/core`'s test facts (ADR 0389). +//! +//! The collector `javascript-jest` is selected by a `jest.config.*` at the project root. jest writes no JUnit of its +//! own and jest-junit is configured only by a `package.json` key or `JEST_JUNIT_*` variables, and the host runs one +//! argv with no variables of its choosing. So the pack owns a config file the host writes for the run +//! (`.specforge/reports/javascript-jest.jest-junit.env.toml`), and the host runs, with consent, `node +//! --env-file={config} node_modules/jest/bin/jest.js --reporters=default --reporters=jest-junit`: node loads the file +//! into jest's environment. Its six lines are both TOML and dotenv. The host substitutes only `{report}` (escaped for +//! a quoted string, ADR 0348 D2), so `{filepath}`, `{classname}` and `{title}` reach jest-junit as its own +//! placeholders. The command runs in the caller's environment less credentials (ADR 0360 D13): its `env` list is what +//! a guest-run tool would be lent, not a filter. node's `--env-file` never overrides a variable already set, so a +//! `JEST_JUNIT_*` variable the caller set wins over the file's line: it can move the report or change the test ids +//! without an error (`JEST_JUNIT_ANCESTOR_SEPARATOR`, `JEST_JUNIT_CLASSNAME`). Unset them before `specforge collect`. +//! +//! Prerequisites: jest and jest-junit are dev dependencies of the project (a missing jest-junit shows only at run +//! time); `--env-file` needs node 20.6 or later. The route is unverified on Windows (ADR 0389 D12). +//! +//! jest-junit writes each case's project-relative `file` (the config turns the attribute on), its `classname` the +//! describe blocks joined by `" > "` and its `name` the test title. Each test is named +//! `js:/# … > test>`, as `@javascript/node-test` names it (ADR 0329 D2): `` is the +//! nearest named `package.json` at or above the file (`specforge-javascript-workspace`). +//! +//! A caller narrows the run with a filter: the host appends `-t `, and jest matches the text against test +//! names, not SpecForge ids (ADR 0389 D9). + +use specforge_code_facts::{relative, test_facts, TestCase, TestId}; +use specforge_code_junit::{cases, Case}; +use specforge_extension_sdk::prelude::*; +use specforge_javascript_workspace::{packages_input, Workspace}; + +const COLLECTOR: &str = "javascript-jest"; +/// The JUnit report jest-junit writes, relative to the project root. +const REPORT: &str = ".specforge/reports/javascript-jest.xml"; +/// The env file the host writes before the run, `{report}` the report's absolute path (ADR 0348 D2). A config name +/// ends `.toml` or `.json`; node's `--env-file` reads any name. +const CONFIG: &str = "jest-junit.env.toml"; +const TEMPLATE: &str = r#"JEST_JUNIT_OUTPUT_FILE = "{report}" +JEST_JUNIT_ADD_FILE_ATTRIBUTE = "true" +JEST_JUNIT_ANCESTOR_SEPARATOR = " > " +JEST_JUNIT_SUITE_NAME = "{filepath}" +JEST_JUNIT_CLASSNAME = "{classname}" +JEST_JUNIT_TITLE = "{title}" +"#; + +#[specforge_extension_sdk::extension( + name = "@javascript/jest", + version = "1.0.0", + description = "Runs jest with jest-junit and records its tests as test facts (@code/core)" +)] +struct JavascriptJest; + +impl Contributions for JavascriptJest { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.2"); + // Its package.json reads name the packages a test id starts with. + c.peer("@javascript/source", "^1.0"); + c.collector(COLLECTOR, |k| { + k.input_format("junit-xml") + .detect_files(&["jest.config.*"]) + .run(&[ + "node", + "--env-file={config}", + "node_modules/jest/bin/jest.js", + "--reporters=default", + "--reporters=jest-junit", + ]) + .config(CONFIG, TEMPLATE) + .filter(&["-t", "{filter}"]) + .env(&["NODE_*", "CI"]) + .install("npm install --save-dev jest jest-junit") + .report(REPORT) + .input(packages_input()) + .answers(&["test", "test_run"]) + .collect(collect); + }); + } +} + +/// The id of `case` and its project-relative file, the file being its `file` attribute read against `cwd`. The path +/// is `classname` split on `" > "` (nothing for a top-level test), then `name`. +fn id(workspace: &Workspace, cwd: &str, case: &Case) -> Result<(TestId, String), String> { + let written = case.file.as_deref().ok_or_else(|| { + format!( + "jest-junit wrote no file for '{}': its file attribute is off (the pack's config turns \ + JEST_JUNIT_ADD_FILE_ATTRIBUTE on)", + case.name + ) + })?; + let file = relative(written, cwd) + .ok_or_else(|| format!("{written}: the test file is outside the project {cwd}"))?; + let path: Vec = case + .classname + .split(" > ") + .filter(|_| !case.classname.is_empty()) + .chain([case.name.as_str()]) + .map(str::to_string) + .collect(); + let (package, under) = workspace.owner(&file).ok_or_else(|| { + format!( + "{file}: no package.json with a name at or above it; {COLLECTOR} names a test \ + js:/#, so give the package a name" + ) + })?; + let id = TestId::js(&package.segment(), under, &path); + Ok((id, file)) +} + +/// Map jest-junit's report to a `test` and a `test_run` fact per test. A report that is not JUnit, a case with no +/// file, a file outside the project and a test with no named package are the collector's error: a test is never +/// dropped silently. +fn collect(input: &CollectInput) -> Result { + let [report] = &input.reports[..] else { + return Err(format!( + "{COLLECTOR} reads one report, {REPORT}; it was given {}", + input.reports.len() + )); + }; + let found = cases(&report.content).map_err(|why| format!("{}: {why}", report.path))?; + let cwd = input + .cwd + .as_deref() + .ok_or("the host sent no cwd: a jest test file is read against the project root")?; + let workspace = Workspace::of(input); + let named = found + .into_iter() + .map(|case| { + let (id, file) = id(&workspace, cwd, &case)?; + Ok(TestCase::of(id, &case, Some(file))) + }) + .collect::, String>>()?; + Ok(CollectOutput { + facts: test_facts(named), + ..CollectOutput::default() + }) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/javascript/jest/src/tests.rs b/extensions/javascript/jest/src/tests.rs new file mode 100644 index 0000000000..fd2b5222f3 --- /dev/null +++ b/extensions/javascript/jest/src/tests.rs @@ -0,0 +1,220 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_javascript_workspace::PACKAGES; +use specforge_test::prelude::*; + +/// jest 30.5.2 with jest-junit 17.0.0's recorded report through the pack's env file (see `fixtures/README.md`). +const RECORDED: &str = include_str!("../fixtures/jest-30.5.2-jest-junit-17.0.0.junit.xml"); + +/// The input the host sends for these reports read at `cwd`, with these `(path, text)` package files read. +fn input(reports: &[&str], cwd: &str, packages: &[(&str, &str)]) -> CollectInput { + let facts: Vec = packages + .iter() + .map(|(path, text)| json!({"path": path, "exists": true, "text": text})) + .collect(); + let reports: Vec = reports + .iter() + .map(|content| json!({"path": REPORT, "content": content})) + .collect(); + serde_json::from_value(json!({ + "reports": reports, + "cwd": cwd, + "files": {PACKAGES: {"facts": facts}}, + })) + .unwrap() +} + +/// The root package `board`. +const BOARD: &[(&str, &str)] = &[("package.json", r#"{"name":"board"}"#)]; + +/// Each fact's `(kind, id, status)`. +fn summary(out: &CollectOutput) -> Vec<(String, String, String)> { + out.facts + .iter() + .map(|f| { + ( + f.kind.clone(), + f.id.clone(), + f.fields["status"].as_str().unwrap().to_string(), + ) + }) + .collect() +} + +#[specforge_test(requirement = "FEATURE-152")] +fn javascript_jest_declares_jest_through_node_and_its_env_file() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.2", false), + ("@javascript/source", "^1.0", false) + ] + ); + let [collector] = &declaration.collectors[..] else { + panic!("one collector: {:?}", declaration.collectors); + }; + assert_eq!(collector.name, "javascript-jest"); + assert_eq!(collector.input_formats, ["junit-xml"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["jest.config.*".to_string()][..]) + ); + assert_eq!(collector.answers, ["test", "test_run"]); + assert_eq!(collector.inputs, [packages_input()]); + assert_eq!(collector.report.as_deref(), Some(REPORT)); + assert_eq!(collector.capture, None); + assert_eq!( + collector.install.as_deref(), + Some("npm install --save-dev jest jest-junit") + ); + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + assert_eq!(capabilities[0]["name"], COLLECTOR); + assert_eq!(capabilities[0]["port"], "process"); + assert_eq!( + capabilities[0]["argv"], + json!([ + "node", + "--env-file={config}", + "node_modules/jest/bin/jest.js", + "--reporters=default", + "--reporters=jest-junit" + ]), + "{capabilities}" + ); + assert_eq!( + capabilities[0]["config"], + json!({"name": "jest-junit.env.toml", "template": TEMPLATE}) + ); + assert_eq!(capabilities[0]["filter"], json!(["-t", "{filter}"])); + // No `JEST_*`: a variable already in the environment would override the env file's. + assert_eq!(capabilities[0]["env"], json!(["NODE_*", "CI"])); +} + +#[specforge_test(requirement = "FEATURE-152")] +fn the_env_file_sets_jest_junits_six_variables_and_only_report_is_the_hosts() { + assert_eq!( + TEMPLATE.lines().collect::>(), + [ + r#"JEST_JUNIT_OUTPUT_FILE = "{report}""#, + r#"JEST_JUNIT_ADD_FILE_ATTRIBUTE = "true""#, + r#"JEST_JUNIT_ANCESTOR_SEPARATOR = " > ""#, + r#"JEST_JUNIT_SUITE_NAME = "{filepath}""#, + r#"JEST_JUNIT_CLASSNAME = "{classname}""#, + r#"JEST_JUNIT_TITLE = "{title}""#, + ] + ); + // The host's placeholders, `{report}` and `{config}`: only the first, once. + assert_eq!(TEMPLATE.matches("{report}").count(), 1); + assert!(!TEMPLATE.contains("{config}")); +} + +#[specforge_test(requirement = "FEATURE-152")] +fn jests_recorded_report_names_its_tests_by_their_ancestors_then_title() { + let out = collect(&input(&[RECORDED], "/project", BOARD)).unwrap(); + let file = "js:board/test/board.test.js"; + let expected = [ + ("board > inner > adds", "passed", 1), + ("board > inner > fails", "failed", 1), + ("board > skipped", "skipped", 0), + ("top level", "passed", 0), + ]; + assert_eq!( + summary(&out), + expected + .iter() + .flat_map(|(name, status, _)| [ + ( + "test".to_string(), + format!("{file}#{name}"), + status.to_string() + ), + ( + "test_run".to_string(), + format!("run:{file}#{name}"), + status.to_string() + ), + ]) + .collect::>() + ); + for fact in out.facts.iter().filter(|f| f.kind == "test") { + assert_eq!(fact.fields["file"], "test/board.test.js", "{}", fact.id); + } + let top = out + .facts + .iter() + .find(|f| f.id == format!("{file}#top level")); + assert_eq!(top.unwrap().fields["suite"], json!([])); + let durations: Vec<&Value> = out + .facts + .iter() + .filter(|f| f.kind == "test_run") + .map(|f| &f.fields["duration_ms"]) + .collect(); + assert_eq!( + durations, + expected + .map(|(_, _, ms)| json!(ms)) + .iter() + .collect::>() + ); +} + +#[specforge_test(requirement = "FEATURE-152")] +fn a_case_without_a_file_says_jest_junits_file_attribute_is_off() { + let report = r#""#; + assert_eq!( + collect(&input(&[report], "/project", BOARD)).unwrap_err(), + "jest-junit wrote no file for 'adds': its file attribute is off (the pack's config turns \ + JEST_JUNIT_ADD_FILE_ATTRIBUTE on)" + ); +} + +#[specforge_test(requirement = "FEATURE-152")] +fn a_workspace_test_is_named_after_its_nearest_package() { + let packages = [ + ("package.json", r#"{"name":"app"}"#), + ("packages/core/package.json", r#"{"name":"@acme/core"}"#), + ]; + let report = r#" + + "#; + let out = collect(&input(&[report], "/work/app", &packages)).unwrap(); + assert_eq!(out.facts[0].id, "js:@acme/core/test/x.test.js#adds"); + assert_eq!(out.facts[0].fields["file"], "packages/core/test/x.test.js"); +} + +#[specforge_test(requirement = "FEATURE-152")] +fn a_test_no_named_package_owns_or_outside_the_project_is_the_collectors_error() { + let why = collect(&input(&[RECORDED], "/project", &[])).unwrap_err(); + assert_eq!( + why, + "test/board.test.js: no package.json with a name at or above it; javascript-jest names a test \ + js:/#, so give the package a name" + ); + let outside = r#""#; + assert_eq!( + collect(&input(&[outside], "/w", BOARD)).unwrap_err(), + "/elsewhere/a.test.js: the test file is outside the project /w" + ); +} + +#[specforge_test(requirement = "FEATURE-152")] +fn zero_or_two_reports_is_the_collectors_error() { + for reports in [&[][..], &[RECORDED, RECORDED][..]] { + let why = collect(&input(reports, "/project", BOARD)).unwrap_err(); + assert_eq!( + why, + format!( + "javascript-jest reads one report, {REPORT}; it was given {}", + reports.len() + ) + ); + } +} diff --git a/extensions/javascript/jest/wasm/inputs.json b/extensions/javascript/jest/wasm/inputs.json new file mode 100644 index 0000000000..31c936de45 --- /dev/null +++ b/extensions/javascript/jest/wasm/inputs.json @@ -0,0 +1,93 @@ +{ + "artifact": "specforge_ext_javascript_jest.wasm", + "artifact_sha256": "a29c037ad47b2207f9fd98eaeef0599c06267c793e78726781d1ffe4ec1ccff8", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/javascript/jest/Cargo.lock": "dd48026a54d5d8fcafbb5c4c0552c00cbb8ce9c4ba287a9e30982bfbb1d9595c", + "extensions/javascript/jest/Cargo.toml": "6431dd8a7761ccf98054e021f2bc1b5b21209a30de8ecfbca4d6db448d454aa0", + "extensions/javascript/jest/src/lib.rs": "68e942181c02287a4408597acdff8428a80b07574e386da33eab36a2b1de1d94", + "extensions/javascript/workspace/Cargo.toml": "6fe0f3ed1ffd7dc74f67755828ca813c06b3ef5f65e71046b20ce965be21c305", + "extensions/javascript/workspace/src/lib.rs": "bfa9070faa64aed3f7109cfb2c82578e9b4197bfb6aa7a0baaf1de244d3b8560" + } +} diff --git a/extensions/javascript/jest/wasm/specforge_ext_javascript_jest.wasm b/extensions/javascript/jest/wasm/specforge_ext_javascript_jest.wasm new file mode 100644 index 0000000000..afcf1485cd Binary files /dev/null and b/extensions/javascript/jest/wasm/specforge_ext_javascript_jest.wasm differ diff --git a/extensions/javascript/lint/Cargo.lock b/extensions/javascript/lint/Cargo.lock new file mode 100644 index 0000000000..18fd5e5582 --- /dev/null +++ b/extensions/javascript/lint/Cargo.lock @@ -0,0 +1,575 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-sarif" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-javascript-lint" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-code-sarif", + "specforge-extension-sdk", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/javascript/lint/Cargo.toml b/extensions/javascript/lint/Cargo.toml new file mode 100644 index 0000000000..66e3c81562 --- /dev/null +++ b/extensions/javascript/lint/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "specforge-ext-javascript-lint" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-sarif = { path = "../../code/sarif" } +specforge-code-facts = { path = "../../code/facts" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" diff --git a/extensions/javascript/lint/src/lib.rs b/extensions/javascript/lint/src/lib.rs new file mode 100644 index 0000000000..29c2bf05d4 --- /dev/null +++ b/extensions/javascript/lint/src/lib.rs @@ -0,0 +1,88 @@ +//! @javascript/lint — runs ESLint with its SARIF formatter and records its findings as `@code/core`'s +//! `static_finding` facts (ADR 0389). +//! +//! The collector `javascript-lint` is selected by an `eslint.config.*` at the project root: the project's own flat +//! config decides the rules. The host runs, with consent, `npx --no -- eslint --format +//! @microsoft/eslint-formatter-sarif --output-file {report} .`. `npx --no` never downloads anything: ESLint and the +//! formatter must be dev dependencies of the project. ESLint loads the project's config and its plugins, which are +//! code the project chose (ADR 0389 D9). ESLint exits 1 when it finds problems and still writes the report; the host +//! does not judge the exit code (ADR 0348 D4), it reads the report. +//! +//! The SARIF is read by `specforge-code-sarif` and minted by `specforge-code-facts` against `@javascript/source`'s +//! items: one `static_finding` per result, citing the innermost item holding its line, else the package holding its +//! file. A result in a file outside the project is skipped and counted, and the pack returns one warning naming the +//! report and the paths, which the host shows as W203 (ADR 0389 D7); a result whose path names no file (the project +//! root itself) is skipped and named in a warning of its own. + +use specforge_code_facts::{finding_facts, no_file_line, outside_line}; +use specforge_extension_sdk::prelude::*; + +const COLLECTOR: &str = "javascript-lint"; +/// The SARIF ESLint writes, relative to the project root. +const REPORT: &str = ".specforge/reports/javascript-lint.sarif"; + +#[specforge_extension_sdk::extension( + name = "@javascript/lint", + version = "1.0.0", + description = "Runs ESLint with its SARIF formatter and records its findings as static_finding facts (@code/core)" +)] +struct JavascriptLint; + +impl Contributions for JavascriptLint { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.2"); + // Its items and packages place each finding; without them a finding cites nothing. + c.peer("@javascript/source", "^1.0"); + c.collector(COLLECTOR, |k| { + k.input_format("sarif") + .detect_files(&["eslint.config.*"]) + // No filter: a filtered run lints part of the project. + .run(&[ + "npx", + "--no", + "--", + "eslint", + "--format", + "@microsoft/eslint-formatter-sarif", + "--output-file", + "{report}", + ".", + ]) + .env(&["NODE_*", "ESLINT_*", "CI"]) + .install("npm install --save-dev eslint @microsoft/eslint-formatter-sarif") + .report(REPORT) + .input(Input::facts(&["item", "package"])) + .answers(&["static_finding"]) + .collect(collect); + }); + } +} + +/// Map ESLint's SARIF to `static_finding` facts, and the paths it skipped, outside the project or naming no file, to a +/// warning each. +fn collect(input: &CollectInput) -> Result { + let [report] = &input.reports[..] else { + return Err(format!( + "{COLLECTOR} reads one report, {REPORT}; it was given {}", + input.reports.len() + )); + }; + let cwd = input.cwd.as_deref().ok_or( + "the host sent no cwd: ESLint's SARIF names absolute file: URIs, read against the project root", + )?; + let sarif = specforge_code_sarif::read(&report.content, cwd) + .map_err(|why| format!("{}: {why}", report.path))?; + Ok(CollectOutput { + facts: finding_facts(&sarif.results, &input.facts), + warnings: outside_line(&report.path, &sarif.outside) + .into_iter() + .chain(no_file_line(&report.path, &sarif.no_file)) + .collect(), + ..CollectOutput::default() + }) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/javascript/lint/src/tests.rs b/extensions/javascript/lint/src/tests.rs new file mode 100644 index 0000000000..9e3e045726 --- /dev/null +++ b/extensions/javascript/lint/src/tests.rs @@ -0,0 +1,154 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_test::prelude::*; + +/// The SARIF reader's ESLint 10.15.0 recording: `src/board view.js` of the package `board` at `/project`. +const ESLINT_10_15: &str = include_str!("../../../code/sarif/fixtures/eslint-10.15.0.sarif"); +/// The SARIF reader's served facts for that recording, as JSON. +const ITEMS: &str = include_str!("../../../code/sarif/fixtures/eslint-10.15.0.items.json"); +/// The SARIF reader's accepted snapshot of the facts `ESLINT_10_15` mints with `ITEMS` served. +const ESLINT_10_15_FACTS: &str = include_str!( + "../../../code/sarif/src/snapshots/specforge_code_sarif__tests__eslint_10_15.snap" +); + +/// The input the host sends for these reports at `/project`, the reader's items served. +fn input(reports: &[&str]) -> CollectInput { + CollectInput { + reports: reports + .iter() + .map(|content| CollectReportFile { + path: REPORT.to_string(), + content: content.to_string(), + }) + .collect(), + cwd: Some("/project".to_string()), + facts: serde_json::from_str(ITEMS).expect("the served facts parse"), + ..CollectInput::default() + } +} + +/// The JSON body of an insta snapshot, after its `---` header. +fn snapshot(text: &str) -> Value { + let body = text.splitn(3, "---\n").nth(2).expect("a snapshot body"); + serde_json::from_str(body).expect("the snapshot parses") +} + +#[specforge_test(requirement = "FEATURE-145")] +fn javascript_lint_declares_eslint_with_the_sarif_formatter_and_its_peers() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.2", false), + ("@javascript/source", "^1.0", false) + ] + ); + let [collector] = &declaration.collectors[..] else { + panic!("one collector: {:?}", declaration.collectors); + }; + assert_eq!(collector.name, COLLECTOR); + assert_eq!(collector.input_formats, ["sarif"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["eslint.config.*".to_string()][..]) + ); + assert_eq!(collector.answers, ["static_finding"]); + assert_eq!(collector.inputs, [Input::facts(&["item", "package"])]); + assert_eq!(collector.report.as_deref(), Some(REPORT)); + assert_eq!( + collector.install.as_deref(), + Some("npm install --save-dev eslint @microsoft/eslint-formatter-sarif") + ); + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + assert_eq!(capabilities[0]["name"], COLLECTOR); + assert_eq!(capabilities[0]["port"], "process"); + assert_eq!( + capabilities[0]["argv"], + json!([ + "npx", + "--no", + "--", + "eslint", + "--format", + "@microsoft/eslint-formatter-sarif", + "--output-file", + "{report}", + "." + ]), + "{capabilities}" + ); + assert_eq!(capabilities[0]["env"], json!(["NODE_*", "ESLINT_*", "CI"])); + assert!(capabilities[0].get("filter").is_none_or(Value::is_null)); +} + +#[specforge_test(requirement = "FEATURE-145")] +fn an_eslint_report_mints_the_readers_static_findings_and_no_warning() { + let out = collect(&input(&[ESLINT_10_15])).unwrap(); + assert_eq!( + serde_json::to_value(&out.facts).unwrap(), + snapshot(ESLINT_10_15_FACTS) + ); + assert_eq!(out.warnings, Vec::::new()); +} + +#[specforge_test(requirement = "FEATURE-145")] +fn a_result_outside_the_project_is_skipped_with_one_warning() { + let outside = ESLINT_10_15.replacen( + "file:///project/src/board%20view.js\",\n \"index\": 1", + "file:///elsewhere/vendor.js\",\n \"index\": 1", + 1, + ); + assert_ne!(outside, ESLINT_10_15, "the recording names its file by uri"); + let out = collect(&input(&[&outside])).unwrap(); + let rules: Vec<&str> = out + .facts + .iter() + .map(|f| f.fields["rule"].as_str().unwrap_or_default()) + .collect(); + assert_eq!(rules, ["no-undef", "no-console", "eqeqeq"]); + assert_eq!( + out.warnings, + [format!( + "{REPORT}: skipped 1 file(s) outside the project: /elsewhere/vendor.js" + )] + ); +} + +#[specforge_test(requirement = "FEATURE-145")] +fn a_result_naming_no_file_is_skipped_with_its_own_warning() { + let rooted = ESLINT_10_15.replacen( + "file:///project/src/board%20view.js\",\n \"index\": 1", + "file:///project\",\n \"index\": 1", + 1, + ); + assert_ne!(rooted, ESLINT_10_15, "the recording names its file by uri"); + let out = collect(&input(&[&rooted])).unwrap(); + assert_eq!(out.facts.len(), 3, "{:?}", out.facts); + assert_eq!( + out.warnings, + [format!( + "{REPORT}: skipped 1 path(s) naming no file: /project" + )] + ); +} + +#[specforge_test(requirement = "FEATURE-145")] +fn zero_or_two_reports_or_a_bad_one_is_the_collectors_error() { + for reports in [&[][..], &[ESLINT_10_15, ESLINT_10_15][..]] { + let why = collect(&input(reports)).unwrap_err(); + assert!(why.contains(COLLECTOR) && why.contains(REPORT), "{why}"); + } + let why = collect(&input(&["garbage"])).unwrap_err(); + assert!(why.starts_with(&format!("{REPORT}: no JSON")), "{why}"); + let no_cwd = CollectInput { + cwd: None, + ..input(&[ESLINT_10_15]) + }; + assert!(collect(&no_cwd).unwrap_err().contains("no cwd")); +} diff --git a/extensions/javascript/lint/wasm/inputs.json b/extensions/javascript/lint/wasm/inputs.json new file mode 100644 index 0000000000..c1ca601606 --- /dev/null +++ b/extensions/javascript/lint/wasm/inputs.json @@ -0,0 +1,93 @@ +{ + "artifact": "specforge_ext_javascript_lint.wasm", + "artifact_sha256": "f3e3bd3325b546dd30dce0742d3001ddb2d00cabfd93b129005c9bbce430b688", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/code/sarif/Cargo.toml": "b344b54dbd7e76f934c2489cd059b46855d865711d403962da2baf35b1a45fe9", + "extensions/code/sarif/src/lib.rs": "3c8ec851ae444069ff720310d58178879121a01d1fb4eb54a1753e22bd407b0f", + "extensions/javascript/lint/Cargo.lock": "e43596d76828b2ab30b522e6821c3a8d18088385315f5f557c45b9bf73c01f28", + "extensions/javascript/lint/Cargo.toml": "fe01540dae00fca5c1585dcad97b398d85262c2e0b61acb711ce1235d3b78efe", + "extensions/javascript/lint/src/lib.rs": "edad17ee9bfd04f7bf41fe1bf0c22d30a47362b949f40ae2b349ce71fe76d0c9" + } +} diff --git a/extensions/javascript/lint/wasm/specforge_ext_javascript_lint.wasm b/extensions/javascript/lint/wasm/specforge_ext_javascript_lint.wasm new file mode 100644 index 0000000000..45a8da723e Binary files /dev/null and b/extensions/javascript/lint/wasm/specforge_ext_javascript_lint.wasm differ diff --git a/extensions/javascript/node-test/src/lib.rs b/extensions/javascript/node-test/src/lib.rs index dfa754b609..f198e6fa69 100644 --- a/extensions/javascript/node-test/src/lib.rs +++ b/extensions/javascript/node-test/src/lib.rs @@ -13,8 +13,8 @@ //! runner pack names a test alike: an entity cites a test by its id, and `@code/core` checks the reference. A test //! fact's `file` is the project-relative path (ADR 0347 D8). -use specforge_code_facts::{test_facts, TestCase, TestId}; -use specforge_code_junit::{cases, relative, Case}; +use specforge_code_facts::{relative, test_facts, TestCase, TestId}; +use specforge_code_junit::{cases, Case}; use specforge_extension_sdk::prelude::*; use specforge_javascript_workspace::{packages_input, Workspace}; diff --git a/extensions/javascript/node-test/wasm/inputs.json b/extensions/javascript/node-test/wasm/inputs.json index 286e27d071..533d721789 100644 --- a/extensions/javascript/node-test/wasm/inputs.json +++ b/extensions/javascript/node-test/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "specforge_ext_javascript_node_test.wasm", - "artifact_sha256": "a1ac345d8954f902f82b6aee52dd9849a1453454563e3286277a77bfe402e9e2", + "artifact_sha256": "7f9a34dd438f2dc4b5905f5b28d5c3aad1db559fa82daea2d41efbd63c30001f", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,29 +55,38 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", - "extensions/code/facts/src/ids.rs": "e3f1f07f70da4786c0ca0b301594b1dc812c2a45808dbe1a5f4905805eccce97", - "extensions/code/facts/src/lib.rs": "5a9733980787f23265ab7f374840d6f61bf2ecbdad3471df86e68c0f2e699769", - "extensions/code/facts/src/mint.rs": "e71f130aaeaeeca2d4c5afa59a36c60fa5ac8bc26db2f4a8276c71024305925e", - "extensions/code/facts/src/paths.rs": "890973baefd07c33e93c6c12ae882083c2d969de91bb3c697bc271ec03474eae", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", - "extensions/code/junit/src/lib.rs": "dfeb44e386f4865b2c5570d389bfd6ff246ccf69122ee36ec7feb9db8a394f35", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", "extensions/javascript/node-test/Cargo.lock": "792148965fbe218ea426a5616fe96900a422779caed4bf48a27774ceb07ec0e3", "extensions/javascript/node-test/Cargo.toml": "6af05b564d44cf575dac2c7811c92578d181f77171253b47178ccd7cfd17a512", - "extensions/javascript/node-test/src/lib.rs": "08274fcfe9627d656cb70f8e954a8dab3dc6e80a365952746f7493fcfea930f6", + "extensions/javascript/node-test/src/lib.rs": "5b3231fbfda5bff8fd7d9c5ff5e524edc85a636b8e32dc8e8f24d65af7da838c", "extensions/javascript/workspace/Cargo.toml": "6fe0f3ed1ffd7dc74f67755828ca813c06b3ef5f65e71046b20ce965be21c305", "extensions/javascript/workspace/src/lib.rs": "bfa9070faa64aed3f7109cfb2c82578e9b4197bfb6aa7a0baaf1de244d3b8560" } diff --git a/extensions/javascript/node-test/wasm/specforge_ext_javascript_node_test.wasm b/extensions/javascript/node-test/wasm/specforge_ext_javascript_node_test.wasm index 2362e2ea54..4a75a86a5e 100644 Binary files a/extensions/javascript/node-test/wasm/specforge_ext_javascript_node_test.wasm and b/extensions/javascript/node-test/wasm/specforge_ext_javascript_node_test.wasm differ diff --git a/extensions/javascript/playwright/Cargo.lock b/extensions/javascript/playwright/Cargo.lock new file mode 100644 index 0000000000..0c4c19f5e7 --- /dev/null +++ b/extensions/javascript/playwright/Cargo.lock @@ -0,0 +1,576 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-javascript-playwright" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-code-junit", + "specforge-extension-sdk", + "specforge-javascript-workspace", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-javascript-workspace" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/javascript/playwright/Cargo.toml b/extensions/javascript/playwright/Cargo.toml new file mode 100644 index 0000000000..d32afd3b83 --- /dev/null +++ b/extensions/javascript/playwright/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "specforge-ext-javascript-playwright" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-junit = { path = "../../code/junit" } +specforge-code-facts = { path = "../../code/facts" } +specforge-javascript-workspace = { path = "../workspace" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" diff --git a/extensions/javascript/playwright/fixtures/README.md b/extensions/javascript/playwright/fixtures/README.md new file mode 100644 index 0000000000..5bdca6d57f --- /dev/null +++ b/extensions/javascript/playwright/fixtures/README.md @@ -0,0 +1,5 @@ +# @javascript/playwright fixtures + +| Fixture | Source | +|---------|--------| +| `playwright-1.65.1.junit.xml` | recorded with Playwright 1.65.1 by the Phase 11 research from standard output: `npx playwright test --reporter=junit` with `testDir: './test'`, so the one file `test/board.spec.js` is written `board.spec.js` (the tests serve a root `package.json` named `board`): `describe("board")` holding `describe("inner")` with a passing and a failing test, and a skipped test, then a top-level test. The research directory in the failure's stack trace is replaced by `/project` | diff --git a/extensions/javascript/playwright/fixtures/playwright-1.65.1.junit.xml b/extensions/javascript/playwright/fixtures/playwright-1.65.1.junit.xml new file mode 100644 index 0000000000..b38683a1eb --- /dev/null +++ b/extensions/javascript/playwright/fixtures/playwright-1.65.1.junit.xml @@ -0,0 +1,43 @@ + + + + + + + + + + { + 5 | test('adds', async () => { expect(new Board().add(1).cards.length).toBe(1); }); + > 6 | test('fails', async () => { expect(1).toBe(2); }); + | ^ + 7 | }); + 8 | test.skip('skipped', async () => {}); + 9 | }); + at /project/test/board.spec.js:6:43 + + Error Context: ../test-results/board-board-inner-fails/error-context.md +]]> + + + + + + + + + + + + + + diff --git a/extensions/javascript/playwright/src/lib.rs b/extensions/javascript/playwright/src/lib.rs new file mode 100644 index 0000000000..2569c3cbd4 --- /dev/null +++ b/extensions/javascript/playwright/src/lib.rs @@ -0,0 +1,134 @@ +//! @javascript/playwright — runs Playwright and records its tests as `@code/core`'s test facts (ADR 0389). +//! +//! The collector `javascript-playwright` is selected by a `playwright.config.*` at the project root. The host runs, +//! with consent, `npx --no -- playwright test --reporter=junit`, its artifacts kept under +//! `.specforge/reports/javascript-playwright-results` instead of the project's `test-results`. Playwright writes its +//! JUnit to standard output unless told a file, so the host captures it into +//! `.specforge/reports/javascript-playwright/javascript-playwright.stdout.txt` and passes it as +//! `CollectInput::stdout`; `specforge collect --report ` passes a saved report as the one report instead. The +//! command runs in the caller's environment less credentials (ADR 0360 D13): its `env` list is what a guest-run tool +//! would be lent, not a filter, so every `PLAYWRIGHT_*` variable the caller set reaches the run. +//! `PLAYWRIGHT_JUNIT_OUTPUT_NAME` and its kin move the report off standard output, where the collect reads it; unset +//! them before `specforge collect`. `npx --no` never downloads anything: `@playwright/test` +//! must be a dev dependency of the project, its browsers installed. +//! +//! Each case's `classname` is its file and its `name` the describe blocks then the test title joined by `" › "` +//! (U+203A). Each test is named `js:/# … > test>`, as `@javascript/node-test` names it (ADR +//! 0329 D2), `` the nearest named `package.json` at or above the file. Playwright's file names are relative +//! to the config's `testDir`, not to the project: a test in `tests/a.spec.ts` with `testDir: "tests"` is named +//! `a.spec.ts`, and its package is the one that owns `a.spec.ts` read from the project root (ADR 0389 D9, accepted). +//! +//! A caller narrows the run with a filter: the host appends `--grep `, and Playwright matches the text against +//! test titles, not SpecForge ids (ADR 0389 D9). + +use specforge_code_facts::{relative, test_facts, TestCase, TestId}; +use specforge_code_junit::{cases, Case}; +use specforge_extension_sdk::prelude::*; +use specforge_javascript_workspace::{packages_input, Workspace}; + +const COLLECTOR: &str = "javascript-playwright"; +/// The report directory, relative to the project root: the host keeps the captured standard output in it. +const REPORT: &str = ".specforge/reports/javascript-playwright"; +/// Where the host keeps the captured standard output: `/.stdout.txt`. +const CAPTURE: &str = ".specforge/reports/javascript-playwright/javascript-playwright.stdout.txt"; + +#[specforge_extension_sdk::extension( + name = "@javascript/playwright", + version = "1.0.0", + description = "Runs Playwright and records its tests as test facts (@code/core)" +)] +struct JavascriptPlaywright; + +impl Contributions for JavascriptPlaywright { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.2"); + // Its package.json reads name the packages a test id starts with. + c.peer("@javascript/source", "^1.0"); + c.collector(COLLECTOR, |k| { + k.input_format("junit-xml") + .detect_files(&["playwright.config.*"]) + .run(&[ + "npx", + "--no", + "--", + "playwright", + "test", + "--reporter=junit", + "--output=.specforge/reports/javascript-playwright-results", + ]) + .filter(&["--grep", "{filter}"]) + .env(&["NODE_*", "PLAYWRIGHT_BROWSERS_PATH", "CI"]) + .install("npm install --save-dev @playwright/test") + .report(REPORT) + .capture_stdout() + .input(packages_input()) + .answers(&["test", "test_run"]) + .collect(collect); + }); + } +} + +/// The id of `case` and its file, the file being its `classname` (relative to Playwright's `testDir`). The path is +/// `name` split on `" › "`. +fn id(workspace: &Workspace, cwd: &str, case: &Case) -> Result<(TestId, String), String> { + if case.classname.is_empty() { + return Err(format!( + "Playwright's JUnit reporter wrote no classname (the test file) for '{}'", + case.name + )); + } + let file = relative(&case.classname, cwd).ok_or_else(|| { + format!( + "{}: the test file is outside the project {cwd}", + case.classname + ) + })?; + let path: Vec = case.name.split(" \u{203a} ").map(str::to_string).collect(); + let (package, under) = workspace.owner(&file).ok_or_else(|| { + format!( + "{file}: no package.json with a name at or above it; {COLLECTOR} names a test \ + js:/#, so give the package a name" + ) + })?; + let id = TestId::js(&package.segment(), under, &path); + Ok((id, file)) +} + +/// Map Playwright's captured JUnit (else the one report given) to a `test` and a `test_run` fact per test. A text +/// that is not JUnit, a file outside the project and a test with no named package are the collector's error: a test +/// is never dropped silently. +fn collect(input: &CollectInput) -> Result { + let (path, text) = match (&input.stdout, &input.reports[..]) { + (Some(stdout), _) => (CAPTURE, stdout.as_str()), + (None, [report]) => (report.path.as_str(), report.content.as_str()), + (None, reports) => { + return Err(format!( + "{COLLECTOR}: Playwright's standard output was not captured, and it reads one report in its \ + place; it was given {}", + reports.len() + )) + } + }; + let found = cases(text).map_err(|why| format!("{path}: {why}"))?; + let cwd = input + .cwd + .as_deref() + .ok_or("the host sent no cwd: a Playwright test file is read against the project root")?; + let workspace = Workspace::of(input); + let named = found + .into_iter() + .map(|case| { + let (id, file) = id(&workspace, cwd, &case)?; + Ok(TestCase::of(id, &case, Some(file))) + }) + .collect::, String>>()?; + Ok(CollectOutput { + facts: test_facts(named), + ..CollectOutput::default() + }) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/javascript/playwright/src/tests.rs b/extensions/javascript/playwright/src/tests.rs new file mode 100644 index 0000000000..98de84f004 --- /dev/null +++ b/extensions/javascript/playwright/src/tests.rs @@ -0,0 +1,176 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_javascript_workspace::PACKAGES; +use specforge_test::prelude::*; + +/// Playwright 1.65.1's recorded standard output (see `fixtures/README.md`): one file, `board.spec.js`, relative to +/// the config's `testDir`. +const RECORDED: &str = include_str!("../fixtures/playwright-1.65.1.junit.xml"); + +/// The input the host sends at `/project`: `stdout` as captured, these report files, these `(path, text)` package +/// files read. +fn input(stdout: Option<&str>, reports: &[&str], packages: &[(&str, &str)]) -> CollectInput { + let facts: Vec = packages + .iter() + .map(|(path, text)| json!({"path": path, "exists": true, "text": text})) + .collect(); + let reports: Vec = reports + .iter() + .map(|content| json!({"path": "saved/playwright.xml", "content": content})) + .collect(); + serde_json::from_value(json!({ + "stdout": stdout, + "reports": reports, + "cwd": "/project", + "files": {PACKAGES: {"facts": facts}}, + })) + .unwrap() +} + +/// The root package `board`. +const BOARD: &[(&str, &str)] = &[("package.json", r#"{"name":"board"}"#)]; + +/// Each fact's `(kind, id, status)`. +fn summary(out: &CollectOutput) -> Vec<(String, String, String)> { + out.facts + .iter() + .map(|f| { + ( + f.kind.clone(), + f.id.clone(), + f.fields["status"].as_str().unwrap().to_string(), + ) + }) + .collect() +} + +#[specforge_test(requirement = "FEATURE-153")] +fn javascript_playwright_declares_playwright_with_its_stdout_captured() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.2", false), + ("@javascript/source", "^1.0", false) + ] + ); + let [collector] = &declaration.collectors[..] else { + panic!("one collector: {:?}", declaration.collectors); + }; + assert_eq!(collector.name, "javascript-playwright"); + assert_eq!(collector.input_formats, ["junit-xml"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["playwright.config.*".to_string()][..]) + ); + assert_eq!(collector.answers, ["test", "test_run"]); + assert_eq!(collector.inputs, [packages_input()]); + assert_eq!(collector.report.as_deref(), Some(REPORT)); + assert_eq!(collector.capture.as_deref(), Some("stdout")); + assert_eq!( + collector.install.as_deref(), + Some("npm install --save-dev @playwright/test") + ); + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + assert_eq!(capabilities[0]["name"], COLLECTOR); + assert_eq!(capabilities[0]["port"], "process"); + assert_eq!( + capabilities[0]["argv"], + json!([ + "npx", + "--no", + "--", + "playwright", + "test", + "--reporter=junit", + "--output=.specforge/reports/javascript-playwright-results" + ]), + "{capabilities}" + ); + assert_eq!(capabilities[0]["filter"], json!(["--grep", "{filter}"])); + // Not `PLAYWRIGHT_*`: `PLAYWRIGHT_JUNIT_OUTPUT_NAME` would move the report off standard output. + assert_eq!( + capabilities[0]["env"], + json!(["NODE_*", "PLAYWRIGHT_BROWSERS_PATH", "CI"]) + ); +} + +#[specforge_test(requirement = "FEATURE-153")] +fn playwrights_captured_report_names_its_tests_by_their_title_path() { + let out = collect(&input(Some(RECORDED), &[], BOARD)).unwrap(); + let file = "js:board/board.spec.js"; + let expected = [ + ("board > inner > adds", "passed"), + ("board > inner > fails", "failed"), + ("board > skipped", "skipped"), + ("top level", "passed"), + ]; + assert_eq!( + summary(&out), + expected + .iter() + .flat_map(|(name, status)| [ + ( + "test".to_string(), + format!("{file}#{name}"), + status.to_string() + ), + ( + "test_run".to_string(), + format!("run:{file}#{name}"), + status.to_string() + ), + ]) + .collect::>() + ); + let adds = &out.facts[0]; + assert_eq!(adds.fields["suite"], json!(["board", "inner"])); + assert_eq!(adds.fields["name"], "adds"); + // The file as Playwright writes it: relative to its testDir, not the project (ADR 0389 D9). + assert_eq!(adds.fields["file"], "board.spec.js"); + assert_eq!(out.facts[1].fields["duration_ms"], 2); + // The skipped case carries no time attribute: its run has no duration. + let skipped = &out.facts[5]; + assert_eq!(skipped.kind, "test_run"); + assert!(!skipped.fields.contains_key("duration_ms"), "{skipped:?}"); +} + +#[specforge_test(requirement = "FEATURE-153")] +fn one_saved_report_reads_as_the_captured_stdout() { + let captured = collect(&input(Some(RECORDED), &[], BOARD)).unwrap(); + let saved = collect(&input(None, &[RECORDED], BOARD)).unwrap(); + assert_eq!(summary(&saved), summary(&captured)); +} + +#[specforge_test(requirement = "FEATURE-153")] +fn no_capture_and_not_one_report_is_the_collectors_error() { + for reports in [&[][..], &[RECORDED, RECORDED][..]] { + let why = collect(&input(None, reports, BOARD)).unwrap_err(); + assert_eq!( + why, + format!( + "javascript-playwright: Playwright's standard output was not captured, and it reads one report \ + in its place; it was given {}", + reports.len() + ) + ); + } + let why = collect(&input(Some("Error: no tests found"), &[], BOARD)).unwrap_err(); + assert!(why.starts_with(&format!("{CAPTURE}: ")), "{why}"); +} + +#[specforge_test(requirement = "FEATURE-153")] +fn a_test_no_named_package_owns_is_the_collectors_error() { + let why = collect(&input(Some(RECORDED), &[], &[])).unwrap_err(); + assert_eq!( + why, + "board.spec.js: no package.json with a name at or above it; javascript-playwright names a test \ + js:/#, so give the package a name" + ); +} diff --git a/extensions/javascript/playwright/wasm/inputs.json b/extensions/javascript/playwright/wasm/inputs.json new file mode 100644 index 0000000000..971a72e165 --- /dev/null +++ b/extensions/javascript/playwright/wasm/inputs.json @@ -0,0 +1,93 @@ +{ + "artifact": "specforge_ext_javascript_playwright.wasm", + "artifact_sha256": "a0b5a549d9605c12b39b3afc8b889ad6eb00f9b029102a288bfc3478b45f5ef5", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/javascript/playwright/Cargo.lock": "841a3f7c50bfa47d7fdc34a7ecdb6969517d1959460c4fa2dc5836afa2e9d351", + "extensions/javascript/playwright/Cargo.toml": "9443fe8bf9a31adae83a99b001c0fc2172578dcb3618db9e2b6c9bcf44af0a14", + "extensions/javascript/playwright/src/lib.rs": "cae1bb204730191b12db187e3c1ab217a25c1c5e68780ca49fc9797dbf74ea1a", + "extensions/javascript/workspace/Cargo.toml": "6fe0f3ed1ffd7dc74f67755828ca813c06b3ef5f65e71046b20ce965be21c305", + "extensions/javascript/workspace/src/lib.rs": "bfa9070faa64aed3f7109cfb2c82578e9b4197bfb6aa7a0baaf1de244d3b8560" + } +} diff --git a/extensions/javascript/playwright/wasm/specforge_ext_javascript_playwright.wasm b/extensions/javascript/playwright/wasm/specforge_ext_javascript_playwright.wasm new file mode 100644 index 0000000000..1f612c728b Binary files /dev/null and b/extensions/javascript/playwright/wasm/specforge_ext_javascript_playwright.wasm differ diff --git a/extensions/javascript/source/queries/js-tests.scm b/extensions/javascript/source/queries/js-tests.scm new file mode 100644 index 0000000000..b512fa6940 --- /dev/null +++ b/extensions/javascript/source/queries/js-tests.scm @@ -0,0 +1,111 @@ +; @javascript/source: the test calls of a JavaScript or TypeScript test file, for the host's syntax import (ADR 0393 D4). +; Run only on test files. Read by the typescript grammar (.ts .mts .cts) and the tsx grammar (.tsx .js .jsx .mjs .cjs). +; +; Captures (the tags convention, ADR 0344 D1: each pattern has exactly one role capture): +; @definition.test a call of `test` or `it`, or of one of their members (`test.skip`, `it.concurrent`) +; @definition.suite a call of `describe` or `suite`, or of one of their members; a call that a runner's member +; call returns (`test.each([…])("n %s", fn)`) +; @definition.subtest a call `.test(…)`: the pack counts it only inside a test +; @name the first argument, when it is a string or a template: the call's name is static +; @part that string's or template's fragments and escape sequences, in order: the pack decodes them +; @dynamic a template's substitution: the name is not static +; @modifier `skip`, `todo` or `only` called on `test`, `it`, `describe` or `suite` +; @callback a function written as an argument after the first +; @skip_option an options object argument with a `skip` key (`{ skip: true }`, `{ skip }`): node may skip it +; A capture whose name starts with _ only feeds a predicate. +; +; Every call of a runner's name matches its plain pattern, whatever its arguments, so a call with a dynamic name still +; holds the calls inside it (the pack mints nothing under it); the matches of one call merge in the pack. A member +; call other than skip, todo and only (`.each`, `.concurrent`) gets no @name: it is never minted. + +; ---------------------------------------------------------------- test, it +((call_expression function: (identifier) @_callee) @definition.test + (#any-of? @_callee "test" "it")) +((call_expression function: (identifier) @_callee + arguments: (arguments . (string [(string_fragment) (escape_sequence)]* @part) @name)) @definition.test + (#any-of? @_callee "test" "it")) +((call_expression function: (identifier) @_callee + arguments: (arguments . (template_string [(string_fragment) (escape_sequence)]* @part) @name)) @definition.test + (#any-of? @_callee "test" "it")) +((call_expression function: (identifier) @_callee + arguments: (arguments . (template_string (template_substitution) @dynamic))) @definition.test + (#any-of? @_callee "test" "it")) +((call_expression function: (identifier) @_callee + arguments: (arguments . (_) [(arrow_function) (function_expression) (generator_function)] @callback)) @definition.test + (#any-of? @_callee "test" "it")) + +; ---------------------------------------------------------------- test.skip, it.todo, test.only, it.concurrent, … +((call_expression function: (member_expression object: (identifier) @_callee)) @definition.test + (#any-of? @_callee "test" "it")) +((call_expression function: (member_expression object: (identifier) @_callee property: (property_identifier) @modifier) + arguments: (arguments . (string [(string_fragment) (escape_sequence)]* @part) @name)) @definition.test + (#any-of? @_callee "test" "it") (#any-of? @modifier "skip" "todo" "only")) +((call_expression function: (member_expression object: (identifier) @_callee property: (property_identifier) @modifier) + arguments: (arguments . (template_string [(string_fragment) (escape_sequence)]* @part) @name)) @definition.test + (#any-of? @_callee "test" "it") (#any-of? @modifier "skip" "todo" "only")) +((call_expression function: (member_expression object: (identifier) @_callee property: (property_identifier) @modifier) + arguments: (arguments . (template_string (template_substitution) @dynamic))) @definition.test + (#any-of? @_callee "test" "it") (#any-of? @modifier "skip" "todo" "only")) + +; ---------------------------------------------------------------- describe, suite +((call_expression function: (identifier) @_callee) @definition.suite + (#any-of? @_callee "describe" "suite")) +((call_expression function: (identifier) @_callee + arguments: (arguments . (string [(string_fragment) (escape_sequence)]* @part) @name)) @definition.suite + (#any-of? @_callee "describe" "suite")) +((call_expression function: (identifier) @_callee + arguments: (arguments . (template_string [(string_fragment) (escape_sequence)]* @part) @name)) @definition.suite + (#any-of? @_callee "describe" "suite")) +((call_expression function: (identifier) @_callee + arguments: (arguments . (template_string (template_substitution) @dynamic))) @definition.suite + (#any-of? @_callee "describe" "suite")) + +; ---------------------------------------------------------------- describe.skip, suite.only, describe.concurrent, … +((call_expression function: (member_expression object: (identifier) @_callee)) @definition.suite + (#any-of? @_callee "describe" "suite")) +((call_expression function: (member_expression object: (identifier) @_callee property: (property_identifier) @modifier) + arguments: (arguments . (string [(string_fragment) (escape_sequence)]* @part) @name)) @definition.suite + (#any-of? @_callee "describe" "suite") (#any-of? @modifier "skip" "todo" "only")) +((call_expression function: (member_expression object: (identifier) @_callee property: (property_identifier) @modifier) + arguments: (arguments . (template_string [(string_fragment) (escape_sequence)]* @part) @name)) @definition.suite + (#any-of? @_callee "describe" "suite") (#any-of? @modifier "skip" "todo" "only")) +((call_expression function: (member_expression object: (identifier) @_callee property: (property_identifier) @modifier) + arguments: (arguments . (template_string (template_substitution) @dynamic))) @definition.suite + (#any-of? @_callee "describe" "suite") (#any-of? @modifier "skip" "todo" "only")) + +; ---------------------------------------------------------------- test.each([…])(…), describe.skip.each`…`(…) +((call_expression function: (call_expression + function: (member_expression object: [(identifier) @_callee (member_expression object: (identifier) @_callee)]))) + @definition.suite + (#any-of? @_callee "test" "it" "describe" "suite")) + +; ---------------------------------------------------------------- t.test (a subtest) +((call_expression function: (member_expression object: (identifier) property: (property_identifier) @_method)) @definition.subtest + (#eq? @_method "test")) +((call_expression function: (member_expression object: (identifier) property: (property_identifier) @_method) + arguments: (arguments . (string [(string_fragment) (escape_sequence)]* @part) @name)) @definition.subtest + (#eq? @_method "test")) +((call_expression function: (member_expression object: (identifier) property: (property_identifier) @_method) + arguments: (arguments . (template_string [(string_fragment) (escape_sequence)]* @part) @name)) @definition.subtest + (#eq? @_method "test")) +((call_expression function: (member_expression object: (identifier) property: (property_identifier) @_method) + arguments: (arguments . (template_string (template_substitution) @dynamic))) @definition.subtest + (#eq? @_method "test")) +((call_expression function: (member_expression object: (identifier) property: (property_identifier) @_method) + arguments: (arguments . (_) [(arrow_function) (function_expression) (generator_function)] @callback)) + @definition.subtest + (#eq? @_method "test")) + +; ---------------------------------------------------------------- { skip: … } options +((call_expression function: [(identifier) @_callee (member_expression object: (identifier) @_callee)] + arguments: (arguments (object [(pair key: (property_identifier) @_key) (pair key: (string (string_fragment) @_key)) + (shorthand_property_identifier) @_key]) @skip_option)) @definition.test + (#any-of? @_callee "test" "it") (#eq? @_key "skip")) +((call_expression function: [(identifier) @_callee (member_expression object: (identifier) @_callee)] + arguments: (arguments (object [(pair key: (property_identifier) @_key) (pair key: (string (string_fragment) @_key)) + (shorthand_property_identifier) @_key]) @skip_option)) @definition.suite + (#any-of? @_callee "describe" "suite") (#eq? @_key "skip")) +((call_expression function: (member_expression object: (identifier) property: (property_identifier) @_method) + arguments: (arguments (object [(pair key: (property_identifier) @_key) (pair key: (string (string_fragment) @_key)) + (shorthand_property_identifier) @_key]) @skip_option)) @definition.subtest + (#eq? @_method "test") (#eq? @_key "skip")) diff --git a/extensions/javascript/source/src/calls.rs b/extensions/javascript/source/src/calls.rs new file mode 100644 index 0000000000..26adf9ffe8 --- /dev/null +++ b/extensions/javascript/source/src/calls.rs @@ -0,0 +1,208 @@ +//! A test file's test calls as definitions (ADR 0393 D4). +//! +//! The matches of one call merge into one [`Call`] (`queries/js-tests.scm` matches a call once per pattern that names +//! it). A call is counted when its name is static and not empty (its first argument a string, or a template with no +//! substitution: node names an empty one `` or after its function) and it is a `describe` or `suite`, a +//! `test` or `it` with `skip`, `todo` or `only` or a function argument, or a subtest `.test(…)` with a function +//! argument inside a test. It is minted when it and every call around it are counted and no call around it is skipped: +//! a call with a dynamic name (`.each`, `.concurrent` included) mints nothing, nor anything inside it, and raises +//! nothing; node never runs a skipped call's function, so nothing inside it is a test. A minted call is a `function` +//! item with the attribute `test`, its path the names of the calls around it, outermost first, then its own. +//! +//! node's JUnit report writes a test or a suite as a `` exactly when a test, suite or subtest ran inside it, +//! and as a `` otherwise: a `describe` with nothing inside, one with no function, and any `.skip` call are +//! test cases. So a minted call carries the test id node-test mints from the same path ([`TestId::js`]) when it is +//! called with `.skip`, or when no runner call sits inside it, minted or not (a subtest with a dynamic name, a +//! function reference or only options still makes its parent a ``). A call whose options may skip it +//! (`{ skip: … }`) and that holds runner calls carries none: whether node reports it or what it holds is decided when +//! it runs. Shortcut: a subtest a helper registers out of the call's span (`await check(t)`) is not seen, so that test +//! keeps an id node reports as a suite; upgrade if X2 names such a test missing in a real project. + +use specforge_code_facts::{location, Definition, ItemId, ItemKind, Names, TestId, Visibility}; +use specforge_extension_sdk::host::{SyntaxMatch, SyntaxRole, SyntaxSpan}; +use specforge_javascript_workspace::Package; + +use crate::items::decoded; + +/// What a call is, as the query's `@definition.` names it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Role { + Test, + Suite, + Subtest, +} + +impl Role { + fn of(kind: &str) -> Option { + Some(match kind { + "test" => Role::Test, + "suite" => Role::Suite, + "subtest" => Role::Subtest, + _ => return None, + }) + } +} + +/// One call: every match of its span, merged. +struct Call { + span: SyntaxSpan, + role: Role, + /// Its first argument's value, when that is a string or a template. + literal: Option, + /// Its template has a substitution. + dynamic: bool, + modifier: bool, + /// Called with `.skip`: node never runs its function. + skip: bool, + /// An options argument has a `skip` key: node may skip it. + skip_option: bool, + callback: bool, + /// The index of the innermost call whose span holds this one. + parent: Option, +} + +impl Call { + fn merge(&mut self, found: &SyntaxMatch) { + let named = |name: &'static str| found.captures.iter().filter(move |c| c.name == name); + // A quantified capture may match more than once: the first match naming the call gives its parts. + if self.literal.is_none() && named("name").next().is_some() { + self.literal = Some(decoded(&named("part").collect::>())); + } + self.dynamic |= named("dynamic").next().is_some(); + self.modifier |= named("modifier").next().is_some(); + self.skip |= named("modifier").any(|c| c.text == "skip"); + self.skip_option |= named("skip_option").next().is_some(); + self.callback |= named("callback").next().is_some(); + } + + /// Its name when static and not empty. + fn name(&self) -> Option<&str> { + self.literal + .as_deref() + .filter(|name| !self.dynamic && !name.is_empty()) + } +} + +/// The test calls of a file as merged calls, in source order (the reader sorts matches by start, then by end +/// descending, so the matches of one call are adjacent and a holder comes before what it holds). +fn calls(matches: &[SyntaxMatch]) -> Vec { + let mut calls: Vec = Vec::new(); + let mut open: Vec = Vec::new(); + let found = matches + .iter() + .filter(|m| m.role == SyntaxRole::Definition) + .filter_map(|m| Some((Role::of(&m.kind)?, m))); + for (role, found) in found { + let (start, end) = (found.span.start.byte, found.span.end.byte); + if let Some(last) = calls + .last_mut() + .filter(|c| (c.span.start.byte, c.span.end.byte) == (start, end)) + { + last.merge(found); + continue; + } + while let Some(&top) = open.last() { + let held = calls[top].span; + if held.start.byte <= start && end <= held.end.byte { + break; + } + open.pop(); + } + let mut call = Call { + span: found.span, + role, + literal: None, + dynamic: false, + modifier: false, + skip: false, + skip_option: false, + callback: false, + parent: open.last().copied(), + }; + call.merge(found); + open.push(calls.len()); + calls.push(call); + } + calls +} + +/// Whether the call `at` counts as a test or a suite on its own, whatever is around it. +fn counted(calls: &[Call], at: usize) -> bool { + let call = &calls[at]; + call.name().is_some() + && match call.role { + Role::Suite => true, + Role::Test => call.modifier || call.callback, + Role::Subtest => { + call.callback && call.parent.is_some_and(|p| calls[p].role != Role::Suite) + } + } +} + +/// Whether the call `at` may register a test node under the call around it when that one runs, minted or not: any +/// test or suite call, and a subtest call inside a test (in a suite's body `.test(…)` is no subtest). +fn registers(calls: &[Call], at: usize) -> bool { + let call = &calls[at]; + call.parent.is_some_and(|parent| match call.role { + Role::Test | Role::Suite => true, + Role::Subtest => calls[parent].role != Role::Suite, + }) +} + +/// The test calls of `file` (project-relative; `under` the directory of `package`, which owns it), parsed as +/// `matches` by the test query. +pub(crate) fn read( + package: &Package, + file: &str, + under: &str, + matches: &[SyntaxMatch], +) -> Vec { + let calls = calls(matches); + let segment = package.segment(); + // Each call's path when minted; a holder comes before what it holds. + let mut paths: Vec>> = Vec::with_capacity(calls.len()); + let mut holds = vec![false; calls.len()]; + let top: Vec = Vec::new(); + for (at, call) in calls.iter().enumerate() { + let around = match call.parent { + // node never runs a skipped call's function: nothing inside it is a test. + Some(parent) if calls[parent].skip || calls[parent].skip_option => None, + Some(parent) => paths[parent].as_ref(), + None => Some(&top), + }; + let path = around + .zip(call.name()) + .filter(|_| counted(&calls, at)) + .map(|(around, name)| { + let mut path = around.clone(); + path.push(name.to_string()); + path + }); + if let Some(parent) = call.parent.filter(|_| registers(&calls, at)) { + holds[parent] = true; + } + paths.push(path); + } + calls + .iter() + .zip(paths) + .enumerate() + .filter_map(|(at, (call, path))| { + let path = path?; + let leaf = call.skip || !holds[at]; + Some(Definition { + id: ItemId::js(&segment, under, &path), + package: package.id.clone(), + kind: ItemKind::Function, + visibility: Visibility::js(false), + file: file.to_string(), + at: location(file, call.span.start, call.span.end), + signature: None, + doc: None, + attrs: vec!["test".to_string()], + names: Names::new(), + test_id: leaf.then(|| TestId::js(&segment, under, &path)), + }) + }) + .collect() +} diff --git a/extensions/javascript/source/src/files.rs b/extensions/javascript/source/src/files.rs index 735ba25301..387bf87d49 100644 --- a/extensions/javascript/source/src/files.rs +++ b/extensions/javascript/source/src/files.rs @@ -3,11 +3,13 @@ //! The host lists the project's files of each source extension (one `files` read per extension: a glob has no //! alternation). A listed file is read when a package the pack reads owns it ([`Workspace::owner`]: a file under none //! is outside the pack, as a `.rs` file no crate reaches is outside `@rust/source`) and its path inside that package is -//! neither a test file (a runner pack holds the tests; their helpers are no API) nor generated output. A package is -//! read unless its `package.json`, inside the package above it or the project, is a test's or generated output's -//! ([`read_packages`]). The kept files of one grammar are +//! neither a test file (a runner pack holds the tests; their helpers are no API) nor generated output ([`kept`]). A +//! test file that `node --test` runs by default, not generated output, is parsed too, with the test query, for its +//! test calls only, when its package is the one node-test names it after ([`tested`], ADR 0393 D4): a test file of a +//! package the pack does not read gives no item. A package is read unless its `package.json`, inside the package above +//! it or the project, is a test's or generated output's ([`read_packages`]). The selected files of one grammar are //! parsed in one request, the files an answer's cap left unparsed asked again. A listing the host truncated is -//! replaced, for its extension, by a parse of its glob whose answer the same rules filter. +//! replaced, for its extension, by a parse of its glob whose answer the same selection filters. use std::collections::{BTreeMap, BTreeSet}; @@ -18,7 +20,7 @@ use specforge_extension_sdk::host::{ use specforge_extension_sdk::prelude::*; use specforge_javascript_workspace::{Package, Workspace}; -use crate::{COLLECTOR, QUERY}; +use crate::COLLECTOR; /// The grammar of TypeScript (`.ts .mts .cts`, a `.d.ts` too): its `x` cast parses only there. pub(crate) const TYPESCRIPT: &str = "typescript"; @@ -125,6 +127,35 @@ pub(crate) fn kept(workspace: &Workspace, path: &str) -> bool { .is_some_and(|(_, under)| readable(under)) } +/// Whether `node --test` runs the project-relative `path` by default (node 23.6 and later, whose type stripping runs +/// `.ts .mts .cts`): `*.test.*`, `*-test.*`, `*_test.*`, `test-*.*`, `test.*`, or any file under a `test` directory, +/// of an extension node runs. node-test is the runner whose ids the test calls carry. +fn node_runs(path: &str) -> bool { + let (dirs, name) = split(path); + let Some((stem, extension)) = name.rsplit_once('.') else { + return false; + }; + ["js", "cjs", "mjs", "ts", "mts", "cts"].contains(&extension) + && ([".test", "-test", "_test"] + .iter() + .any(|suffix| stem.ends_with(suffix)) + || stem.starts_with("test-") + || stem == "test" + || dirs.contains(&"test")) +} + +/// Whether the pack reads the project-relative `path` for its test calls: `node --test` runs it, a package the pack +/// reads (`workspace`) owns it and is the one node-test names it after (the owner among `all` the named packages, a +/// fixture's under a test directory included), and the path inside that package is a test file and not generated +/// output. +pub(crate) fn tested(workspace: &Workspace, all: &Workspace, path: &str) -> bool { + let named = all.owner(path).map(|(package, _)| &package.dir); + node_runs(path) + && workspace.owner(path).is_some_and(|(package, under)| { + named == Some(&package.dir) && is_test(under) && !is_generated(under) + }) +} + /// `workspace` without the packages the pack does not read: one whose `package.json`, inside the nearest package the /// pack reads above it (from the project root when there is none), is not readable (a fixture under `tests/`, a copy /// under `build/`), and so every package below it; their files are read by no package. @@ -157,8 +188,16 @@ pub(crate) struct Parsed { pub matches: Vec, } -/// Every kept file of the project's listings, parsed, by path. -pub(crate) fn parsed(input: &CollectInput, workspace: &Workspace) -> Result, String> { +/// Every file of the project's listings that `select` ([`kept`] or [`tested`]) accepts, parsed with `query`, by path. +/// A file the reader could not parse (one the fs port withholds included) is the collector's error when `warnings` is +/// `None` (a kept source file: the pack reads every one or none), else a warning naming it and no item (a test file: +/// its test calls are best-effort, and a test call never minted is never missing). +pub(crate) fn parsed( + input: &CollectInput, + select: &dyn Fn(&str) -> bool, + query: &str, + mut warnings: Option<&mut Vec>, +) -> Result, String> { let mut by_language: BTreeMap<&str, Vec> = BTreeMap::new(); let mut globbed = Vec::new(); for listing in &LISTINGS { @@ -172,7 +211,7 @@ pub(crate) fn parsed(input: &CollectInput, workspace: &Workspace) -> Result Result SyntaxRequest { +/// `files` in `language`, read from the project root with `query`. +fn request(language: &str, files: SyntaxFiles, query: &str) -> SyntaxRequest { SyntaxRequest { source: SyntaxSource::Worktree { root: "project".to_string(), }, files, language: language.to_string(), - query: QUERY.to_string(), + query: query.to_string(), } } -/// `file`'s matches; `None` for a file deleted since the listing. A file the reader could not parse otherwise (one -/// the fs port withholds included) is the collector's error, never an item dropped. -fn answered(file: SyntaxFile) -> Result, String> { - match file.outcome { - SyntaxOutcome::Parsed { matches, .. } => Ok(Some(Parsed { +/// `file`'s matches; `None` for a file deleted since the listing. A file the reader could not parse otherwise is the +/// collector's error, or with `warnings` a warning naming it ([`parsed`]). +fn answered( + file: SyntaxFile, + warnings: Option<&mut Vec>, +) -> Result, String> { + match (file.outcome, warnings) { + (SyntaxOutcome::Parsed { matches, .. }, _) => Ok(Some(Parsed { path: file.path, matches, })), - SyntaxOutcome::NotParsed { - reason: NotParsed::Missing, - } => Ok(None), - SyntaxOutcome::NotParsed { reason } => Err(format!( + ( + SyntaxOutcome::NotParsed { + reason: NotParsed::Missing, + }, + _, + ) => Ok(None), + (SyntaxOutcome::NotParsed { reason }, Some(warnings)) => { + warnings.push(format!( + "{}: the host's reader did not parse this test file ({}); {COLLECTOR} reads no test call from it", + file.path, + reason.name() + )); + Ok(None) + } + (SyntaxOutcome::NotParsed { reason }, None) => Err(format!( "{}: the host's reader did not parse it ({}); {COLLECTOR} reads every kept source file or none", file.path, reason.name() @@ -230,9 +285,14 @@ fn answered(file: SyntaxFile) -> Result, String> { /// The files of `request` that `keep` accepts, every one parsed whatever the answer's cap ([`parse_all`]): a glob's /// walk stopped short is the collector's error, as is a file whose matches alone pass the cap. -fn all_parsed(request: SyntaxRequest, keep: impl Fn(&str) -> bool) -> Result, String> { - parse_all(COLLECTOR, request, keep)? - .into_iter() - .filter_map(|file| answered(file).transpose()) - .collect() +fn all_parsed( + request: SyntaxRequest, + keep: impl Fn(&str) -> bool, + mut warnings: Option<&mut Vec>, +) -> Result, String> { + let mut parsed = Vec::new(); + for file in parse_all(COLLECTOR, request, keep)? { + parsed.extend(answered(file, warnings.as_deref_mut())?); + } + Ok(parsed) } diff --git a/extensions/javascript/source/src/items.rs b/extensions/javascript/source/src/items.rs index cec2d230da..4a935933b6 100644 --- a/extensions/javascript/source/src/items.rs +++ b/extensions/javascript/source/src/items.rs @@ -162,7 +162,7 @@ impl<'m> Group<'m> { /// A string's value from its fragments and escape sequences, as the grammar splits it: each escape decoded /// (`\'` is `'`, `\u{41}` is `A`, a line continuation nothing), and a surrogate pair written as two `\u` escapes /// one character (`\uD83D\uDE00` is `😀`), as JavaScript reads it. A lone surrogate keeps its escaped text. -fn decoded(parts: &[&SyntaxCapture]) -> String { +pub(crate) fn decoded(parts: &[&SyntaxCapture]) -> String { let mut value = String::new(); // A high surrogate's escape whose low half may follow: its code unit and its text. let mut high: Option<(u32, &str)> = None; @@ -180,7 +180,8 @@ fn decoded(parts: &[&SyntaxCapture]) -> String { match (escape, unit) { (_, Some(first @ 0xD800..=0xDBFF)) => high = Some((first, &part.text)), (Some(escape), _) => value.push_str(&unescaped(escape)), - (None, _) => value.push_str(&part.text), + // A template's line end is a line feed in its value, a CRLF's or a lone CR's alike (a string has none). + (None, _) => value.push_str(&part.text.replace("\r\n", "\n").replace('\r', "\n")), } } if let Some((_, text)) = high { diff --git a/extensions/javascript/source/src/lib.rs b/extensions/javascript/source/src/lib.rs index e943efeb04..b01b97c41f 100644 --- a/extensions/javascript/source/src/lib.rs +++ b/extensions/javascript/source/src/lib.rs @@ -11,7 +11,13 @@ //! `js:/::[.]` ([`items`]), minted by `specforge-code-facts`; every named package becomes //! a `pkg:npm/` package fact, the target of its items' `package` ([`packages`]). A second package of one name is //! `pkg:npm/#`, its items `js:@/…` (`specforge-javascript-workspace`). +//! +//! A test file is parsed with the test query (`queries/js-tests.scm`) for its test calls only (ADR 0393 D4): each +//! statically named `test`, `it`, `describe` or `suite` call, and each subtest, is a `function` item with the +//! attribute `test`, and a call node reports as a test case carries the test id node-test mints for it ([`calls`]). +//! Its helpers are no item. +mod calls; mod files; mod items; mod packages; @@ -23,6 +29,8 @@ use specforge_javascript_workspace::{packages_input, Workspace}; const COLLECTOR: &str = "javascript-source"; /// The pack's query, compiled by the host's reader for either grammar. const QUERY: &str = include_str!("../queries/js-tags.scm"); +/// The test query, run on test files only. +const TESTS: &str = include_str!("../queries/js-tests.scm"); #[specforge_extension_sdk::extension( name = "@javascript/source", @@ -53,20 +61,29 @@ impl Contributions for JavascriptSource { } } -/// Every item of every kept source file, and every named package, as facts. +/// Every item of every kept source file, every test call of every test file, and every named package, as facts; a +/// test file the reader could not parse is a warning, a source file the collector's error ([`files::parsed`]). fn collect(input: &CollectInput) -> Result { - let workspace = files::read_packages(Workspace::of(input)); - let parsed = files::parsed(input, &workspace)?; + let all = Workspace::of(input); + let workspace = files::read_packages(all.clone()); let mut definitions = Vec::new(); - for file in &parsed { + for file in files::parsed(input, &|path| files::kept(&workspace, path), QUERY, None)? { if let Some((package, under)) = workspace.owner(&file.path) { definitions.extend(items::read(package, &file.path, under, &file.matches)); } } + let tested = |path: &str| files::tested(&workspace, &all, path); + let mut warnings = Vec::new(); + for file in files::parsed(input, &tested, TESTS, Some(&mut warnings))? { + if let Some((package, under)) = workspace.owner(&file.path) { + definitions.extend(calls::read(package, &file.path, under, &file.matches)); + } + } let mut facts = item_facts(definitions); facts.extend(packages::facts(&workspace)); Ok(CollectOutput { facts, + warnings, ..CollectOutput::default() }) } diff --git a/extensions/javascript/source/src/tests.rs b/extensions/javascript/source/src/tests.rs index 1ee6af8f6e..af6e5d1079 100644 --- a/extensions/javascript/source/src/tests.rs +++ b/extensions/javascript/source/src/tests.rs @@ -17,6 +17,7 @@ use specforge_test::prelude::*; use super::*; use crate::files::LISTINGS; +mod calls; mod keep; mod marks; mod names; @@ -302,7 +303,7 @@ fn a_file_is_read_by_the_grammar_its_extension_names() { } #[specforge_test(requirement = "FEATURE-056")] -fn a_test_file_is_never_parsed() { +fn a_test_file_is_parsed_only_for_its_test_calls() { let files = [ APP, ("src/a.js", "export const a = 1;\n"), @@ -318,11 +319,30 @@ fn a_test_file_is_never_parsed() { ("tests/g.ts", "function helper() {}\n"), ("src/__tests__/h.jsx", "function helper() {}\n"), ("src/__mocks__/i.cjs", "function helper() {}\n"), + ("src/k.test.ts", "function helper() {}\n"), + ("src/l.test.tsx", "function helper() {}\n"), + ("test/m.jsx", "function helper() {}\n"), + ("src/test.n.js", "function helper() {}\n"), ]; let (out, asked) = run(host(&files), &[]); + // The source files with the pack's query, then the test files `node --test` runs with the test query: a helper + // is no item. A test file node does not run by default (`.spec.`, `tests/`, `__tests__/`, `__mocks__/`, `.tsx`, + // `.jsx`, `test.n.js`) is read by neither query. + let tests = [ + "src/a.test.js", + "src/c-test.js", + "src/d_test.mjs", + "src/test-e.js", + "src/test.js", + "test/f.js", + ]; assert_eq!( asked_paths(&asked), - [("tsx", vec!["attest/x.js", "src/a.js", "src/latest.js"])] + [ + ("tsx", vec!["attest/x.js", "src/a.js", "src/latest.js"]), + ("tsx", tests.to_vec()), + ("typescript", vec!["src/k.test.ts"]), + ] ); assert_eq!( items(&out.unwrap()), @@ -386,10 +406,15 @@ fn a_truncated_listing_parses_its_glob_and_filters_the_answer() { ("src/c.ts", "export const c = 1;\n"), ("vendor.min.js", "var a=1;\n"), ]; + // The glob is parsed twice: for the source files, then for the test files' test calls. let (out, asked) = run(host(&files), &["js"]); assert_eq!( asked_paths(&asked), - [("typescript", vec!["src/c.ts"]), ("tsx", vec!["**/*.js"])] + [ + ("typescript", vec!["src/c.ts"]), + ("tsx", vec!["**/*.js"]), + ("tsx", vec!["**/*.js"]) + ] ); assert_eq!( items(&out.unwrap()), @@ -410,7 +435,9 @@ fn a_truncated_listing_parses_its_glob_and_filters_the_answer() { [ ("typescript", vec!["src/c.ts"]), ("tsx", vec!["**/*.js"]), - ("tsx", vec!["src/b.js"]) + ("tsx", vec!["src/b.js"]), + ("tsx", vec!["**/*.js"]), + ("tsx", vec!["src/a.test.js"]) ] ); assert_eq!(items(&out.unwrap()).len(), 3); diff --git a/extensions/javascript/source/src/tests/calls.rs b/extensions/javascript/source/src/tests/calls.rs new file mode 100644 index 0000000000..d5bc6e6307 --- /dev/null +++ b/extensions/javascript/source/src/tests/calls.rs @@ -0,0 +1,362 @@ +//! A test file's test calls: each statically named one an item with the attribute `test`, a test case carrying the id +//! node-test mints for it (ADR 0393 D4). + +use specforge_code_facts::TestId; + +use super::*; + +/// The taskboard fixture's test file and the JUnit report node recorded running it. +const TASKBOARD_TESTS: &str = + include_str!("../../../../../gsd/parity/fixtures/taskboard/test/tasks.test.js"); +const TASKBOARD_JUNIT: &str = include_str!("../../../../../gsd/parity/goldens/taskboard/junit.xml"); + +/// `(attrs, test_id)` of the item `id`. +fn marks(facts: &[Fact], id: &str) -> (Value, Option) { + let fact = item(facts, id); + ( + fact.fields["attrs"].clone(), + fact.fields.get("test_id").cloned(), + ) +} + +/// The value of the attribute `name` in an XML element's text. +fn attribute<'x>(element: &'x str, name: &str) -> &'x str { + let start = element.find(&format!(" {name}=\"")).expect("the attribute") + name.len() + 3; + let len = element[start..].find('"').expect("its closing quote"); + &element[start..start + len] +} + +#[specforge_test(requirement = "FEATURE-056")] +fn the_taskboards_test_calls_carry_the_ids_node_test_mints() { + let package = ("package.json", r#"{"name":"taskboard"}"#); + let source = ("src/tasks.js", "export function addTask() {}\n"); + let alone = run(host(&[package, source]), &[]).0.unwrap(); + let facts = run( + host(&[package, source, ("test/tasks.test.js", TASKBOARD_TESTS)]), + &[], + ) + .0 + .unwrap(); + // node-test's ids, from the recorded report: a top-level test's path is its name. + let node_ids: Vec = TASKBOARD_JUNIT + .split(" = items(&facts) + .into_iter() + .filter(|id| id.starts_with("js:taskboard/test/")) + .collect(); + assert_eq!( + tests, + [ + "js:taskboard/test/tasks.test.js::a task is added with the next id", + "js:taskboard/test/tasks.test.js::a task is completed by its id", + "js:taskboard/test/tasks.test.js::completing an unknown id throws", + ] + ); + for (id, node_id) in tests.iter().zip(&node_ids) { + assert_eq!(item(&facts, id).fields["kind"], json!(["function"]), "{id}"); + assert_eq!( + marks(&facts, id), + (json!(["test"]), Some(json!(node_id))), + "{id}" + ); + } + // The source file's items are what they are without the test file. + let source_items = |facts: &[Fact]| -> Vec { + facts + .iter() + .filter(|f| f.id.starts_with("js:taskboard/src/")) + .cloned() + .collect() + }; + assert_eq!(source_items(&facts), source_items(&alone)); + assert_eq!(items(&alone), ["js:taskboard/src/tasks.js::addTask"]); +} + +/// Each item of the package `app`'s file `file` holding `text`, with its test id: every one has the attribute `test`. +fn tests_in(file: &str, text: &str) -> Vec<(String, Option)> { + let facts = collected(&[(file, text)]); + items(&facts) + .into_iter() + .map(|id| { + let (attrs, test_id) = marks(&facts, id); + assert_eq!(attrs, json!(["test"]), "{id}"); + ( + id.to_string(), + test_id.map(|t| t.as_str().unwrap().to_string()), + ) + }) + .collect() +} + +/// `(item id, test id)` of `test/b.test.js` of the package `app`, by the item's path. +fn test_item(path: &str, test_id: Option<&str>) -> (String, Option) { + ( + format!("js:app/test/b.test.js::{path}"), + test_id.map(|name| format!("js:app/test/b.test.js#{name}")), + ) +} + +#[specforge_test(requirement = "FEATURE-056")] +fn a_suite_names_its_tests_and_carries_no_test_id() { + let text = r#" +import { describe, it } from "node:test"; +describe("board", () => { + describe("inner", () => { + it("adds", () => {}); + }); +}); +"#; + assert_eq!( + tests_in("test/b.test.js", text), + [ + test_item("board", None), + test_item("board.inner", None), + test_item("board.inner.adds", Some("board > inner > adds")), + ] + ); +} + +#[specforge_test(requirement = "FEATURE-056")] +fn a_test_with_a_subtest_carries_no_test_id() { + let text = r#" +test("parent", async (t) => { + await t.test("child", () => {}); + assert.ok(/x/.test("x")); +}); +"#; + assert_eq!( + tests_in("test/b.test.js", text), + [ + test_item("parent", None), + test_item("parent.child", Some("parent > child")), + ] + ); +} + +#[specforge_test(requirement = "FEATURE-056")] +fn the_runner_shorthands_are_tests() { + let text = r#" +test.skip("s"); +test.todo("t"); +it.only("o", () => {}); +describe.skip("d", () => {}); +"#; + assert_eq!( + tests_in("test/b.test.js", text), + [ + test_item("d", Some("d")), + test_item("o", Some("o")), + test_item("s", Some("s")), + test_item("t", Some("t")), + ] + ); +} + +/// A test file and the `` paths `node --test --test-reporter=junit` (node v26.13.0) wrote running it, each +/// path's names joined by ` > `: a `` is never among them. +const NODE_FILE: &str = r#"const { test, it, describe, suite } = require("node:test"); +test("dyn", async (t) => { for (const n of ["a"]) await t.test(n, () => {}); }); +test("ref", async (t) => { await t.test("x", fnRef); }); +function fnRef() {} +test("opt", async (t) => { await t.test("q", { skip: true }); }); +test("nocbsub", async (t) => { await t.test("w"); }); +describe.skip("ds", () => { it("inner", () => {}); }); +test.skip("ts", async (t) => { await t.test("sub", () => {}); }); +test.todo("tt", async (t) => { await t.test("tsub", () => {}); }); +describe.todo("dt", () => { it("dtinner", () => {}); }); +describe("empty", () => {}); +describe("nocb"); +suite("suitenocb"); +test(""); +test("", () => {}); +describe("", () => { it("inanon", () => {}); }); +test("nested plain", async () => { test("np child", () => {}); }); +test("nested it", async () => { await it("ni child", () => {}); }); +test("optskip", { skip: true }, async (t) => { await t.test("os child", () => {}); }); +describe("doptskip", { skip: true }, () => { it("dos child", () => {}); }); +test("leafskip", { "skip": "why" }, () => {}); +test("opttodo", { todo: true }, async (t) => { await t.test("ot child", () => {}); }); +test("no callback"); +test.todo("todo nocb"); +describe("only holder", () => { it.only("o1", () => {}); it("o2", () => {}); }); +test("crlf\ +cont", () => {}); +test("u \u0041", () => {}); +test(`tpl +line`, () => {}); +it.skip("itskip", () => { it("never"); }); +"#; +const NODE_CASES: [&str; 28] = [ + "dyn > a", + "ref > x", + "opt > q", + "nocbsub > w", + "ds", + "ts", + "tt > tsub", + "dt > dtinner", + "empty", + "nocb", + "suitenocb", + "", + "", + " > inanon", + "nested plain > np child", + "nested it > ni child", + "optskip", + "doptskip", + "leafskip", + "opttodo > ot child", + "no callback", + "todo nocb", + "only holder > o1", + "only holder > o2", + "crlfcont", + "u A", + "tpl\nline", + "itskip", +]; + +#[specforge_test(requirement = "FEATURE-056")] +fn every_test_id_is_a_test_case_node_reports() { + let found = tests_in("test/b.test.js", NODE_FILE); + let path = |id: &str| { + id.strip_prefix("js:app/test/b.test.js#") + .expect("the file's test id") + .to_string() + }; + for (item, test_id) in &found { + if let Some(test_id) = test_id { + assert!( + NODE_CASES.contains(&path(test_id).as_str()), + "{item}: node reports no {test_id}" + ); + } + } + assert_eq!( + found, + [ + test_item("crlfcont", Some("crlfcont")), + // A suite holding nothing, or with no function, is a test case; one holding a test is a suite. + test_item("doptskip", None), + test_item("ds", Some("ds")), + test_item("dt", None), + test_item("dt.dtinner", Some("dt > dtinner")), + // A test whose subtest is not minted (a dynamic name, a function reference, options only, no function) + // is a suite all the same. + test_item("dyn", None), + test_item("empty", Some("empty")), + test_item("itskip", Some("itskip")), + test_item("leafskip", Some("leafskip")), + test_item("nested it", None), + test_item("nested it.ni child", Some("nested it > ni child")), + test_item("nested plain", None), + test_item("nested plain.np child", Some("nested plain > np child")), + test_item("nocb", Some("nocb")), + test_item("nocbsub", None), + test_item("only holder", None), + test_item("only holder.o1", Some("only holder > o1")), + test_item("only holder.o2", Some("only holder > o2")), + test_item("opt", None), + // Options that may skip it: whether it or what it holds is reported is decided when it runs. + test_item("optskip", None), + // A todo test runs its function: what it holds is reported. + test_item("opttodo", None), + test_item("opttodo.ot child", Some("opttodo > ot child")), + test_item("ref", None), + test_item("suitenocb", Some("suitenocb")), + test_item("todo nocb", Some("todo nocb")), + test_item("tpl\nline", Some("tpl\nline")), + // A skipped call is a test case, and nothing inside it runs. + test_item("ts", Some("ts")), + test_item("tt", None), + test_item("tt.tsub", Some("tt > tsub")), + test_item("u A", Some("u A")), + ] + ); +} + +#[specforge_test(requirement = "FEATURE-056")] +fn a_template_name_in_a_crlf_file_has_node_line_ends() { + // node v26.13.0 named these `a b`, `cd` and `ef`: a template's line end is a line feed, a continuation none. + let text = "test(`a\r\nb`, () => {});\r\ntest(\"c\\\r\nd\", () => {});\r\ntest(`e\\\r\nf`, () => {});\r\n"; + assert_eq!( + tests_in("test/b.test.js", text), + [ + test_item("a\nb", Some("a\nb")), + test_item("cd", Some("cd")), + test_item("ef", Some("ef")), + ] + ); +} + +#[specforge_test(requirement = "FEATURE-056")] +fn a_dynamic_name_mints_nothing() { + let text = r#" +const name = "n", b = "b", y = 1; +test(name, () => {}); +test("a" + b, () => {}); +test(`x ${y}`, () => {}); +test.each([1])("n %s", () => {}); +it.concurrent("c", () => {}); +test("no callback"); +regex.test("text"); +describe(name, () => { + test("inside", () => {}); +}); +describe.each([1])("each %s", () => { + test("inside each", () => {}); +}); +"#; + assert_eq!(tests_in("test/b.test.js", text), []); +} + +#[specforge_test(requirement = "FEATURE-056")] +fn a_template_without_substitution_and_escapes_are_decoded() { + let text = r#" +test(`plain template`, () => {}); +test("quote \" and \u0041", () => {}); +"#; + assert_eq!( + tests_in("test/b.test.js", text), + [ + test_item("plain template", Some("plain template")), + test_item("quote \" and A", Some("quote \" and A")), + ] + ); +} + +#[specforge_test(requirement = "FEATURE-056")] +fn a_test_call_outside_a_test_file_is_ignored() { + let facts = collected(&[("src/helper.js", "test(\"x\", () => {});\n")]); + assert_eq!(items(&facts), Vec::<&str>::new()); +} + +#[specforge_test(requirement = "FEATURE-056")] +fn a_typescript_test_file_is_read_by_its_grammar() { + let text = "it(\"typed\", (): void => {});\nconst n = 1;\n"; + let (out, asked) = run(host(&[APP, ("test/b.test.ts", text)]), &[]); + assert_eq!( + asked_paths(&asked), + [("typescript", vec!["test/b.test.ts"])] + ); + let facts = out.unwrap(); + assert_eq!( + marks(&facts, "js:app/test/b.test.ts::typed").1, + Some(json!("js:app/test/b.test.ts#typed")) + ); +} diff --git a/extensions/javascript/source/src/tests/keep.rs b/extensions/javascript/source/src/tests/keep.rs index d803f78c84..f905e1f026 100644 --- a/extensions/javascript/source/src/tests/keep.rs +++ b/extensions/javascript/source/src/tests/keep.rs @@ -37,6 +37,15 @@ fn a_short_walk_is_the_collectors_error_whatever_the_answers_cap() { } } +#[specforge_test(requirement = "FEATURE-056")] +fn a_test_files_helpers_are_no_item_beside_its_test_calls() { + let facts = collected(&[( + "src/b.test.js", + "export const t = 1;\nfunction helper() {}\ntest(\"works\", () => helper());\n", + )]); + assert_eq!(items(&facts), ["js:app/src/b.test.js::works"]); +} + #[specforge_test(requirement = "FEATURE-056")] fn a_kept_file_the_fs_port_withholds_is_the_collectors_error() { let files = [ @@ -56,6 +65,31 @@ fn a_kept_file_the_fs_port_withholds_is_the_collectors_error() { ); } +#[specforge_test(requirement = "FEATURE-056")] +fn a_test_file_the_reader_could_not_parse_is_a_warning_and_no_item() { + let files = [ + APP, + ("src/a.js", "export const a = 1;\n"), + ("test/held.test.js", "test(\"h\", () => {});\n"), + ("test/ok.test.js", "test(\"ok\", () => {});\n"), + ]; + let withheld = Host { + denied: vec!["test/held.test.js"], + ..host(&files) + }; + let input = input(&withheld, &[]); + let out = serve(Rc::new(withheld), || collect(&input)).expect("the collector answers"); + assert_eq!( + items(&out.facts), + ["js:app/src/a.js::a", "js:app/test/ok.test.js::ok"] + ); + assert_eq!( + out.warnings, + ["test/held.test.js: the host's reader did not parse this test file (denied); javascript-source reads no \ + test call from it"] + ); +} + #[specforge_test(requirement = "FEATURE-056")] fn the_keep_rules_judge_a_path_inside_its_package_a_package_json_too() { // A named package under tests/ or build/ of the root package is no package the pack reads, nor are its files. @@ -115,3 +149,15 @@ fn the_keep_rules_judge_a_path_inside_its_package_a_package_json_too() { assert_eq!(packages(&unnamed), ["pkg:npm/tool"]); assert_eq!(items(&unnamed), ["js:tool/src/a.js::a"]); } + +#[specforge_test(requirement = "FEATURE-056")] +fn a_fixture_packages_test_file_gives_no_item() { + // node runs `test/fixtures/proj/a.test.js`, and node-test names it after `proj`, a package this pack does not + // read: under `app` its id would be `js:app/test/fixtures/proj/a.test.js#x`, one no report holds. + let facts = collected(&[ + ("test/fixtures/proj/package.json", r#"{"name":"proj"}"#), + ("test/fixtures/proj/a.test.js", "test(\"x\", () => {});\n"), + ("test/fixtures/plain/b.test.js", "test(\"y\", () => {});\n"), + ]); + assert_eq!(items(&facts), ["js:app/test/fixtures/plain/b.test.js::y"]); +} diff --git a/extensions/javascript/source/wasm/inputs.json b/extensions/javascript/source/wasm/inputs.json index 2980fa5688..3cd4b8fd9d 100644 --- a/extensions/javascript/source/wasm/inputs.json +++ b/extensions/javascript/source/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "specforge_ext_javascript_source.wasm", - "artifact_sha256": "2cda95250c91ca49c5316bb310cf304c04d1b52de9d418d1d0bdd039519bdad1", + "artifact_sha256": "f62e455bdd957d308290e1b2118e7141eccdde3205e683098326295fcb753c3c", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,32 +55,43 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", - "extensions/code/facts/src/ids.rs": "e3f1f07f70da4786c0ca0b301594b1dc812c2a45808dbe1a5f4905805eccce97", - "extensions/code/facts/src/lib.rs": "5a9733980787f23265ab7f374840d6f61bf2ecbdad3471df86e68c0f2e699769", - "extensions/code/facts/src/mint.rs": "e71f130aaeaeeca2d4c5afa59a36c60fa5ac8bc26db2f4a8276c71024305925e", - "extensions/code/facts/src/paths.rs": "890973baefd07c33e93c6c12ae882083c2d969de91bb3c697bc271ec03474eae", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", - "extensions/code/junit/src/lib.rs": "dfeb44e386f4865b2c5570d389bfd6ff246ccf69122ee36ec7feb9db8a394f35", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", "extensions/javascript/source/Cargo.lock": "102756e7c41a24420712a8741966300bbc34c10c7b336cabae61351437273843", "extensions/javascript/source/Cargo.toml": "3d3ec2ee17e8fe3708cabaa13dd58f05444793daf31867738c0db660ea886b14", "extensions/javascript/source/queries/js-tags.scm": "93e7d113d7df671dff9ce49868abe3f7546b1b535c4a6dc906bfe4de4b0f2f05", - "extensions/javascript/source/src/files.rs": "825284607376566e4574cb0904a042a62d25a6795cbaf034ae3775a38cacf4a6", - "extensions/javascript/source/src/items.rs": "dfafa60da925a296d1b5b5a07195ab7b434d7be5e4eff44915ccfc2361b4bf7d", - "extensions/javascript/source/src/lib.rs": "c4cc357ba5a17e133f2f565a91ed1f15c0aa6b58662ba341861e51e81285ff31", + "extensions/javascript/source/queries/js-tests.scm": "a3d624e9f8edd622cff8b358360b40d99539b0b2c1a9edd2e51028232733a978", + "extensions/javascript/source/src/calls.rs": "e8ff042455713d744251b3e8d260f4ab9cf5493071932feeaade8059f0e93e9b", + "extensions/javascript/source/src/files.rs": "3d345ab471e20e2f598b6b4b58787829ecbb101111f07f05851a2dd3f3e81636", + "extensions/javascript/source/src/items.rs": "011aeeeaaa2a222ac753a8f062a4276535f6e938101e3a96d5b5efa7549c6275", + "extensions/javascript/source/src/lib.rs": "10e54ee5b00a451d412183b15c61c9d41d49845927b3d0fb6d6b8e26e1b2d6f8", "extensions/javascript/source/src/packages.rs": "e4ac7d0881f1b21a57f1cdb9a2e10a884c44908364e68a9ac9c69b42298cbfd2", "extensions/javascript/workspace/Cargo.toml": "6fe0f3ed1ffd7dc74f67755828ca813c06b3ef5f65e71046b20ce965be21c305", "extensions/javascript/workspace/src/lib.rs": "bfa9070faa64aed3f7109cfb2c82578e9b4197bfb6aa7a0baaf1de244d3b8560" diff --git a/extensions/javascript/source/wasm/specforge_ext_javascript_source.wasm b/extensions/javascript/source/wasm/specforge_ext_javascript_source.wasm index 65299e4d67..d7bb4b4e9e 100644 Binary files a/extensions/javascript/source/wasm/specforge_ext_javascript_source.wasm and b/extensions/javascript/source/wasm/specforge_ext_javascript_source.wasm differ diff --git a/extensions/javascript/vitest/Cargo.lock b/extensions/javascript/vitest/Cargo.lock new file mode 100644 index 0000000000..4c4c0df6a9 --- /dev/null +++ b/extensions/javascript/vitest/Cargo.lock @@ -0,0 +1,576 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-javascript-vitest" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-code-junit", + "specforge-extension-sdk", + "specforge-javascript-workspace", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-javascript-workspace" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/javascript/vitest/Cargo.toml b/extensions/javascript/vitest/Cargo.toml new file mode 100644 index 0000000000..64599c50db --- /dev/null +++ b/extensions/javascript/vitest/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "specforge-ext-javascript-vitest" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-junit = { path = "../../code/junit" } +specforge-code-facts = { path = "../../code/facts" } +specforge-javascript-workspace = { path = "../workspace" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" diff --git a/extensions/javascript/vitest/fixtures/README.md b/extensions/javascript/vitest/fixtures/README.md new file mode 100644 index 0000000000..e2c0d7a180 --- /dev/null +++ b/extensions/javascript/vitest/fixtures/README.md @@ -0,0 +1,5 @@ +# @javascript/vitest fixtures + +| Fixture | Source | +|---------|--------| +| `vitest-5.1.1.junit.xml` | recorded with vitest 5.1.1 by the Phase 11 research: `npx vitest run --reporter=default --reporter=junit --outputFile.junit=` over one file, `test/board.test.js` (the tests serve a root `package.json` named `board`): `describe("board")` holding `describe("inner")` with a passing and a failing test, and a skipped test, then a top-level test. The machine's hostname is replaced by `host`; the report held no absolute path | diff --git a/extensions/javascript/vitest/fixtures/vitest-5.1.1.junit.xml b/extensions/javascript/vitest/fixtures/vitest-5.1.1.junit.xml new file mode 100644 index 0000000000..549e34e836 --- /dev/null +++ b/extensions/javascript/vitest/fixtures/vitest-5.1.1.junit.xml @@ -0,0 +1,25 @@ + + + + + + + +AssertionError: expected 1 to be 2 // Object.is equality + +- Expected ++ Received + +- 2 ++ 1 + + ❯ test/board.test.js:6:37 + + + + + + + + + diff --git a/extensions/javascript/vitest/src/lib.rs b/extensions/javascript/vitest/src/lib.rs new file mode 100644 index 0000000000..143176c078 --- /dev/null +++ b/extensions/javascript/vitest/src/lib.rs @@ -0,0 +1,121 @@ +//! @javascript/vitest — runs vitest and records its tests as `@code/core`'s test facts (ADR 0389). +//! +//! The collector `javascript-vitest` is selected by a `vitest.config.*` or `vitest.workspace.*` at the project root. +//! The host runs, with consent, `npx --no -- vitest run` with two reporters: `default` to standard output, so the +//! person sees vitest's usual output, and `junit` to `.specforge/reports/javascript-vitest.xml`, the report this pack +//! reads. `npx --no` never downloads anything: vitest must be a dev dependency of the project. +//! +//! vitest writes one `` per file, named by the file, and each case's `classname` is that project-relative +//! file; its `name` is the describe blocks then the test title joined by `" > "`. Each test is named +//! `js:/# … > test>`, as `@javascript/node-test` names it (ADR 0329 D2): `` is the +//! nearest named `package.json` at or above the file (`specforge-javascript-workspace`), `` the path under it. +//! +//! A caller narrows the run with a filter: the host appends `-t `, and vitest matches the text against test +//! names, not SpecForge ids (ADR 0389 D9). +//! +//! The legacy `@specforge/vitest` stays a separate pack with the collector `vitest`, reading vitest's JSON report for +//! entity results (owner decision D4); this pack's collector is `javascript-vitest`, so the two never clash. + +use specforge_code_facts::{relative, test_facts, TestCase, TestId}; +use specforge_code_junit::{cases, Case}; +use specforge_extension_sdk::prelude::*; +use specforge_javascript_workspace::{packages_input, Workspace}; + +const COLLECTOR: &str = "javascript-vitest"; +/// The JUnit report vitest writes, relative to the project root. +const REPORT: &str = ".specforge/reports/javascript-vitest.xml"; + +#[specforge_extension_sdk::extension( + name = "@javascript/vitest", + version = "1.0.0", + description = "Runs vitest and records its tests as test facts (@code/core)" +)] +struct JavascriptVitest; + +impl Contributions for JavascriptVitest { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.2"); + // Its package.json reads name the packages a test id starts with. + c.peer("@javascript/source", "^1.0"); + c.collector(COLLECTOR, |k| { + k.input_format("junit-xml") + .detect_files(&["vitest.config.*", "vitest.workspace.*"]) + .run(&[ + "npx", + "--no", + "--", + "vitest", + "run", + "--reporter=default", + "--reporter=junit", + "--outputFile.junit={report}", + ]) + .filter(&["-t", "{filter}"]) + .env(&["NODE_*", "VITEST_*", "CI"]) + .install("npm install --save-dev vitest") + .report(REPORT) + .input(packages_input()) + .answers(&["test", "test_run"]) + .collect(collect); + }); + } +} + +/// The id of `case` and its project-relative file, the file being its `classname` read against `cwd`. The path is +/// `name` split on `" > "`: vitest names the suite after the file, so `Case::path` would repeat it. +fn id(workspace: &Workspace, cwd: &str, case: &Case) -> Result<(TestId, String), String> { + if case.classname.is_empty() { + return Err(format!( + "vitest's JUnit reporter wrote no classname (the test file) for '{}'", + case.name + )); + } + let file = relative(&case.classname, cwd).ok_or_else(|| { + format!( + "{}: the test file is outside the project {cwd}", + case.classname + ) + })?; + let path: Vec = case.name.split(" > ").map(str::to_string).collect(); + let (package, under) = workspace.owner(&file).ok_or_else(|| { + format!( + "{file}: no package.json with a name at or above it; {COLLECTOR} names a test \ + js:/#, so give the package a name" + ) + })?; + let id = TestId::js(&package.segment(), under, &path); + Ok((id, file)) +} + +/// Map vitest's JUnit report to a `test` and a `test_run` fact per test. A report that is not JUnit, a file outside +/// the project and a test with no named package are the collector's error: a test is never dropped silently. +fn collect(input: &CollectInput) -> Result { + let [report] = &input.reports[..] else { + return Err(format!( + "{COLLECTOR} reads one report, {REPORT}; it was given {}", + input.reports.len() + )); + }; + let found = cases(&report.content).map_err(|why| format!("{}: {why}", report.path))?; + let cwd = input + .cwd + .as_deref() + .ok_or("the host sent no cwd: a vitest test file is read against the project root")?; + let workspace = Workspace::of(input); + let named = found + .into_iter() + .map(|case| { + let (id, file) = id(&workspace, cwd, &case)?; + Ok(TestCase::of(id, &case, Some(file))) + }) + .collect::, String>>()?; + Ok(CollectOutput { + facts: test_facts(named), + ..CollectOutput::default() + }) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/javascript/vitest/src/tests.rs b/extensions/javascript/vitest/src/tests.rs new file mode 100644 index 0000000000..37244aa58e --- /dev/null +++ b/extensions/javascript/vitest/src/tests.rs @@ -0,0 +1,212 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_javascript_workspace::PACKAGES; +use specforge_test::prelude::*; + +/// vitest 5.1.1's recorded report (see `fixtures/README.md`): one file, `test/board.test.js`. +const RECORDED: &str = include_str!("../fixtures/vitest-5.1.1.junit.xml"); + +/// The input the host sends for these reports read at `cwd`, with these `(path, text)` package files read. +fn input(reports: &[&str], cwd: &str, packages: &[(&str, &str)]) -> CollectInput { + let facts: Vec = packages + .iter() + .map(|(path, text)| json!({"path": path, "exists": true, "text": text})) + .collect(); + let reports: Vec = reports + .iter() + .map(|content| json!({"path": REPORT, "content": content})) + .collect(); + serde_json::from_value(json!({ + "reports": reports, + "cwd": cwd, + "files": {PACKAGES: {"facts": facts}}, + })) + .unwrap() +} + +/// The root package `board`. +const BOARD: &[(&str, &str)] = &[("package.json", r#"{"name":"board"}"#)]; + +/// Each fact's `(kind, id, status)`. +fn summary(out: &CollectOutput) -> Vec<(String, String, String)> { + out.facts + .iter() + .map(|f| { + ( + f.kind.clone(), + f.id.clone(), + f.fields["status"].as_str().unwrap().to_string(), + ) + }) + .collect() +} + +#[specforge_test(requirement = "FEATURE-151")] +fn javascript_vitest_declares_vitest_with_its_junit_reporter_and_its_peers() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.2", false), + ("@javascript/source", "^1.0", false) + ] + ); + let [collector] = &declaration.collectors[..] else { + panic!("one collector: {:?}", declaration.collectors); + }; + assert_eq!(collector.name, "javascript-vitest"); + assert_eq!(collector.input_formats, ["junit-xml"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some( + &[ + "vitest.config.*".to_string(), + "vitest.workspace.*".to_string() + ][..] + ) + ); + assert_eq!(collector.answers, ["test", "test_run"]); + assert_eq!(collector.inputs, [packages_input()]); + assert_eq!(collector.report.as_deref(), Some(REPORT)); + assert_eq!(collector.capture, None); + assert_eq!( + collector.install.as_deref(), + Some("npm install --save-dev vitest") + ); + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + assert_eq!(capabilities[0]["name"], COLLECTOR); + assert_eq!(capabilities[0]["port"], "process"); + assert_eq!( + capabilities[0]["argv"], + json!([ + "npx", + "--no", + "--", + "vitest", + "run", + "--reporter=default", + "--reporter=junit", + "--outputFile.junit={report}" + ]), + "{capabilities}" + ); + assert_eq!(capabilities[0]["filter"], json!(["-t", "{filter}"])); + assert_eq!(capabilities[0]["env"], json!(["NODE_*", "VITEST_*", "CI"])); +} + +#[specforge_test(requirement = "FEATURE-151")] +fn vitests_recorded_report_names_its_tests_as_node_test_does() { + let out = collect(&input(&[RECORDED], "/project", BOARD)).unwrap(); + let file = "js:board/test/board.test.js"; + let expected = [ + ("board > inner > adds", "passed", 1), + ("board > inner > fails", "failed", 3), + ("board > skipped", "skipped", 0), + ("top level", "passed", 0), + ]; + assert_eq!( + summary(&out), + expected + .iter() + .flat_map(|(name, status, _)| [ + ( + "test".to_string(), + format!("{file}#{name}"), + status.to_string() + ), + ( + "test_run".to_string(), + format!("run:{file}#{name}"), + status.to_string() + ), + ]) + .collect::>() + ); + for fact in out.facts.iter().filter(|f| f.kind == "test") { + assert_eq!(fact.fields["file"], "test/board.test.js", "{}", fact.id); + } + let adds = &out.facts[0]; + assert_eq!(adds.fields["suite"], json!(["board", "inner"])); + assert_eq!(adds.fields["name"], "adds"); + let durations: Vec<&Value> = out + .facts + .iter() + .filter(|f| f.kind == "test_run") + .map(|f| &f.fields["duration_ms"]) + .collect(); + assert_eq!( + durations, + expected + .map(|(_, _, ms)| json!(ms)) + .iter() + .collect::>() + ); + assert!( + out.entity_results.is_empty() && out.unlinked.is_empty(), + "facts only" + ); +} + +#[specforge_test(requirement = "FEATURE-151")] +fn a_workspace_test_is_named_after_its_nearest_package() { + let packages = [ + ("package.json", r#"{"name":"app"}"#), + ("packages/core/package.json", r#"{"name":"@acme/core"}"#), + ]; + let report = r#" + + "#; + let out = collect(&input(&[report], "/work/app", &packages)).unwrap(); + assert_eq!(out.facts[0].id, "js:@acme/core/test/x.test.ts#adds"); + assert_eq!(out.facts[0].fields["file"], "packages/core/test/x.test.ts"); +} + +#[specforge_test(requirement = "FEATURE-151")] +fn a_test_no_named_package_owns_is_the_collectors_error() { + for packages in [&[][..], &[("package.json", r#"{"private":true}"#)][..]] { + let why = collect(&input(&[RECORDED], "/project", packages)).unwrap_err(); + assert_eq!( + why, + "test/board.test.js: no package.json with a name at or above it; javascript-vitest names a test \ + js:/#, so give the package a name", + "{packages:?}" + ); + } +} + +#[specforge_test(requirement = "FEATURE-151")] +fn a_file_outside_the_project_or_no_file_is_the_collectors_error() { + let outside = r#""#; + assert_eq!( + collect(&input(&[outside], "/w", BOARD)).unwrap_err(), + "../a.test.js: the test file is outside the project /w" + ); + let none = r#""#; + assert_eq!( + collect(&input(&[none], "/w", BOARD)).unwrap_err(), + "vitest's JUnit reporter wrote no classname (the test file) for 'adds'" + ); +} + +#[specforge_test(requirement = "FEATURE-151")] +fn zero_or_two_reports_or_not_junit_is_the_collectors_error() { + for reports in [&[][..], &[RECORDED, RECORDED][..]] { + let why = collect(&input(reports, "/project", BOARD)).unwrap_err(); + assert_eq!( + why, + format!( + "javascript-vitest reads one report, {REPORT}; it was given {}", + reports.len() + ) + ); + } + let why = collect(&input(&[r#"{"testResults":[]}"#], "/project", BOARD)).unwrap_err(); + assert!(why.starts_with(&format!("{REPORT}: ")), "{why}"); + assert!(why.contains("not a JUnit report"), "{why}"); +} diff --git a/extensions/javascript/vitest/wasm/inputs.json b/extensions/javascript/vitest/wasm/inputs.json new file mode 100644 index 0000000000..df33e006e0 --- /dev/null +++ b/extensions/javascript/vitest/wasm/inputs.json @@ -0,0 +1,93 @@ +{ + "artifact": "specforge_ext_javascript_vitest.wasm", + "artifact_sha256": "6066a45e2595d8ccb98dff0fac211f43fe5e0a0b6fea7137e58d538e4bb19a52", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/javascript/vitest/Cargo.lock": "1eda52927ed04497f40ad82735cd0a04761d1c9b839b5397347e988dce4c3c9f", + "extensions/javascript/vitest/Cargo.toml": "553d44ddd367a8809803e8a7711f9115a5d3e05567274e16c8bcda8f7bb34a35", + "extensions/javascript/vitest/src/lib.rs": "f963ba8785782ac3e1fc3d7c4165ea2f1335898104d181563cf7038319713b86", + "extensions/javascript/workspace/Cargo.toml": "6fe0f3ed1ffd7dc74f67755828ca813c06b3ef5f65e71046b20ce965be21c305", + "extensions/javascript/workspace/src/lib.rs": "bfa9070faa64aed3f7109cfb2c82578e9b4197bfb6aa7a0baaf1de244d3b8560" + } +} diff --git a/extensions/javascript/vitest/wasm/specforge_ext_javascript_vitest.wasm b/extensions/javascript/vitest/wasm/specforge_ext_javascript_vitest.wasm new file mode 100644 index 0000000000..676b924b16 Binary files /dev/null and b/extensions/javascript/vitest/wasm/specforge_ext_javascript_vitest.wasm differ diff --git a/extensions/product/Cargo.lock b/extensions/product/Cargo.lock index a03950f8eb..33b321bbe9 100644 --- a/extensions/product/Cargo.lock +++ b/extensions/product/Cargo.lock @@ -159,9 +159,9 @@ checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -868,9 +868,9 @@ checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/extensions/product/wasm/inputs.json b/extensions/product/wasm/inputs.json index c097479c12..b656aa5347 100644 --- a/extensions/product/wasm/inputs.json +++ b/extensions/product/wasm/inputs.json @@ -1,6 +1,6 @@ { "artifact": "specforge_ext_product.wasm", - "artifact_sha256": "710a9ae771873e72c43d0875ce6694056feea1e315a6f5c902bfaffe5b87b8f4", + "artifact_sha256": "e4c6b69e1962f9fe2e7bfefd3d8a17fa55af6f28ec1d3c017d3ef5b34924c747", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", @@ -10,12 +10,12 @@ "crates/leaf/cycles/src/lib.rs": "18b6d9b085c507c2f0e52c1011d2d92526ac2e0e3f459d282d086ed5f497a920", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -25,29 +25,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -59,18 +59,18 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", - "extensions/product/Cargo.lock": "d88b11bd05a64b0dd94e45b1e104ad5792a23a3315834c42f1d98b958cc6f70c", + "extensions/product/Cargo.lock": "3ee32e65af5301bd3fc176b76da7858caa057cf79afa3a5a9f595bd993327346", "extensions/product/Cargo.toml": "d80e8940361fa79d82feb8c58176ba79bd6bfe0fb0f0835d67b9fa1c489816ea", "extensions/product/src/commands.rs": "9be9858864a2e1331df3c10c4e87b10d3a33af373a46d1bc2d460f24aee7a883", "extensions/product/src/commands/coverage_matrices.rs": "9f21a80c97cfb4624a08c26bd7f0db8be834ce320ba441626612b53d081e7426", diff --git a/extensions/product/wasm/specforge_ext_product.wasm b/extensions/product/wasm/specforge_ext_product.wasm index 4a79003eb0..e8fcd833a4 100755 Binary files a/extensions/product/wasm/specforge_ext_product.wasm and b/extensions/product/wasm/specforge_ext_product.wasm differ diff --git a/extensions/rust/api/Cargo.lock b/extensions/rust/api/Cargo.lock new file mode 100644 index 0000000000..92cc5e2f95 --- /dev/null +++ b/extensions/rust/api/Cargo.lock @@ -0,0 +1,576 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-api" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-rust-api" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-api", + "specforge-code-facts", + "specforge-extension-sdk", + "specforge-protocol-types", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/rust/api/Cargo.toml b/extensions/rust/api/Cargo.toml new file mode 100644 index 0000000000..0e1dc92804 --- /dev/null +++ b/extensions/rust/api/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "specforge-ext-rust-api" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-api = { path = "../../code/api" } +specforge-code-facts = { path = "../../code/facts" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" +# is_install_line: the host's rule for a collector's install line. +specforge-protocol-types = { path = "../../../crates/leaf/protocol-types" } diff --git a/extensions/rust/api/src/lib.rs b/extensions/rust/api/src/lib.rs new file mode 100644 index 0000000000..35a0b9d1a1 --- /dev/null +++ b/extensions/rust/api/src/lib.rs @@ -0,0 +1,199 @@ +//! @rust/api — runs cargo public-api and records the crate's public API as `@code/core`'s `api_item` facts +//! (ADR 0389). +//! +//! The collector `rust-api` is selected by a `Cargo.toml` at the project root. The host runs, with consent, +//! `cargo-public-api --color never -ss`: the program is `cargo-public-api`, so a missing tool is "not found on PATH" +//! with its install line. `-ss` omits blanket and auto-trait impls, which every type has; derived impls stay, as they +//! are real surface. cargo public-api builds the crate's rustdoc JSON, so it runs build scripts and proc macros, which +//! the approval shows as it shows the command, and it needs a nightly toolchain, which it finds by itself when the +//! active one is stable (ADR 0389 D9). +//! +//! cargo public-api reads one package per run and has no `--workspace`: the root package, unless a caller names +//! another (`specforge collect --runner rust-api --filter `, which the host passes as `--package `). A +//! virtual workspace has no root package, so each crate is its own filtered run. +//! +//! The tool prints the API to standard output only, which the host captures into +//! `.specforge/reports/rust-api/rust-api.stdout.txt` and passes as `CollectInput::stdout`; `specforge collect --report +//! ` passes a saved capture as the one report instead. `specforge-code-api` reads the text and +//! `specforge-code-facts` mints one `api_item` per public entry, citing the one `@rust/source` item of the library +//! crate its path names. A failed run (a missing nightly toolchain, a failed build) prints its error to stderr and no +//! entry to stdout, so a capture with no entry gives one warning saying nothing was recorded, which the host shows as +//! W203, instead of a clean run. +//! +//! The accepted API (ADR 0390 D3) is a committed `public-api.txt` (the read `accepted`, glob `**/public-api.txt`, files +//! up to 4 MiB): cargo public-api's own snapshot file, `tests/public-api.txt` or `tests/snapshots/public-api.txt`. It +//! must be written with the pack's own flags, `cargo public-api --color never -ss > public-api.txt` (a snapshot test's +//! builder omitting blanket and auto-trait impls the same way), or every impl the run omits reads as removed. Only a +//! crate on both sides is judged: each item's `api_item` then carries `change` (`added`, `unchanged`, `changed`, +//! `narrowed`, `removed`) against it; without an accepted file the facts carry none. Accepting a break is committing +//! the updated file. A snapshot of the run's crate (its `pub mod ` line) that does not parse, or two files naming +//! one crate (the old `tests/public-api.txt` kept beside `tests/snapshots/public-api.txt`), is the collector's error +//! naming them; a file the host did not serve (over 4 MiB, not UTF-8) or naming no crate the run read, broken or not, +//! is one warning naming it, which the host shows as W203, and the collect goes on. +//! Limits: cargo public-api prints public items only, so a narrowing (`pub` to `pub(crate)`) reads as removed; the +//! line holds the attributes, so adding any attribute (`#[must_use]` as `#[non_exhaustive]`) reads as changed; the +//! tool's ordering and format are not stable, so a tool upgrade can change every line: regenerate the file with the +//! version that runs. + +use std::collections::{BTreeMap, BTreeSet}; + +use specforge_code_api::{read_rust_text, rust_text_crate}; +use specforge_code_facts::{api_facts, api_facts_against, ApiEntry}; +use specforge_extension_sdk::prelude::*; + +const COLLECTOR: &str = "rust-api"; +/// The read of the committed accepted API files. +const ACCEPTED: &str = "accepted"; +/// The report directory, relative to the project root: the host keeps the captured standard output in it. +const REPORT: &str = ".specforge/reports/rust-api"; +/// Where the host keeps the captured standard output: `/.stdout.txt`. +const CAPTURE: &str = ".specforge/reports/rust-api/rust-api.stdout.txt"; + +#[specforge_extension_sdk::extension( + name = "@rust/api", + version = "1.0.0", + description = "Runs cargo public-api and records the crate's public API as api_item facts (@code/core)" +)] +struct RustApi; + +impl Contributions for RustApi { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.4"); + // Its items are what an api_item cites; without them an entry cites nothing. + c.peer("@rust/source", "^1.0"); + c.collector(COLLECTOR, |k| { + k.input_format("public-api-text") + .detect_files(&["Cargo.toml"]) + .run(&["cargo-public-api", "--color", "never", "-ss"]) + .filter(&["--package", "{filter}"]) + .env(&[ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "RUSTDOCFLAGS", + "RUST_LOG", + ]) + .install( + "cargo install cargo-public-api --locked (and: rustup toolchain install nightly --profile \ + minimal)", + ) + .report(REPORT) + .capture_stdout() + .input(Input::facts(&["item", "package"])) + .input(Input::files( + ACCEPTED, + FileReadSpec::glob("**/public-api.txt").text_up_to(TEXT_MAX_CEILING_BYTES), + )) + .answers(&["api_item"]) + .collect(collect); + }); + } +} + +/// Map cargo public-api's captured text (else the one report given) to `api_item` facts. +fn collect(input: &CollectInput) -> Result { + let (path, text) = match (&input.stdout, &input.reports[..]) { + (Some(stdout), _) => (CAPTURE, stdout.as_str()), + (None, [report]) => (report.path.as_str(), report.content.as_str()), + (None, reports) => { + return Err(format!( + "{COLLECTOR}: cargo public-api's standard output was not captured, and it reads one report in its \ + place; it was given {}", + reports.len() + )) + } + }; + let entries = read_rust_text(text).map_err(|why| format!("{path}: {why}"))?; + let mut warnings = Vec::new(); + let accepted = accepted(input, &entries, &mut warnings)?; + // The tool prints its errors (a missing nightly toolchain, a failed build) to stderr, so stdout holds no entry. + if entries.is_empty() { + warnings.push(format!( + "{path}: no public API item was read; if cargo public-api failed (a missing nightly toolchain, a failed \ + build), nothing was recorded" + )); + } + let facts = if accepted.is_empty() { + api_facts(&entries, &input.facts) + } else { + api_facts_against(&entries, &accepted, &input.facts) + }; + Ok(CollectOutput { + facts, + warnings, + ..CollectOutput::default() + }) +} + +/// The entries of the served accepted files that name a crate of `entries`; a warning for each file not served or +/// naming none (a broken snapshot of another crate included), and for a read that matched more files than were served. +/// A snapshot of a crate of `entries` that does not parse, and two files naming one crate, are the collector's error: +/// the accepted side of a crate is one file. +fn accepted( + input: &CollectInput, + entries: &[ApiEntry], + warnings: &mut Vec, +) -> Result, String> { + let Some(read) = input.files.get(ACCEPTED) else { + return Ok(Vec::new()); + }; + // The file each crate's accepted entries came from. + let mut first: BTreeMap = BTreeMap::new(); + if read.truncated { + warnings.push(format!( + "the read '{ACCEPTED}' (**/public-api.txt) stopped early: the host's walk reached its cap of \ + {GLOB_VISITS_MAX} entries, or more than {FILE_READ_MAX} files matched; no break was judged against a \ + file not read" + )); + } + let crates: BTreeSet<&str> = entries.iter().map(|e| e.container.as_str()).collect(); + let mut accepted = Vec::new(); + for file in &read.facts { + let Some(text) = file.text.as_deref().filter(|_| file.error.is_none()) else { + let error = file.error.as_deref().unwrap_or("no text"); + warnings.push(format!( + "{}: the accepted API was not read ({error}); no break was judged for it", + file.path + )); + continue; + }; + let mut read = match read_rust_text(text) { + Ok(read) => read, + Err(why) if rust_text_crate(text).is_some_and(|name| crates.contains(name)) => { + return Err(format!("{}: {why}", file.path)); + } + Err(why) => { + warnings.push(format!( + "{}: not a snapshot of a crate this run read ({why}); no break was judged for it", + file.path + )); + continue; + } + }; + read.retain(|e| crates.contains(e.container.as_str())); + if read.is_empty() { + warnings.push(format!( + "{}: names no crate this run read; no break was judged for it", + file.path + )); + } + for entry in &read { + let named = *first.entry(entry.container.clone()).or_insert(&file.path); + if named != file.path { + return Err(format!( + "{named} and {}: two accepted API files of the crate; keep one", + file.path + )); + } + } + accepted.extend(read); + } + Ok(accepted) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/rust/api/src/tests.rs b/extensions/rust/api/src/tests.rs new file mode 100644 index 0000000000..cc20e32fe9 --- /dev/null +++ b/extensions/rust/api/src/tests.rs @@ -0,0 +1,316 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_test::prelude::*; + +/// The API reader's `cargo public-api` snapshot (hand-written to the tool's lines): crate `example_api`. +const SNAPSHOT: &str = include_str!("../../../code/api/fixtures/rust.public-api.txt"); +/// The API reader's served items for it, as JSON. +const ITEMS: &str = include_str!("../../../code/api/fixtures/items.json"); +/// The API reader's accepted snapshot of the facts `SNAPSHOT` mints with `ITEMS` served. +const SNAPSHOT_FACTS: &str = + include_str!("../../../code/api/src/snapshots/specforge_code_api__tests__rust.snap"); + +/// The input the host sends: `stdout` as captured, these report files, the reader's items served. +fn input(stdout: Option<&str>, reports: &[&str]) -> CollectInput { + CollectInput { + stdout: stdout.map(ToString::to_string), + reports: reports + .iter() + .map(|content| CollectReportFile { + path: "saved/public-api.txt".to_string(), + content: content.to_string(), + }) + .collect(), + facts: serde_json::from_str(ITEMS).expect("the served facts parse"), + ..CollectInput::default() + } +} + +/// The input of a captured run printing `stdout`, the host serving `read` as the accepted files. +fn against(stdout: &str, read: Value) -> CollectInput { + CollectInput { + files: serde_json::from_value(json!({ ACCEPTED: read })).expect("the read parses"), + ..input(Some(stdout), &[]) + } +} + +/// A committed accepted file the host served with its text. +fn served(path: &str, text: &str) -> Value { + json!({"path": path, "exists": true, "text": text}) +} + +/// Each fact's `change`, absent as `None`. +fn changes(out: &CollectOutput) -> Vec> { + out.facts + .iter() + .map(|f| f.fields.get("change").and_then(Value::as_str)) + .collect() +} + +/// The JSON body of an insta snapshot, after its `---` header. +fn snapshot(text: &str) -> Value { + let body = text.splitn(3, "---\n").nth(2).expect("a snapshot body"); + serde_json::from_str(body).expect("the snapshot parses") +} + +#[specforge_test(requirement = "FEATURE-150")] +fn rust_api_declares_cargo_public_api_with_its_stdout_captured_its_filter_and_its_peers() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.4", false), + ("@rust/source", "^1.0", false) + ] + ); + let [collector] = &declaration.collectors[..] else { + panic!("one collector: {:?}", declaration.collectors); + }; + assert_eq!(collector.name, COLLECTOR); + assert_eq!(collector.input_formats, ["public-api-text"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["Cargo.toml".to_string()][..]) + ); + assert_eq!(collector.answers, ["api_item"]); + assert_eq!( + collector.inputs, + [ + Input::facts(&["item", "package"]), + Input::files( + ACCEPTED, + FileReadSpec::glob("**/public-api.txt").text_up_to(TEXT_MAX_CEILING_BYTES) + ) + ] + ); + assert_eq!(collector.report.as_deref(), Some(REPORT)); + assert_eq!(collector.capture.as_deref(), Some("stdout")); + let install = collector.install.as_deref().expect("an install line"); + assert_eq!( + install, + "cargo install cargo-public-api --locked (and: rustup toolchain install nightly --profile minimal)" + ); + assert!( + specforge_protocol_types::is_install_line(install), + "{install}" + ); + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + assert_eq!(capabilities[0]["name"], COLLECTOR); + assert_eq!(capabilities[0]["port"], "process"); + assert_eq!( + capabilities[0]["argv"], + json!(["cargo-public-api", "--color", "never", "-ss"]), + "{capabilities}" + ); + assert_eq!(capabilities[0]["filter"], json!(["--package", "{filter}"])); + assert_eq!( + capabilities[0]["env"], + json!([ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "RUSTDOCFLAGS", + "RUST_LOG" + ]) + ); +} + +#[specforge_test(requirement = "FEATURE-150")] +fn a_captured_public_api_run_or_a_saved_one_mints_the_readers_facts() { + for given in [input(Some(SNAPSHOT), &[]), input(None, &[SNAPSHOT])] { + let out = collect(&given).unwrap(); + assert_eq!( + serde_json::to_value(&out.facts).unwrap(), + snapshot(SNAPSHOT_FACTS) + ); + assert_eq!(out.warnings, Vec::::new()); + } +} + +#[specforge_test(requirement = "FEATURE-150")] +fn no_capture_and_no_single_report_or_a_bad_line_is_the_collectors_error() { + for reports in [&[][..], &[SNAPSHOT, SNAPSHOT][..]] { + let why = collect(&input(None, reports)).unwrap_err(); + assert!( + why.contains(COLLECTOR) && why.contains("standard output was not captured"), + "{why}" + ); + } + let why = collect(&input(Some("pub mod demo\ngarbage\n"), &[])).unwrap_err(); + assert!( + why.starts_with(&format!("{CAPTURE}: ")) && why.contains("line 2"), + "{why}" + ); +} + +#[specforge_test(requirement = "FEATURE-150")] +fn no_api_item_read_is_no_fact_and_one_warning() { + // A missing nightly toolchain: cargo public-api's error goes to stderr and stdout holds nothing. + for given in [input(Some(""), &[]), input(None, &[""])] { + let out = collect(&given).unwrap(); + assert_eq!(out.facts, Vec::::new()); + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + assert!( + out.warnings[0].contains("no public API item was read"), + "{:?}", + out.warnings + ); + } +} + +#[specforge_test(requirement = "FEATURE-150")] +fn no_accepted_file_served_is_todays_facts() { + let out = collect(&against(SNAPSHOT, json!({"facts": []}))).unwrap(); + assert_eq!( + serde_json::to_value(&out.facts).unwrap(), + snapshot(SNAPSHOT_FACTS) + ); + assert_eq!(out.warnings, Vec::::new()); +} + +#[specforge_test(requirement = "FEATURE-150")] +fn an_accepted_file_equal_to_the_run_marks_every_item_unchanged() { + let read = json!({"facts": [served("tests/public-api.txt", SNAPSHOT)]}); + let out = collect(&against(SNAPSHOT, read)).unwrap(); + assert!(!out.facts.is_empty()); + assert!( + changes(&out).iter().all(|c| *c == Some("unchanged")), + "{:?}", + changes(&out) + ); + assert_eq!(out.warnings, Vec::::new()); +} + +#[specforge_test(requirement = "FEATURE-150")] +fn an_accepted_function_the_run_lacks_is_removed() { + let gone = "pub const fn example_api::function(x: u32) -> u32"; + let stdout: String = SNAPSHOT + .lines() + .filter(|line| *line != gone) + .map(|line| format!("{line}\n")) + .collect(); + let read = json!({"facts": [served("tests/public-api.txt", SNAPSHOT)]}); + let out = collect(&against(&stdout, read)).unwrap(); + let removed: Vec<&Fact> = out + .facts + .iter() + .filter(|f| f.fields.get("change") == Some(&json!("removed"))) + .collect(); + let [fact] = &removed[..] else { + panic!("one removed item: {removed:?}"); + }; + assert_eq!(fact.fields["accepted_signature"], json!(gone)); + assert_eq!( + changes(&out) + .iter() + .filter(|c| **c == Some("unchanged")) + .count(), + out.facts.len() - 1 + ); +} + +#[specforge_test(requirement = "FEATURE-150")] +fn an_unreadable_accepted_file_is_the_collectors_error_naming_it() { + let broken = "<<<<<<< HEAD\npub mod example_api\ngarbage\n"; + let read = json!({"facts": [served("tests/public-api.txt", broken)]}); + let why = collect(&against(SNAPSHOT, read)).unwrap_err(); + assert!( + why.starts_with("tests/public-api.txt: ") && why.contains("line 1"), + "{why}" + ); +} + +#[specforge_test(requirement = "FEATURE-150")] +fn a_broken_file_of_another_crate_or_no_snapshot_is_one_warning_and_the_collect_goes_on() { + for (path, text) in [ + ("other/tests/public-api.txt", "pub mod other_api\ngarbage\n"), + ( + "docs/public-api.txt", + "The public API of this project, in prose.\n", + ), + ] { + let read = json!({"facts": [served(path, text)]}); + let out = collect(&against(SNAPSHOT, read)).unwrap(); + assert_eq!( + serde_json::to_value(&out.facts).unwrap(), + snapshot(SNAPSHOT_FACTS) + ); + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + assert!( + out.warnings[0].starts_with(&format!( + "{path}: not a snapshot of a crate this run read (line " + )), + "{:?}", + out.warnings + ); + } +} + +#[specforge_test(requirement = "FEATURE-150")] +fn two_accepted_files_of_the_crate_are_the_collectors_error_naming_both() { + let read = json!({"facts": [ + served("tests/public-api.txt", SNAPSHOT), + served("tests/snapshots/public-api.txt", SNAPSHOT), + ]}); + let why = collect(&against(SNAPSHOT, read)).unwrap_err(); + assert_eq!( + why, + "tests/public-api.txt and tests/snapshots/public-api.txt: two accepted API files of the crate; keep one" + ); + // Two files of two crates are no conflict: each judges its own. + let read = json!({"facts": [ + served("tests/public-api.txt", SNAPSHOT), + served("other/tests/public-api.txt", "pub mod other_api\npub fn other_api::f()\n"), + ]}); + let out = collect(&against(SNAPSHOT, read)).unwrap(); + assert!(changes(&out).iter().all(|c| *c == Some("unchanged"))); +} + +#[specforge_test(requirement = "FEATURE-150")] +fn an_accepted_file_not_served_or_of_another_crate_is_one_warning_and_no_change() { + let unserved = json!({"path": "tests/public-api.txt", "exists": true, "bytes": 5_000_000, "error": "too_large"}); + let foreign = served( + "other/tests/public-api.txt", + "pub mod other_api\npub fn other_api::f()\n", + ); + for (file, says) in [ + (unserved, "the accepted API was not read (too_large)"), + (foreign, "names no crate this run read"), + ] { + let path = file["path"].as_str().unwrap().to_string(); + let out = collect(&against(SNAPSHOT, json!({ "facts": [file] }))).unwrap(); + assert_eq!( + serde_json::to_value(&out.facts).unwrap(), + snapshot(SNAPSHOT_FACTS) + ); + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + assert!( + out.warnings[0].starts_with(&format!("{path}: ")) && out.warnings[0].contains(says), + "{:?}", + out.warnings + ); + } +} + +#[specforge_test(requirement = "FEATURE-150")] +fn a_truncated_accepted_read_is_one_warning() { + let read = json!({"facts": [served("tests/public-api.txt", SNAPSHOT)], "truncated": true}); + let out = collect(&against(SNAPSHOT, read)).unwrap(); + assert!(changes(&out).iter().all(|c| *c == Some("unchanged"))); + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + // The guest cannot tell the walk's entry cap from the file cap: the warning names both. + assert!( + out.warnings[0].contains("stopped early: the host's walk reached its cap of 20000 entries") + && out.warnings[0].contains("or more than 2000 files matched"), + "{:?}", + out.warnings + ); +} diff --git a/extensions/rust/api/wasm/inputs.json b/extensions/rust/api/wasm/inputs.json new file mode 100644 index 0000000000..ca74e9a94d --- /dev/null +++ b/extensions/rust/api/wasm/inputs.json @@ -0,0 +1,96 @@ +{ + "artifact": "specforge_ext_rust_api.wasm", + "artifact_sha256": "263d5b439f99f786ac1d0a0f05c0f4db7b5c9d8839a8193612b9ad6ab6c4d85e", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/api/Cargo.toml": "0ec7e09fd08c471d405b140f2f4ba08a827759ef2d43ed4285b1b2a0b3240f07", + "extensions/code/api/src/js_model.rs": "287c3fd4d4feb64a934f2a3d724dee672b0ed778fcf9ff6b9396dab545210221", + "extensions/code/api/src/js_report.rs": "028ffa203f1e122d9e429afc4a467a2ac5b34bf82f5cebe2f4b391c0a30e7370", + "extensions/code/api/src/lib.rs": "24cfeed2f5f84c8a68e9e3900f4580ea754e23e3293a0cb0374edb249f77e0bb", + "extensions/code/api/src/rust_text.rs": "158bfe14aca8f178b5e623ba6acd58eb75f483328c9be5186498ec7d5cd55ebd", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/rust/api/Cargo.lock": "1af68f23027c44bf971230b01cc3164bfb76655e216f31246051d5d6abc4647b", + "extensions/rust/api/Cargo.toml": "be22f357e2ad2b1305bd2665512e95866efa1526bec3841363e43b7a1df32579", + "extensions/rust/api/src/lib.rs": "2607ebb7e700ebb657f2de2af92a52c67a69175b4fc2e7b4a94f66e9dbd43751" + } +} diff --git a/extensions/rust/api/wasm/specforge_ext_rust_api.wasm b/extensions/rust/api/wasm/specforge_ext_rust_api.wasm new file mode 100644 index 0000000000..43866e608a Binary files /dev/null and b/extensions/rust/api/wasm/specforge_ext_rust_api.wasm differ diff --git a/extensions/rust/cargo/Cargo.toml b/extensions/rust/cargo/Cargo.toml index 1c517eb19e..5550caab8c 100644 --- a/extensions/rust/cargo/Cargo.toml +++ b/extensions/rust/cargo/Cargo.toml @@ -10,8 +10,9 @@ crate-type = ["cdylib"] specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } specforge-code-facts = { path = "../../code/facts" } specforge-rust-manifest = { path = "../manifest" } +# The `exclude` setting's value (ADR 0393 D7). +serde_json = "1.0" [dev-dependencies] # Spec links: #[specforge_test(behavior = "…", verify = "…")] (ADR 0002). specforge-test = { path = "../../../integrations/rust/specforge-test" } -serde_json = "1.0" diff --git a/extensions/rust/cargo/src/lib.rs b/extensions/rust/cargo/src/lib.rs index 396fc4f0fd..275539eacb 100644 --- a/extensions/rust/cargo/src/lib.rs +++ b/extensions/rust/cargo/src/lib.rs @@ -6,9 +6,14 @@ //! and autodiscovery included, and each package becomes one `package` fact minted by `specforge-code-facts`: //! `pkg:cargo/`, located at its `[package]` table, with its targets and the project packages it depends on. //! -//! A manifest whose text the host withheld, one cargo's reader cannot read, and a read that matched more files than -//! the host serves are the collector's error: a package is never dropped silently. +//! A manifest whose text the host withheld, one cargo's reader cannot read, and a read that stopped early (the host's +//! walk reached its entry cap, or more files matched than it serves) are the collector's error: a package is never +//! dropped silently. +//! +//! A project's `exclude` setting lists directories whose manifests are not its packages (a fixture's or an example's +//! crate): a package in or under one is answered by no fact (ADR 0393 D7). +use serde_json::Value; use specforge_code_facts::Package; use specforge_extension_sdk::prelude::*; use specforge_rust_manifest::read_packages; @@ -42,6 +47,13 @@ struct RustCargo; impl Contributions for RustCargo { fn contribute(c: &mut ContributionsBuilder) { c.peer("@code/core", "^1.1"); + c.setting("exclude", |s| { + s.string_list().default(Vec::::new()).describe( + "Project-relative directories whose manifests are no packages of this project (a fixture's or an \ + example's crate): @rust/cargo answers no package for a manifest in or under one, so @rust/source \ + reads no item there; the tool-running packs still run over the whole cargo workspace", + ); + }); c.collector(COLLECTOR, |k| { k.detect_files(&["Cargo.toml"]) .answers(&["package"]) @@ -57,16 +69,16 @@ impl Contributions for RustCargo { } } -/// The paths and texts of the served read `name`'s files; the collector's error when the read matched more files than -/// the host serves, as a package or a target would be missing. +/// The paths and texts of the served read `name`'s files; the collector's error when the read stopped early (the +/// host's walk reached its entry cap, or more files matched than it serves), as a package or a target would be missing. fn read(input: &CollectInput, name: &str) -> Result)>, String> { let Some(read) = input.files.get(name) else { return Ok(Vec::new()); }; if read.truncated { return Err(format!( - "the read '{name}' matched more files than the host serves ({FILE_READ_MAX}): rust-cargo would miss \ - packages or targets, so it reads none" + "the read '{name}' stopped early: the host's walk reached its cap of {GLOB_VISITS_MAX} entries, or more \ + than {FILE_READ_MAX} files matched; rust-cargo would miss packages or targets, so it reads none" )); } read.facts @@ -81,8 +93,56 @@ fn read(input: &CollectInput, name: &str) -> Result) .collect() } -/// Every package the served manifests declare, as a `package` fact. +/// Every package the served manifests declare outside the project's `exclude` directories, as a `package` fact. fn collect(input: &CollectInput) -> Result { + packages_of(input, &exclude_list(Settings::current().get("exclude"))?) +} + +/// The `exclude` setting's directories, normalized to their segments joined by one `/` (`./examples//shop/` is +/// `examples/shop`): the collector's error on an entry that is not a project-relative directory below the root +/// (absolute, a drive's, with a `\` or a `..` segment, or with no segment but `.`). +fn exclude_list(value: Option<&Value>) -> Result, String> { + let refuse = |entry: &dyn std::fmt::Display| { + format!("exclude entry '{entry}' is not a project-relative directory") + }; + let Some(value) = value else { + return Ok(Vec::new()); + }; + let entries = value.as_array().ok_or_else(|| refuse(value))?; + entries + .iter() + .map(|entry| { + let text = entry.as_str().ok_or_else(|| refuse(entry))?; + let drive = + text.as_bytes().get(1) == Some(&b':') && text.as_bytes()[0].is_ascii_alphabetic(); + let segments: Vec<&str> = text + .split('/') + .filter(|s| !s.is_empty() && *s != ".") + .collect(); + if segments.is_empty() + || text.starts_with('/') + || text.contains('\\') + || drive + || segments.contains(&"..") + { + return Err(refuse(&text)); + } + Ok(segments.join("/")) + }) + .collect() +} + +/// Whether the package directory `dir` is an entry of `list` or lies under one. +fn excluded(dir: &str, list: &[String]) -> bool { + list.iter().any(|entry| { + dir.strip_prefix(entry.as_str()) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('/')) + }) +} + +/// Every package the served manifests declare outside the directories `exclude` lists, as a `package` fact. The +/// filter follows the read, so a workspace's inheritance sees every manifest. +fn packages_of(input: &CollectInput, exclude: &[String]) -> Result { let manifests = read(input, MANIFESTS)? .into_iter() .map(|(path, text)| match text { @@ -96,7 +156,11 @@ fn collect(input: &CollectInput) -> Result { } let packages = read_packages(&manifests, &listing).map_err(|e| e.to_string())?; Ok(CollectOutput { - facts: packages.iter().map(Package::fact).collect(), + facts: packages + .iter() + .filter(|package| !excluded(&package.path, exclude)) + .map(Package::fact) + .collect(), ..CollectOutput::default() }) } diff --git a/extensions/rust/cargo/src/tests.rs b/extensions/rust/cargo/src/tests.rs index d959959676..e9c945ed55 100644 --- a/extensions/rust/cargo/src/tests.rs +++ b/extensions/rust/cargo/src/tests.rs @@ -1,5 +1,6 @@ use super::*; -use serde_json::{json, Value}; +use serde_json::json; +use specforge_extension_sdk::SettingsItem; use specforge_test::prelude::*; /// The input the host sends for these `(path, text)` manifests and these listed target files. @@ -44,6 +45,17 @@ fn rust_cargo_declares_its_collector_its_reads_and_its_peer() { .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) .collect(); assert_eq!(peers, [("@code/core", "^1.1", false)]); + let [SettingsItem::Setting(exclude)] = &declaration.settings[..] else { + panic!("one setting: {:?}", declaration.settings); + }; + assert_eq!( + ( + exclude.name.as_str(), + exclude.field_type.as_str(), + &exclude.default + ), + ("exclude", "string_list", &Some(json!([]))) + ); let [collector] = &declaration.collectors[..] else { panic!("one collector: {:?}", declaration.collectors); }; @@ -167,6 +179,12 @@ fn a_withheld_or_truncated_read_is_the_collectors_error() { .unwrap(); let why = collect(&truncated).unwrap_err(); assert!(why.contains(&format!("'{read}'")), "{why}"); + // The guest cannot tell the walk's entry cap from the file cap: the error names both. + assert!( + why.contains("stopped early: the host's walk reached its cap of 20000 entries") + && why.contains("or more than 2000 files matched"), + "{why}" + ); } let unreadable = collect(&input(&[("bad/Cargo.toml", "[package\n")], &[])).unwrap_err(); assert!(unreadable.starts_with("bad/Cargo.toml: "), "{unreadable}"); @@ -192,3 +210,76 @@ fn a_package_fact_is_located_at_its_package_table() { .collect(); assert_eq!(at, [("crates/base/Cargo.toml", 3, 2, 3, 9)]); } + +#[specforge_test(requirement = "FEATURE-002")] +#[specforge_test(requirement = "FEATURE-108")] +fn a_directory_excludes_itself_and_what_lies_under_it() { + let examples = ["examples".to_string()]; + assert!(excluded("examples/shop", &examples)); + assert!(excluded("examples/shop", &["examples/shop".to_string()])); + assert!(!excluded("examplesx", &examples), "a whole segment only"); + assert!(!excluded("", &examples), "the root is under no entry"); +} + +#[specforge_test(requirement = "FEATURE-002")] +#[specforge_test(requirement = "FEATURE-108")] +fn the_exclude_list_takes_project_relative_directories_only() { + assert_eq!(exclude_list(None), Ok(Vec::new())); + assert_eq!( + exclude_list(Some(&json!([ + "gsd/parity/fixtures/", + "examples", + "./examples", + "examples/./shop", + "examples//shop", + "examples//" + ]))), + Ok([ + "gsd/parity/fixtures", + "examples", + "examples", + "examples/shop", + "examples/shop", + "examples" + ] + .map(str::to_string) + .to_vec()), + "an entry is normalized to the segments a package path is written in" + ); + for (entry, named) in [ + (json!("/abs"), "/abs"), + (json!("C:/x"), "C:/x"), + (json!(""), ""), + (json!("."), "."), + (json!("./"), "./"), + (json!("examples\\shop"), "examples\\shop"), + (json!("a/../b"), "a/../b"), + (json!(7), "7"), + ] { + assert_eq!( + exclude_list(Some(&json!([entry]))), + Err(format!( + "exclude entry '{named}' is not a project-relative directory" + )) + ); + } +} + +#[specforge_test(requirement = "FEATURE-002")] +#[specforge_test(requirement = "FEATURE-108")] +fn a_member_under_an_excluded_directory_is_no_package() { + let manifests = [ + ("Cargo.toml", ROOT), + ("crates/app/Cargo.toml", APP), + ("crates/base/Cargo.toml", BASE), + ("fixtures/x/Cargo.toml", BASE), + ]; + let out = packages_of(&input(&manifests, &[]), &["fixtures".to_string()]).unwrap(); + assert_eq!(ids(&out.facts), ["pkg:cargo/app", "pkg:cargo/base"]); + let out = packages_of(&input(&manifests, &[]), &["crates/base".to_string()]).unwrap(); + assert_eq!( + ids(&out.facts), + ["pkg:cargo/app", "pkg:cargo/base#fixtures/x"], + "a workspace member excluded after the read; its twin keeps its own id" + ); +} diff --git a/extensions/rust/cargo/wasm/inputs.json b/extensions/rust/cargo/wasm/inputs.json index 31ab9a0882..0a1d805589 100644 --- a/extensions/rust/cargo/wasm/inputs.json +++ b/extensions/rust/cargo/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "specforge_ext_rust_cargo.wasm", - "artifact_sha256": "6095ae970f56d96142d71b11bad218d338365b2c261cf427a335b39874c1914f", + "artifact_sha256": "f5707f4251f7d2e9f9a9cbb53f0f3e388812e4bffd1e472aeb2397dfa187bafc", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,29 +55,38 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", - "extensions/code/facts/src/ids.rs": "e3f1f07f70da4786c0ca0b301594b1dc812c2a45808dbe1a5f4905805eccce97", - "extensions/code/facts/src/lib.rs": "5a9733980787f23265ab7f374840d6f61bf2ecbdad3471df86e68c0f2e699769", - "extensions/code/facts/src/mint.rs": "e71f130aaeaeeca2d4c5afa59a36c60fa5ac8bc26db2f4a8276c71024305925e", - "extensions/code/facts/src/paths.rs": "890973baefd07c33e93c6c12ae882083c2d969de91bb3c697bc271ec03474eae", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", - "extensions/code/junit/src/lib.rs": "dfeb44e386f4865b2c5570d389bfd6ff246ccf69122ee36ec7feb9db8a394f35", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", "extensions/rust/cargo/Cargo.lock": "cf6bb004a3d04f51f2f0bd9c7536129b8200f278e138ea6e7e9306850a1eeab9", - "extensions/rust/cargo/Cargo.toml": "dca804e3681974e9dbd61c7df3628dcf21c522da88d33aac2881cf15e0fc3d76", - "extensions/rust/cargo/src/lib.rs": "65f6d8482ae2f39603e128b8601f5969c6d5636e02fe06859b023ac4fd87391a", + "extensions/rust/cargo/Cargo.toml": "b805b9ba66235e26472882ccbef6bbd2eafe810188d796efbfaba1e13ed05089", + "extensions/rust/cargo/src/lib.rs": "e6c1867cd428bd73731ec32ddb291ceff40084829ac94f0229ef83350ed6bcc1", "extensions/rust/manifest/Cargo.toml": "62c82a2b93bcc30ab59bcebda88e10cfa51575d48189e3cd8aacc0f2bbe9b1b6", "extensions/rust/manifest/src/lib.rs": "28abdde779d70db8b897c5affbaa5b7589ee818fed5c8df3ee81881989659baf", "extensions/rust/manifest/src/listing.rs": "6e37cfa735ce49a1e665f3f2a6b1a74f2444364913f3affecd4e8029121cdb6f" diff --git a/extensions/rust/cargo/wasm/specforge_ext_rust_cargo.wasm b/extensions/rust/cargo/wasm/specforge_ext_rust_cargo.wasm index 8c7759c76b..0b6e3d48fc 100644 Binary files a/extensions/rust/cargo/wasm/specforge_ext_rust_cargo.wasm and b/extensions/rust/cargo/wasm/specforge_ext_rust_cargo.wasm differ diff --git a/extensions/rust/coverage/Cargo.lock b/extensions/rust/coverage/Cargo.lock new file mode 100644 index 0000000000..0ceb981a51 --- /dev/null +++ b/extensions/rust/coverage/Cargo.lock @@ -0,0 +1,574 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-lcov" +version = "1.0.0" +dependencies = [ + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-rust-coverage" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-code-lcov", + "specforge-extension-sdk", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/rust/coverage/Cargo.toml b/extensions/rust/coverage/Cargo.toml new file mode 100644 index 0000000000..3f055ab936 --- /dev/null +++ b/extensions/rust/coverage/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "specforge-ext-rust-coverage" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-lcov = { path = "../../code/lcov" } +specforge-code-facts = { path = "../../code/facts" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" diff --git a/extensions/rust/coverage/fixtures/README.md b/extensions/rust/coverage/fixtures/README.md new file mode 100644 index 0000000000..af758e41e4 --- /dev/null +++ b/extensions/rust/coverage/fixtures/README.md @@ -0,0 +1,8 @@ +# @rust/coverage fixtures + +| Fixture | Source | +|---------|--------| +| `outside.info` | hand-written LCOV in `cargo llvm-cov --lcov` form: one section in the project (`/project/src/lib.rs`, the LCOV reader's `add`), one at `/elsewhere/a.rs` (a path dependency beside the workspace) and one at `../../etc/passwd` | + +The llvm-cov tracefile the tests read is the LCOV reader's hand-written `extensions/code/lcov/fixtures/llvm-cov.info`: +cargo-llvm-cov was not installed on the authoring host. Replace it with a recording when one is made. diff --git a/extensions/rust/coverage/fixtures/outside.info b/extensions/rust/coverage/fixtures/outside.info new file mode 100644 index 0000000000..1b75552e88 --- /dev/null +++ b/extensions/rust/coverage/fixtures/outside.info @@ -0,0 +1,16 @@ +TN: +SF:/project/src/lib.rs +FN:3,_RNvCs4fqI2P2rA04_4demo3add +FNDA:4,_RNvCs4fqI2P2rA04_4demo3add +DA:3,4 +DA:4,4 +DA:5,4 +end_of_record +SF:/elsewhere/a.rs +FN:1,_RNvCsX_5other1f +FNDA:1,_RNvCsX_5other1f +DA:1,1 +end_of_record +SF:../../etc/passwd +DA:1,1 +end_of_record diff --git a/extensions/rust/coverage/src/lib.rs b/extensions/rust/coverage/src/lib.rs new file mode 100644 index 0000000000..69534bd7e0 --- /dev/null +++ b/extensions/rust/coverage/src/lib.rs @@ -0,0 +1,95 @@ +//! @rust/coverage — runs the project's tests under cargo-llvm-cov and records its LCOV coverage as `@code/core`'s +//! `coverage` facts (ADR 0389). +//! +//! The collector `rust-coverage` is selected by a `Cargo.toml` at the project root. The host runs, with consent, +//! `cargo-llvm-cov llvm-cov nextest --workspace --ignore-run-fail --lcov --output-path {report}`: the program is +//! `cargo-llvm-cov`, so a missing tool is "not found on PATH" with its install line, and nextest runs the tests, as +//! `@rust/test` does: the collector `requires` `cargo-nextest`, so `specforge doctor` looks it up too. +//! `--ignore-run-fail` makes a failing test still write the report. The run builds the workspace a second time, +//! instrumented, under `target/llvm-cov-target`, and runs the project's own tests (ADR 0389 D9). It runs +//! in the caller's environment and declares the cargo, rustup and LLVM variables it reads, so the approval names them. +//! +//! The LCOV is read by `specforge-code-lcov` and minted by `specforge-code-facts` against `@rust/source`'s items: a +//! `coverage` fact per item a line reaches, one per file for what no item holds. A file outside the project (a path +//! dependency beside the workspace) is skipped and counted, and the pack returns one warning naming the report and the +//! paths, which the host shows as W203 (ADR 0389 D7). + +use specforge_code_facts::{coverage_facts, outside_line}; +use specforge_extension_sdk::prelude::*; + +const COLLECTOR: &str = "rust-coverage"; +/// The LCOV cargo-llvm-cov writes, relative to the project root. +const REPORT: &str = ".specforge/reports/rust-coverage.lcov"; + +#[specforge_extension_sdk::extension( + name = "@rust/coverage", + version = "1.0.0", + description = "Runs cargo llvm-cov and records its LCOV coverage as coverage facts (@code/core)" +)] +struct RustCoverage; + +impl Contributions for RustCoverage { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.2"); + // Its items place each line; without them every line is its file's. + c.peer("@rust/source", "^1.0"); + c.collector(COLLECTOR, |k| { + k.input_format("lcov") + .detect_files(&["Cargo.toml"]) + // No filter: a filtered run is partial coverage. + .run(&[ + "cargo-llvm-cov", + "llvm-cov", + "nextest", + "--workspace", + "--ignore-run-fail", + "--lcov", + "--output-path", + "{report}", + ]) + .env(&[ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "RUSTDOCFLAGS", + "LLVM_*", + ]) + // `nextest` runs cargo-nextest: doctor looks it up beside cargo-llvm-cov. + .requires(&["cargo-nextest"]) + .install("cargo install cargo-llvm-cov cargo-nextest --locked") + .report(REPORT) + .input(Input::facts(&["item"])) + .answers(&["coverage"]) + .collect(collect); + }); + } +} + +/// Map cargo-llvm-cov's LCOV to `coverage` facts, and the files it skipped as outside the project to one warning. +fn collect(input: &CollectInput) -> Result { + let [report] = &input.reports[..] else { + return Err(format!( + "{COLLECTOR} reads one report, {REPORT}; it was given {}", + input.reports.len() + )); + }; + let cwd = input.cwd.as_deref().ok_or( + "the host sent no cwd: cargo-llvm-cov writes absolute file paths, read against the project root", + )?; + let read = specforge_code_lcov::read(&report.content, cwd) + .map_err(|why| format!("{}: {why}", report.path))?; + Ok(CollectOutput { + facts: coverage_facts(&read.files, &input.facts), + warnings: outside_line(&report.path, &read.outside) + .into_iter() + .collect(), + ..CollectOutput::default() + }) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/rust/coverage/src/tests.rs b/extensions/rust/coverage/src/tests.rs new file mode 100644 index 0000000000..07d184b5f7 --- /dev/null +++ b/extensions/rust/coverage/src/tests.rs @@ -0,0 +1,139 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_test::prelude::*; + +/// The LCOV reader's hand-written `cargo llvm-cov --lcov` tracefile: crate `demo` at `/project`. +const LLVM_COV: &str = include_str!("../../../code/lcov/fixtures/llvm-cov.info"); +/// The LCOV reader's served `item` and `package` facts for that crate, as JSON. +const ITEMS: &str = include_str!("../../../code/lcov/fixtures/items.json"); +/// The LCOV reader's accepted snapshot of the facts `LLVM_COV` mints with `ITEMS` served. +const LLVM_COV_FACTS: &str = + include_str!("../../../code/lcov/src/snapshots/specforge_code_lcov__tests__llvm_cov.snap"); +/// Hand-written (see `fixtures/README.md`): one section in the project, two outside it. +const OUTSIDE: &str = include_str!("../fixtures/outside.info"); + +/// The input the host sends for these reports at `/project`, the reader's items served. +fn input(reports: &[&str]) -> CollectInput { + CollectInput { + reports: reports + .iter() + .map(|content| CollectReportFile { + path: REPORT.to_string(), + content: content.to_string(), + }) + .collect(), + cwd: Some("/project".to_string()), + facts: serde_json::from_str(ITEMS).expect("the served facts parse"), + ..CollectInput::default() + } +} + +/// The JSON body of an insta snapshot, after its `---` header. +fn snapshot(text: &str) -> Value { + let body = text.splitn(3, "---\n").nth(2).expect("a snapshot body"); + serde_json::from_str(body).expect("the snapshot parses") +} + +#[specforge_test(requirement = "FEATURE-143")] +fn rust_coverage_declares_llvm_cov_its_install_line_and_its_peers() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.2", false), + ("@rust/source", "^1.0", false) + ] + ); + let [collector] = &declaration.collectors[..] else { + panic!("one collector: {:?}", declaration.collectors); + }; + assert_eq!(collector.name, COLLECTOR); + assert_eq!(collector.input_formats, ["lcov"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["Cargo.toml".to_string()][..]) + ); + assert_eq!(collector.answers, ["coverage"]); + assert_eq!(collector.inputs, [Input::facts(&["item"])]); + assert_eq!(collector.report.as_deref(), Some(REPORT)); + assert_eq!( + collector.install.as_deref(), + Some("cargo install cargo-llvm-cov cargo-nextest --locked") + ); + assert_eq!(collector.requires, ["cargo-nextest"]); + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + assert_eq!(capabilities[0]["name"], COLLECTOR); + assert_eq!(capabilities[0]["port"], "process"); + assert_eq!( + capabilities[0]["argv"], + json!([ + "cargo-llvm-cov", + "llvm-cov", + "nextest", + "--workspace", + "--ignore-run-fail", + "--lcov", + "--output-path", + "{report}" + ]), + "{capabilities}" + ); + assert_eq!( + capabilities[0]["env"], + json!([ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "RUSTDOCFLAGS", + "LLVM_*" + ]) + ); + assert!(capabilities[0].get("filter").is_none_or(Value::is_null)); +} + +#[specforge_test(requirement = "FEATURE-143")] +fn an_llvm_cov_report_mints_the_readers_coverage_facts_and_no_warning() { + let out = collect(&input(&[LLVM_COV])).unwrap(); + assert_eq!( + serde_json::to_value(&out.facts).unwrap(), + snapshot(LLVM_COV_FACTS) + ); + assert_eq!(out.warnings, Vec::::new()); +} + +#[specforge_test(requirement = "FEATURE-143")] +fn a_file_outside_the_project_is_skipped_with_one_warning() { + let out = collect(&input(&[OUTSIDE])).unwrap(); + let ids: Vec<&str> = out.facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!(ids, ["cov:rust:demo::add"]); + assert_eq!(out.facts[0].fields["lines_found"], 3); + assert_eq!( + out.warnings, + [format!( + "{REPORT}: skipped 2 file(s) outside the project: /elsewhere/a.rs, ../../etc/passwd" + )] + ); +} + +#[specforge_test(requirement = "FEATURE-143")] +fn zero_or_two_reports_or_a_bad_one_is_the_collectors_error() { + for reports in [&[][..], &[LLVM_COV, LLVM_COV][..]] { + let why = collect(&input(reports)).unwrap_err(); + assert!(why.contains(COLLECTOR) && why.contains(REPORT), "{why}"); + } + let why = collect(&input(&["garbage"])).unwrap_err(); + assert!(why.starts_with(&format!("{REPORT}: line 1:")), "{why}"); + let no_cwd = CollectInput { + cwd: None, + ..input(&[LLVM_COV]) + }; + assert!(collect(&no_cwd).unwrap_err().contains("no cwd")); +} diff --git a/extensions/rust/coverage/wasm/inputs.json b/extensions/rust/coverage/wasm/inputs.json new file mode 100644 index 0000000000..784031b01a --- /dev/null +++ b/extensions/rust/coverage/wasm/inputs.json @@ -0,0 +1,93 @@ +{ + "artifact": "specforge_ext_rust_coverage.wasm", + "artifact_sha256": "5e27dc9bfb7dc1dfd06ee83cc54e2de481d31dd58795693088647d559701a1bc", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/code/lcov/Cargo.toml": "4beea7242b208263bcd13a5144693e9d16def91f0f05cd836be84a251f1a17c0", + "extensions/code/lcov/src/lib.rs": "48f980fd4ec553a09ae2cec049a524046de13a66d81a534e07271baae1130c87", + "extensions/rust/coverage/Cargo.lock": "a818e5deb85315013e9811d6bf8b220d46c43d5cb3d42c39e7d9e8fd603c72cf", + "extensions/rust/coverage/Cargo.toml": "440b49bcfcfc28ad97af599555ee744da121ca38be357bd164b5762e49d83550", + "extensions/rust/coverage/src/lib.rs": "727ca72ca8944d5cdbe9b4539e5cc7cdc109d3dfe111c1fedde5be9e6279a43b" + } +} diff --git a/extensions/rust/coverage/wasm/specforge_ext_rust_coverage.wasm b/extensions/rust/coverage/wasm/specforge_ext_rust_coverage.wasm new file mode 100644 index 0000000000..b6df9c1356 Binary files /dev/null and b/extensions/rust/coverage/wasm/specforge_ext_rust_coverage.wasm differ diff --git a/extensions/rust/deps/Cargo.lock b/extensions/rust/deps/Cargo.lock new file mode 100644 index 0000000000..1a54b540e1 --- /dev/null +++ b/extensions/rust/deps/Cargo.lock @@ -0,0 +1,586 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-cyclonedx" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-osv" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-rust-deps" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-cyclonedx", + "specforge-code-facts", + "specforge-code-osv", + "specforge-extension-sdk", + "specforge-protocol-types", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/rust/deps/Cargo.toml b/extensions/rust/deps/Cargo.toml new file mode 100644 index 0000000000..8f6c305572 --- /dev/null +++ b/extensions/rust/deps/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "specforge-ext-rust-deps" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-cyclonedx = { path = "../../code/cyclonedx" } +specforge-code-osv = { path = "../../code/osv" } +specforge-code-facts = { path = "../../code/facts" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" +# is_install_line: the host's rule for a collector's install line. +specforge-protocol-types = { path = "../../../crates/leaf/protocol-types" } diff --git a/extensions/rust/deps/fixtures/README.md b/extensions/rust/deps/fixtures/README.md new file mode 100644 index 0000000000..4b54605a1b --- /dev/null +++ b/extensions/rust/deps/fixtures/README.md @@ -0,0 +1,11 @@ +# @rust/deps fixtures + +cargo-cyclonedx was not installable on the host where these were written, so both fixtures are hand-written. + +| Fixture | Source | +|---------|--------| +| `ledger.cdx.json` | hand-written in the shape of the CycloneDX reader's `cargo.cdx.json` (cargo-cyclonedx, specVersion `1.5`): the BOM of the workspace member `ledger` 0.1.0, root `pkg:cargo/ledger@0.1.0?download_url=file://.`, one component `rust_decimal` 1.36.0, which the root depends on | +| `packages.json` | hand-written served facts: the `package` facts the collectors receive, `pkg:cargo/demo` at the project root and `pkg:cargo/ledger` at `crates/ledger` | + +The tests also read the CycloneDX reader's hand-written `../../code/cyclonedx/fixtures/cargo.cdx.json` (root +`pkg:cargo/demo`) and the OSV reader's recorded report `../../code/osv/fixtures/osv-scanner-2.7.1.json`. diff --git a/extensions/rust/deps/fixtures/ledger.cdx.json b/extensions/rust/deps/fixtures/ledger.cdx.json new file mode 100644 index 0000000000..aea607fbf2 --- /dev/null +++ b/extensions/rust/deps/fixtures/ledger.cdx.json @@ -0,0 +1,48 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "serialNumber": "urn:uuid:7d2e4f60-3a1b-4c8d-9e0f-2b3c4d5e6f70", + "metadata": { + "timestamp": "2026-11-23T12:00:00.000000000Z", + "tools": [{"vendor": "CycloneDX", "name": "cargo-cyclonedx", "version": "0.5.10"}], + "component": { + "type": "library", + "bom-ref": "path+file:///project/crates/ledger#ledger@0.1.0", + "name": "ledger", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/ledger@0.1.0?download_url=file://.", + "components": [ + { + "type": "library", + "bom-ref": "path+file:///project/crates/ledger#ledger@0.1.0 bin-target-0", + "name": "ledger", + "version": "0.1.0", + "purl": "pkg:cargo/ledger@0.1.0?download_url=file://.#src/lib.rs" + } + ] + } + }, + "components": [ + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rust_decimal@1.36.0", + "name": "rust_decimal", + "version": "1.36.0", + "scope": "required", + "licenses": [{"expression": "MIT"}], + "purl": "pkg:cargo/rust_decimal@1.36.0" + } + ], + "dependencies": [ + { + "ref": "path+file:///project/crates/ledger#ledger@0.1.0", + "dependsOn": ["registry+https://github.com/rust-lang/crates.io-index#rust_decimal@1.36.0"] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rust_decimal@1.36.0", + "dependsOn": [] + } + ] +} diff --git a/extensions/rust/deps/fixtures/packages.json b/extensions/rust/deps/fixtures/packages.json new file mode 100644 index 0000000000..d5aa9703ee --- /dev/null +++ b/extensions/rust/deps/fixtures/packages.json @@ -0,0 +1,6 @@ +[ + {"kind": "package", "id": "pkg:cargo/demo", + "fields": {"name": "demo", "version": "0.1.0", "path": ""}}, + {"kind": "package", "id": "pkg:cargo/ledger", + "fields": {"name": "ledger", "version": "0.1.0", "path": "crates/ledger"}} +] diff --git a/extensions/rust/deps/src/lib.rs b/extensions/rust/deps/src/lib.rs new file mode 100644 index 0000000000..c6cf3924e2 --- /dev/null +++ b/extensions/rust/deps/src/lib.rs @@ -0,0 +1,154 @@ +//! @rust/deps — runs cargo-cyclonedx and osv-scanner and records a Rust project's dependencies and their known +//! vulnerabilities as `@code/core`'s `dependency` and `vulnerability` facts (ADR 0389). A collector runs one +//! command, so the pack holds two. +//! +//! The collector `rust-sbom` is selected by a `Cargo.toml` at the project root. The host runs, with consent, +//! `cargo-cyclonedx cyclonedx --format json --spec-version 1.5 --all-features --override-filename rust-sbom.cdx`. +//! cargo-cyclonedx has no output path and appends the format's extension `.json` to the name it is given: it writes +//! one BOM named `rust-sbom.cdx.json` beside each workspace member's `Cargo.toml`. So the report is the glob +//! `**/rust-sbom.cdx.json`, read fresh after each run +//! (ADR 0389 D6), and a project may add `rust-sbom.cdx.json` to its `.gitignore`. cargo-cyclonedx calls `cargo +//! metadata`, which may run build scripts (ADR 0389 D9). Every BOM the glob hands in is read by +//! `specforge-code-cyclonedx` and minted by `specforge-code-facts` against `@rust/cargo`'s packages: one `dependency` +//! fact per component, citing the served package its BOM's root names. A BOM whose root names no served package is +//! an error naming that report: it is no report about this project. +//! +//! The collector `rust-osv` is selected by a `Cargo.lock`. The host runs, with consent, `osv-scanner scan source +//! --lockfile Cargo.lock --format json --output-file {report}`. The scan sends the lockfile's package names and +//! versions to the OSV API over the network, which the approval shows (ADR 0389 D9). osv-scanner exits 1 when it +//! finds vulnerabilities and 128 when it finds no lockfile (then it writes no report: E045); the host judges neither +//! exit code (ADR 0348 D4), it reads the report. Each record becomes a `vulnerability` fact citing the served cargo +//! packages at or under the lockfile's directory; every package the scan lists that no served package holds is +//! returned as one warning line, which the host shows as W203 (ADR 0389 D7), never dropped. + +use specforge_code_facts::{dependency_facts, vulnerability_facts}; +use specforge_extension_sdk::prelude::*; + +const SBOM: &str = "rust-sbom"; +/// Every BOM cargo-cyclonedx writes, one beside each member manifest, relative to the project root. +const SBOM_REPORT: &str = "**/rust-sbom.cdx.json"; +const OSV: &str = "rust-osv"; +/// The report osv-scanner writes, relative to the project root. +const OSV_REPORT: &str = ".specforge/reports/rust-osv.json"; + +#[specforge_extension_sdk::extension( + name = "@rust/deps", + version = "1.0.0", + description = "Runs cargo-cyclonedx and osv-scanner and records dependencies and vulnerabilities as facts (@code/core)" +)] +struct RustDeps; + +impl Contributions for RustDeps { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.2"); + // It brings @rust/cargo, whose packages are what a BOM's root names and a lockfile's directory holds. + c.peer("@rust/source", "^1.0"); + c.collector(SBOM, |k| { + k.input_format("cyclonedx-json") + .detect_files(&["Cargo.toml"]) + .run(&[ + "cargo-cyclonedx", + "cyclonedx", + "--format", + "json", + "--spec-version", + "1.5", + "--all-features", + "--override-filename", + "rust-sbom.cdx", + ]) + .env(&[ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "SOURCE_DATE_EPOCH", + ]) + .install("cargo install cargo-cyclonedx --locked") + .report(SBOM_REPORT) + .input(Input::facts(&["package"])) + .answers(&["dependency"]) + .collect(collect_sbom); + }); + c.collector(OSV, |k| { + k.input_format("osv-json") + .detect_files(&["Cargo.lock"]) + .run(&[ + "osv-scanner", + "scan", + "source", + "--lockfile", + "Cargo.lock", + "--format", + "json", + "--output-file", + "{report}", + ]) + .env(&[ + "HTTPS_PROXY", + "HTTP_PROXY", + "NO_PROXY", + "https_proxy", + "http_proxy", + "no_proxy", + "OSV_*", + ]) + .install("go install github.com/google/osv-scanner/v2/cmd/osv-scanner@latest (or: brew install osv-scanner)") + .report(OSV_REPORT) + .input(Input::facts(&["package"])) + .answers(&["vulnerability"]) + .collect(collect_osv); + }); + } +} + +/// Map every BOM cargo-cyclonedx wrote to `dependency` facts of the served package each root names. +fn collect_sbom(input: &CollectInput) -> Result { + if input.reports.is_empty() { + return Err(format!( + "{SBOM} reads every {SBOM_REPORT} cargo-cyclonedx wrote; it was given none" + )); + } + let mut reports: Vec<&CollectReportFile> = input.reports.iter().collect(); + reports.sort_by(|a, b| a.path.cmp(&b.path)); + let mut boms = Vec::with_capacity(reports.len()); + for report in reports { + let bom = specforge_code_cyclonedx::read(&report.content) + .map_err(|why| format!("{}: {why}", report.path))?; + // Minted one BOM at a time first, so an error names the report whose root is not served. + dependency_facts(std::slice::from_ref(&bom), &input.facts) + .map_err(|why| format!("{}: {why}", report.path))?; + boms.push(bom); + } + Ok(CollectOutput { + facts: dependency_facts(&boms, &input.facts)?, + ..CollectOutput::default() + }) +} + +/// Map osv-scanner's report to `vulnerability` facts, and every package it lists that no served package holds to a +/// warning line. +fn collect_osv(input: &CollectInput) -> Result { + let [report] = &input.reports[..] else { + return Err(format!( + "{OSV} reads one report, {OSV_REPORT}; it was given {}", + input.reports.len() + )); + }; + let cwd = input.cwd.as_deref().ok_or( + "the host sent no cwd: osv-scanner's report names absolute lockfile paths, read against the project root", + )?; + let scan = specforge_code_osv::read(&report.content, cwd) + .map_err(|why| format!("{}: {why}", report.path))?; + let minted = vulnerability_facts(&scan, &input.facts); + Ok(CollectOutput { + facts: minted.facts, + warnings: minted.skipped, + ..CollectOutput::default() + }) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/rust/deps/src/tests.rs b/extensions/rust/deps/src/tests.rs new file mode 100644 index 0000000000..82c610dad5 --- /dev/null +++ b/extensions/rust/deps/src/tests.rs @@ -0,0 +1,248 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_extension_sdk::ExtensionDeclaration; +use specforge_test::prelude::*; + +/// The CycloneDX reader's hand-written cargo-cyclonedx BOM of the root package `demo`. +const DEMO_BOM: &str = include_str!("../../../code/cyclonedx/fixtures/cargo.cdx.json"); +/// The hand-written BOM of the member `ledger` at `crates/ledger`. +const LEDGER_BOM: &str = include_str!("../fixtures/ledger.cdx.json"); +/// The OSV reader's osv-scanner 2.7.1 recording: `Cargo.lock` (smallvec 1.6.0) and `web/package-lock.json` (lodash +/// 4.17.15) of `/project`. +const OSV_SCANNER_2_7_1: &str = include_str!("../../../code/osv/fixtures/osv-scanner-2.7.1.json"); +/// The served `package` facts: `pkg:cargo/demo` at the root, `pkg:cargo/ledger` at `crates/ledger`. +const PACKAGES: &str = include_str!("../fixtures/packages.json"); + +/// The input the host sends for these `(path, content)` reports at `/project`, the pack's packages served. +fn input(reports: &[(&str, &str)]) -> CollectInput { + CollectInput { + reports: reports + .iter() + .map(|(path, content)| CollectReportFile { + path: path.to_string(), + content: content.to_string(), + }) + .collect(), + cwd: Some("/project".to_string()), + facts: serde_json::from_str(PACKAGES).expect("the served facts parse"), + ..CollectInput::default() + } +} + +/// The process capability of the collector `name`, with no filter. +fn capability(declaration: &ExtensionDeclaration, name: &str) -> Value { + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + let capability = capabilities + .as_array() + .unwrap() + .iter() + .find(|c| c["name"] == name) + .unwrap_or_else(|| panic!("a capability {name}: {capabilities}")) + .clone(); + assert_eq!(capability["port"], "process"); + assert!(capability.get("filter").is_none_or(Value::is_null)); + capability +} + +#[specforge_test(requirement = "FEATURE-148")] +fn rust_deps_declares_cargo_cyclonedx_over_a_glob_and_osv_scanner_over_the_lockfile() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.2", false), + ("@rust/source", "^1.0", false) + ] + ); + let names: Vec<&str> = declaration + .collectors + .iter() + .map(|c| c.name.as_str()) + .collect(); + assert_eq!(names, [SBOM, OSV]); + + let sbom = &declaration.collectors[0]; + assert_eq!(sbom.input_formats, ["cyclonedx-json"]); + assert_eq!( + sbom.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["Cargo.toml".to_string()][..]) + ); + assert_eq!(sbom.answers, ["dependency"]); + assert_eq!(sbom.inputs, [Input::facts(&["package"])]); + assert_eq!(sbom.report.as_deref(), Some("**/rust-sbom.cdx.json")); + assert_eq!( + sbom.install.as_deref(), + Some("cargo install cargo-cyclonedx --locked") + ); + let run = capability(&declaration, SBOM); + assert_eq!( + run["argv"], + json!([ + "cargo-cyclonedx", + "cyclonedx", + "--format", + "json", + "--spec-version", + "1.5", + "--all-features", + "--override-filename", + "rust-sbom.cdx" + ]) + ); + assert_eq!( + run["env"], + json!([ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "SOURCE_DATE_EPOCH" + ]) + ); + + let osv = &declaration.collectors[1]; + assert_eq!(osv.input_formats, ["osv-json"]); + assert_eq!( + osv.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["Cargo.lock".to_string()][..]) + ); + assert_eq!(osv.answers, ["vulnerability"]); + assert_eq!(osv.inputs, [Input::facts(&["package"])]); + assert_eq!(osv.report.as_deref(), Some(OSV_REPORT)); + let install = osv.install.as_deref().expect("an install line"); + assert!( + specforge_protocol_types::is_install_line(install), + "{install}" + ); + let run = capability(&declaration, OSV); + assert_eq!( + run["argv"], + json!([ + "osv-scanner", + "scan", + "source", + "--lockfile", + "Cargo.lock", + "--format", + "json", + "--output-file", + "{report}" + ]) + ); + assert_eq!( + run["env"], + json!([ + "HTTPS_PROXY", + "HTTP_PROXY", + "NO_PROXY", + "https_proxy", + "http_proxy", + "no_proxy", + "OSV_*" + ]) + ); +} + +#[specforge_test(requirement = "FEATURE-148")] +fn every_bom_the_glob_hands_in_mints_the_dependencies_of_its_own_package() { + // Given out of order: the collector reads them sorted by path. + let out = collect_sbom(&input(&[ + ("crates/ledger/rust-sbom.cdx.json", LEDGER_BOM), + ("rust-sbom.cdx.json", DEMO_BOM), + ])) + .unwrap(); + let minted: Vec<(&str, &str)> = out + .facts + .iter() + .map(|f| { + let package = f.fields["package"].as_str().unwrap(); + assert!( + f.id.starts_with(&format!("dep:{package}/")), + "{} of {package}", + f.id + ); + (package, f.fields["name"].as_str().unwrap()) + }) + .collect(); + assert_eq!( + minted, + [ + ("pkg:cargo/demo", "itoa"), + ("pkg:cargo/demo", "serde"), + ("pkg:cargo/demo", "serde_derive"), + ("pkg:cargo/ledger", "rust_decimal"), + ] + ); + let direct: Vec> = out + .facts + .iter() + .map(|f| f.fields.get("direct").and_then(Value::as_bool)) + .collect(); + assert_eq!(direct, [Some(false), Some(true), Some(false), Some(true)]); + assert_eq!(out.warnings, Vec::::new()); +} + +#[specforge_test(requirement = "FEATURE-148")] +fn no_bom_or_one_about_no_served_package_is_the_sbom_collectors_error() { + let why = collect_sbom(&input(&[])).unwrap_err(); + assert!(why.contains(SBOM) && why.contains(SBOM_REPORT), "{why}"); + let stranger = LEDGER_BOM.replace("pkg:cargo/ledger@", "pkg:cargo/stranger@"); + let why = collect_sbom(&input(&[ + ("rust-sbom.cdx.json", DEMO_BOM), + ("crates/stranger/rust-sbom.cdx.json", &stranger), + ])) + .unwrap_err(); + assert!( + why.starts_with("crates/stranger/rust-sbom.cdx.json: ") + && why.contains("names no collected package"), + "{why}" + ); + let why = collect_sbom(&input(&[("rust-sbom.cdx.json", "garbage")])).unwrap_err(); + assert!(why.starts_with("rust-sbom.cdx.json: no JSON"), "{why}"); +} + +#[specforge_test(requirement = "FEATURE-148")] +fn a_recorded_osv_scan_cites_the_root_crate_and_warns_of_each_package_it_skips() { + let out = collect_osv(&input(&[(OSV_REPORT, OSV_SCANNER_2_7_1)])).unwrap(); + let ids: Vec<&str> = out.facts.iter().map(|f| f.id.as_str()).collect(); + assert_eq!( + ids, + [ + "vuln:pkg:cargo/demo/GHSA-43w2-9j62-hq99", + "vuln:pkg:cargo/demo/RUSTSEC-2021-0003" + ] + ); + // lodash of web/package-lock.json: this pack serves no npm package, so it is named, not dropped. + assert_eq!( + out.warnings, + ["'lodash' 4.17.15 in 'web/package-lock.json' (5 records) is skipped: no collected pkg:npm package lies \ + at or under the lockfile's directory"] + ); +} + +#[specforge_test(requirement = "FEATURE-148")] +fn zero_or_two_scans_or_a_bad_one_is_the_osv_collectors_error() { + for reports in [ + &[][..], + &[ + (OSV_REPORT, OSV_SCANNER_2_7_1), + (OSV_REPORT, OSV_SCANNER_2_7_1), + ][..], + ] { + let why = collect_osv(&input(reports)).unwrap_err(); + assert!(why.contains(OSV) && why.contains(OSV_REPORT), "{why}"); + } + let why = collect_osv(&input(&[(OSV_REPORT, "garbage")])).unwrap_err(); + assert!(why.starts_with(&format!("{OSV_REPORT}: no JSON")), "{why}"); + let no_cwd = CollectInput { + cwd: None, + ..input(&[(OSV_REPORT, OSV_SCANNER_2_7_1)]) + }; + assert!(collect_osv(&no_cwd).unwrap_err().contains("no cwd")); +} diff --git a/extensions/rust/deps/wasm/inputs.json b/extensions/rust/deps/wasm/inputs.json new file mode 100644 index 0000000000..90bafd2d92 --- /dev/null +++ b/extensions/rust/deps/wasm/inputs.json @@ -0,0 +1,95 @@ +{ + "artifact": "specforge_ext_rust_deps.wasm", + "artifact_sha256": "a1a16bc43081e22cbebd8f4051bfe3eb96b1082f6a7db9871fc102258589ffbc", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/cyclonedx/Cargo.toml": "26066b84a4d10419509350276717b316340d2a60e5c4a75752b2439afa6ea46d", + "extensions/code/cyclonedx/src/lib.rs": "7123dc3e319e203cfa0594bad454f9ca6605b5258163fa63d6a3de643d9a3909", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/code/osv/Cargo.toml": "60be7012d312638636f64a736ead96529b134fc08f3b5aa9f0b481af8eadca17", + "extensions/code/osv/src/lib.rs": "47c587bd88b2fc3d1aa4885aa4d4c3666f59ddbb6a4aff1408a5e06618e0cff9", + "extensions/rust/deps/Cargo.lock": "a494e6bd8c1c9591af34ce2735e1a22301fe4dec2bf5e8a6d7fdfbcad0bcec45", + "extensions/rust/deps/Cargo.toml": "cd5b815291ff376c25a349386890ced63010035dc381dcec570558942d4ed6cf", + "extensions/rust/deps/src/lib.rs": "3fda92ea1a516affd34f5d7f204f45b88119d9ca322d2a58e932e6b450b38981" + } +} diff --git a/extensions/rust/deps/wasm/specforge_ext_rust_deps.wasm b/extensions/rust/deps/wasm/specforge_ext_rust_deps.wasm new file mode 100644 index 0000000000..64108cd605 Binary files /dev/null and b/extensions/rust/deps/wasm/specforge_ext_rust_deps.wasm differ diff --git a/extensions/rust/lint/Cargo.lock b/extensions/rust/lint/Cargo.lock new file mode 100644 index 0000000000..9c3c743e25 --- /dev/null +++ b/extensions/rust/lint/Cargo.lock @@ -0,0 +1,682 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "windows-sys", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "insta" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67d3d2e287e4b86c10b3f3b641033d1f89b74bdb39d05f34952e2b9a6fe21cd" +dependencies = [ + "console", + "once_cell", + "serde", + "similar", + "tempfile", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-ext-rust-lint" +version = "1.0.0" +dependencies = [ + "insta", + "serde_json", + "specforge-code-facts", + "specforge-extension-sdk", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/rust/lint/Cargo.toml b/extensions/rust/lint/Cargo.toml new file mode 100644 index 0000000000..27f3a40011 --- /dev/null +++ b/extensions/rust/lint/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "specforge-ext-rust-lint" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-facts = { path = "../../code/facts" } +serde_json = "1.0" + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +insta = { version = "1.46.3", features = ["json"] } diff --git a/extensions/rust/lint/fixtures/README.md b/extensions/rust/lint/fixtures/README.md new file mode 100644 index 0000000000..d04fc37530 --- /dev/null +++ b/extensions/rust/lint/fixtures/README.md @@ -0,0 +1,6 @@ +# @rust/lint fixtures + +| Fixture | Source | +|---------|--------| +| `clippy-0.1.98.jsonl` | recorded with clippy 0.1.98 (cargo 1.98.1) by the Phase 11 research: `cargo clippy --workspace --all-targets --message-format=json -- -W clippy::unwrap_used` over the crate `demo` (one `src/lib.rs`: `Board`, `Board::len`, `first`, `tests::reads`), standard output only, absolute paths replaced by `/project` with `sed -E 's#/private/tmp/[^"<> ]*/research-tools/[^/"<> \#]*#/project#g' > clippy-0.1.98.jsonl`. Eight `compiler-message` lines, each of the four diagnostics twice (`--all-targets` checks the library as lib and as lib test), two `compiler-artifact`, one `build-finished` | +| `items.json` | hand-written served facts: the `item` facts of the recorded crate's `src/lib.rs` at their real extents (outer attributes included) and its root `package` | diff --git a/extensions/rust/lint/fixtures/clippy-0.1.98.jsonl b/extensions/rust/lint/fixtures/clippy-0.1.98.jsonl new file mode 100644 index 0000000000..ab8b6e3861 --- /dev/null +++ b/extensions/rust/lint/fixtures/clippy-0.1.98.jsonl @@ -0,0 +1,11 @@ +{"reason":"compiler-message","package_id":"path+file:///project#demo@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"demo","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"message":{"rendered":"warning: unused variable: `unused`\n --> src/lib.rs:12:9\n |\n12 | let unused = 3;\n | ^^^^^^ help: if this is intentional, prefix it with an underscore: `_unused`\n |\n = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default\n\n","$message_type":"diagnostic","children":[{"children":[],"code":null,"level":"note","message":"`#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default","rendered":null,"spans":[]},{"children":[],"code":null,"level":"help","message":"if this is intentional, prefix it with an underscore","rendered":null,"spans":[{"byte_end":183,"byte_start":177,"column_end":15,"column_start":9,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":12,"line_start":12,"suggested_replacement":"_unused","suggestion_applicability":"MachineApplicable","text":[{"highlight_end":15,"highlight_start":9,"text":" let unused = 3;"}]}]}],"level":"warning","message":"unused variable: `unused`","spans":[{"byte_end":183,"byte_start":177,"column_end":15,"column_start":9,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":12,"line_start":12,"suggested_replacement":null,"suggestion_applicability":null,"text":[{"highlight_end":15,"highlight_start":9,"text":" let unused = 3;"}]}],"code":{"code":"unused_variables","explanation":null}}} +{"reason":"compiler-message","package_id":"path+file:///project#demo@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"demo","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"message":{"rendered":"warning: struct `Board` has a public `len` method, but no `is_empty` method\n --> src/lib.rs:6:5\n |\n6 | pub fn len(&self) -> usize {\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#len_without_is_empty\n = note: `#[warn(clippy::len_without_is_empty)]` on by default\n\n","$message_type":"diagnostic","children":[{"children":[],"code":null,"level":"help","message":"for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#len_without_is_empty","rendered":null,"spans":[]},{"children":[],"code":null,"level":"note","message":"`#[warn(clippy::len_without_is_empty)]` on by default","rendered":null,"spans":[]}],"level":"warning","message":"struct `Board` has a public `len` method, but no `is_empty` method","spans":[{"byte_end":86,"byte_start":60,"column_end":31,"column_start":5,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":6,"line_start":6,"suggested_replacement":null,"suggestion_applicability":null,"text":[{"highlight_end":31,"highlight_start":5,"text":" pub fn len(&self) -> usize {"}]}],"code":{"code":"clippy::len_without_is_empty","explanation":null}}} +{"reason":"compiler-message","package_id":"path+file:///project#demo@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"demo","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"message":{"rendered":"warning: unneeded `return` statement\n --> src/lib.rs:7:9\n |\n7 | return self.cards.len();\n | ^^^^^^^^^^^^^^^^^^^^^^^\n |\n = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#needless_return\n = note: `#[warn(clippy::needless_return)]` on by default\nhelp: remove `return`\n |\n7 - return self.cards.len();\n7 + self.cards.len()\n |\n\n","$message_type":"diagnostic","children":[{"children":[],"code":null,"level":"help","message":"for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#needless_return","rendered":null,"spans":[]},{"children":[],"code":null,"level":"note","message":"`#[warn(clippy::needless_return)]` on by default","rendered":null,"spans":[]},{"children":[],"code":null,"level":"help","message":"remove `return`","rendered":null,"spans":[{"byte_end":120,"byte_start":97,"column_end":32,"column_start":9,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":7,"line_start":7,"suggested_replacement":"self.cards.len()","suggestion_applicability":"MachineApplicable","text":[{"highlight_end":32,"highlight_start":9,"text":" return self.cards.len();"}]},{"byte_end":121,"byte_start":120,"column_end":33,"column_start":32,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":7,"line_start":7,"suggested_replacement":"","suggestion_applicability":"MachineApplicable","text":[{"highlight_end":33,"highlight_start":32,"text":" return self.cards.len();"}]}]}],"level":"warning","message":"unneeded `return` statement","spans":[{"byte_end":120,"byte_start":97,"column_end":32,"column_start":9,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":7,"line_start":7,"suggested_replacement":null,"suggestion_applicability":null,"text":[{"highlight_end":32,"highlight_start":9,"text":" return self.cards.len();"}]}],"code":{"code":"clippy::needless_return","explanation":null}}} +{"reason":"compiler-message","package_id":"path+file:///project#demo@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"demo","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"message":{"rendered":"warning: used `unwrap()` on an `Option` value\n --> src/lib.rs:13:5\n |\n13 | v.unwrap()\n | ^^^^^^^^^^\n |\n = note: if this value is `None`, it will panic\n = help: consider using `expect()` to provide a better panic message\n = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#unwrap_used\n = note: requested on the command line with `-W clippy::unwrap-used`\n\n","$message_type":"diagnostic","children":[{"children":[],"code":null,"level":"note","message":"if this value is `None`, it will panic","rendered":null,"spans":[]},{"children":[],"code":null,"level":"help","message":"consider using `expect()` to provide a better panic message","rendered":null,"spans":[]},{"children":[],"code":null,"level":"help","message":"for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#unwrap_used","rendered":null,"spans":[]},{"children":[],"code":null,"level":"note","message":"requested on the command line with `-W clippy::unwrap-used`","rendered":null,"spans":[]}],"level":"warning","message":"used `unwrap()` on an `Option` value","spans":[{"byte_end":203,"byte_start":193,"column_end":15,"column_start":5,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":13,"line_start":13,"suggested_replacement":null,"suggestion_applicability":null,"text":[{"highlight_end":15,"highlight_start":5,"text":" v.unwrap()"}]}],"code":{"code":"clippy::unwrap_used","explanation":null}}} +{"reason":"compiler-message","package_id":"path+file:///project#demo@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"demo","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"message":{"rendered":"warning: unused variable: `unused`\n --> src/lib.rs:12:9\n |\n12 | let unused = 3;\n | ^^^^^^ help: if this is intentional, prefix it with an underscore: `_unused`\n |\n = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default\n\n","$message_type":"diagnostic","children":[{"children":[],"code":null,"level":"note","message":"`#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default","rendered":null,"spans":[]},{"children":[],"code":null,"level":"help","message":"if this is intentional, prefix it with an underscore","rendered":null,"spans":[{"byte_end":183,"byte_start":177,"column_end":15,"column_start":9,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":12,"line_start":12,"suggested_replacement":"_unused","suggestion_applicability":"MachineApplicable","text":[{"highlight_end":15,"highlight_start":9,"text":" let unused = 3;"}]}]}],"level":"warning","message":"unused variable: `unused`","spans":[{"byte_end":183,"byte_start":177,"column_end":15,"column_start":9,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":12,"line_start":12,"suggested_replacement":null,"suggestion_applicability":null,"text":[{"highlight_end":15,"highlight_start":9,"text":" let unused = 3;"}]}],"code":{"code":"unused_variables","explanation":null}}} +{"reason":"compiler-message","package_id":"path+file:///project#demo@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"demo","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"message":{"rendered":"warning: struct `Board` has a public `len` method, but no `is_empty` method\n --> src/lib.rs:6:5\n |\n6 | pub fn len(&self) -> usize {\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#len_without_is_empty\n = note: `#[warn(clippy::len_without_is_empty)]` on by default\n\n","$message_type":"diagnostic","children":[{"children":[],"code":null,"level":"help","message":"for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#len_without_is_empty","rendered":null,"spans":[]},{"children":[],"code":null,"level":"note","message":"`#[warn(clippy::len_without_is_empty)]` on by default","rendered":null,"spans":[]}],"level":"warning","message":"struct `Board` has a public `len` method, but no `is_empty` method","spans":[{"byte_end":86,"byte_start":60,"column_end":31,"column_start":5,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":6,"line_start":6,"suggested_replacement":null,"suggestion_applicability":null,"text":[{"highlight_end":31,"highlight_start":5,"text":" pub fn len(&self) -> usize {"}]}],"code":{"code":"clippy::len_without_is_empty","explanation":null}}} +{"reason":"compiler-message","package_id":"path+file:///project#demo@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"demo","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"message":{"rendered":"warning: unneeded `return` statement\n --> src/lib.rs:7:9\n |\n7 | return self.cards.len();\n | ^^^^^^^^^^^^^^^^^^^^^^^\n |\n = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#needless_return\n = note: `#[warn(clippy::needless_return)]` on by default\nhelp: remove `return`\n |\n7 - return self.cards.len();\n7 + self.cards.len()\n |\n\n","$message_type":"diagnostic","children":[{"children":[],"code":null,"level":"help","message":"for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#needless_return","rendered":null,"spans":[]},{"children":[],"code":null,"level":"note","message":"`#[warn(clippy::needless_return)]` on by default","rendered":null,"spans":[]},{"children":[],"code":null,"level":"help","message":"remove `return`","rendered":null,"spans":[{"byte_end":120,"byte_start":97,"column_end":32,"column_start":9,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":7,"line_start":7,"suggested_replacement":"self.cards.len()","suggestion_applicability":"MachineApplicable","text":[{"highlight_end":32,"highlight_start":9,"text":" return self.cards.len();"}]},{"byte_end":121,"byte_start":120,"column_end":33,"column_start":32,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":7,"line_start":7,"suggested_replacement":"","suggestion_applicability":"MachineApplicable","text":[{"highlight_end":33,"highlight_start":32,"text":" return self.cards.len();"}]}]}],"level":"warning","message":"unneeded `return` statement","spans":[{"byte_end":120,"byte_start":97,"column_end":32,"column_start":9,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":7,"line_start":7,"suggested_replacement":null,"suggestion_applicability":null,"text":[{"highlight_end":32,"highlight_start":9,"text":" return self.cards.len();"}]}],"code":{"code":"clippy::needless_return","explanation":null}}} +{"reason":"compiler-message","package_id":"path+file:///project#demo@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"demo","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"message":{"rendered":"warning: used `unwrap()` on an `Option` value\n --> src/lib.rs:13:5\n |\n13 | v.unwrap()\n | ^^^^^^^^^^\n |\n = note: if this value is `None`, it will panic\n = help: consider using `expect()` to provide a better panic message\n = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#unwrap_used\n = note: requested on the command line with `-W clippy::unwrap-used`\n\n","$message_type":"diagnostic","children":[{"children":[],"code":null,"level":"note","message":"if this value is `None`, it will panic","rendered":null,"spans":[]},{"children":[],"code":null,"level":"help","message":"consider using `expect()` to provide a better panic message","rendered":null,"spans":[]},{"children":[],"code":null,"level":"help","message":"for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#unwrap_used","rendered":null,"spans":[]},{"children":[],"code":null,"level":"note","message":"requested on the command line with `-W clippy::unwrap-used`","rendered":null,"spans":[]}],"level":"warning","message":"used `unwrap()` on an `Option` value","spans":[{"byte_end":203,"byte_start":193,"column_end":15,"column_start":5,"expansion":null,"file_name":"src/lib.rs","is_primary":true,"label":null,"line_end":13,"line_start":13,"suggested_replacement":null,"suggestion_applicability":null,"text":[{"highlight_end":15,"highlight_start":5,"text":" v.unwrap()"}]}],"code":{"code":"clippy::unwrap_used","explanation":null}}} +{"reason":"compiler-artifact","package_id":"path+file:///project#demo@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"demo","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/project/target/debug/deps/libdemo-e5848d5951bb63c7.rmeta"],"executable":null,"fresh":false} +{"reason":"compiler-artifact","package_id":"path+file:///project#demo@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"demo","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":true},"features":[],"filenames":["/project/target/debug/deps/libdemo-dacb77a37e443bcc.rmeta"],"executable":null,"fresh":false} +{"reason":"build-finished","success":true} diff --git a/extensions/rust/lint/fixtures/items.json b/extensions/rust/lint/fixtures/items.json new file mode 100644 index 0000000000..16750aa286 --- /dev/null +++ b/extensions/rust/lint/fixtures/items.json @@ -0,0 +1,21 @@ +[ + {"kind": "item", "id": "rust:demo::Board", + "fields": {"kind": ["struct"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "public"}, + "at": [{"file": "src/lib.rs", "start_line": 1, "start_col": 1, "end_line": 3, "end_col": 2}]}, + {"kind": "item", "id": "rust:demo::Board::len", + "fields": {"kind": ["fn"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "public"}, + "at": [{"file": "src/lib.rs", "start_line": 6, "start_col": 5, "end_line": 8, "end_col": 6}]}, + {"kind": "item", "id": "rust:demo::first", + "fields": {"kind": ["fn"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "public"}, + "at": [{"file": "src/lib.rs", "start_line": 11, "start_col": 1, "end_line": 14, "end_col": 2}]}, + {"kind": "item", "id": "rust:demo::tests", + "fields": {"kind": ["mod"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "private", + "attrs": ["cfg(test)"]}, + "at": [{"file": "src/lib.rs", "start_line": 16, "start_col": 1, "end_line": 23, "end_col": 2}]}, + {"kind": "item", "id": "rust:demo::tests::reads", + "fields": {"kind": ["fn"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "private", + "attrs": ["test"], "test_id": "rust:demo#tests::reads"}, + "at": [{"file": "src/lib.rs", "start_line": 18, "start_col": 5, "end_line": 22, "end_col": 6}]}, + {"kind": "package", "id": "pkg:cargo/demo", + "fields": {"name": "demo", "version": "0.1.0", "path": ""}} +] diff --git a/extensions/rust/lint/src/clippy.rs b/extensions/rust/lint/src/clippy.rs new file mode 100644 index 0000000000..fda53fed89 --- /dev/null +++ b/extensions/rust/lint/src/clippy.rs @@ -0,0 +1,145 @@ +//! cargo's JSON messages (`--message-format=json`) as SARIF results (ADR 0389 D8): clippy writes no SARIF, so the pack +//! converts its diagnostics into [`SarifResult`] values for `specforge-code-facts`' `finding_facts`. Text in, values +//! out: nothing here opens a file. + +use std::collections::BTreeSet; + +use serde_json::Value; +use specforge_code_facts::{place, shown, Level, Place, SarifResult, UNKNOWN}; + +/// The tool every result names. +const TOOL: &str = "clippy"; + +/// What a capture converts to: its results, and the paths of the primary spans it skipped, each once and [`shown`]. +#[derive(Debug, Default, PartialEq)] +pub(crate) struct Converted { + pub(crate) results: Vec, + /// Paths outside the project (a registry crate's macro). + pub(crate) outside: Vec, + /// Paths naming no file: rustc's pseudo names (``, ``) and a path resolving to the root itself. + pub(crate) no_file: Vec, +} + +/// The results of cargo's JSON lines `text`, their files relative to the project root `cwd`, and the paths of the +/// primary spans it skipped as outside the project or naming no file. +/// +/// A line whose `reason` is `compiler-message` and whose message has a code or a primary span is one result: the rule +/// is `message.code.code` (a rustc lint keeps its bare name, `unused_variables`), else `unknown`; the level is +/// `message.level` (`error`, `warning`, `note` and `help` as note, anything else `unknown`); the message is +/// `message.message`; the file and lines are the span marked `is_primary` (`file_name`, `line_start`, `line_end`), +/// only that one. Other reasons, summaries with neither code nor span ("2 warnings emitted") and blank lines are +/// ignored. Results equal on rule, file, lines and message appear once, in first-seen order: `--all-targets` checks a +/// library twice (lib and lib test) and repeats each of its diagnostics. A primary span outside the project (a +/// registry crate's macro) is counted, not kept; so is one naming no file (rustc's ``), which no finding +/// can cite. +/// +/// A capture cut off inside a line or between two is an error, so it fails instead of dropping findings: a line that is +/// no JSON, named by its 1-based number, or no `build-finished` record, which cargo writes last on every run that ends, +/// failed builds included (a run killed by a signal stops before it). +pub(crate) fn results(text: &str, cwd: &str) -> Result { + let mut converted = Converted::default(); + let mut seen = BTreeSet::new(); + let mut seen_skipped = BTreeSet::new(); + let mut finished = false; + for (at, line) in text.lines().enumerate() { + if line.trim().is_empty() { + continue; + } + let value: Value = + serde_json::from_str(line).map_err(|e| format!("line {}: no JSON: {e}", at + 1))?; + match value.get("reason").and_then(Value::as_str) { + Some("compiler-message") => {} + Some("build-finished") => { + finished = true; + continue; + } + _ => continue, + } + let Some(message) = value.get("message") else { + continue; + }; + let rule = message.pointer("/code/code").and_then(Value::as_str); + let primary = message + .get("spans") + .and_then(Value::as_array) + .and_then(|spans| { + spans + .iter() + .find(|span| span.get("is_primary").and_then(Value::as_bool) == Some(true)) + }); + if rule.is_none() && primary.is_none() { + continue; + } + let (file, line, end_line) = match primary { + None => (None, None, None), + Some(span) => { + let file = match span.get("file_name").and_then(Value::as_str) { + None => None, + Some(name) => match place(name, cwd) { + Place::File(file) => Some(file), + unplaced => { + let path = shown(name); + if seen_skipped.insert(path.clone()) { + match unplaced { + Place::NoFile => converted.no_file.push(path), + _ => converted.outside.push(path), + } + } + continue; + } + }, + }; + (file, number(span, "line_start"), number(span, "line_end")) + } + }; + let result = SarifResult { + tool: TOOL.to_string(), + rule: rule.unwrap_or(UNKNOWN).to_string(), + level: level(message.get("level").and_then(Value::as_str)), + message: message + .get("message") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + file, + line, + end_line, + }; + let key = ( + result.rule.clone(), + result.file.clone(), + result.line, + result.end_line, + result.message.clone(), + ); + if seen.insert(key) { + converted.results.push(result); + } + } + if !finished { + return Err( + "no `build-finished` record: the capture stops before cargo's last line, so the run was cut off (killed \ + or crashed) and its findings may be partial" + .to_string(), + ); + } + Ok(converted) +} + +/// cargo's diagnostic level as a SARIF level. +fn level(level: Option<&str>) -> Level { + match level { + Some("error") => Level::Error, + Some("warning") => Level::Warning, + Some("note" | "help") => Level::Note, + _ => Level::Unknown, + } +} + +/// The 1-based line number at `name` of `span`, if it is one. +fn number(span: &Value, name: &str) -> Option { + span.get(name) + .and_then(Value::as_u64) + .and_then(|line| usize::try_from(line).ok()) + .filter(|&line| line >= 1) +} diff --git a/extensions/rust/lint/src/lib.rs b/extensions/rust/lint/src/lib.rs new file mode 100644 index 0000000000..fdd341039a --- /dev/null +++ b/extensions/rust/lint/src/lib.rs @@ -0,0 +1,103 @@ +//! @rust/lint — runs cargo clippy and records its diagnostics as `@code/core`'s `static_finding` facts (ADR 0389). +//! +//! The collector `rust-lint` is selected by a `Cargo.toml` at the project root. The host runs, with consent, +//! `cargo-clippy clippy --workspace --all-targets --message-format=json`: the program is `cargo-clippy`, so a missing +//! component is "not found on PATH" with its install line. clippy builds the workspace and runs its build scripts and +//! proc macros, which the approval shows as it shows the command (ADR 0389 D9). cargo writes its JSON messages to +//! standard output, which the host captures into `.specforge/reports/rust-lint/rust-lint.stdout.txt` and passes as +//! `CollectInput::stdout`; `specforge collect --report ` passes a saved capture as the one report instead. +//! +//! clippy writes no SARIF, and the host runs one argv, so no `clippy-sarif` pipe: [`clippy`] converts the JSON +//! messages into the SARIF reader's results, and `specforge-code-facts` mints one `static_finding` per diagnostic +//! against `@rust/source`'s items (ADR 0389 D8). Only a diagnostic's primary span is kept. `--all-targets` checks a +//! library twice, as lib and as lib test, and repeats each of its diagnostics: the converter keeps one. A span in a +//! file outside the project (a registry crate's macro) is skipped and counted, and the pack returns one warning naming +//! the capture and the paths, which the host shows as W203 (ADR 0389 D7). A span naming no file (rustc's pseudo names +//! such as ``) is skipped and counted the same way, in a warning of its own, never minted. + +use specforge_code_facts::{finding_facts, no_file_line, outside_line}; +use specforge_extension_sdk::prelude::*; + +mod clippy; + +const COLLECTOR: &str = "rust-lint"; +/// The report directory, relative to the project root: the host keeps the captured standard output in it. +const REPORT: &str = ".specforge/reports/rust-lint"; +/// Where the host keeps the captured standard output: `/.stdout.txt`. +const CAPTURE: &str = ".specforge/reports/rust-lint/rust-lint.stdout.txt"; + +#[specforge_extension_sdk::extension( + name = "@rust/lint", + version = "1.0.0", + description = "Runs cargo clippy and records its diagnostics as static_finding facts (@code/core)" +)] +struct RustLint; + +impl Contributions for RustLint { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.2"); + // Its items and packages place each finding; without them a finding cites nothing. + c.peer("@rust/source", "^1.0"); + c.collector(COLLECTOR, |k| { + k.input_format("cargo-json") + .detect_files(&["Cargo.toml"]) + // No filter: a filtered run lints part of the workspace. + .run(&[ + "cargo-clippy", + "clippy", + "--workspace", + "--all-targets", + "--message-format=json", + ]) + .env(&[ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "RUSTDOCFLAGS", + "CLIPPY_*", + ]) + .install("rustup component add clippy") + .report(REPORT) + .capture_stdout() + .input(Input::facts(&["item", "package"])) + .answers(&["static_finding"]) + .collect(collect); + }); + } +} + +/// Map clippy's captured JSON messages (else the one report given) to `static_finding` facts, and the paths it skipped, +/// outside the project or naming no file, to a warning each. +fn collect(input: &CollectInput) -> Result { + let (path, text) = match (&input.stdout, &input.reports[..]) { + (Some(stdout), _) => (CAPTURE, stdout.as_str()), + (None, [report]) => (report.path.as_str(), report.content.as_str()), + (None, reports) => { + return Err(format!( + "{COLLECTOR}: clippy's standard output was not captured, and it reads one report in its place; it \ + was given {}", + reports.len() + )) + } + }; + let cwd = input + .cwd + .as_deref() + .ok_or("the host sent no cwd: a clippy span's file is read against the project root")?; + let converted = clippy::results(text, cwd).map_err(|why| format!("{path}: {why}"))?; + Ok(CollectOutput { + facts: finding_facts(&converted.results, &input.facts), + warnings: outside_line(path, &converted.outside) + .into_iter() + .chain(no_file_line(path, &converted.no_file)) + .collect(), + ..CollectOutput::default() + }) +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/rust/lint/src/snapshots/specforge_ext_rust_lint__tests__clippy__clippy_0_1_98.snap b/extensions/rust/lint/src/snapshots/specforge_ext_rust_lint__tests__clippy__clippy_0_1_98.snap new file mode 100644 index 0000000000..b82b8ac578 --- /dev/null +++ b/extensions/rust/lint/src/snapshots/specforge_ext_rust_lint__tests__clippy__clippy_0_1_98.snap @@ -0,0 +1,94 @@ +--- +source: src/tests.rs +expression: facts +--- +[ + { + "kind": "static_finding", + "id": "sarif:clippy/unused_variables#src%2Flib.rs:12", + "fields": { + "file": "src/lib.rs", + "item": "rust:demo::first", + "level": "warning", + "line": 12, + "message": "unused variable: `unused`", + "rule": "unused_variables", + "tool": "clippy" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 12, + "start_col": 1, + "end_line": 13, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:clippy/clippy%3A%3Alen_without_is_empty#src%2Flib.rs:6", + "fields": { + "file": "src/lib.rs", + "item": "rust:demo::Board::len", + "level": "warning", + "line": 6, + "message": "struct `Board` has a public `len` method, but no `is_empty` method", + "rule": "clippy::len_without_is_empty", + "tool": "clippy" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 6, + "start_col": 1, + "end_line": 7, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:clippy/clippy%3A%3Aneedless_return#src%2Flib.rs:7", + "fields": { + "file": "src/lib.rs", + "item": "rust:demo::Board::len", + "level": "warning", + "line": 7, + "message": "unneeded `return` statement", + "rule": "clippy::needless_return", + "tool": "clippy" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 7, + "start_col": 1, + "end_line": 8, + "end_col": 1 + } + ] + }, + { + "kind": "static_finding", + "id": "sarif:clippy/clippy%3A%3Aunwrap_used#src%2Flib.rs:13", + "fields": { + "file": "src/lib.rs", + "item": "rust:demo::first", + "level": "warning", + "line": 13, + "message": "used `unwrap()` on an `Option` value", + "rule": "clippy::unwrap_used", + "tool": "clippy" + }, + "at": [ + { + "file": "src/lib.rs", + "start_line": 13, + "start_col": 1, + "end_line": 14, + "end_col": 1 + } + ] + } +] diff --git a/extensions/rust/lint/src/tests.rs b/extensions/rust/lint/src/tests.rs new file mode 100644 index 0000000000..0ac59afbba --- /dev/null +++ b/extensions/rust/lint/src/tests.rs @@ -0,0 +1,493 @@ +use super::*; +use serde_json::{json, Value}; +use specforge_test::prelude::*; + +/// clippy 0.1.98's recording (see `fixtures/README.md`): crate `demo` at `/project`. +const RECORDED: &str = include_str!("../fixtures/clippy-0.1.98.jsonl"); +/// The converter's accepted snapshot of the facts `RECORDED` mints with `fixtures/items.json` served. +const RECORDED_FACTS: &str = + include_str!("snapshots/specforge_ext_rust_lint__tests__clippy__clippy_0_1_98.snap"); + +/// The input the host sends at `/project`: `stdout` as captured, these report files, the recorded crate's items. +fn input(stdout: Option<&str>, reports: &[&str]) -> CollectInput { + CollectInput { + stdout: stdout.map(ToString::to_string), + reports: reports + .iter() + .map(|content| CollectReportFile { + path: "saved/clippy.jsonl".to_string(), + content: content.to_string(), + }) + .collect(), + cwd: Some("/project".to_string()), + facts: serde_json::from_str(include_str!("../fixtures/items.json")) + .expect("the served facts parse"), + ..CollectInput::default() + } +} + +/// The JSON body of an insta snapshot, after its `---` header. +fn snapshot(text: &str) -> Value { + let body = text.splitn(3, "---\n").nth(2).expect("a snapshot body"); + serde_json::from_str(body).expect("the snapshot parses") +} + +#[specforge_test(requirement = "FEATURE-146")] +fn rust_lint_declares_clippy_with_its_stdout_captured_and_its_peers() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.2", false), + ("@rust/source", "^1.0", false) + ] + ); + let [collector] = &declaration.collectors[..] else { + panic!("one collector: {:?}", declaration.collectors); + }; + assert_eq!(collector.name, COLLECTOR); + assert_eq!(collector.input_formats, ["cargo-json"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["Cargo.toml".to_string()][..]) + ); + assert_eq!(collector.answers, ["static_finding"]); + assert_eq!(collector.inputs, [Input::facts(&["item", "package"])]); + assert_eq!(collector.report.as_deref(), Some(REPORT)); + assert_eq!(collector.capture.as_deref(), Some("stdout")); + assert_eq!( + collector.install.as_deref(), + Some("rustup component add clippy") + ); + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + assert_eq!(capabilities[0]["name"], COLLECTOR); + assert_eq!(capabilities[0]["port"], "process"); + assert_eq!( + capabilities[0]["argv"], + json!([ + "cargo-clippy", + "clippy", + "--workspace", + "--all-targets", + "--message-format=json" + ]), + "{capabilities}" + ); + assert_eq!( + capabilities[0]["env"], + json!([ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "RUSTDOCFLAGS", + "CLIPPY_*" + ]) + ); + assert!(capabilities[0].get("filter").is_none_or(Value::is_null)); +} + +#[specforge_test(requirement = "FEATURE-146")] +fn a_captured_clippy_run_or_a_saved_one_mints_the_converters_facts() { + for given in [input(Some(RECORDED), &[]), input(None, &[RECORDED])] { + let out = collect(&given).unwrap(); + assert_eq!( + serde_json::to_value(&out.facts).unwrap(), + snapshot(RECORDED_FACTS) + ); + assert_eq!(out.warnings, Vec::::new()); + } +} + +#[specforge_test(requirement = "FEATURE-146")] +fn no_capture_and_no_single_report_is_the_collectors_error() { + for reports in [&[][..], &[RECORDED, RECORDED][..]] { + let why = collect(&input(None, reports)).unwrap_err(); + assert!( + why.contains(COLLECTOR) && why.contains("standard output was not captured"), + "{why}" + ); + } + let why = collect(&input(Some("{\"reason\""), &[])).unwrap_err(); + assert!( + why.starts_with(&format!("{CAPTURE}: line 1: no JSON")), + "{why}" + ); + let no_cwd = CollectInput { + cwd: None, + ..input(Some(RECORDED), &[]) + }; + assert!(collect(&no_cwd).unwrap_err().contains("no cwd")); +} + +#[specforge_test(requirement = "FEATURE-146")] +fn a_span_outside_the_project_is_skipped_with_one_warning_naming_the_capture() { + // The first message's primary span moves into a registry crate. + let (first, rest) = RECORDED.split_once('\n').expect("more than one line"); + let mut first: Value = serde_json::from_str(first).expect("the first line parses"); + first["message"]["spans"][0]["file_name"] = json!("/home/u/.cargo/registry/src/x/lib.rs"); + let outside = format!("{first}\n{rest}"); + let out = collect(&input(Some(&outside), &[])).unwrap(); + assert_eq!( + out.facts.len(), + 4, + "the lib test copy of the first finding is kept" + ); + assert_eq!( + out.warnings, + [format!( + "{CAPTURE}: skipped 1 file(s) outside the project: /home/u/.cargo/registry/src/x/lib.rs" + )] + ); +} + +#[specforge_test(requirement = "FEATURE-146")] +fn a_span_naming_no_file_is_skipped_with_its_own_warning() { + let (first, rest) = RECORDED.split_once('\n').expect("more than one line"); + let mut first: Value = serde_json::from_str(first).expect("the first line parses"); + first["message"]["spans"][0]["file_name"] = json!(""); + let out = collect(&input(Some(&format!("{first}\n{rest}")), &[])).unwrap(); + assert_eq!( + out.facts.len(), + 4, + "the lib test copy of the first finding is kept" + ); + assert_eq!( + out.warnings, + [format!( + "{CAPTURE}: skipped 1 path(s) naming no file: " + )] + ); +} + +/// The converter's unit tests: cargo JSON lines in, SARIF results out. +mod clippy { + use crate::clippy::{results, Converted}; + use serde_json::json; + use specforge_code_facts::{finding_facts, Level, SarifResult}; + use specforge_extension_sdk::prelude::Fact; + + /// clippy 0.1.98's recording (see `fixtures/README.md`): crate `demo` at `/project`. + const CLIPPY_0_1_98: &str = include_str!("../fixtures/clippy-0.1.98.jsonl"); + /// The served facts of the recorded crate, as JSON. + const ITEMS: &str = include_str!("../fixtures/items.json"); + + /// One `compiler-message` line: a diagnostic of `level` with `code`, its `spans` as written. + fn message(code: Option<&str>, level: &str, text: &str, spans: serde_json::Value) -> String { + json!({ + "reason": "compiler-message", + "package_id": "path+file:///project#demo@0.1.0", + "message": { + "code": code.map(|code| json!({"code": code, "explanation": null})), + "level": level, + "message": text, + "spans": spans, + "children": [], + }, + }) + .to_string() + } + + /// `lines` as one capture, ended by the `build-finished` record cargo writes last. + fn finished>(lines: &[S]) -> String { + let mut text: Vec<&str> = lines.iter().map(AsRef::as_ref).collect(); + text.push(r#"{"reason":"build-finished","success":true}"#); + text.join("\n") + } + + /// A span of `file` over the lines `start` to `end`. + fn span(file: &str, start: u64, end: u64, primary: bool) -> serde_json::Value { + json!({"file_name": file, "line_start": start, "line_end": end, "is_primary": primary}) + } + + fn result(rule: &str, level: Level, text: &str, place: (&str, usize, usize)) -> SarifResult { + SarifResult { + tool: "clippy".to_string(), + rule: rule.to_string(), + level, + message: text.to_string(), + file: Some(place.0.to_string()), + line: Some(place.1), + end_line: Some(place.2), + } + } + + #[test] + fn a_clippy_message_reads_its_code_level_message_and_primary_span() { + let text = finished(&[ + message( + Some("clippy::needless_return"), + "warning", + "unneeded `return` statement", + json!([ + span("src/other.rs", 2, 2, false), + span("src/lib.rs", 7, 8, true) + ]), + ), + message( + Some("unused_variables"), + "error", + "unused variable", + json!([span("src/lib.rs", 12, 12, true)]), + ), + ]); + let Converted { + results: read, + outside, + .. + } = results(&text, "/project").expect("the lines read"); + assert_eq!( + read, + [ + result( + "clippy::needless_return", + Level::Warning, + "unneeded `return` statement", + ("src/lib.rs", 7, 8) + ), + result( + "unused_variables", + Level::Error, + "unused variable", + ("src/lib.rs", 12, 12) + ), + ] + ); + assert!(outside.is_empty()); + } + + #[test] + fn a_clippy_level_maps_to_sarif_and_a_codeless_message_with_a_span_is_unknown() { + let levels = ["error", "warning", "note", "help", "failure-note"]; + let text: Vec = levels + .iter() + .enumerate() + .map(|(at, level)| { + message( + None, + level, + "m", + json!([span("src/lib.rs", at as u64 + 1, at as u64 + 1, true)]), + ) + }) + .collect(); + let Converted { results: read, .. } = + results(&finished(&text), "/project").expect("the lines read"); + let read: Vec<(&str, Level)> = read.iter().map(|r| (r.rule.as_str(), r.level)).collect(); + assert_eq!( + read, + [ + ("unknown", Level::Error), + ("unknown", Level::Warning), + ("unknown", Level::Note), + ("unknown", Level::Note), + ("unknown", Level::Unknown), + ] + ); + } + + #[test] + fn other_clippy_reasons_summaries_and_blank_lines_are_ignored() { + let text = [ + json!({"reason": "compiler-artifact", "package_id": "x"}).to_string(), + json!({"reason": "build-script-executed", "package_id": "x"}).to_string(), + String::new(), + " ".to_string(), + message(None, "warning", "2 warnings emitted", json!([])), + message(Some("dead_code"), "warning", "never used", json!([])), + json!({"reason": "build-finished", "success": true}).to_string(), + ] + .join("\n"); + let Converted { + results: read, + outside, + .. + } = results(&text, "/project").expect("the lines read"); + let rules: Vec<(&str, Option<&str>)> = read + .iter() + .map(|r| (r.rule.as_str(), r.file.as_deref())) + .collect(); + assert_eq!(rules, [("dead_code", None)]); + assert!(outside.is_empty()); + assert_eq!( + results(&finished::<&str>(&[]), "/project"), + Ok(Converted::default()) + ); + } + + #[test] + fn a_clippy_span_naming_no_file_is_counted_apart_not_kept() { + let text = finished(&[ + message( + Some("A"), + "warning", + "a", + json!([span("", 4, 4, true)]), + ), + message( + Some("B"), + "warning", + "b", + json!([span("", 1, 1, true)]), + ), + message(Some("C"), "warning", "c", json!([span(".", 1, 1, true)])), + message( + Some("D"), + "warning", + "d", + json!([span("/project", 1, 1, true)]), + ), + message( + Some("E"), + "warning", + "e", + json!([span("src/lib.rs", 5, 5, true)]), + ), + ]); + let converted = results(&text, "/project").expect("the lines read"); + let kept: Vec<(&str, Option<&str>)> = converted + .results + .iter() + .map(|r| (r.rule.as_str(), r.file.as_deref())) + .collect(); + assert_eq!(kept, [("E", Some("src/lib.rs"))]); + assert_eq!( + converted.no_file, + ["", "", ".", "/project"] + ); + assert!(converted.outside.is_empty(), "{:?}", converted.outside); + } + + #[test] + fn a_clippy_capture_with_no_build_finished_record_is_cut_off() { + // A run killed between two lines: every line is whole JSON, but cargo's last record is missing. + let whole = message( + Some("A"), + "warning", + "a", + json!([span("src/lib.rs", 1, 1, true)]), + ); + for text in [whole.as_str(), ""] { + let error = results(text, "/project").expect_err("cut off"); + assert!(error.starts_with("no `build-finished` record"), "{error}"); + } + let (recorded, _) = CLIPPY_0_1_98 + .trim_end() + .rsplit_once('\n') + .expect("more than one line"); + assert!(results(recorded, "/project").is_err()); + } + + #[test] + fn a_clippy_finding_repeated_by_all_targets_appears_once_in_first_seen_order() { + let a = message( + Some("A"), + "warning", + "a", + json!([span("src/lib.rs", 1, 1, true)]), + ); + let b = message( + Some("B"), + "warning", + "b", + json!([span("src/lib.rs", 2, 2, true)]), + ); + let a_elsewhere = message( + Some("A"), + "warning", + "a", + json!([span("src/lib.rs", 3, 3, true)]), + ); + let text = finished(&[&a, &b, &a, &b, &a_elsewhere]); + let Converted { results: read, .. } = results(&text, "/project").expect("the lines read"); + let read: Vec<(&str, Option)> = + read.iter().map(|r| (r.rule.as_str(), r.line)).collect(); + assert_eq!(read, [("A", Some(1)), ("B", Some(2)), ("A", Some(3))]); + } + + #[test] + fn a_clippy_span_outside_the_project_is_counted_once_not_kept() { + let registry = "/home/u/.cargo/registry/src/x/lib.rs"; + let text = finished(&[ + message( + Some("A"), + "warning", + "a", + json!([span(registry, 4, 4, true)]), + ), + message( + Some("B"), + "warning", + "b", + json!([span(registry, 9, 9, true)]), + ), + message( + Some("C"), + "warning", + "c", + json!([span("../beside/src/lib.rs", 1, 1, true)]), + ), + message( + Some("D"), + "warning", + "d", + json!([span("/project/src/lib.rs", 5, 5, true)]), + ), + ]); + let Converted { + results: read, + outside, + .. + } = results(&text, "/project").expect("the lines read"); + let kept: Vec<(&str, Option<&str>)> = read + .iter() + .map(|r| (r.rule.as_str(), r.file.as_deref())) + .collect(); + assert_eq!(kept, [("D", Some("src/lib.rs"))]); + assert_eq!(outside, [registry, "../beside/src/lib.rs"]); + } + + #[test] + fn a_clippy_line_that_is_no_json_is_an_error_naming_it() { + let whole = message( + Some("A"), + "warning", + "a", + json!([span("src/lib.rs", 1, 1, true)]), + ); + let cut = &whole[..whole.len() / 2]; + let error = results(&format!("{whole}\n\n{cut}"), "/project").expect_err("cut off"); + assert!(error.starts_with("line 3: no JSON"), "{error}"); + } + + #[test] + fn a_recorded_clippy_0_1_98_run_mints_each_finding_once() { + let Converted { + results: read, + outside, + .. + } = results(CLIPPY_0_1_98, "/project").expect("the recording reads"); + assert!(outside.is_empty()); + let placed: Vec<(&str, Option)> = + read.iter().map(|r| (r.rule.as_str(), r.line)).collect(); + assert_eq!( + placed, + [ + ("unused_variables", Some(12)), + ("clippy::len_without_is_empty", Some(6)), + ("clippy::needless_return", Some(7)), + ("clippy::unwrap_used", Some(13)), + ] + ); + let served: Vec = serde_json::from_str(ITEMS).expect("the served facts parse"); + let facts = finding_facts(&read, &served); + insta::assert_json_snapshot!("clippy_0_1_98", facts); + } +} diff --git a/extensions/rust/lint/wasm/inputs.json b/extensions/rust/lint/wasm/inputs.json new file mode 100644 index 0000000000..81003aaace --- /dev/null +++ b/extensions/rust/lint/wasm/inputs.json @@ -0,0 +1,92 @@ +{ + "artifact": "specforge_ext_rust_lint.wasm", + "artifact_sha256": "004241f436af1f6c741b57bb8bc5373bc3c7648b80b0afffb59bb311ef48032f", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/rust/lint/Cargo.lock": "c112c6054ba4b9ad716e9939123a148aeaaad07a3f112c7249a2e9c39ecde416", + "extensions/rust/lint/Cargo.toml": "e797663c08f3843a39235ce7bf80622eed0f1cc91c07d09208f366a39ed05949", + "extensions/rust/lint/src/clippy.rs": "a3857eaa909d643a5f5121be515a320df4328096a43e4fb9535fd6e9ac916382", + "extensions/rust/lint/src/lib.rs": "90d8c435acd87691e42251e123484c05391838ad41d725bb9027e1842081b9a2" + } +} diff --git a/extensions/rust/lint/wasm/specforge_ext_rust_lint.wasm b/extensions/rust/lint/wasm/specforge_ext_rust_lint.wasm new file mode 100644 index 0000000000..ed39aff49b Binary files /dev/null and b/extensions/rust/lint/wasm/specforge_ext_rust_lint.wasm differ diff --git a/extensions/rust/proof/Cargo.lock b/extensions/rust/proof/Cargo.lock new file mode 100644 index 0000000000..f9294ac284 --- /dev/null +++ b/extensions/rust/proof/Cargo.lock @@ -0,0 +1,571 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "specforge-code-facts" +version = "1.0.0" +dependencies = [ + "serde_json", + "sha2", + "specforge-code-junit", + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-junit" +version = "1.0.0" +dependencies = [ + "specforge-extension-sdk", +] + +[[package]] +name = "specforge-code-kani" +version = "1.0.0" + +[[package]] +name = "specforge-ext-rust-proof" +version = "1.0.0" +dependencies = [ + "serde_json", + "specforge-code-facts", + "specforge-code-kani", + "specforge-extension-sdk", + "specforge-protocol-types", + "specforge-test", +] + +[[package]] +name = "specforge-extension-sdk" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", + "specforge-extension-sdk-macros", + "specforge-protocol-types", + "wit-bindgen", +] + +[[package]] +name = "specforge-extension-sdk-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "specforge-protocol-types", + "syn 2.0.119", +] + +[[package]] +name = "specforge-protocol-types" +version = "0.3.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "specforge-test" +version = "0.1.0" +dependencies = [ + "crossbeam-queue", + "libc", + "serde", + "serde_json", + "specforge-protocol-types", + "specforge-test-macros", +] + +[[package]] +name = "specforge-test-macros" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb56df3e06b8e6b77e37d2969a50ba51281029a9aeb3855e76b7f49b6418847" +dependencies = [ + "leb128", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6bb07c5576b608f7a2a9baa2294c1a3584a249965d695a9814a496cb6d232f" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fbde0881f24199b81cf49b6ff8f9c145ac8eb1b7fc439adb5c099734f7d90e" +dependencies = [ + "ahash", + "bitflags", + "hashbrown 0.14.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4bac478334a647374ff24a74b66737a4cb586dc8288bc3080a93252cd1105c" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb7e3df01cd43cfa1cb52602e4fc05cb2b62217655f6705639b6953eb0a3fed2" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2de7a3b06b9725d129b5cbd1beca968feed919c433305a23da46843185ecdd6" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a767d1a8eb4e908bfc53febc48b87ada545703b16fe0148ee7736a29a01417" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b185c342d0d27bd83d4080f5a66cf3b4f247fa49d679bceb66e11cc7eb58b99" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f725e3885fc5890648be5c5cbc1353b755dc932aa5f1aa7de968b912a3280743" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.215.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "935a97eaffd57c3b413aa510f8f0b550a4a9fe7d59e79cd8b89a83dcb860321f" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/extensions/rust/proof/Cargo.toml b/extensions/rust/proof/Cargo.toml new file mode 100644 index 0000000000..b1c6d4e596 --- /dev/null +++ b/extensions/rust/proof/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "specforge-ext-rust-proof" +version = "1.0.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +specforge-extension-sdk = { path = "../../../crates/runtime/extension-sdk" } +specforge-code-kani = { path = "../../code/kani" } +specforge-code-facts = { path = "../../code/facts" } + +[dev-dependencies] +# Spec links: #[specforge_test(requirement = "…")] (ADR 0002). +specforge-test = { path = "../../../integrations/rust/specforge-test" } +serde_json = "1.0" +# is_install_line: the host's rule for a collector's install line. +specforge-protocol-types = { path = "../../../crates/leaf/protocol-types" } diff --git a/extensions/rust/proof/fixtures/README.md b/extensions/rust/proof/fixtures/README.md new file mode 100644 index 0000000000..8446647e13 --- /dev/null +++ b/extensions/rust/proof/fixtures/README.md @@ -0,0 +1,8 @@ +# @rust/proof fixtures + +The Kani outputs are the Kani reader's own fixtures (`extensions/code/kani/fixtures`), hand-written to Kani's regular +output because Kani was not installable on the authoring host. + +| Fixture | Source | +|---------|--------| +| `items.json` | hand-written served facts: the `item` facts `@rust/source` answers for the harnesses of the Kani reader's `one-crate.txt`, `failed.txt` and `workspace.txt`: crate `demo` (`src/lib.rs`: `add`, `#[cfg(kani)] mod proofs`, its harnesses `proofs::check_add` and `proofs::check_bound`), crate `ledger` (`crates/ledger/src/lib.rs`: `proofs::balance_never_negative`, `proofs::transfer_conserves`) and crate `vault` (`crates/vault/src/lib.rs`: `checks::seal_roundtrip`), and their `package` facts. A `#[kani::proof]` function is a plain item: no `test` attribute, no `test_id` | diff --git a/extensions/rust/proof/fixtures/items.json b/extensions/rust/proof/fixtures/items.json new file mode 100644 index 0000000000..1269a10779 --- /dev/null +++ b/extensions/rust/proof/fixtures/items.json @@ -0,0 +1,33 @@ +[ + {"kind": "item", "id": "rust:demo::add", + "fields": {"kind": ["function"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "public"}, + "at": [{"file": "src/lib.rs", "start_line": 1, "start_col": 1, "end_line": 3, "end_col": 2}]}, + {"kind": "item", "id": "rust:demo::proofs", + "fields": {"kind": ["module"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "private", + "attrs": ["cfg(kani)"]}, + "at": [{"file": "src/lib.rs", "start_line": 5, "start_col": 1, "end_line": 23, "end_col": 2}]}, + {"kind": "item", "id": "rust:demo::proofs::check_add", + "fields": {"kind": ["function"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "private"}, + "at": [{"file": "src/lib.rs", "start_line": 8, "start_col": 5, "end_line": 12, "end_col": 6}]}, + {"kind": "item", "id": "rust:demo::proofs::check_bound", + "fields": {"kind": ["function"], "package": "pkg:cargo/demo", "file": "src/lib.rs", "visibility": "private"}, + "at": [{"file": "src/lib.rs", "start_line": 15, "start_col": 5, "end_line": 22, "end_col": 6}]}, + {"kind": "item", "id": "rust:ledger::proofs::balance_never_negative", + "fields": {"kind": ["function"], "package": "pkg:cargo/ledger", "file": "crates/ledger/src/lib.rs", + "visibility": "private"}, + "at": [{"file": "crates/ledger/src/lib.rs", "start_line": 30, "start_col": 5, "end_line": 36, "end_col": 6}]}, + {"kind": "item", "id": "rust:ledger::proofs::transfer_conserves", + "fields": {"kind": ["function"], "package": "pkg:cargo/ledger", "file": "crates/ledger/src/lib.rs", + "visibility": "private"}, + "at": [{"file": "crates/ledger/src/lib.rs", "start_line": 38, "start_col": 5, "end_line": 43, "end_col": 6}]}, + {"kind": "item", "id": "rust:vault::checks::seal_roundtrip", + "fields": {"kind": ["function"], "package": "pkg:cargo/vault", "file": "crates/vault/src/lib.rs", + "visibility": "private"}, + "at": [{"file": "crates/vault/src/lib.rs", "start_line": 19, "start_col": 5, "end_line": 24, "end_col": 6}]}, + {"kind": "package", "id": "pkg:cargo/demo", + "fields": {"name": "demo", "version": "0.1.0", "path": ""}}, + {"kind": "package", "id": "pkg:cargo/ledger", + "fields": {"name": "ledger", "version": "0.1.0", "path": "crates/ledger"}}, + {"kind": "package", "id": "pkg:cargo/vault", + "fields": {"name": "vault", "version": "0.1.0", "path": "crates/vault"}} +] diff --git a/extensions/rust/proof/src/lib.rs b/extensions/rust/proof/src/lib.rs new file mode 100644 index 0000000000..2553177e48 --- /dev/null +++ b/extensions/rust/proof/src/lib.rs @@ -0,0 +1,224 @@ +//! @rust/proof — runs Kani and records each proof harness as `@code/core`'s `test` and `test_run` facts (ADR 0389). +//! +//! The collector `rust-proof` is selected by a `Cargo.toml` at the project root. The host runs, with consent, +//! `cargo-kani --workspace --output-format regular`: the program is `cargo-kani`, so a missing Kani is "not found on +//! PATH" with its install line. Kani builds the crates and model-checks them, which the approval shows as it shows the +//! command. It prints its results to standard output only, which the host captures into +//! `.specforge/reports/rust-proof/rust-proof.stdout.txt` and passes as `CollectInput::stdout`; `specforge collect +//! --report ` passes a saved capture as the one report instead. `specforge-code-kani` reads the text. +//! +//! Each harness becomes the test `rust:#`, passed when Kani says SUCCESSFUL and failed when it +//! says FAILED, placed at the item `@rust/source` answered for the harness function. Kani prints a harness's path +//! without its crate, and one `Complete` line per crate: the crate of a run is the one whose served items hold every +//! harness of it (`rust:::`), and none or several is the collector's error naming the harnesses +//! (ADR 0389 D10). A harness is a test fact but not an item's `test_id`: `@rust/source` does not see +//! `#[kani::proof]` as a test and is unchanged. +//! +//! An output cut off inside a run is the collector's error (the reader's). An output with no harness at all reads the +//! same whether the crate has none or Kani stopped before verifying (a failed build prints to stderr), so the pack +//! returns one warning saying nothing was checked, which the host shows as W203, instead of a clean run. +//! +//! A caller narrows the run with a filter (`specforge collect --runner rust-proof --filter `): the host appends +//! `--harness `, which Kani matches against harness names. Kani runs on Linux x86_64 and macOS only; it is not +//! supported on Windows (ADR 0389 D12). + +use std::collections::{BTreeMap, BTreeSet}; + +use specforge_code_facts::{test_facts, TestCase, TestId}; +use specforge_code_kani::{read, Run, Verdict}; +use specforge_extension_sdk::prelude::*; + +const COLLECTOR: &str = "rust-proof"; +/// The report directory, relative to the project root: the host keeps the captured standard output in it. +const REPORT: &str = ".specforge/reports/rust-proof"; +/// Where the host keeps the captured standard output: `/.stdout.txt`. +const CAPTURE: &str = ".specforge/reports/rust-proof/rust-proof.stdout.txt"; + +#[specforge_extension_sdk::extension( + name = "@rust/proof", + version = "1.0.0", + description = "Runs Kani and records each proof harness as test facts (@code/core)" +)] +struct RustProof; + +impl Contributions for RustProof { + fn contribute(c: &mut ContributionsBuilder) { + c.peer("@code/core", "^1.2"); + // Its items name each harness's crate and place it; without them no harness can be named. + c.peer("@rust/source", "^1.0"); + c.collector(COLLECTOR, |k| { + k.input_format("kani-regular") + .detect_files(&["Cargo.toml"]) + .run(&["cargo-kani", "--workspace", "--output-format", "regular"]) + .filter(&["--harness", "{filter}"]) + .env(&[ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "KANI_*", + ]) + .install("cargo install --locked kani-verifier && cargo kani setup") + .report(REPORT) + .capture_stdout() + .input(Input::facts(&["item", "package"])) + .answers(&["test", "test_run"]) + .collect(collect); + }); + } +} + +/// Map Kani's captured text (else the one report given) to a `test` and a `test_run` fact per harness. +fn collect(input: &CollectInput) -> Result { + let (path, text) = match (&input.stdout, &input.reports[..]) { + (Some(stdout), _) => (CAPTURE, stdout.as_str()), + (None, [report]) => (report.path.as_str(), report.content.as_str()), + (None, reports) => { + return Err(format!( + "{COLLECTOR}: Kani's standard output was not captured, and it reads one report in its place; it \ + was given {}", + reports.len() + )) + } + }; + let runs = read(text).map_err(|why| format!("{path}: {why}"))?; + let served = Served::of(&input.facts); + let mut tests = Vec::new(); + for run in runs.iter().filter(|run| !run.harnesses.is_empty()) { + let krate = crate_of(run, &served)?; + for harness in &run.harnesses { + let Some((_, path, item)) = served + .holders(&harness.name) + .into_iter() + .find(|(c, _, _)| *c == krate) + else { + return Err(format!( + "{COLLECTOR}: no item of the crate {krate} holds the harness '{}'", + harness.name + )); + }; + let status = match harness.verdict { + Verdict::Successful => TestStatus::Passed, + Verdict::Failed => TestStatus::Failed, + }; + let test = TestCase { + seconds: harness.seconds, + ran: true, + ..TestCase::unrun(TestId::rust(&krate, path), status) + }; + tests.push(test.placed(item)); + } + } + // Kani's stdout looks the same when the crate has no harness and when Kani never reached one (a failed build). + let warnings = tests + .is_empty() + .then(|| { + format!( + "{path}: no proof harness was read; if cargo-kani failed to start or to build the crate, nothing \ + was checked" + ) + }) + .into_iter() + .collect(); + Ok(CollectOutput { + facts: test_facts(tests), + warnings, + ..CollectOutput::default() + }) +} + +/// The served `item` facts, looked up by id and by the path after their crate. +struct Served<'f> { + by_id: BTreeMap<&'f str, &'f Fact>, + /// `rust:::` as `` to each `(, item)`; a crate segment never holds `::`. + by_path: BTreeMap<&'f str, Vec<(&'f str, &'f Fact)>>, +} + +impl<'f> Served<'f> { + fn of(facts: &'f [Fact]) -> Served<'f> { + let mut served = Served { + by_id: BTreeMap::new(), + by_path: BTreeMap::new(), + }; + for fact in facts.iter().filter(|fact| fact.kind == "item") { + served.by_id.insert(fact.id.as_str(), fact); + if let Some((krate, path)) = fact + .id + .strip_prefix("rust:") + .and_then(|id| id.split_once("::")) + { + if !krate.is_empty() { + served.by_path.entry(path).or_default().push((krate, fact)); + } + } + } + served + } + + /// Each `(crate, harness path, item)` the harness `name` can be: the item `rust:::`, or the item + /// `rust:` when the name starts with its crate (then the path is the rest). + fn holders<'n>(&self, name: &'n str) -> Vec<(&'f str, &'n str, &'f Fact)> { + let mut holders: Vec<(&'f str, &'n str, &'f Fact)> = self + .by_path + .get(name) + .into_iter() + .flatten() + .map(|(krate, item)| (*krate, name, *item)) + .collect(); + if let Some((_, path)) = name.split_once("::") { + if let Some(item) = self.by_id.get(format!("rust:{name}").as_str()) { + if let Some((krate, _)) = item + .id + .strip_prefix("rust:") + .and_then(|id| id.split_once("::")) + { + holders.push((krate, path, *item)); + } + } + } + holders + } +} + +/// The one crate whose served items hold every harness of `run`: Kani prints a harness's path without its crate and +/// one `Complete` line per crate, so a run is one crate's (ADR 0389 D10). None or several is the collector's error, +/// never a guess. +fn crate_of(run: &Run, served: &Served) -> Result { + let mut common: Option> = None; + for harness in &run.harnesses { + let crates: BTreeSet<&str> = served + .holders(&harness.name) + .into_iter() + .map(|(krate, _, _)| krate) + .collect(); + common = Some(match common { + None => crates, + Some(kept) => kept.intersection(&crates).copied().collect(), + }); + } + let common: Vec<&str> = common.unwrap_or_default().into_iter().collect(); + let names = run + .harnesses + .iter() + .map(|h| format!("'{}'", h.name)) + .collect::>() + .join(", "); + match common[..] { + [krate] => Ok(krate.to_string()), + [] => Err(format!( + "{COLLECTOR}: no crate's served items hold every harness of one Kani run ({names}), as an item \ + rust:::; collect @rust/source first" + )), + _ => Err(format!( + "{COLLECTOR}: the crates {} each hold every harness of one Kani run ({names}): the run's crate is \ + ambiguous", + common.join(" and ") + )), + } +} + +specforge_extension_sdk::component_guest!(build = specforge_extension_build); + +#[cfg(test)] +mod tests; diff --git a/extensions/rust/proof/src/tests.rs b/extensions/rust/proof/src/tests.rs new file mode 100644 index 0000000000..ed75f7b4f1 --- /dev/null +++ b/extensions/rust/proof/src/tests.rs @@ -0,0 +1,290 @@ +use super::*; +use serde_json::json; +use specforge_test::prelude::*; + +/// The Kani reader's one-crate output: crate `demo`'s harness `proofs::check_add`, successful. +const ONE_CRATE: &str = include_str!("../../../code/kani/fixtures/one-crate.txt"); +/// Two runs: crate `ledger`'s two harnesses, then crate `vault`'s one. +const WORKSPACE: &str = include_str!("../../../code/kani/fixtures/workspace.txt"); +/// Crate `demo`: `proofs::check_add` successful, `proofs::check_bound` failed. +const FAILED: &str = include_str!("../../../code/kani/fixtures/failed.txt"); +/// No harness found. +const NONE: &str = include_str!("../../../code/kani/fixtures/none.txt"); +/// The served items of the crates the Kani outputs name. +const ITEMS: &str = include_str!("../fixtures/items.json"); + +/// The input the host sends: `stdout` as captured, these report files, the fixture's items served. +fn input(stdout: Option<&str>, reports: &[&str]) -> CollectInput { + CollectInput { + stdout: stdout.map(ToString::to_string), + reports: reports + .iter() + .map(|content| CollectReportFile { + path: "saved/kani.txt".to_string(), + content: content.to_string(), + }) + .collect(), + facts: serde_json::from_str(ITEMS).expect("the served facts parse"), + ..CollectInput::default() + } +} + +/// Each fact's `(kind, id, status)`. +fn summary(out: &CollectOutput) -> Vec<(&str, &str, &str)> { + out.facts + .iter() + .map(|f| { + ( + f.kind.as_str(), + f.id.as_str(), + f.fields["status"].as_str().unwrap(), + ) + }) + .collect() +} + +#[specforge_test(requirement = "FEATURE-154")] +fn rust_proof_declares_kani_with_its_stdout_captured_its_filter_and_its_peers() { + let declaration = crate::specforge_extension_build().declaration(); + let peers: Vec<(&str, &str, bool)> = declaration + .handshake + .peer_dependencies + .iter() + .map(|p| (p.name.as_str(), p.version.as_str(), p.optional)) + .collect(); + assert_eq!( + peers, + [ + ("@code/core", "^1.2", false), + ("@rust/source", "^1.0", false) + ] + ); + let [collector] = &declaration.collectors[..] else { + panic!("one collector: {:?}", declaration.collectors); + }; + assert_eq!(collector.name, COLLECTOR); + assert_eq!(collector.input_formats, ["kani-regular"]); + assert_eq!( + collector.auto_detect.as_ref().map(|d| &d.file_patterns[..]), + Some(&["Cargo.toml".to_string()][..]) + ); + assert_eq!(collector.answers, ["test", "test_run"]); + assert_eq!(collector.inputs, [Input::facts(&["item", "package"])]); + assert_eq!(collector.report.as_deref(), Some(REPORT)); + assert_eq!(collector.capture.as_deref(), Some("stdout")); + let install = collector.install.as_deref().expect("an install line"); + assert_eq!( + install, + "cargo install --locked kani-verifier && cargo kani setup" + ); + assert!( + specforge_protocol_types::is_install_line(install), + "{install}" + ); + let capabilities = serde_json::to_value(&declaration.capabilities).unwrap(); + assert_eq!(capabilities[0]["name"], COLLECTOR); + assert_eq!(capabilities[0]["port"], "process"); + assert_eq!( + capabilities[0]["argv"], + json!(["cargo-kani", "--workspace", "--output-format", "regular"]), + "{capabilities}" + ); + assert_eq!(capabilities[0]["filter"], json!(["--harness", "{filter}"])); + assert_eq!( + capabilities[0]["env"], + json!([ + "CARGO_*", + "RUSTUP_*", + "RUSTC", + "RUSTC_*", + "RUSTFLAGS", + "KANI_*" + ]) + ); +} + +#[specforge_test(requirement = "FEATURE-154")] +fn a_harness_becomes_a_test_placed_at_its_item() { + for given in [input(Some(ONE_CRATE), &[]), input(None, &[ONE_CRATE])] { + let out = collect(&given).unwrap(); + assert_eq!( + summary(&out), + [ + ("test", "rust:demo#proofs::check_add", "passed"), + ("test_run", "run:rust:demo#proofs::check_add", "passed"), + ] + ); + let test = &out.facts[0]; + assert_eq!(test.fields["file"], "src/lib.rs"); + assert_eq!(test.fields["binary"], "demo"); + assert_eq!( + test.at, + [FactLocation { + file: "src/lib.rs".to_string(), + start_line: 8, + start_col: 5, + end_line: 12, + end_col: 6, + }] + ); + assert_eq!(out.facts[1].fields["duration_ms"], 390); + assert_eq!(out.warnings, Vec::::new()); + } +} + +/// Kani's output of one run holding these successful harnesses. +fn run_of(harnesses: &[&str]) -> String { + let mut text = String::new(); + for name in harnesses { + text.push_str(&format!( + "Checking harness {name}...\nVERIFICATION:- SUCCESSFUL\n" + )); + } + let n = harnesses.len(); + text.push_str(&format!( + "Complete - {n} successfully verified harnesses, 0 failures, {n} total.\n" + )); + text +} + +/// A served item `id` (no place). +fn item(id: &str) -> Fact { + Fact::new("item", id).field("file", "src/lib.rs") +} + +/// The input of `stdout` with only `items` served. +fn served(stdout: &str, items: &[&str]) -> CollectInput { + CollectInput { + stdout: Some(stdout.to_string()), + facts: items.iter().map(|id| item(id)).collect(), + ..CollectInput::default() + } +} + +#[specforge_test(requirement = "FEATURE-154")] +fn each_run_of_a_workspace_is_named_by_the_crate_holding_its_harnesses() { + let out = collect(&input(Some(WORKSPACE), &[])).unwrap(); + let tests: Vec<(&str, &str, &str)> = summary(&out) + .into_iter() + .filter(|(kind, _, _)| *kind == "test") + .collect(); + assert_eq!( + tests, + [ + ( + "test", + "rust:ledger#proofs::balance_never_negative", + "passed" + ), + ("test", "rust:ledger#proofs::transfer_conserves", "passed"), + ("test", "rust:vault#checks::seal_roundtrip", "passed"), + ] + ); + let vault = out + .facts + .iter() + .find(|f| f.id == "rust:vault#checks::seal_roundtrip") + .unwrap(); + assert_eq!(vault.fields["file"], "crates/vault/src/lib.rs"); + assert_eq!(vault.at[0].start_line, 19); +} + +#[specforge_test(requirement = "FEATURE-154")] +fn the_crate_must_hold_every_harness_of_the_run() { + let out = collect(&served( + &run_of(&["proofs::p", "proofs::q"]), + &[ + "rust:a::proofs::p", + "rust:b::proofs::p", + "rust:a::proofs::q", + ], + )) + .unwrap(); + let ids: Vec<&str> = summary(&out).into_iter().map(|(_, id, _)| id).collect(); + assert_eq!( + ids, + [ + "rust:a#proofs::p", + "run:rust:a#proofs::p", + "rust:a#proofs::q", + "run:rust:a#proofs::q" + ] + ); +} + +#[specforge_test(requirement = "FEATURE-154")] +fn a_run_no_crate_or_two_crates_hold_wholly_is_the_collectors_error() { + let why = collect(&served( + &run_of(&["proofs::p", "proofs::q"]), + &["rust:a::proofs::p", "rust:b::proofs::q"], + )) + .unwrap_err(); + assert!( + why.starts_with(COLLECTOR) + && why.contains("'proofs::p', 'proofs::q'") + && why.contains("collect @rust/source first"), + "{why}" + ); + let why = collect(&served( + &run_of(&["proofs::p"]), + &["rust:a::proofs::p", "rust:b::proofs::p"], + )) + .unwrap_err(); + assert!( + why.starts_with(COLLECTOR) && why.contains("a and b") && why.contains("'proofs::p'"), + "{why}" + ); + let why = collect(&served(&run_of(&["proofs::p"]), &[])).unwrap_err(); + assert!(why.contains("collect @rust/source first"), "{why}"); +} + +#[specforge_test(requirement = "FEATURE-154")] +fn a_harness_named_with_its_crate_keeps_the_path_after_it() { + let out = collect(&served( + &run_of(&["demo::proofs::p"]), + &["rust:demo::proofs::p"], + )) + .unwrap(); + assert_eq!(out.facts[0].id, "rust:demo#proofs::p"); + assert_eq!(out.facts[0].fields["file"], "src/lib.rs"); +} + +#[specforge_test(requirement = "FEATURE-154")] +fn a_failed_harness_is_a_failed_test() { + let out = collect(&input(Some(FAILED), &[])).unwrap(); + assert_eq!( + summary(&out), + [ + ("test", "rust:demo#proofs::check_add", "passed"), + ("test_run", "run:rust:demo#proofs::check_add", "passed"), + ("test", "rust:demo#proofs::check_bound", "failed"), + ("test_run", "run:rust:demo#proofs::check_bound", "failed"), + ] + ); +} + +#[specforge_test(requirement = "FEATURE-154")] +fn no_capture_is_the_collectors_error_and_no_harness_is_no_fact_and_one_warning() { + for reports in [&[][..], &[ONE_CRATE, ONE_CRATE][..]] { + let why = collect(&input(None, reports)).unwrap_err(); + assert!( + why.contains(COLLECTOR) && why.contains("standard output was not captured"), + "{why}" + ); + } + let why = collect(&input(Some("Checking harness p...\n"), &[])).unwrap_err(); + assert!(why.starts_with(&format!("{CAPTURE}: ")), "{why}"); + // No harness read (none in the crate, or Kani stopped at the build) says so instead of looking clean. + for text in [NONE, "", "Kani Rust Verifier 0.67.0 (cargo plugin)\n"] { + let out = collect(&input(Some(text), &[])).unwrap(); + assert_eq!(out.facts, Vec::::new(), "{text:?}"); + assert_eq!( + out.warnings, + [format!( + "{CAPTURE}: no proof harness was read; if cargo-kani failed to start or to build the crate, \ + nothing was checked" + )], + "{text:?}" + ); + } +} diff --git a/extensions/rust/proof/wasm/inputs.json b/extensions/rust/proof/wasm/inputs.json new file mode 100644 index 0000000000..7b91e6f3f3 --- /dev/null +++ b/extensions/rust/proof/wasm/inputs.json @@ -0,0 +1,93 @@ +{ + "artifact": "specforge_ext_rust_proof.wasm", + "artifact_sha256": "442074d523860bc5b25a53950afb160559e45b5831d5b969667a52af82493eb3", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", + "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", + "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", + "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", + "extensions/code/kani/Cargo.toml": "0a1ebc8bfa43ad3fe143dcc90979a869b77e54fbb1a287739574281ce2449cc0", + "extensions/code/kani/src/lib.rs": "6d9c17556182ccfc1c1b70829a068168bf23ad5b1826b5b6ce2130a4a8ca76d3", + "extensions/rust/proof/Cargo.lock": "6b9c05c3eb20e0c517a2d31b21a051cbd52c6464232f6bf363839b8335e7ee31", + "extensions/rust/proof/Cargo.toml": "bbea968c8a08278e8160aa577a1ddce81d8fbf10256087aaf423942ee709e7f4", + "extensions/rust/proof/src/lib.rs": "ee5909b9416af39d0ee1e2a1f2aaa34d8756a1652d61fb97ce3ad07fbd887681" + } +} diff --git a/extensions/rust/proof/wasm/specforge_ext_rust_proof.wasm b/extensions/rust/proof/wasm/specforge_ext_rust_proof.wasm new file mode 100644 index 0000000000..c6cea392bb Binary files /dev/null and b/extensions/rust/proof/wasm/specforge_ext_rust_proof.wasm differ diff --git a/extensions/rust/source/queries/rust-tags.scm b/extensions/rust/source/queries/rust-tags.scm index 1ad0a6cc3c..08affd5acf 100644 --- a/extensions/rust/source/queries/rust-tags.scm +++ b/extensions/rust/source/queries/rust-tags.scm @@ -24,6 +24,8 @@ ; An outer attribute: its path, and the whole attribute (`cfg(unix)`). (attribute_item (attribute . (_) @path) @attribute) @reference.attribute +; An inner attribute (`#![cfg(unix)]`), of the file or of the body around it. +(inner_attribute_item (attribute . (_) @path) @attribute) @reference.inner_attribute ; The file a module declaration names: `#[path = "…"]`, or each `path = "…"` of a `#[cfg_attr(…)]`. (attribute_item (attribute . (identifier) @_path (#eq? @_path "path") value: (string_literal (string_content) @file))) @@ -38,6 +40,10 @@ (#any-of? @path "specforge_test" "spec" "specforge_test_macros::test" "specforge_test::test" "specforge::test") arguments: (token_tree . (identifier) . (string_literal (string_content) @id)))) @reference.entity +; An attribute naming the identifier `__guard_only` among its arguments: the macro registers no test for it. +(attribute_item + (attribute arguments: (token_tree (identifier) @_guard (#eq? @_guard "__guard_only")))) + @reference.guard_only ; An outer doc comment, `///` or `/** */`. (line_comment outer: (outer_doc_comment_marker) doc: (doc_comment) @doc) @reference.doc (block_comment outer: (outer_doc_comment_marker) doc: (doc_comment) @doc) @reference.doc diff --git a/extensions/rust/source/src/items.rs b/extensions/rust/source/src/items.rs index 884a1df4da..c6a7afe6e5 100644 --- a/extensions/rust/source/src/items.rs +++ b/extensions/rust/source/src/items.rs @@ -3,6 +3,8 @@ //! comments of the contiguous run of lines directly above it. A test function knows the id nextest gives it and the //! entity its spec-link attribute names (D7). +use std::collections::{BTreeMap, BTreeSet}; + use specforge_code_facts::{ location, signature_spelling, Definition, ItemId, ItemKind, Names, Owner, Signature, Visibility, }; @@ -19,6 +21,8 @@ pub(crate) struct Child { pub inline: Vec, pub dirs: Vec, pub paths: Vec, + /// The `cfg(…)` attributes its file inherits: those around and on its `mod` declaration ([`read`]). + pub cfgs: Vec, } /// Where a definition sits inside its file: the inline modules around it (outermost first) and the `impl` or @@ -29,14 +33,20 @@ struct Context { } /// The definitions of `file` (the module `module` of `krate`, parsed as `matches`) pushed onto `out`, and the file -/// modules it declares. +/// modules it declares. `inherited` holds the `cfg(…)` attributes the file's `mod` declarations put on it: a +/// definition records those, the file's inner `#![cfg(…)]`, those of every definition around it (outer, and inner in +/// its body) and its own, outermost first, as each compiles it out (ADR 0393 D5). pub(crate) fn read( krate: &Crate, module: &[String], file: &ModuleFile, matches: &[SyntaxMatch], + inherited: &[String], out: &mut Vec, ) -> Vec { + let inner = inner_cfgs(matches); + let mut in_file = inherited.to_vec(); + in_file.extend(inner.get(&None).into_iter().flatten().cloned()); let mut children = Vec::new(); for (at, found) in matches.iter().enumerate() { if found.role != SyntaxRole::Definition { @@ -55,6 +65,11 @@ pub(crate) fn read( path.extend(context.inline.iter().cloned()); let id = ItemId::rust(&krate.segment, &path, context.owner.as_ref(), name); let test = matches!(kind, ItemKind::Function | ItemKind::Method) && is_test(&above); + let mut cfgs = in_file.clone(); + cfgs.extend(around_cfgs(matches, at, &inner)); + cfgs.extend(cfg_texts(above.iter().copied())); + let mut seen = BTreeSet::new(); + cfgs.retain(|cfg| seen.insert(cfg.clone())); out.push(Definition { test_id: if test { id.test_id(krate.edition) @@ -69,7 +84,7 @@ pub(crate) fn read( at: location(&file.file, found.span.start, found.span.end), signature: signature(found), doc: doc(&above), - attrs: attrs(&above, test), + attrs: attrs(&above, test, cfgs.clone()), names: names(&file.file, &above), }); if kind == ItemKind::Module && capture(found, "body").is_none() { @@ -78,6 +93,7 @@ pub(crate) fn read( inline: context.inline, dirs: inline_dirs(matches, at), paths: captures(&above, "module_file", "file"), + cfgs, }); } } @@ -234,15 +250,58 @@ fn doc(above: &[&SyntaxMatch]) -> Option { (!doc.is_empty()).then_some(doc) } -/// The attributes an item fact records: `test` for a test, `ignore` for an ignored one, each `cfg(…)` with its -/// whitespace collapsed. -fn attrs(above: &[&SyntaxMatch], test: bool) -> Vec { - let mut attrs: Vec = above - .iter() - .filter(|found| found.kind == "attribute" && capture(found, "path") == Some("cfg")) +/// The text of each `cfg(…)` attribute among `found`, outer or inner, its whitespace collapsed. +fn cfg_texts<'m>(found: impl Iterator) -> Vec { + found + .filter(|found| { + matches!(found.kind.as_str(), "attribute" | "inner_attribute") + && capture(found, "path") == Some("cfg") + }) .filter_map(|found| capture(found, "attribute")) .map(|text| text.split_whitespace().collect::>().join(" ")) - .collect(); + .collect() +} + +/// The inner `#![cfg(…)]` attributes of a file's matches, by the definition whose body holds them (`None`: the file). +fn inner_cfgs(matches: &[SyntaxMatch]) -> BTreeMap, Vec> { + let mut inner: BTreeMap, Vec> = BTreeMap::new(); + for found in matches.iter().filter(|m| m.kind == "inner_attribute") { + inner + .entry(found.parent) + .or_default() + .extend(cfg_texts(std::iter::once(found))); + } + inner +} + +/// The `cfg(…)` attributes of every definition around the definition `at`, outermost first: each one's outer +/// attributes, then the inner ones in its body. +fn around_cfgs( + matches: &[SyntaxMatch], + at: usize, + inner: &BTreeMap, Vec>, +) -> Vec { + let mut chain = Vec::new(); + let mut parent = matches[at].parent; + while let Some(index) = parent.filter(|index| (*index as usize) < matches.len()) { + chain.push(index); + parent = matches[index as usize].parent; + } + chain + .into_iter() + .rev() + .flat_map(|index| { + let mut cfgs = cfg_texts(attached(matches, index as usize).into_iter()); + cfgs.extend(inner.get(&Some(index)).into_iter().flatten().cloned()); + cfgs + }) + .collect() +} + +/// The attributes an item fact records: each `cfg(…)` that compiles it out (`cfgs`), then `test` for a test and +/// `ignore` for an ignored one. +fn attrs(above: &[&SyntaxMatch], test: bool, cfgs: Vec) -> Vec { + let mut attrs = cfgs; if test { attrs.push("test".to_string()); if attribute_paths(above).any(|path| path == "ignore") { @@ -261,10 +320,38 @@ fn attribute_paths<'m>(above: &'m [&SyntaxMatch]) -> impl Iterator bool { - attribute_paths(above).any(|path| { - path == "test" || path.ends_with("::test") || path == "specforge_test" || path == "spec" + let mut lowest = None; + for found in above.iter().filter(|found| found.kind == "attribute") { + let path: String = capture(found, "path") + .unwrap_or_default() + .split_whitespace() + .collect(); + let path = path.trim_start_matches("::"); + if SPEC_LINKS.contains(&path) { + lowest = Some(found.span); + } else if path == "test" || path.ends_with("::test") { + return true; + } + } + lowest.is_some_and(|span| { + !above.iter().any(|found| { + found.kind == "guard_only" + && (found.span.start.byte, found.span.end.byte) == (span.start.byte, span.end.byte) + }) }) } diff --git a/extensions/rust/source/src/modules.rs b/extensions/rust/source/src/modules.rs index e2d4fe8dbc..2e4b3746f1 100644 --- a/extensions/rust/source/src/modules.rs +++ b/extensions/rust/source/src/modules.rs @@ -76,6 +76,8 @@ pub(crate) struct Module { pub krate: usize, pub path: Vec, pub candidates: Vec, + /// The `cfg(…)` attributes its `mod` declarations put on it (none on a crate root). + pub cfgs: Vec, } /// A candidate file of a module and the directory its child modules' files live in. @@ -107,6 +109,7 @@ pub(crate) fn walk(crates: &[Crate]) -> Result, String> { krate, path: Vec::new(), candidates: vec![ModuleFile::mod_rs(joined("", &c.root)?)], + cfgs: Vec::new(), }) }) .collect(); @@ -135,7 +138,14 @@ pub(crate) fn walk(crates: &[Crate]) -> Result, String> { continue; } let krate = &crates[module.krate]; - for child in items::read(krate, &module.path, candidate, matches, &mut definitions) { + for child in items::read( + krate, + &module.path, + candidate, + matches, + &module.cfgs, + &mut definitions, + ) { next.extend(child_modules(module.krate, &module.path, candidate, child)); } } @@ -163,6 +173,7 @@ fn child_modules(krate: usize, path: &[String], file: &ModuleFile, child: Child) krate, path: module_path.clone(), candidates, + cfgs: child.cfgs.clone(), }; if child.paths.is_empty() { let dir = join_dir(&inline_dir, &child.name); diff --git a/extensions/rust/source/src/tests.rs b/extensions/rust/source/src/tests.rs index 2d12c4015c..8033391334 100644 --- a/extensions/rust/source/src/tests.rs +++ b/extensions/rust/source/src/tests.rs @@ -527,7 +527,47 @@ fn attributes_belong_to_the_item_directly_below_them() { assert_eq!(attrs("rust:toy::b"), None, "a blank line ends the run"); assert_eq!(attrs("rust:toy::c"), Some(json!(["cfg(test)"]))); assert_eq!(attrs("rust:toy::m"), Some(json!(["cfg(all(unix, test))"]))); - assert_eq!(attrs("rust:toy::m::d"), Some(json!(["cfg(x)"]))); + assert_eq!( + attrs("rust:toy::m::d"), + Some(json!(["cfg(all(unix, test))", "cfg(x)"])), + "the module's cfg compiles it out with it" + ); +} + +#[specforge_test(requirement = "FEATURE-004")] +#[specforge_test(requirement = "FEATURE-113")] +fn a_test_records_the_cfgs_of_its_module_its_file_and_its_mod_declaration() { + let facts = collected(&[ + ( + "src/lib.rs", + "#[cfg(windows)]\nmod w {\n #[test]\n fn a() {}\n}\nmod n {\n #![cfg(windows)]\n #[test]\n \ + fn b() {}\n}\n#[cfg(test)]\nmod plat;\n#[cfg(test)]\nmod plat_test {\n #[cfg(test)]\n #[test]\n \ + fn c() {}\n}\n", + ), + ( + "src/plat.rs", + "#![cfg(unix)]\nmod inner {\n #[test]\n fn d() {}\n}\n", + ), + ]); + let attrs = |id: &str| item(&facts, id).fields.get("attrs").cloned(); + assert_eq!( + attrs("rust:toy::w::a"), + Some(json!(["cfg(windows)", "test"])) + ); + assert_eq!( + attrs("rust:toy::n::b"), + Some(json!(["cfg(windows)", "test"])) + ); + assert_eq!( + attrs("rust:toy::plat::inner::d"), + Some(json!(["cfg(test)", "cfg(unix)", "test"])), + "the mod declaration's cfg, then the file's inner one" + ); + assert_eq!( + attrs("rust:toy::plat_test::c"), + Some(json!(["cfg(test)", "test"])), + "a cfg written twice is recorded once" + ); } /// `(attrs, test_id)` of the item `id`. @@ -548,9 +588,16 @@ fn a_test_function_carries_the_id_nextest_gives_it() { )]); assert_eq!( marks(&facts, "rust:toy::tests::adds"), - (Some(json!(["test"])), Some(json!("rust:toy#tests::adds"))) + ( + Some(json!(["cfg(test)", "test"])), + Some(json!("rust:toy#tests::adds")) + ) + ); + assert_eq!( + marks(&facts, "rust:toy::tests::helper"), + (Some(json!(["cfg(test)"])), None), + "no test, and compiled out with its module" ); - assert_eq!(marks(&facts, "rust:toy::tests::helper"), (None, None)); assert_eq!( marks(&facts, "rust:toy::tests"), (Some(json!(["cfg(test)"])), None) @@ -664,6 +711,64 @@ fn a_runner_attribute_ending_in_test_marks_a_test() { assert_eq!(tests, ["rust:toy::a", "rust:toy::b"]); } +#[specforge_test(requirement = "FEATURE-004")] +#[specforge_test(requirement = "FEATURE-113")] +fn a_guard_only_helper_carries_no_test_id() { + let facts = collected(&[( + "src/lib.rs", + "#[specforge_test_macros::test(behavior = \"create_user\", __guard_only)]\nfn helper() {}\n\ + #[specforge_test_macros::test(behavior = \"a\", __guard_only)]\n\ + #[specforge_test_macros::test(invariant = \"b\", __guard_only)]\nfn multi() {}\n\ + #[test]\n#[specforge_test_macros::test(behavior = \"c\", __guard_only)]\nfn real() {}\n\ + #[spec(behavior = \"__guard_only\")]\nfn named() {}\n", + )]); + assert_eq!(marks(&facts, "rust:toy::helper"), (None, None)); + assert_eq!(marks(&facts, "rust:toy::multi"), (None, None)); + assert_eq!( + marks(&facts, "rust:toy::real").1, + Some(json!("rust:toy#real")) + ); + assert_eq!( + marks(&facts, "rust:toy::named").1, + Some(json!("rust:toy#named")), + "the word inside a string is no argument" + ); +} + +#[specforge_test(requirement = "FEATURE-004")] +#[specforge_test(requirement = "FEATURE-113")] +fn stacked_spec_link_attributes_register_as_the_macro_does() { + let facts = collected(&[( + "src/lib.rs", + "#[specforge_test(requirement = \"A\")]\n#[specforge_test(requirement = \"B\", __guard_only)]\nfn top() {}\n\ + #[specforge_test(requirement = \"A\", __guard_only)]\n#[specforge_test(requirement = \"B\")]\nfn low() {}\n\ + #[specforge_test(requirement = \"A\", __guard_only)]\n#[tokio::test]\nasync fn runner() {}\n\ + #[spec(behavior = r#\"a\"b\"#, __guard_only)]\nfn raw() {}\n\ + #[spec(behavior = 'x', note = '\"', __guard_only)]\nfn chars() {}\n", + )]); + // The top one leaves registering to the one below, which is a guard only: no test is registered. + assert_eq!(marks(&facts, "rust:toy::top").1, None); + assert_eq!( + marks(&facts, "rust:toy::low").1, + Some(json!("rust:toy#low")) + ); + assert_eq!( + marks(&facts, "rust:toy::runner").1, + Some(json!("rust:toy#runner")), + "a runner attribute registers it itself" + ); + assert_eq!( + marks(&facts, "rust:toy::raw").1, + None, + "a raw string hides no __guard_only after it" + ); + assert_eq!( + marks(&facts, "rust:toy::chars").1, + None, + "nor does a char literal" + ); +} + #[specforge_test(requirement = "FEATURE-004")] #[specforge_test(requirement = "FEATURE-113")] fn a_test_in_an_inline_module_keeps_its_module_path() { diff --git a/extensions/rust/source/wasm/inputs.json b/extensions/rust/source/wasm/inputs.json index e4f383ac14..db666a218a 100644 --- a/extensions/rust/source/wasm/inputs.json +++ b/extensions/rust/source/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "specforge_ext_rust_source.wasm", - "artifact_sha256": "6fdc50bcbe048696517ed28b2395c00317c2c255d54609f483d87f23bb7a8c0f", + "artifact_sha256": "ab03de5f21e15c85418e6ef77066a8d0152eaeea093bc57e9a3c14bed0748edb", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,31 +55,40 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", - "extensions/code/facts/src/ids.rs": "e3f1f07f70da4786c0ca0b301594b1dc812c2a45808dbe1a5f4905805eccce97", - "extensions/code/facts/src/lib.rs": "5a9733980787f23265ab7f374840d6f61bf2ecbdad3471df86e68c0f2e699769", - "extensions/code/facts/src/mint.rs": "e71f130aaeaeeca2d4c5afa59a36c60fa5ac8bc26db2f4a8276c71024305925e", - "extensions/code/facts/src/paths.rs": "890973baefd07c33e93c6c12ae882083c2d969de91bb3c697bc271ec03474eae", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", - "extensions/code/junit/src/lib.rs": "dfeb44e386f4865b2c5570d389bfd6ff246ccf69122ee36ec7feb9db8a394f35", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", "extensions/rust/source/Cargo.lock": "b7ece3e2a5107a0bd0c9e6da8f45f9934435ef62826855a93bc391ebd2794672", "extensions/rust/source/Cargo.toml": "f2db9fb8355198d290803723d1d4f426bbbfe7679fd6f2a2503c700348249f55", - "extensions/rust/source/queries/rust-tags.scm": "d5d75e5c96a368966dba7c5352e3384bb9b3d83601a9ac38e43a98b6a70d7be0", - "extensions/rust/source/src/items.rs": "aac60ebb5cff1410fe20a3f10eea5c20a3f6c3fd744d4dd563be0cb465921279", + "extensions/rust/source/queries/rust-tags.scm": "cffa28e36b1d06e4e786e834f760cdc29ca3f965b139bc51c50fa724667b4501", + "extensions/rust/source/src/items.rs": "b1a638c4e388ab5a7742fac917035e1634bf51ecdb373ff85e07f64ded189d98", "extensions/rust/source/src/lib.rs": "2ead74be86e99eee68a8ddad703e87c81c4dce1863c2b03d507731b2dc7673e1", - "extensions/rust/source/src/modules.rs": "7550a48b9c114bf1d0c839e9804eb8d7d9f27ba3513962d367eb732c538e6535" + "extensions/rust/source/src/modules.rs": "32fd15a396e81cd6b6ff5abb47ab4ae7467d527ffdff287509e9737176dfb9b6" } } diff --git a/extensions/rust/source/wasm/specforge_ext_rust_source.wasm b/extensions/rust/source/wasm/specforge_ext_rust_source.wasm index 971ab5ceed..2eeb1933cb 100644 Binary files a/extensions/rust/source/wasm/specforge_ext_rust_source.wasm and b/extensions/rust/source/wasm/specforge_ext_rust_source.wasm differ diff --git a/extensions/rust/test/src/cfg.rs b/extensions/rust/test/src/cfg.rs new file mode 100644 index 0000000000..b177361d70 --- /dev/null +++ b/extensions/rust/test/src/cfg.rs @@ -0,0 +1,162 @@ +//! Which test items count as compiled out on the host: a `cfg(…)` attribute whose predicate is false here +//! (ADR 0393 D5). Only platform atoms decide; a feature, `test` or any other atom is unknown, so a test a forgotten +//! feature compiled out stays missing instead of being hidden as skipped. +//! +//! The guest learns the host's family from its input: the canonical project root the host passes as `cwd` is a unix +//! path (`/…`) or a Windows one (`C:\…`, `\\?\C:\…`). That decides `unix`, `windows` and `target_family`, and +//! `target_os` on a Windows host. Which unix it is (`target_os = "linux"` or `"macos"`) nothing in the input tells, so +//! there `target_os` is unknown but for `"windows"`: a test gated on another unix's `target_os` stays missing. + +/// A predicate's value on the host: `None` when it does not decide. +type Value = Option; + +/// The host's target family. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Family { + Unix, + Windows, +} + +impl Family { + /// The family whose paths the canonical project root `cwd` is written in; `None` without a root, or for one in + /// neither form. + pub(crate) fn of(cwd: Option<&str>) -> Option { + let cwd = cwd?; + let drive = cwd.as_bytes().get(1) == Some(&b':') && cwd.as_bytes()[0].is_ascii_alphabetic(); + if cwd.starts_with('/') { + Some(Family::Unix) + } else if drive || cwd.starts_with(r"\\") { + Some(Family::Windows) + } else { + None + } + } + + /// Its `target_family` value. + fn name(self) -> &'static str { + match self { + Family::Unix => "unix", + Family::Windows => "windows", + } + } +} + +/// Whether `attr` (an item's recorded attribute, `cfg(windows)`) is a `cfg(…)` whose predicate parses and is false on +/// a host of `family` (`None`: nothing is decided). Anything that does not parse is not excluded. +pub(crate) fn excludes(attr: &str, family: Option) -> bool { + let Some(family) = family else { + return false; + }; + let mut parser = Parser { rest: attr, family }; + parser.ident() == Some("cfg") + && matches!(parser.list().as_deref(), Some([Some(false)])) + && parser.rest.trim().is_empty() +} + +/// The value of the atom `name` (`name = "value"` when `value` is given) on a host of `family`: a native host is of +/// one family, and a Windows host's `target_os` is `"windows"`. +fn holds(family: Family, name: &str, value: Option<&str>) -> Value { + match (name, value) { + ("unix", None) => Some(family == Family::Unix), + ("windows", None) => Some(family == Family::Windows), + ("target_family", Some(value)) => Some(value == family.name()), + ("target_os", Some(value)) if family == Family::Windows => Some(value == "windows"), + ("target_os", Some("windows")) => Some(false), + _ => None, + } +} + +/// `all(…)`: false when a member is, true when every member is, else unknown. +fn all(members: &[Value]) -> Value { + if members.contains(&Some(false)) { + Some(false) + } else if members.iter().all(|v| *v == Some(true)) { + Some(true) + } else { + None + } +} + +/// `any(…)`: true when a member is, false when every member is, else unknown. +fn any(members: &[Value]) -> Value { + if members.contains(&Some(true)) { + Some(true) + } else if members.iter().all(|v| *v == Some(false)) { + Some(false) + } else { + None + } +} + +/// A recursive-descent reader of rustc's cfg predicate grammar, evaluating as it reads. +struct Parser<'a> { + rest: &'a str, + family: Family, +} + +impl<'a> Parser<'a> { + fn eat(&mut self, c: char) -> bool { + self.rest = self.rest.trim_start(); + match self.rest.strip_prefix(c) { + Some(rest) => { + self.rest = rest; + true + } + None => false, + } + } + + fn ident(&mut self) -> Option<&'a str> { + self.rest = self.rest.trim_start(); + let end = self + .rest + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .unwrap_or(self.rest.len()); + let (word, rest) = self.rest.split_at(end); + self.rest = rest; + (!word.is_empty()).then_some(word) + } + + fn string(&mut self) -> Option<&'a str> { + if !self.eat('"') { + return None; + } + let (text, rest) = self.rest.split_once('"')?; + self.rest = rest; + Some(text) + } + + /// One predicate's value; `None` when it does not parse. + fn predicate(&mut self) -> Option { + let name = self.ident()?; + if self.eat('=') { + return Some(holds(self.family, name, Some(self.string()?))); + } + Some(match name { + "all" => all(&self.list()?), + "any" => any(&self.list()?), + "not" => match self.list()?[..] { + [one] => one.map(|v| !v), + _ => return None, + }, + _ => holds(self.family, name, None), + }) + } + + /// A parenthesized, comma-separated list of predicates (a trailing comma allowed), each evaluated. + fn list(&mut self) -> Option> { + if !self.eat('(') { + return None; + } + let mut members = Vec::new(); + loop { + if self.eat(')') { + return Some(members); + } + members.push(self.predicate()?); + if !self.eat(',') { + return self.eat(')').then_some(members); + } + } + } +} diff --git a/extensions/rust/test/src/lib.rs b/extensions/rust/test/src/lib.rs index 65698e1cae..288fba0b36 100644 --- a/extensions/rust/test/src/lib.rs +++ b/extensions/rust/test/src/lib.rs @@ -18,15 +18,19 @@ //! Each case sits in exactly one ``, named by its binary id (`toy`, `toy::bin/toy`, `toy::api`): the test //! is `rust:#`. It is served `@rust/source`'s items; a test whose id an item's `test_id` holds takes //! the item's places, file and names. nextest omits an ignored test from its report, so every item marked `test` and -//! `ignore` whose id the report lacks becomes a `skipped` test without a run: a cited ignored test is held. +//! `ignore` whose id the report lacks becomes a `skipped` test without a run: a cited ignored test is held. So does +//! a test item a `cfg(…)` compiles out on the host (`cfg(windows)` on a unix host, ADR 0393 D5), the host's family read +//! from the project root it passes as `cwd`. use std::collections::{BTreeMap, BTreeSet}; use std::str::FromStr; -use specforge_code_facts::{test_facts, Names, TestCase, TestId}; +use specforge_code_facts::{test_facts, TestCase, TestId}; use specforge_code_junit::cases; use specforge_extension_sdk::prelude::*; +mod cfg; + const COLLECTOR: &str = "rust-test"; /// The JUnit report nextest writes, relative to the project root. const REPORT: &str = ".specforge/reports/rust-test.xml"; @@ -83,47 +87,12 @@ impl Contributions for RustTest { struct Item<'f> { fact: &'f Fact, ignored: bool, + /// A `cfg(…)` attribute compiles it out on the host (ADR 0393 D5). + excluded: bool, } -impl Item<'_> { - /// `case` placed at this item: its places, file and names. - fn place(&self, case: TestCase) -> TestCase { - let names: Names = self - .fact - .fields - .get("names") - .and_then(|names| names.as_array()) - .into_iter() - .flatten() - .filter_map(|name| name.as_str()) - .map(|name| { - let places = self - .fact - .named_at - .get("names") - .and_then(|named| named.get(name)) - .cloned() - .unwrap_or_default(); - (name.to_string(), places) - }) - .collect(); - TestCase { - file: case.file.or_else(|| { - self.fact - .fields - .get("file") - .and_then(|f| f.as_str()) - .map(str::to_string) - }), - names, - at: self.fact.at.clone(), - ..case - } - } -} - -/// The served items by the test id they hold. -fn items(facts: &[Fact]) -> BTreeMap<&str, Item<'_>> { +/// The served items by the test id they hold, judged for a host of `family`. +fn items(facts: &[Fact], family: Option) -> BTreeMap<&str, Item<'_>> { facts .iter() .filter(|fact| fact.kind == "item") @@ -137,14 +106,23 @@ fn items(facts: &[Fact]) -> BTreeMap<&str, Item<'_>> { .flatten() .filter_map(|a| a.as_str()) .collect(); - let ignored = attrs.contains(&"test") && attrs.contains(&"ignore"); - Some((test_id, Item { fact, ignored })) + let test = attrs.contains(&"test"); + let ignored = test && attrs.contains(&"ignore"); + let excluded = test && attrs.iter().any(|attr| cfg::excludes(attr, family)); + Some(( + test_id, + Item { + fact, + ignored, + excluded, + }, + )) }) .collect() } -/// Map nextest's JUnit report to a `test` and a `test_run` fact per case, and a `skipped` test per ignored test item -/// the report lacks. A report whose case is not in exactly one `` is not nextest's: the collector's error. +/// Map nextest's JUnit report to a `test` and a `test_run` fact per case, and a `skipped` test per ignored or +/// cfg-excluded test item the report lacks (ADR 0393 D5). A report whose case is not in exactly one `` is not nextest's: the collector's error. fn collect(input: &CollectInput) -> Result { let [report] = &input.reports[..] else { return Err(format!( @@ -153,7 +131,7 @@ fn collect(input: &CollectInput) -> Result { )); }; let found = cases(&report.content).map_err(|why| format!("{}: {why}", report.path))?; - let items = items(&input.facts); + let items = items(&input.facts, cfg::Family::of(input.cwd.as_deref())); let mut reported = BTreeSet::new(); let mut tests = Vec::new(); for case in &found { @@ -170,15 +148,15 @@ fn collect(input: &CollectInput) -> Result { let key = id.to_string(); let test = TestCase::of(id, case, None); tests.push(match items.get(key.as_str()) { - Some(item) => item.place(test), + Some(item) => test.placed(item.fact), None => test, }); reported.insert(key); } for (test_id, item) in &items { - if item.ignored && !reported.contains(*test_id) { + if (item.ignored || item.excluded) && !reported.contains(*test_id) { let id = TestId::from_str(test_id).map_err(|e| format!("{}: {e}", item.fact.id))?; - tests.push(item.place(TestCase::unrun(id, TestStatus::Skipped))); + tests.push(TestCase::unrun(id, TestStatus::Skipped).placed(item.fact)); } } Ok(CollectOutput { diff --git a/extensions/rust/test/src/tests.rs b/extensions/rust/test/src/tests.rs index 137d1b3835..e88a3e766f 100644 --- a/extensions/rust/test/src/tests.rs +++ b/extensions/rust/test/src/tests.rs @@ -6,13 +6,14 @@ use specforge_test::prelude::*; /// `tests::nested::deep`, the bins `extra` and `toy-crate` and the integration test `tests`, its ignored test absent. const TOY: &str = include_str!("../fixtures/toy.xml"); -/// The input the host sends for `report`, these item facts served. +/// The input a unix host sends for `report`, these item facts served. fn input(report: &str, items: Vec) -> CollectInput { CollectInput { reports: vec![CollectReportFile { path: REPORT.to_string(), content: report.to_string(), }], + cwd: Some("/work/toy-crate".to_string()), facts: items, ..CollectInput::default() } @@ -285,3 +286,172 @@ fn an_empty_report_has_no_test() { assert_eq!(out.facts, Vec::::new(), "{report:?}"); } } + +#[specforge_test(requirement = "FEATURE-004")] +#[specforge_test(requirement = "FEATURE-114")] +fn a_test_compiled_out_on_the_host_the_report_omits_is_a_skipped_test_without_a_run() { + let windows = item( + "rust:toy-crate/test/tests::windows_only", + "rust:toy-crate::tests#windows_only", + &["cfg(windows)", "test"], + "tests/tests.rs", + 7, + ); + let out = collect(&input(TOY, vec![windows])).unwrap(); + let facts: Vec<(&str, &str, &str)> = summary(&out) + .into_iter() + .filter(|(_, id, _)| id.contains("windows_only")) + .collect(); + assert_eq!( + facts, + [("test", "rust:toy-crate::tests#windows_only", "skipped")], + "no test_run" + ); + let skipped = out + .facts + .iter() + .find(|f| f.id == "rust:toy-crate::tests#windows_only") + .unwrap(); + assert_eq!(skipped.fields["file"], "tests/tests.rs"); +} + +#[specforge_test(requirement = "FEATURE-004")] +#[specforge_test(requirement = "FEATURE-114")] +fn a_cfg_excluded_test_the_report_holds_keeps_its_status() { + let deep = item( + "rust:toy-crate::tests::nested::deep", + "rust:toy-crate#tests::nested::deep", + &["cfg(windows)", "test"], + "src/lib.rs", + 6, + ); + let out = collect(&input(TOY, vec![deep])).unwrap(); + let deep: Vec<(&str, &str, &str)> = summary(&out) + .into_iter() + .filter(|(_, id, _)| id.ends_with("#tests::nested::deep")) + .collect(); + assert_eq!( + deep, + [ + ("test", "rust:toy-crate#tests::nested::deep", "passed"), + ( + "test_run", + "run:rust:toy-crate#tests::nested::deep", + "passed" + ), + ] + ); +} + +#[specforge_test(requirement = "FEATURE-004")] +#[specforge_test(requirement = "FEATURE-114")] +fn a_feature_or_test_gated_test_the_report_omits_stays_missing() { + for cfg in [r#"cfg(feature = "tokio")"#, "cfg(test)"] { + let gated = item( + "rust:toy-crate/test/tests::gated", + "rust:toy-crate::tests#gated", + &[cfg, "test"], + "tests/tests.rs", + 9, + ); + let out = collect(&input(TOY, vec![gated])).unwrap(); + assert!( + !out.facts.iter().any(|f| f.id.contains("gated")), + "{cfg}: an unknown predicate hides no missing test" + ); + } +} + +#[specforge_test(requirement = "FEATURE-004")] +#[specforge_test(requirement = "FEATURE-114")] +fn only_a_platform_predicate_false_on_a_unix_host_excludes() { + let unix = Some(cfg::Family::Unix); + for (attr, excluded) in [ + ("cfg(windows)", true), + ("cfg(unix)", false), + (r#"cfg(target_os = "windows")"#, true), + // Which unix the host is, nothing tells. + (r#"cfg(target_os = "linux")"#, false), + (r#"cfg(not(target_os = "macos"))"#, false), + (r#"cfg(target_family = "windows")"#, true), + (r#"cfg(target_family = "wasm")"#, true), + (r#"cfg(target_family = "unix")"#, false), + ("cfg(not(unix))", true), + ("cfg(not(windows))", false), + (r#"cfg(all(windows, feature = "x"))"#, true), + (r#"cfg(any(windows, feature = "x"))"#, false), + (r#"cfg(any(windows, target_os = "windows"))"#, true), + (r#"cfg(feature = "x")"#, false), + ("cfg(", false), + ("cfg(all(windows, test,))", true), + ("cfg(any())", true), + ("cfg(all())", false), + ("cfg(windows) x", false), + ("cfg_attr(windows, ignore)", false), + ] { + assert_eq!(cfg::excludes(attr, unix), excluded, "{attr}"); + } +} + +#[specforge_test(requirement = "FEATURE-004")] +#[specforge_test(requirement = "FEATURE-114")] +fn a_windows_host_decides_the_unix_predicates_and_every_target_os() { + let windows = Some(cfg::Family::Windows); + for (attr, excluded) in [ + ("cfg(windows)", false), + ("cfg(unix)", true), + (r#"cfg(target_os = "windows")"#, false), + (r#"cfg(target_os = "linux")"#, true), + (r#"cfg(target_os = "macos")"#, true), + (r#"cfg(target_family = "unix")"#, true), + ("cfg(not(windows))", true), + (r#"cfg(feature = "x")"#, false), + ] { + assert_eq!(cfg::excludes(attr, windows), excluded, "{attr}"); + } + // With no project root nothing is decided, so nothing is excluded. + assert!(!cfg::excludes("cfg(windows)", None)); +} + +#[specforge_test(requirement = "FEATURE-004")] +#[specforge_test(requirement = "FEATURE-114")] +fn the_host_family_is_the_form_of_its_project_root() { + use cfg::Family; + for (cwd, family) in [ + (Some("/home/ci/project"), Some(Family::Unix)), + (Some(r"C:\work\project"), Some(Family::Windows)), + (Some(r"\\?\C:\work\project"), Some(Family::Windows)), + (Some("project"), None), + (None, None), + ] { + assert_eq!(Family::of(cwd), family, "{cwd:?}"); + } + // On a Windows host a `cfg(unix)` test the report omits is skipped, and a `cfg(windows)` one stays missing. + let unix_only = item( + "rust:toy-crate/test/tests::unix_only", + "rust:toy-crate::tests#unix_only", + &["cfg(unix)", "test"], + "tests/tests.rs", + 7, + ); + let windows_only = item( + "rust:toy-crate/test/tests::windows_only", + "rust:toy-crate::tests#windows_only", + &["cfg(windows)", "test"], + "tests/tests.rs", + 9, + ); + let on_windows = CollectInput { + cwd: Some(r"C:\work\toy-crate".to_string()), + ..input(TOY, vec![unix_only, windows_only]) + }; + let out = collect(&on_windows).unwrap(); + let only: Vec<(&str, &str, &str)> = summary(&out) + .into_iter() + .filter(|(_, id, _)| id.ends_with("_only")) + .collect(); + assert_eq!( + only, + [("test", "rust:toy-crate::tests#unix_only", "skipped")] + ); +} diff --git a/extensions/rust/test/wasm/inputs.json b/extensions/rust/test/wasm/inputs.json index 9961851fb8..a196b806dd 100644 --- a/extensions/rust/test/wasm/inputs.json +++ b/extensions/rust/test/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "specforge_ext_rust_test.wasm", - "artifact_sha256": "2b1416a6b212a90001d73c84cdb05125fa9d9f1deb8844ba9cb436d5308dd4ec", + "artifact_sha256": "cf5bc5aa715b01118f23cc801e33a58aa460eec4d06615fa998cf53b0e85df78", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,28 +55,38 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", "extensions/code/facts/Cargo.toml": "78711c072008558fb21fc45885a253dd47f50b0e4d38791e8820a899d8f27d2b", - "extensions/code/facts/src/ids.rs": "e3f1f07f70da4786c0ca0b301594b1dc812c2a45808dbe1a5f4905805eccce97", - "extensions/code/facts/src/lib.rs": "5a9733980787f23265ab7f374840d6f61bf2ecbdad3471df86e68c0f2e699769", - "extensions/code/facts/src/mint.rs": "e71f130aaeaeeca2d4c5afa59a36c60fa5ac8bc26db2f4a8276c71024305925e", - "extensions/code/facts/src/paths.rs": "890973baefd07c33e93c6c12ae882083c2d969de91bb3c697bc271ec03474eae", + "extensions/code/facts/src/accepted.rs": "e4ac2a4d178964150dd57a76f534212742ccb6470a677a31d2312e662ce3a96f", + "extensions/code/facts/src/api.rs": "95ab73c3243d001df2f14736fd37d0b86fe0160fdb1fe41beaf0ea732e86cd86", + "extensions/code/facts/src/coverage.rs": "753322a3faebf6d81b3f890daa8fce1be08ae7a839f7aa33691a5f60df4c1c2f", + "extensions/code/facts/src/cvss.rs": "6cf21e349338c7c73e233b7234e4d1434145f56271dc4fec5b6b5b1acd8bc896", + "extensions/code/facts/src/dependency.rs": "6a9a3026cc09b1e81965fefd5acfe8f59bf8a4b18231dd18416068324b311876", + "extensions/code/facts/src/finding.rs": "83dad7687ceea13aac254f5fc3beab70561de195263253358aed522bcb042b43", + "extensions/code/facts/src/ids.rs": "1abbb4ccc99d1b58f75364238485fc741b56a1a564464b59e78db26ded1446d4", + "extensions/code/facts/src/lib.rs": "5f5661cee16ccbbb2ec10cfe213d01c585d1ae9952cc9d027481ac1d5db864d4", + "extensions/code/facts/src/mint.rs": "d31be5272b19ac2a37535a25a1a2863038d642a2b937c568df833993b238a34e", + "extensions/code/facts/src/paths.rs": "6486d4fbf94d60ccd6bd2d7e4290511f3d58bcc1f2411e474df53e49b1f54c58", + "extensions/code/facts/src/places.rs": "cc795fad8f37fe8aa7d6e7a7874e25f73d7545285d93eb39f8eeb736794e6505", + "extensions/code/facts/src/report.rs": "f17d7115595c8b7014e4bb93b08db268889186f9b8366ee001baf21be8a8f111", "extensions/code/facts/src/syntax.rs": "ddba57880c79d41a7c2e7bf0aca1c07a612977cb3194e5e366ccdb80f96031d4", + "extensions/code/facts/src/vulnerability.rs": "1f6834b23376c5451e7fe7c259089a88ce612d49551eb99507593141d8f35ebe", "extensions/code/junit/Cargo.toml": "0cf8fd46f5d31313c6edd4c030fd0d8e49140c4382558cf362bb101b761cb8b2", - "extensions/code/junit/src/lib.rs": "dfeb44e386f4865b2c5570d389bfd6ff246ccf69122ee36ec7feb9db8a394f35", + "extensions/code/junit/src/lib.rs": "f8f71c0b6823ef7d12722d4f962ba94b012f3c9ecd05ca4506bd9f8b19105cb2", "extensions/code/junit/src/xml.rs": "fa399f0b4782f298aaf8a2407f25c6112a9c40dbcf98951def06f8e06976dc20", "extensions/rust/test/Cargo.lock": "1fb6f6b819ab1252e8f2d604133bfddefde77856486b1628b58e237016575b5e", "extensions/rust/test/Cargo.toml": "04bd7f58112bb61c7852dcb03408a6188a1c08f4e1ca04ea5c9a4ce564900d2f", - "extensions/rust/test/src/lib.rs": "ae7f6cfc13bb0d1ebb4a926a6bebb7bee63aa80ca733c8aad3a37ea6219a1cf9" + "extensions/rust/test/src/cfg.rs": "b26b2dbebaa1a975e908795373ac3424669d345b10df7d8717286b357e345665", + "extensions/rust/test/src/lib.rs": "444d098a44fe04299aa4a7b61426290cda0d625c956933722a03a76cf47b856c" } } diff --git a/extensions/rust/test/wasm/specforge_ext_rust_test.wasm b/extensions/rust/test/wasm/specforge_ext_rust_test.wasm index 81aa4c510b..bb393ac059 100644 Binary files a/extensions/rust/test/wasm/specforge_ext_rust_test.wasm and b/extensions/rust/test/wasm/specforge_ext_rust_test.wasm differ diff --git a/extensions/software/wasm/inputs.json b/extensions/software/wasm/inputs.json index 0eaa920709..7e071d6642 100644 --- a/extensions/software/wasm/inputs.json +++ b/extensions/software/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "specforge_ext_software.wasm", - "artifact_sha256": "e337a1f752043d4c69aec47668ef17dbe8f5297d383a5e17bd50261c0c11eb45", + "artifact_sha256": "8cc320f08e900725452e520a7d9cc76ec3dc102e24fae2f7f28ed1d9833fe8ff", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,14 +55,14 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", diff --git a/extensions/software/wasm/specforge_ext_software.wasm b/extensions/software/wasm/specforge_ext_software.wasm index 1d8ba502e6..f7b66c1b41 100755 Binary files a/extensions/software/wasm/specforge_ext_software.wasm and b/extensions/software/wasm/specforge_ext_software.wasm differ diff --git a/extensions/testing/wasm/inputs.json b/extensions/testing/wasm/inputs.json index 4fbab1e1c0..45599eb3f4 100644 --- a/extensions/testing/wasm/inputs.json +++ b/extensions/testing/wasm/inputs.json @@ -1,6 +1,6 @@ { "artifact": "specforge_ext_testing.wasm", - "artifact_sha256": "13bcac623afdbf9989be3004c4ff99ec7e39ea09d26b69e64e59980ac93be5e8", + "artifact_sha256": "9aaaf42ad1e407f21e23f9cf6869721bd6ada098d9ec308e580735a7dc0febfd", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", @@ -8,12 +8,12 @@ "crates/leaf/coverage/src/lib.rs": "7f3ae9dfe19a63906be5d810f2d0106c955ca61580d6b73777f11758f5945e10", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -23,29 +23,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -57,14 +57,14 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", diff --git a/extensions/testing/wasm/specforge_ext_testing.wasm b/extensions/testing/wasm/specforge_ext_testing.wasm index f8a8e122cd..378cc34d02 100644 Binary files a/extensions/testing/wasm/specforge_ext_testing.wasm and b/extensions/testing/wasm/specforge_ext_testing.wasm differ diff --git a/extensions/vitest/wasm/inputs.json b/extensions/vitest/wasm/inputs.json index 1096f5c236..5743d8e2ac 100644 --- a/extensions/vitest/wasm/inputs.json +++ b/extensions/vitest/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "specforge_ext_vitest.wasm", - "artifact_sha256": "30f87a155849a2eaed1655e43a6d3ebb9593ec0fd42903c19edc191573350914", + "artifact_sha256": "6fca01dc0223ccf87a7235ee490a50cbdf72c641b9a51bee78cb58599c5b6f6d", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,14 +55,14 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", diff --git a/extensions/vitest/wasm/specforge_ext_vitest.wasm b/extensions/vitest/wasm/specforge_ext_vitest.wasm index 2301bb4e40..bf9e32d76a 100644 Binary files a/extensions/vitest/wasm/specforge_ext_vitest.wasm and b/extensions/vitest/wasm/specforge_ext_vitest.wasm differ diff --git a/fixtures/docref-extension/wasm/docref.wasm b/fixtures/docref-extension/wasm/docref.wasm index aae38d00f2..f55dc77e64 100644 Binary files a/fixtures/docref-extension/wasm/docref.wasm and b/fixtures/docref-extension/wasm/docref.wasm differ diff --git a/fixtures/docref-extension/wasm/inputs.json b/fixtures/docref-extension/wasm/inputs.json index 98635e47bc..962e61cd7e 100644 --- a/fixtures/docref-extension/wasm/inputs.json +++ b/fixtures/docref-extension/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "docref.wasm", - "artifact_sha256": "8664098a6f653a3d18f11cfc90ec39b4965da7e94e2d7482221448d10804288f", + "artifact_sha256": "4ef2efd48b7966ee20ec730f0403346ef475a48122fea069724aa8d95ba608f2", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,14 +55,14 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", diff --git a/fixtures/greet-extension/src/contributions.rs b/fixtures/greet-extension/src/contributions.rs index 804962b8e6..672d0ad4e4 100644 --- a/fixtures/greet-extension/src/contributions.rs +++ b/fixtures/greet-extension/src/contributions.rs @@ -114,6 +114,7 @@ impl Contributions for Greet { unlinked: Vec::new(), plan: None, facts: Vec::new(), + warnings: Vec::new(), }) }); }); diff --git a/fixtures/greet-extension/wasm/greet.wasm b/fixtures/greet-extension/wasm/greet.wasm index 5e6152b409..5194648119 100644 Binary files a/fixtures/greet-extension/wasm/greet.wasm and b/fixtures/greet-extension/wasm/greet.wasm differ diff --git a/fixtures/greet-extension/wasm/inputs.json b/fixtures/greet-extension/wasm/inputs.json index 9bd8f1fff2..3731f904e0 100644 --- a/fixtures/greet-extension/wasm/inputs.json +++ b/fixtures/greet-extension/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "greet.wasm", - "artifact_sha256": "529a48a87819e659359d8ee344dd2b46d024eb79999321bff96222e17190adfb", + "artifact_sha256": "db06f6ffd684c7bebbf9f3f2ebfc3a309da738056428e7a687135e07c0e97583", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,20 +55,20 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", "fixtures/greet-extension/Cargo.lock": "9d5b9897879187b79bb30dd0b9662f8a8e72fddca3ca06c33b5622a90ca72249", "fixtures/greet-extension/Cargo.toml": "4daca3f6a924aa2b804311992f24bd07d7fb785fd3cb83b79d3521e462072124", - "fixtures/greet-extension/src/contributions.rs": "b0768fbea53518f4cbbfdcb2955fa2586b0c38bfec1e5d4454d61f78ea5c450e", + "fixtures/greet-extension/src/contributions.rs": "e70a27bf11a51747c4e5e322d81b7f97d30cfbaaedc97ae332eb71bea78bed9c", "fixtures/greet-extension/src/lib.rs": "e0521642bba7ae2971b70189c7acf0b76c2d748b87b3822e15257018cd08c5ab" } } diff --git a/fixtures/sandbox-probe/wasm/inputs.json b/fixtures/sandbox-probe/wasm/inputs.json index 978152bad9..1e43a87c44 100644 --- a/fixtures/sandbox-probe/wasm/inputs.json +++ b/fixtures/sandbox-probe/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "sandbox_probe.wasm", - "artifact_sha256": "49d7926ac15117871fb2b21130bb18d3d8e99bc0f781d1b5516ae2d3473840f9", + "artifact_sha256": "ea97632e4892af1a1c42425b13cbebd1f466a2ae79b56eec84c731d7b9bb82d0", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,14 +55,14 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", diff --git a/fixtures/sandbox-probe/wasm/sandbox_probe.wasm b/fixtures/sandbox-probe/wasm/sandbox_probe.wasm index 395bafb9f3..e824b38450 100644 Binary files a/fixtures/sandbox-probe/wasm/sandbox_probe.wasm and b/fixtures/sandbox-probe/wasm/sandbox_probe.wasm differ diff --git a/gate/src/blob_inputs.rs b/gate/src/blob_inputs.rs index 38cf2cecd9..3a4cec8bc9 100644 --- a/gate/src/blob_inputs.rs +++ b/gate/src/blob_inputs.rs @@ -1,7 +1,7 @@ //! `/wasm/inputs.json`: what one committed blob (a builtin under `extensions/`, a fixture under -//! `fixtures/`, an example project's own extension under `examples//extension`, or `@gsd/core` under -//! `gsd/core`, the one builtin outside `extensions/`) was built from. `build-blobs` writes and checks it through this -//! module; a quick run asks it which blobs a change set feeds. A blob is named by its crate directory from the +//! `fixtures/`, an example project's own extension under `examples//extension`, or `@gsd/core` and +//! `@gsd/import` under `gsd/core` and `gsd/import`, the two builtins outside `extensions/`) was built from. +//! `build-blobs` writes and checks it through this module; a quick run asks it which blobs a change set feeds. A blob is named by its crate directory from the //! repository root. The JSON is unchanged byte for byte. use std::collections::BTreeMap; @@ -150,9 +150,14 @@ pub fn inherited_tables(manifest: &str) -> String { } /// The crates that commit a blob besides the builtins under `extensions/` ([`crate::repo::EXTENSION_CRATES`]), as -/// `repo::expand` patterns: the fixtures, the example projects' extensions and `@gsd/core` (ADR 0366 D2), so a `gsd/` -/// input feeds the `builtins` check once its record exists. -pub const BLOB_CRATES: &[&str] = &["fixtures/*", "examples/*/extension", "gsd/core"]; +/// `repo::expand` patterns: the fixtures, the example projects' extensions, `@gsd/core` (ADR 0366 D2) and +/// `@gsd/import` (ADR 0391 D12), so a `gsd/` input feeds the `builtins` check once its record exists. +pub const BLOB_CRATES: &[&str] = &[ + "fixtures/*", + "examples/*/extension", + "gsd/core", + "gsd/import", +]; /// The gsd workspace, from the repository root: one Cargo workspace with one lock and its own `.cargo/config.toml`. const GSD_WORKSPACE: &str = "gsd"; @@ -201,8 +206,8 @@ pub fn workspace_inputs(crate_dir: &str) -> Vec { } /// Every committed blob with a record: the crate directories (`extensions/`, `extensions//`, -/// `fixtures/`, `examples//extension`, `gsd/core`, sorted) whose `wasm/inputs.json` exists; an extension library has -/// none, so it is no blob. +/// `fixtures/`, `examples//extension`, `gsd/core`, `gsd/import`, sorted) whose `wasm/inputs.json` exists; +/// an extension library has none, so it is no blob. pub fn blobs(repo_root: &Path) -> Result, String> { let suffix = format!("/wasm/{FILE}"); let mut found: Vec = crate::repo::EXTENSION_CRATES diff --git a/gate/src/blob_inputs/tests.rs b/gate/src/blob_inputs/tests.rs index 707f414928..dab468de7d 100644 --- a/gate/src/blob_inputs/tests.rs +++ b/gate/src/blob_inputs/tests.rs @@ -9,16 +9,28 @@ fn fed(paths: &[&str]) -> Vec { } /// The blobs that record their inputs today: the builtins. The fixtures join at the round's re-vendor. -const BUILTIN_CRATES: [&str; 14] = [ +const BUILTIN_CRATES: [&str; 26] = [ "extensions/cargo-test", "extensions/checks", "extensions/code/core", "extensions/formal", "extensions/governance", + "extensions/javascript/api", + "extensions/javascript/coverage", + "extensions/javascript/deps", + "extensions/javascript/jest", + "extensions/javascript/lint", "extensions/javascript/node-test", + "extensions/javascript/playwright", "extensions/javascript/source", + "extensions/javascript/vitest", "extensions/product", + "extensions/rust/api", "extensions/rust/cargo", + "extensions/rust/coverage", + "extensions/rust/deps", + "extensions/rust/lint", + "extensions/rust/proof", "extensions/rust/source", "extensions/rust/test", "extensions/software", @@ -26,12 +38,24 @@ const BUILTIN_CRATES: [&str; 14] = [ "extensions/vitest", ]; -/// The builtins that link the `@code` extension libraries. -const CODE_LINKERS: [&str; 6] = [ +/// The builtins that link code-facts. code-facts links code-junit, so these are junit's linkers too. +const CODE_FACTS_LINKERS: [&str; 18] = [ "extensions/code/core", + "extensions/javascript/api", + "extensions/javascript/coverage", + "extensions/javascript/deps", + "extensions/javascript/jest", + "extensions/javascript/lint", "extensions/javascript/node-test", + "extensions/javascript/playwright", "extensions/javascript/source", + "extensions/javascript/vitest", + "extensions/rust/api", "extensions/rust/cargo", + "extensions/rust/coverage", + "extensions/rust/deps", + "extensions/rust/lint", + "extensions/rust/proof", "extensions/rust/source", "extensions/rust/test", ]; @@ -50,12 +74,53 @@ fn a_record_round_trips_byte_for_byte() { #[test] fn a_change_to_the_junit_library_feeds_the_builtins_that_link_it() { - assert_eq!(fed(&["extensions/code/junit/src/lib.rs"]), CODE_LINKERS); + assert_eq!( + fed(&["extensions/code/junit/src/lib.rs"]), + CODE_FACTS_LINKERS + ); } #[test] fn a_change_to_the_code_facts_library_feeds_the_builtins_that_link_it() { - assert_eq!(fed(&["extensions/code/facts/src/ids.rs"]), CODE_LINKERS); + assert_eq!( + fed(&["extensions/code/facts/src/ids.rs"]), + CODE_FACTS_LINKERS + ); +} + +/// A report reader is a library each report pack links, so editing one re-vendors exactly the packs that +/// read its format (ADR 0389). +#[test] +fn a_change_to_a_report_reader_feeds_the_packs_that_link_it() { + let readers: [(&str, &[&str]); 5] = [ + ( + "lcov", + &["extensions/javascript/coverage", "extensions/rust/coverage"], + ), + ("api", &["extensions/javascript/api", "extensions/rust/api"]), + ("sarif", &["extensions/javascript/lint"]), + ( + "cyclonedx", + &["extensions/javascript/deps", "extensions/rust/deps"], + ), + ( + "osv", + &["extensions/javascript/deps", "extensions/rust/deps"], + ), + ]; + for (reader, packs) in readers { + let lib = format!("extensions/code/{reader}/src/lib.rs"); + assert_eq!(fed(&[lib.as_str()]), packs, "{lib}"); + } +} + +/// The Kani reader is linked by `@rust/proof` alone (ADR 0389). +#[test] +fn a_change_to_the_kani_reader_feeds_only_rust_proof() { + assert_eq!( + fed(&["extensions/code/kani/src/lib.rs"]), + ["extensions/rust/proof"] + ); } #[test] @@ -67,12 +132,15 @@ fn a_change_to_the_manifest_library_feeds_only_rust_cargo() { } #[test] -fn a_change_to_the_workspace_library_feeds_both_javascript_builtins() { +fn a_change_to_the_workspace_library_feeds_the_javascript_builtins_that_link_it() { assert_eq!( fed(&["extensions/javascript/workspace/src/lib.rs"]), [ + "extensions/javascript/jest", "extensions/javascript/node-test", - "extensions/javascript/source" + "extensions/javascript/playwright", + "extensions/javascript/source", + "extensions/javascript/vitest", ] ); } @@ -128,7 +196,8 @@ fn blobs_lists_the_recorded_blobs() { assert!(listed.iter().all(|l| l.starts_with("extensions/") || l.starts_with("fixtures/") || l.starts_with("examples/") - || l == "gsd/core")); + || l == "gsd/core" + || l == "gsd/import")); } /// A crate of the gsd workspace builds as that workspace does: its lock, its cargo directory and its SDK patch; any diff --git a/gate/src/checks.rs b/gate/src/checks.rs index 2fade099f9..ec338ecda1 100644 --- a/gate/src/checks.rs +++ b/gate/src/checks.rs @@ -245,7 +245,7 @@ pub static CHECKS: &[Check] = &[ }, Check { name: "guests", - proves: "each guest's tests pass and it is clippy-clean for wasm and native, and each example's extension is clippy-clean for wasm", + proves: "each guest's tests pass under nextest, each run writing its JUnit report under target/nextest//junit-guests/ (ADR 0393 D1), and it is clippy-clean for wasm and native, and each example's extension is clippy-clean for wasm", reach: Reach::Quick, trigger: Trigger::Paths(&[ "extensions/**", @@ -253,11 +253,12 @@ pub static CHECKS: &[Check] = &[ "crates/**", "integrations/rust/**", "Cargo.toml", + ".config/nextest-guests.toml", ]), compiles: false, after: &[], fix: "read /gate/guests.log", - run: steps::guests, + run: crate::guests::run, }, Check { name: "gsd", @@ -373,12 +374,12 @@ pub static CHECKS: &[Check] = &[ }, Check { name: "dogfood", - proves: "the tests' nextest reports, read through @rust/test, prove at least one requirement and fail none (ADR 0374 D5)", + proves: "the nextest reports of the root tests, every guest and the @gsd workspace, read through @rust/test, prove at least one requirement and fail none (ADR 0374 D5, ADR 0393 D3); X2 is 100% on SpecForge, taskboard, ledger and vault (ADR 0388, ADR 0393 D8)", reach: Reach::Full, trigger: Trigger::Always, compiles: false, - after: &["tests"], - fix: "/gate/dogfood.log names each failed requirement: specforge anchors --path /gate/dogfood lists the tests that name it; run them (cargo nextest run --workspace --profile gate -E 'test()') and fix the one that fails; none proven: the tests did not run or named none. Then cargo gate full --only tests,dogfood", + after: &dogfood::REPORTERS, + fix: "/gate/dogfood.log names each failed requirement: specforge anchors --path /gate/dogfood lists the tests that name it; run them (cargo nextest run --workspace --profile gate -E 'test()', a guest's: CARGO_TARGET_DIR=/ext cargo nextest run --manifest-path extensions//Cargo.toml --config-file /gate/nextest-guests/.toml -E 'test()') and fix the one that fails; none proven: the tests did not run or named none. The log also holds the X2 lines; a failed X2 collect or export names its project and step (its scratch copy is /gate/x2/); a missing id is an item with a test id and no test fact: run its test so a report holds it, or mark it ignored or cfg-excluded so @rust/test reports it skipped. Then cargo gate full --only tests,guests,gsd,dogfood", run: dogfood::run, }, Check { @@ -618,7 +619,8 @@ pub(crate) fn doctest_members(repo: &Repo) -> Vec { .collect() } -fn member_has_doctest(repo: &Repo, dir: &str) -> bool { +/// Whether the crate at `dir` (from the repository root) holds a runnable doctest in its `src/`. +pub(crate) fn member_has_doctest(repo: &Repo, dir: &str) -> bool { let mut sources = Vec::new(); collect_rust_sources(&repo.root.join(dir).join("src"), &mut sources); judge::has_runnable_doctest(&sources.iter().map(String::as_str).collect::>()) diff --git a/gate/src/checks/snapshots/gate__checks__tests__the_list_is_pinned.snap b/gate/src/checks/snapshots/gate__checks__tests__the_list_is_pinned.snap index 6b32a53c24..1b81c87a90 100644 --- a/gate/src/checks/snapshots/gate__checks__tests__the_list_is_pinned.snap +++ b/gate/src/checks/snapshots/gate__checks__tests__the_list_is_pinned.snap @@ -29,8 +29,8 @@ root-layout hook always the tracked top-level entries are the root list's (gate/src/root_layout.rs) builtins quick computed: a file some blob's inputs.json records every committed blob was built from the sources it recorded -guests quick extensions/**, examples/*/extension/**, crates/**, integrations/rust/**, Cargo.toml - each guest's tests pass and it is clippy-clean for wasm and native, and each example's extension is clippy-clean for wasm +guests quick extensions/**, examples/*/extension/**, crates/**, integrations/rust/**, Cargo.toml, .config/nextest-guests.toml + each guest's tests pass under nextest, each run writing its JUnit report under target/nextest//junit-guests/ (ADR 0393 D1), and it is clippy-clean for wasm and native, and each example's extension is clippy-clean for wasm gsd quick gsd/**, evaluation/gsd-ab/**, crates/**, Cargo.toml, Cargo.lock, extensions/**/*.wasm (after rustfmt) [compiles] the @gsd workspace is clippy-clean for native and wasm, @gsd/core and @gsd/security build to wasm32-wasip2, and their unit, declaration and black-box tests pass against the specforge binary audit quick **/Cargo.lock @@ -47,7 +47,7 @@ published-schemas quick **/*.spec, **/specforge.json, extensions/**, crates every project's exports validate against the schema `specforge schema --publish` prints for their format specs quick **/*.spec, **/specforge.json, gate/baseline.json, extensions/**, crates/**/src/**, crates/**/Cargo.toml every project, as tracked (collected by @rust/cargo and @rust/source first when it loads them), checks with no error and no warning above the baseline -dogfood full always (after tests) - the tests' nextest reports, read through @rust/test, prove at least one requirement and fail none (ADR 0374 D5) +dogfood full always (after tests, guests, gsd) + the nextest reports of the root tests, every guest and the @gsd workspace, read through @rust/test, prove at least one requirement and fail none (ADR 0374 D5, ADR 0393 D3); X2 is 100% on SpecForge, taskboard, ledger and vault (ADR 0388, ADR 0393 D8) builtins-verify bootstrap always a cold clone rebuilds every committed blob to the vendored bytes diff --git a/gate/src/checks/tests.rs b/gate/src/checks/tests.rs index 024a279a09..ac5119d39e 100644 --- a/gate/src/checks/tests.rs +++ b/gate/src/checks/tests.rs @@ -131,9 +131,9 @@ fn an_unformatted_guest_is_judged_by_the_hook() { .flat_map(|pattern| crate::repo::expand(&this_repo().root, pattern)) .count(); assert_eq!( - manifests, 25, - "fourteen guests, the @code, @rust and @javascript extension libraries (two, one, one), four fixtures, \ - the marketing example's extension, the @gsd workspace and its Rust parity fixture (the ledger)" + manifests, 43, + "twenty-six guests, the @code, @rust and @javascript extension libraries (eight, one, one), four \ + fixtures, the marketing example's extension, the @gsd workspace and its Rust parity fixture (the ledger)" ); } diff --git a/gate/src/dogfood.rs b/gate/src/dogfood.rs index 0a5d4b7479..876055fd11 100644 --- a/gate/src/dogfood.rs +++ b/gate/src/dogfood.rs @@ -1,32 +1,43 @@ //! The `dogfood` check (ADR 0374 D5): the repository's own tests prove its requirements. //! -//! nextest writes a JUnit report under its `gate` and `ci` profiles (`/target/nextest//`; -//! CI downloads each test partition's into its own directory there). Every `junit*.xml` found is merged into the one -//! report `@rust/test` reads ([`crate::junit::merge`]). In a copy of the tracked tree ([`crate::checked_tree`]: no -//! fact store, and no untracked copy of the sources, of this machine is in it), the root project is collected by -//! `rust-cargo`, `rust-source` and `rust-test` over that report; then each requirement's computed `proof` is read -//! from `specforge export --format graph --kinds requirement` and judged by [`crate::judge::requirement_verdict`]. -//! The requirements the guests' tests name come from `specforge anchors --file extensions`: guests run under `cargo -//! test` and write no JUnit, so what only they prove reads `no_test`, and the verdict counts it. - -use std::collections::BTreeSet; +//! nextest writes a JUnit report under its `gate` and `ci` profiles (`/target/nextest//`): +//! the root run's (CI downloads each test partition's into its own directory there), every guest's under +//! `junit-guests//` and the `@gsd` workspace's under `junit-gsd/` (ADR 0393 D2, D3). The check refuses to +//! judge when any of the three sets is missing; every `junit*.xml` found is merged into the one report `@rust/test` +//! reads ([`crate::junit::merge`]). In a copy of the tracked tree ([`crate::checked_tree`]: no fact store, and no +//! untracked copy of the sources, of this machine is in it), the root project is collected by `rust-cargo`, +//! `rust-source` and `rust-test` over that report; then each requirement's computed `proof` is read from `specforge +//! export --format graph --kinds requirement` and judged by [`crate::judge::requirement_verdict`], from the export +//! alone. +//! +//! It also logs X2 (ADR 0388) of SpecForge and each parity fixture, [`crate::x2`] over `specforge export --format +//! graph --kinds item,test`, and X2 is a floor (ADR 0393 D8): every project is logged first, then the check fails any +//! below 100% or at `0/0` ([`x2::floor`]). A failed collect or export of an X2 project is that project's error, and so +//! is a fixture collect answering a Warning or an Error ([`no_warning_or_error`]; an Info passes), and a fixture whose +//! count of items with a test id is not the one its row pins ([`census`]). +//! +//! Before collecting, it runs the floor's end-to-end negative control ([`negative_control`]): a test, ignored in +//! workspace runs, that runs this `specforge` over a ledger copy whose report lacks one case and sees the floor fail. +//! It logs one line, `negative control passed: (ADR 0393 D8)`; a failure is the check's error. + use std::path::{Path, PathBuf}; use serde_json::Value; use crate::checks::Selection; use crate::run::Ctx; -use crate::{checked_tree, judge, junit, steps}; +use crate::{checked_tree, judge, junit, steps, x2}; pub fn run(ctx: &Ctx, _: &Selection) -> Result<(), String> { + // Elsewhere every compiled-out `#[cfg(unix)]` test would read as a missing X2 id, a coverage hole it is not. + if cfg!(not(unix)) { + return Err( + "dogfood's X2 floor assumes a unix host (ADR 0393 D5): run it on Linux or macOS".into(), + ); + } let dir = report_dir(&ctx.repo.root, ctx.mode.nextest_profile()); let found = reports(&dir); - if found.is_empty() { - return Err(format!( - "no nextest JUnit report under {}: run `cargo gate full --only tests` first", - dir.display() - )); - } + report_sets(&dir, &found)?; let mut texts = Vec::new(); for path in &found { ctx.log(&format!("report {}", path.display())); @@ -37,11 +48,12 @@ pub fn run(ctx: &Ctx, _: &Selection) -> Result<(), String> { .map_err(|e| format!("{}: {e}", merged.display()))?; let specforge = ctx.specforge()?; + negative_control(ctx, specforge)?; let tree = ctx.repo.target_dir.join("gate/dogfood"); - checked_tree::copy_tracked(&ctx.repo.root, &steps::tracked_paths(ctx)?, &tree)?; + let tracked = steps::tracked_paths(ctx)?; + checked_tree::copy_tracked(&ctx.repo.root, &tracked, &tree)?; let tree = tree.to_string_lossy().into_owned(); let merged = merged.to_string_lossy().into_owned(); - let online = ["--yes", "--effects", "online", "--format", "json"]; for runner in [ &["rust-cargo"][..], &["rust-source"], @@ -49,7 +61,7 @@ pub fn run(ctx: &Ctx, _: &Selection) -> Result<(), String> { ] { let mut args = vec!["collect", "--path", &tree, "--runner"]; args.extend(runner); - args.extend(online); + args.extend(ONLINE); json(ctx, specforge, &args) .map_err(|e| format!("collecting the root with {}: {e}", runner[0]))?; } @@ -66,37 +78,355 @@ pub fn run(ctx: &Ctx, _: &Selection) -> Result<(), String> { "requirement", ], )?; - let anchors = json( + let (lines, failed) = judge::requirement_verdict(&export); + for line in &lines { + ctx.log(line); + } + let x2 = judge_x2( + std::iter::once(("SpecForge", log_x2(ctx, specforge, "SpecForge", &tree))).chain( + FIXTURES + .iter() + .map(|fixture| (fixture.name, fixture_x2(ctx, specforge, fixture, &tracked))), + ), + ); + let (logged, result) = outcome(failed, &lines, x2); + if let Some(line) = logged { + ctx.log(&line); + } + result +} + +/// The end-to-end negative control of the X2 floor (ADR 0393 D8), `#[ignore]`d in workspace runs. +const CONTROL: &str = "dogfood::tests::x2_floor_fails_a_ledger_copy_missing_one_case"; + +/// How many lines of the control's output a failure carries. +const CONTROL_TAIL: usize = 20; + +/// Run [`CONTROL`] with `SPECFORGE_BIN` set to `specforge`, under nextest's default profile (which writes no JUnit +/// report). Its test binary is built first under the compile turn (dogfood is no compiling check, so the scheduler +/// takes none for it). On success the log gets exactly one line, `negative control passed: (ADR 0393 D8)`, +/// and none of nextest's output; its own failing X2 lines go to the control's temp log, never this one (CONTEXT D-09). +/// An error names the control and carries the tail of nextest's output. +fn negative_control(ctx: &Ctx, specforge: &Path) -> Result<(), String> { + { + let _turn = crate::run::compile_turn(&crate::run::compile_lock_path()); + control_nextest(ctx, specforge, &["--no-run"])?; + } + let filter = format!("test(={CONTROL})"); + control_nextest( ctx, specforge, - &[ - "anchors", - "--path", - &tree, - "--file", - "extensions", - "--format", - "json", - ], + &["--run-ignored", "only", "--no-tests=fail", "-E", &filter], )?; - let (lines, failed) = judge::requirement_verdict(&export, &anchored(&anchors)); - for line in &lines { - ctx.log(line); + ctx.log(&format!("negative control passed: {CONTROL} (ADR 0393 D8)")); + Ok(()) +} + +/// `cargo nextest run -p gate --profile default ` with `SPECFORGE_BIN` set to `specforge`, its output kept out of +/// the log; an error names the control and carries the tail of that output. +fn control_nextest(ctx: &Ctx, specforge: &Path, args: &[&str]) -> Result<(), String> { + let output = ctx + .cmd("cargo") + .args(["nextest", "run", "-p", "gate", "--profile", "default"]) + .args(args) + .env("SPECFORGE_BIN", specforge) + .stdin(std::process::Stdio::null()) + .output() + .map_err(|e| format!("negative control {CONTROL}: running cargo nextest: {e}"))?; + if output.status.success() { + return Ok(()); + } + let said = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let lines: Vec<&str> = said.lines().collect(); + let tail = lines[lines.len().saturating_sub(CONTROL_TAIL)..].join("\n"); + Err(format!( + "negative control {CONTROL} failed ({}):\n{tail}", + output.status + )) +} + +/// X2 as a floor (ADR 0393 D8) over each project's X2, or the error of its collect or export: Ok when every project +/// passes [`x2::floor`], else each failure, joined by line in project order. The iterator is lazy, so each project is +/// collected and logged in turn and a failing SpecForge does not hide the fixtures' lines; the full missing list goes +/// to the log only. +fn judge_x2<'a>( + projects: impl IntoIterator)>, +) -> Result<(), String> { + let errors: Vec = projects + .into_iter() + .filter_map(|(name, x2)| x2.and_then(|x2| x2::floor(name, &x2)).err()) + .collect(); + if errors.is_empty() { + Ok(()) + } else { + Err(errors.join("\n")) } +} + +/// The check's result and what to log first: the requirement verdict's first problem when it `failed` (its first line +/// is the counts, the problems follow), with X2's error logged, which the red run would otherwise drop unseen; else +/// X2's own result. +fn outcome( + failed: bool, + lines: &[String], + x2: Result<(), String>, +) -> (Option, Result<(), String>) { if failed { - // The first line is the counts; the problems follow it. - Err(lines.get(1).or(lines.first()).cloned().unwrap_or_default()) + let problem = lines.get(1).or(lines.first()).cloned().unwrap_or_default(); + (x2.err(), Err(problem)) + } else { + (None, x2) + } +} + +/// What every collect of the check passes besides its runner. +const ONLINE: [&str; 5] = ["--yes", "--effects", "online", "--format", "json"]; + +/// A parity fixture X2 is logged and floored for (ADR 0388 D3), collected in a scratch copy of its tracked files under +/// `/gate/x2/` with a `specforge.json` loading `extensions`: every pack the fixture detects, each report +/// pack reading a report recorded by `gsd/parity/record-reports.sh` (ADR 0393 D9). +struct Fixture { + name: &'static str, + /// The fixture's directory, from the repository root. + dir: &'static str, + extensions: &'static [&'static str], + /// Each collect in order: its runner and the recorded report it reads (`--no-run --report`, from the repository + /// root), if any. + collects: &'static [(&'static str, Option<&'static str>)], + /// How many of its items carry a test id. The fixture is a frozen A/B tree, so another count is an extractor that + /// stopped (or started) minting test ids, which the ratio alone would still read as 100% ([`census`]). + tests: usize, +} + +/// Logged after SpecForge, in this order: taskboard, ledger and vault (CONTEXT D-01, D-10). Vault loads no +/// `@gsd/security`, which its own project file does: X2 reads items and tests only. +const FIXTURES: &[Fixture] = &[ + Fixture { + name: "taskboard", + dir: "gsd/parity/fixtures/taskboard", + extensions: &[ + "@gsd/core", + "@specforge/checks", + "@code/core", + "@javascript/node-test", + "@javascript/source", + "@javascript/coverage", + ], + collects: &[ + ("javascript-source", None), + ("node-test", Some("gsd/parity/goldens/taskboard/junit.xml")), + ( + "javascript-coverage", + Some("gsd/parity/goldens/taskboard/reports/javascript-coverage.lcov"), + ), + ], + tests: 3, + }, + Fixture { + name: "ledger", + dir: "gsd/parity/fixtures/ledger", + extensions: &[ + "@gsd/core", + "@specforge/checks", + "@code/core", + "@rust/cargo", + "@rust/source", + "@rust/test", + "@rust/coverage", + "@rust/lint", + "@rust/deps", + "@rust/api", + ], + collects: &[ + ("rust-cargo", None), + ("rust-source", None), + ("rust-test", Some("gsd/parity/goldens/ledger/rust-test.xml")), + ( + "rust-coverage", + Some("gsd/parity/goldens/ledger/reports/rust-coverage.lcov"), + ), + ( + "rust-lint", + Some("gsd/parity/goldens/ledger/reports/rust-lint.jsonl"), + ), + ( + "rust-sbom", + Some("gsd/parity/goldens/ledger/reports/rust-sbom.cdx.json"), + ), + ( + "rust-osv", + Some("gsd/parity/goldens/ledger/reports/rust-osv.json"), + ), + ( + "rust-api", + Some("gsd/parity/goldens/ledger/reports/rust-api.txt"), + ), + ], + tests: 6, + }, + Fixture { + name: "vault", + dir: "gsd/parity/fixtures/vault", + extensions: &[ + "@gsd/core", + "@specforge/checks", + "@code/core", + "@javascript/node-test", + "@javascript/source", + "@javascript/coverage", + ], + collects: &[ + ("javascript-source", None), + ("node-test", Some("gsd/parity/goldens/vault/junit.xml")), + ( + "javascript-coverage", + Some("gsd/parity/goldens/vault/reports/javascript-coverage.lcov"), + ), + ], + tests: 3, + }, +]; + +/// Collect `fixture` in its scratch copy, log its X2 lines and return its X2; an error names the fixture and the step +/// that failed. +fn fixture_x2( + ctx: &Ctx, + specforge: &Path, + fixture: &Fixture, + tracked: &[String], +) -> Result { + let name = fixture.name; + let prefix = format!("{}/", fixture.dir); + let files: Vec = tracked + .iter() + .filter_map(|path| path.strip_prefix(&prefix).map(String::from)) + .collect(); + let copy = ctx.repo.target_dir.join("gate/x2").join(name); + checked_tree::copy_tracked(&ctx.repo.root.join(fixture.dir), &files, ©) + .map_err(|e| format!("X2 {name}: copying the fixture: {e}"))?; + let project = serde_json::json!({ + "name": name, + "version": "0.1.0", + "spec_root": "spec", + "extensions": fixture.extensions, + }); + let manifest = copy.join("specforge.json"); + std::fs::write(&manifest, format!("{project:#}\n")) + .map_err(|e| format!("X2 {name}: {}: {e}", manifest.display()))?; + let copy = copy.to_string_lossy().into_owned(); + for &(runner, report) in fixture.collects { + let report = report.map(|r| ctx.repo.root.join(r).to_string_lossy().into_owned()); + let mut args = vec!["collect", "--path", copy.as_str(), "--runner", runner]; + if let Some(report) = &report { + args.extend(["--no-run", "--report", report.as_str()]); + } + args.extend(ONLINE); + json(ctx, specforge, &args) + .and_then(|collect| no_warning_or_error(&collect)) + .map_err(|e| format!("X2 {name}: collecting with {runner}: {e}"))?; + } + log_x2(ctx, specforge, name, ©).and_then(|x2| census(name, x2, fixture.tests)) +} + +/// `x2` when exactly `tests` items carry a test id; else an error naming the project and both counts. +fn census(name: &str, x2: x2::X2, tests: usize) -> Result { + if x2.total == tests { + Ok(x2) } else { + Err(format!( + "X2 {name}: {} items carry a test id, expected {tests}: an extractor stopped or started minting test ids", + x2.total + )) + } +} + +/// Ok when a `collect --format json` answer's `diagnostics` hold no Warning and no Error (an Info passes, CONTEXT +/// D-10); else each of them as `: `, joined. An answer with no `diagnostics` array is an error: its shape +/// changed. +fn no_warning_or_error(collect: &Value) -> Result<(), String> { + let diagnostics = collect + .get("diagnostics") + .and_then(Value::as_array) + .ok_or("the answer has no diagnostics array")?; + let text = |d: &Value, key| { + d.get(key) + .and_then(Value::as_str) + .unwrap_or("?") + .to_string() + }; + let bad: Vec = diagnostics + .iter() + .filter(|d| { + matches!( + d.get("severity").and_then(Value::as_str), + Some("Warning" | "Error") + ) + }) + .map(|d| format!("{}: {}", text(d, "code"), text(d, "message"))) + .collect(); + if bad.is_empty() { Ok(()) + } else { + Err(bad.join("; ")) } } +/// Log the X2 lines of the collected project at `path`, read from `specforge export --format graph --kinds +/// item,test`, and return that X2; an error names the project. +fn log_x2(ctx: &Ctx, specforge: &Path, name: &str, path: &str) -> Result { + let export = json( + ctx, + specforge, + &[ + "export", + "--path", + path, + "--format", + "graph", + "--kinds", + "item,test", + ], + ) + .map_err(|e| format!("X2 {name}: exporting its items and tests: {e}"))?; + let (items, tests) = x2::read(&export).map_err(|e| format!("X2 {name}: {e}"))?; + let x2 = x2::ratio(&items, &tests); + for line in x2::lines(name, &x2) { + ctx.log(&line); + } + Ok(x2) +} + /// `/target/nextest/`: where nextest writes the JUnit report of a run under `profile` (its store is /// the workspace root's `target/`, whatever the target directory). pub(crate) fn report_dir(root: &Path, profile: &str) -> PathBuf { root.join("target/nextest").join(profile) } +/// The checks whose nextest reports this check judges, each run before it: the root tests, the guests and the `@gsd` +/// workspace (ADR 0393 D3). A run that runs this check without all of them is refused ([`crate::run::purges_reports`]). +pub(crate) const REPORTERS: [&str; 3] = ["tests", "guests", "gsd"]; + +/// The guests' reports, one directory per guest under the report dir; the name of their CI artifact (ADR 0393 D2). +pub(crate) const GUESTS: &str = "junit-guests"; + +/// The `@gsd` workspace's report directory under the report dir; the name of its CI artifact (ADR 0393 D2). +pub(crate) const GSD: &str = "junit-gsd"; + +/// Empty a report directory before the run that writes it, so a report from an earlier run is never read as current: +/// Ok when it is not there. +pub(crate) fn clear_reports(dir: &Path) -> Result<(), String> { + match std::fs::remove_dir_all(dir) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => { + Err(format!("clearing {}: {e}", dir.display())) + } + _ => Ok(()), + } +} + /// Every file named `junit*.xml` under `dir`, at any depth, sorted by path; none when `dir` is not there. pub(crate) fn reports(dir: &Path) -> Vec { let mut found = Vec::new(); @@ -122,14 +452,26 @@ pub(crate) fn reports(dir: &Path) -> Vec { found } -/// The entity ids `specforge anchors --file … --format json` lists. -fn anchored(anchors: &Value) -> BTreeSet { - anchors["entities"] - .as_array() - .into_iter() - .flatten() - .filter_map(|e| e["entity_id"].as_str().map(String::from)) - .collect() +/// Ok when `found` (the reports under `dir`) holds a report of each set: the root tests' (any not under the guests' +/// or the gsd directory), the guests' and the `@gsd` workspace's. A lost set would read as "all tests" (ADR 0393 D3). +fn report_sets(dir: &Path, found: &[PathBuf]) -> Result<(), String> { + let (guests, gsd) = (dir.join(GUESTS), dir.join(GSD)); + let root = found + .iter() + .any(|path| !path.starts_with(&guests) && !path.starts_with(&gsd)); + for (set, present) in [ + ("root tests", root), + ("guests", found.iter().any(|path| path.starts_with(&guests))), + ("gsd", found.iter().any(|path| path.starts_with(&gsd))), + ] { + if !present { + return Err(format!( + "no {set} JUnit report under {}: run cargo gate full --only tests,guests,gsd,dogfood", + dir.display() + )); + } + } + Ok(()) } /// `specforge `'s stdout as JSON; an error when it exits non-zero (carrying the reason it printed, which the diff --git a/gate/src/dogfood/tests.rs b/gate/src/dogfood/tests.rs index 3837691b74..17d34f064a 100644 --- a/gate/src/dogfood/tests.rs +++ b/gate/src/dogfood/tests.rs @@ -3,7 +3,11 @@ reason = "a test's unwrap is its assertion: a None or an Err fails the test" )] +use std::sync::OnceLock; + use super::*; +use crate::change_set::ChangeSet; +use crate::repo::Repo; fn write(root: &Path, file: &str) { let path = root.join(file); @@ -29,6 +33,16 @@ fn a_local_run_finds_its_one_report() { assert_eq!(reports(&at), [at.join("junit.xml")]); } +#[test] +fn clear_reports_removes_an_earlier_runs_reports_and_accepts_a_missing_directory() { + let dir = tempfile::tempdir().unwrap(); + let at = report_dir(dir.path(), "gate").join(GUESTS); + write(&at, "x/junit.xml"); + clear_reports(&at).unwrap(); + assert!(!at.exists(), "{} is still there", at.display()); + clear_reports(&at).unwrap(); +} + /// CI downloads each test partition's report into its own directory: every one is found, in path order, and an XML /// file that is no nextest report is left out. #[test] @@ -52,43 +66,404 @@ fn the_partitions_reports_are_found_in_their_directories_and_other_xml_is_skippe ); } +fn workflow() -> String { + std::fs::read_to_string(specforge_repo_root::repo_root().join(".github/workflows/ci.yml")) + .unwrap() +} + +/// The CI upload step whose artifact is named `name` runs under the condition `when` (the `if:` before its `with:`, so +/// a wrong shard or event, which would leave dogfood without the report, fails here), keeps `report` (from the +/// repository root, under the `ci` profile's report dir) and fails when it is not there. +fn assert_uploads_or_fails(name: &str, report: &Path, when: &str) { + let workflow = workflow(); + let lines: Vec<&str> = workflow.lines().map(str::trim).collect(); + let at = lines + .iter() + .position(|line| *line == format!("name: {name}")) + .unwrap_or_else(|| panic!("ci.yml: no artifact named {name}")); + let start = lines[..at] + .iter() + .rposition(|line| line.starts_with("- ")) + .unwrap(); + let step: Vec<&str> = lines[start..at] + .iter() + .chain( + lines[at..] + .iter() + .take_while(|line| !line.is_empty() && !line.starts_with("- ")), + ) + .copied() + .collect(); + let condition = format!("if: {when}"); + assert!( + step.contains(&condition.as_str()), + "ci.yml: the {name} upload does not run under `{condition}`: {step:?}" + ); + let report = report_dir(Path::new(""), "ci").join(report); + let report = report.to_string_lossy().replace('\\', "/"); + assert!( + step.contains(&format!("path: {report}").as_str()), + "ci.yml: the {name} upload does not keep {report}: {step:?}" + ); + assert!( + step.contains(&"if-no-files-found: error"), + "ci.yml: the {name} upload passes with no report: {step:?}" + ); +} + /// CI keeps each test partition's report for this check, from where nextest writes it under the `ci` profile. A /// partition whose report is not there fails its upload: the verdict needs one proven requirement, so a lost /// partition would otherwise read as `no_test` on what only it proves and pass. #[test] fn ci_uploads_each_partitions_report_or_fails() { - let path = specforge_repo_root::repo_root().join(".github/workflows/ci.yml"); - let workflow = std::fs::read_to_string(&path).unwrap(); - let step: Vec<&str> = workflow + assert_uploads_or_fails( + "junit-tests-${{ matrix.part }}", + Path::new("junit.xml"), + "github.event_name == 'push'", + ); +} + +/// The specs shard, which runs `guests`, keeps the guests' reports under the artifact named as their directory (ADR +/// 0393 D2). +#[test] +fn ci_uploads_the_guests_reports_or_fails() { + assert_uploads_or_fails( + GUESTS, + Path::new(GUESTS), + "github.event_name == 'push' && matrix.shard == 'specs'", + ); +} + +/// The gsd shard keeps the `@gsd` workspace's report under the artifact named as its directory (ADR 0393 D2). +#[test] +fn ci_uploads_the_gsd_report_or_fails() { + assert_uploads_or_fails( + GSD, + Path::new(GSD), + "github.event_name == 'push' && matrix.shard == 'gsd'", + ); +} + +/// The dogfood job downloads every `junit-*` artifact, not only the test partitions': a download limited to them +/// would leave the guests' and the gsd set out, and `report_sets` would refuse. +#[test] +fn the_dogfood_job_downloads_every_junit_artifact() { + let workflow = workflow(); + let patterns: Vec<&str> = workflow .lines() .map(str::trim) - .skip_while(|line| !line.starts_with("name: junit-tests-")) - .take_while(|line| !line.is_empty() && !line.starts_with("- ")) + .filter(|line| line.starts_with("pattern: junit")) .collect(); - let report = report_dir(Path::new(""), "ci").join("junit.xml"); - let report = report.to_string_lossy().replace('\\', "/"); - assert!( - step.contains(&format!("path: {report}").as_str()), - "{}: the junit-tests upload does not keep {report}: {step:?}", - path.display() + assert_eq!(patterns, ["pattern: junit-*"]); +} + +/// The `@gsd` workspace's nextest store is the repository root's, and its `gate` and `ci` runs write their report in +/// the directory `dogfood` reads: a store left in `gsd/target` would hide every `@gsd` test from it. +#[test] +fn the_gsd_workspace_writes_its_junit_under_the_root_report_dir() { + let path = specforge_repo_root::repo_root().join("gsd/.config/nextest.toml"); + let config = std::fs::read_to_string(&path).unwrap(); + let lines: Vec<&str> = config.lines().map(str::trim).collect(); + let report = format!("path = \"{GSD}/junit.xml\""); + for line in [ + "dir = \"../target/nextest\"", + "[profile.gate.junit]", + "[profile.ci.junit]", + report.as_str(), + ] { + assert!(lines.contains(&line), "{}: no `{line}`", path.display()); + } +} + +/// The root tests', the guests' and the `@gsd` workspace's reports are each required, in the local and the CI layout: +/// a missing set is an error naming it and the run that writes it (ADR 0393 D3). +#[test] +fn dogfood_refuses_without_each_report_set() { + let local = [ + "junit.xml", + "junit-guests/a/junit.xml", + "junit-gsd/junit.xml", + ]; + let ci = [ + "junit-tests-1/junit.xml", + "junit-guests/a/junit.xml", + "junit-gsd/junit.xml", + ]; + for layout in [local, ci] { + let dir = tempfile::tempdir().unwrap(); + for file in layout { + write(dir.path(), file); + } + report_sets(dir.path(), &reports(dir.path())).unwrap(); + } + for (missing, set) in [(0, "root tests"), (1, "guests"), (2, "gsd")] { + let dir = tempfile::tempdir().unwrap(); + for (_, file) in local.iter().enumerate().filter(|(i, _)| *i != missing) { + write(dir.path(), file); + } + let refused = report_sets(dir.path(), &reports(dir.path())).unwrap_err(); + assert!( + refused.starts_with(&format!("no {set} JUnit report under ")), + "{refused}" + ); + assert!( + refused.contains("cargo gate full --only tests,guests,gsd,dogfood"), + "{refused}" + ); + } +} + +#[test] +fn a_failed_requirement_verdict_still_logs_the_x2_error() { + let lines = ["2 of 3 proved".to_string(), "R-01 has no test".to_string()]; + let x2_error = || Err("X2 ledger: collecting with rust-test: boom".to_string()); + let (logged, result) = outcome(true, &lines, x2_error()); + assert_eq!( + logged.as_deref(), + Some("X2 ledger: collecting with rust-test: boom") ); - assert!( - step.contains(&"if-no-files-found: error"), - "{}: the junit-tests upload passes with no report: {step:?}", - path.display() + assert_eq!(result, Err("R-01 has no test".to_string())); + let (logged, result) = outcome(true, &lines, Ok(())); + assert_eq!( + (logged, result), + (None, Err("R-01 has no test".to_string())) ); + // Requirements pass: X2's own outcome is the check's, nothing extra logged. + let (logged, result) = outcome(false, &lines, x2_error()); + assert_eq!(logged, None); + assert_eq!(result, x2_error()); + assert_eq!(outcome(false, &lines, Ok(())), (None, Ok(()))); +} + +fn x2_of(present: usize, missing: &[&str]) -> Result { + Ok(x2::X2 { + present, + total: present + missing.len(), + missing: missing.iter().map(|id| id.to_string()).collect(), + }) } +/// The check's X2 verdict: every project at the floor passes; one below it, at `0/0` or whose collect failed fails the +/// whole, each failure on its own line in project order. #[test] -fn the_anchored_entities_are_the_guest_named_set() { - let anchors = serde_json::json!({"entities": [ - {"entity_id": "FEATURE-001", "kind": "requirement"}, - {"entity_id": "FEATURE-002", "kind": "requirement"}, - {"entity_id": "FEATURE-001", "kind": "requirement"}, - ]}); +fn judge_x2_fails_when_any_project_fails_and_names_each_failure() { assert_eq!( - anchored(&anchors), - BTreeSet::from(["FEATURE-001".to_string(), "FEATURE-002".to_string()]) + judge_x2([("a", x2_of(3, &[])), ("b", x2_of(6, &[]))]), + Ok(()) + ); + assert_eq!( + judge_x2([ + ("a", x2_of(3, &[])), + ("ledger", x2_of(5, &["i"])), + ( + "c", + Err("X2 c: collecting with rust-test: boom".to_string()) + ), + ("d", x2_of(0, &[])), + ]), + Err("X2 ledger: 5/6 (83.3%): missing i\n\ + X2 c: collecting with rust-test: boom\n\ + X2 d: no item has a test_id" + .to_string()) + ); +} + +/// A fixture's count of items with a test id is pinned: fewer (a partial extractor collapse that still reads `n/n`) or +/// more fails, naming the project and both counts. +#[test] +fn census_holds_a_fixture_to_its_pinned_count_of_items_with_a_test_id() { + assert_eq!(census("vault", x2_of(3, &[]).unwrap(), 3).unwrap().total, 3); + assert_eq!( + census("taskboard", x2_of(1, &[]).unwrap(), 3).err(), + Some( + "X2 taskboard: 1 items carry a test id, expected 3: an extractor stopped or started minting test ids" + .to_string() + ) + ); + assert!(census("ledger", x2_of(6, &["x"]).unwrap(), 6).is_err()); +} + +/// A fixture collect passes with Info only; a Warning or an Error fails it, named by code and message, and so does an +/// answer whose shape lost its `diagnostics` array (CONTEXT D-10). +#[test] +fn no_warning_or_error_passes_info_and_names_each_warning_or_error() { + let with = |severity: &str, code: &str| { + serde_json::json!({"diagnostics": [ + {"severity": "Info", "code": "I214", "message": "m"}, + {"severity": severity, "code": code, "message": "bad"}, + ]}) + }; + assert_eq!(no_warning_or_error(&with("Info", "I209")), Ok(())); + assert_eq!( + no_warning_or_error(&serde_json::json!({"diagnostics": []})), + Ok(()) + ); + assert_eq!( + no_warning_or_error(&with("Warning", "W203")), + Err("W203: bad".to_string()) + ); + assert_eq!( + no_warning_or_error(&with("Error", "E104")), + Err("E104: bad".to_string()) + ); + let refused = no_warning_or_error(&serde_json::json!({"facts": 3})).unwrap_err(); + assert!(refused.contains("no diagnostics array"), "{refused}"); +} + +/// The ledger fixture collected by `rust-cargo`, `rust-source` and `rust-test` over `report` (absolute, or from the +/// repository root), with the real row's extensions and census; leaked for the table's `'static` type. +fn ledger_reading(report: String) -> Fixture { + let ledger = FIXTURES.iter().find(|f| f.name == "ledger").unwrap(); + let report: &'static str = Box::leak(report.into_boxed_str()); + Fixture { + name: ledger.name, + dir: ledger.dir, + extensions: ledger.extensions, + collects: Box::leak( + vec![ + ("rust-cargo", None), + ("rust-source", None), + ("rust-test", Some(report)), + ] + .into_boxed_slice(), + ), + tests: ledger.tests, + } +} + +/// The floor's end-to-end negative control (ADR 0393 D8, CONTEXT D-14): the real `specforge` over a ledger copy whose +/// report lacks one case reads `5/6` and the floor fails naming it; over the golden report the floor passes. The +/// dogfood check runs it first; its log is in a tempdir, so the failing line never reaches dogfood.log (D-09). +#[test] +#[ignore = "needs the built specforge in SPECFORGE_BIN; the dogfood check runs it (ADR 0393 D8)"] +fn x2_floor_fails_a_ledger_copy_missing_one_case() { + let bin = std::env::var_os("SPECFORGE_BIN").expect( + "SPECFORGE_BIN must name the built specforge: the dogfood check sets it (cargo gate full --only tests,guests,gsd,dogfood)", + ); + let dir = tempfile::tempdir().unwrap(); + let repo = Repo { + target_dir: dir.path().to_path_buf(), + ..crate::repo::this_repo() + }; + let (specforge, changes) = (OnceLock::new(), ChangeSet::default()); + specforge.set(Ok(PathBuf::from(bin))).unwrap(); + let ctx = Ctx::for_tests(&repo, &changes, &specforge, &dir.path().join("dogfood.log")); + let specforge = ctx.specforge().unwrap(); + let tracked = steps::tracked_paths(&ctx).unwrap(); + + let golden = "gsd/parity/goldens/ledger/rust-test.xml"; + let dropped = "a_memo_with_a_tab_is_refused"; + let text = std::fs::read_to_string(repo.root.join(golden)).unwrap(); + let case = format!(" = text.lines().filter(|line| !line.contains(&case)).collect(); + assert_eq!( + kept.len() + 1, + text.lines().count(), + "{golden}: one self-closing line holds {case}" + ); + let doctored = dir.path().join("rust-test.xml"); + std::fs::write(&doctored, kept.join("\n")).unwrap(); + + // Judged as `run` judges: through `judge_x2` and `outcome`, so a check that only printed X2 fails here. + let fixture = ledger_reading(doctored.to_string_lossy().into_owned()); + let x2 = fixture_x2(&ctx, specforge, &fixture, &tracked); + let (_, result) = outcome(false, &[], judge_x2([("ledger", x2)])); + let failed = result.unwrap_err(); + assert!(failed.contains("X2 ledger: 5/6"), "{failed}"); + assert!(failed.contains(dropped), "{failed}"); + + let x2 = fixture_x2( + &ctx, + specforge, + &ledger_reading(golden.to_string()), + &tracked, + ); + assert_eq!( + outcome(false, &[], judge_x2([("ledger", x2)])), + (None, Ok(())) + ); +} + +/// The `Cargo.toml` of each `members` entry of the workspace manifest `dir/Cargo.toml` (`""` is the root), from the +/// root, a `*` segment expanded. +fn members_of(root: &Path, dir: &str) -> Vec { + let manifest = std::fs::read_to_string(root.join(dir).join("Cargo.toml")).unwrap(); + let list = manifest.split_once("\nmembers = [").unwrap().1; + let list = list.split_once(']').unwrap().0; + list.lines() + .map(|line| line.split('#').next().unwrap()) + .flat_map(|line| line.split('"').skip(1).step_by(2)) + .flat_map(|member| { + let member = if dir.is_empty() { + member.to_string() + } else { + format!("{dir}/{member}") + }; + crate::repo::expand(root, &format!("{member}/Cargo.toml")) + }) + .collect() +} + +/// Every `Cargo.toml` under `dir` (from the root), at any depth, outside build output and `node_modules`. +fn manifests_under(root: &Path, dir: &str) -> Vec { + let mut found = Vec::new(); + let entries = std::fs::read_dir(root.join(dir)) + .unwrap_or_else(|e| panic!("the excluded `{dir}` names no directory: {e}")); + for entry in entries { + let entry = entry.unwrap(); + let name = entry.file_name().to_string_lossy().into_owned(); + let path = format!("{dir}/{name}"); + if entry.file_type().unwrap().is_dir() { + if !matches!(name.as_str(), "target" | "node_modules" | ".git") { + found.extend(manifests_under(root, &path)); + } + } else if name == "Cargo.toml" { + found.push(path); + } + } + found +} + +/// `@rust/cargo`'s `exclude` in `specforge.json` is the one setting that shrinks SpecForge's X2 denominator, so no +/// entry may hide a crate whose tests the gate runs: a root workspace member, a guest (the `guests` check's nextest +/// manifests) or a `gsd/` workspace member. The example extensions, which that check only lints, may sit under one. +#[test] +fn the_rust_cargo_exclude_list_hides_no_crate_whose_tests_run() { + let root = specforge_repo_root::repo_root(); + let json: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(root.join("specforge.json")).unwrap()) + .unwrap(); + let excluded = json["settings"]["@rust/cargo"]["exclude"] + .as_array() + .unwrap(); + let mut tested = members_of(root, ""); + tested.extend(members_of(root, "gsd")); + tested.extend(crate::guests::guests_of(&crate::repo::this_repo())); + for known in [ + "gate/Cargo.toml", + "gsd/core/Cargo.toml", + "extensions/rust/test/Cargo.toml", + ] { + assert!( + tested.iter().any(|m| m == known), + "{known} is not among {tested:?}" + ); + } + let hidden: Vec = excluded + .iter() + // As `@rust/cargo` reads an entry: its non-empty, non-`.` segments joined by one `/`. + .map(|entry| { + let segments = entry.as_str().unwrap().split('/'); + segments + .filter(|s| !s.is_empty() && *s != ".") + .collect::>() + .join("/") + }) + .flat_map(|dir| manifests_under(root, &dir)) + .filter(|manifest| tested.contains(manifest)) + .collect(); + assert!( + hidden.is_empty(), + "specforge.json's @rust/cargo exclude hides crates whose tests run, shrinking X2: {hidden:?}" ); - assert!(anchored(&serde_json::json!({"entities": []})).is_empty()); } diff --git a/gate/src/gsd.rs b/gate/src/gsd.rs index 667392784f..9b42f98069 100644 --- a/gate/src/gsd.rs +++ b/gate/src/gsd.rs @@ -2,9 +2,13 @@ //! tests against the `specforge` binary (ADR gsd/0001 D6, ADR gsd/0002). The workspace patches the in-tree SDK, so a //! kernel change that breaks an `@gsd` extension fails in the pull request that made it. //! -//! Who builds what (ADR 0373 D5): `@gsd/core` is a builtin the CLI embeds, vendored by `revendor` into -//! `gsd/core/wasm/`, and nothing builds its wasm to load it; the suite loads it by name. `@gsd/security` is not -//! vendored: this step builds its wasm from `gsd/` and the suite reads it through `GSD_SECURITY_WASM`. +//! Who builds what (ADR 0373 D5): `@gsd/core` and `@gsd/import` are builtins the CLI embeds, vendored by `revendor` +//! into `gsd/core/wasm/` and `gsd/import/wasm/` (ADR 0391 D12), and nothing builds their wasm to load them; the suite +//! loads them by name. `@gsd/security` is not vendored: this step builds its wasm from `gsd/` and the suite reads it +//! through `GSD_SECURITY_WASM`. +//! +//! The suite's nextest run writes its JUnit report to `target/nextest//junit-gsd/junit.xml` under the +//! repository root (`gsd/.config/nextest.toml`), which the `dogfood` check reads (ADR 0393 D2). use std::path::PathBuf; use std::process::Command; @@ -27,10 +31,11 @@ pub const TRIGGER: &[&str] = &[ ]; /// Stops at the first failing step: clippy for native and wasm, the release build of `@gsd/security`'s wasm (the one -/// `@gsd` wasm anything builds; `@gsd/core` is the builtin the CLI embeds), the `specforge` CLI build, then -/// `cargo nextest run` (every test binary at once; `cargo test` runs them one after another) with `SPECFORGE_BIN` and -/// `GSD_SECURITY_WASM` set to the two artifacts. Cargo runs in `gsd/`: it reads `.cargo/config.toml` (the SDK patch) -/// from its working directory, not from `--manifest-path`. +/// `@gsd` wasm anything builds; `@gsd/core` and `@gsd/import` are builtins the CLI embeds), the `specforge` CLI build, +/// then `cargo nextest run` (every test binary at once; `cargo test` runs them one after another) with `SPECFORGE_BIN` +/// and `GSD_SECURITY_WASM` set to the two artifacts, under the run's nextest profile, after emptying its report +/// directory: the run writes `target/nextest//junit-gsd/junit.xml` (ADR 0393 D2). Cargo runs in `gsd/`: it +/// reads `.cargo/config.toml` (the SDK patch) from its working directory, not from `--manifest-path`. pub fn run(ctx: &Ctx, _: &Selection) -> Result<(), String> { let cargo = |args: &[&str]| cargo(ctx, args); ctx.sh(&mut cargo(&[ @@ -53,9 +58,20 @@ pub fn run(ctx: &Ctx, _: &Selection) -> Result<(), String> { ]))?; let security = build_security_wasm(ctx)?; let specforge = ctx.specforge()?; - ctx.sh(cargo(&["nextest", "run", "--locked", "--no-fail-fast"]) - .env("SPECFORGE_BIN", specforge) - .env("GSD_SECURITY_WASM", security)) + let profile = ctx.mode.nextest_profile(); + crate::dogfood::clear_reports( + &crate::dogfood::report_dir(&ctx.repo.root, profile).join(crate::dogfood::GSD), + )?; + ctx.sh(cargo(&[ + "nextest", + "run", + "--locked", + "--no-fail-fast", + "--profile", + profile, + ]) + .env("SPECFORGE_BIN", specforge) + .env("GSD_SECURITY_WASM", security)) } /// Build `@gsd/security` for `wasm32-wasip2` in release (it is not vendored, ADR 0373 D5), the component the suite diff --git a/gate/src/guests.rs b/gate/src/guests.rs new file mode 100644 index 0000000000..bebf3b1c8c --- /dev/null +++ b/gate/src/guests.rs @@ -0,0 +1,158 @@ +//! The `guests` check (ADR 0393 D1): each extension guest's tests run under `cargo nextest run`, one run per guest +//! manifest (each guest is its own workspace, ADR 0366 D2), and each run writes its JUnit report under the repository +//! root's `target/nextest//junit-guests//`, and a guest whose sources hold a runnable doctest runs it +//! under `cargo test --doc` (nextest runs none); then every guest is clippy-clean for wasm and native, and +//! each example project's extension for wasm. + +use std::path::Path; + +use crate::checks::Selection; +use crate::dogfood::{GUESTS, clear_reports, report_dir}; +use crate::repo::{EXTENSION_CRATES, Repo}; +use crate::run::Ctx; +use crate::steps::finish; + +/// The guests' nextest profiles, without a store or a JUnit path: [`config`] adds both per run. +const BASE: &str = ".config/nextest-guests.toml"; + +pub fn run(ctx: &Ctx, _: &Selection) -> Result<(), String> { + let target = ctx.ext_target(); + let profile = ctx.mode.nextest_profile(); + clear_reports(&report_dir(&ctx.repo.root, profile).join(GUESTS))?; + let base = std::fs::read_to_string(ctx.repo.root.join(BASE)) + .map_err(|e| format!("reading {BASE}: {e}"))?; + let store = ctx.repo.root.join("target/nextest"); + let configs = ctx.repo.target_dir.join("gate/nextest-guests"); + std::fs::create_dir_all(&configs).map_err(|e| format!("{}: {e}", configs.display()))?; + // (what, cargo arguments before the manifest, after it) + let clippy: [(&str, &[&str], &[&str]); 2] = [ + ( + "wasm clippy", + &["clippy", "-q", "--target", "wasm32-wasip2"], + &["--", "-D", "warnings"], + ), + ( + "native clippy", + &["clippy", "-q", "--all-targets"], + &["--", "-D", "warnings"], + ), + ]; + let mut failures = Vec::new(); + let cargo = |args: &[&str], manifest: &str, after: &[&str]| { + let mut cmd = ctx.cmd("cargo"); + // What `build-blobs` does: an incremental guest is another build than CI's. + cmd.env("CARGO_TARGET_DIR", &target) + .env_remove("CARGO_INCREMENTAL"); + cmd.args(args) + .args(["--manifest-path", manifest]) + .args(after); + cmd + }; + for (manifest, slug) in slugged(guests_of(ctx.repo))? { + let file = configs.join(format!("{slug}.toml")); + std::fs::write(&file, config(&base, &store, profile, &slug)?) + .map_err(|e| format!("{}: {e}", file.display()))?; + let file = file.to_string_lossy(); + let tests = [ + "nextest", + "run", + "--no-fail-fast", + "--no-tests=pass", + "--profile", + profile, + "--config-file", + &file, + ]; + if let Err(e) = ctx.sh(&mut cargo(&tests, &manifest, &[])) { + failures.push(format!("{manifest} tests: {e}")); + } + // nextest runs no doctest, and the `doctests` check covers root members only. + let dir = manifest.strip_suffix("/Cargo.toml").unwrap_or(&manifest); + if crate::checks::member_has_doctest(ctx.repo, dir) + && let Err(e) = ctx.sh(&mut cargo(&["test", "-q", "--doc"], &manifest, &[])) + { + failures.push(format!("{manifest} doctests: {e}")); + } + for &(what, before, after) in &clippy { + if let Err(e) = ctx.sh(&mut cargo(before, &manifest, after)) { + failures.push(format!("{manifest} {what}: {e}")); + } + } + } + // An example project's extension gets the wasm clippy pass only: it has no tests and no native use. + for manifest in crate::repo::expand(&ctx.repo.root, "examples/*/extension/Cargo.toml") { + let (what, before, after) = clippy[0]; + if let Err(e) = ctx.sh(&mut cargo(before, &manifest, after)) { + failures.push(format!("{manifest} {what}: {e}")); + } + } + finish(failures) +} + +/// One guest's nextest config: a `[store]` at `store` (a TOML basic string, its `\` and `"` escaped, so any path +/// holds, a Windows one or one with an apostrophe), the committed `base`, then the JUnit path +/// `junit-guests//junit.xml` of `profile`. Refuses a store holding a control character and a slug outside ASCII +/// lowercase letters, digits and `-`. +pub(crate) fn config( + base: &str, + store: &Path, + profile: &str, + slug: &str, +) -> Result { + let store = store.to_string_lossy(); + if store.contains(char::is_control) { + return Err(format!( + "the nextest store {store:?} holds a control character" + )); + } + let store = store.replace('\\', "\\\\").replace('"', "\\\""); + if slug.is_empty() + || !slug + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') + { + return Err(format!( + "the guest slug {slug:?} is not ASCII lowercase letters, digits and `-`" + )); + } + let end = if base.ends_with('\n') { "" } else { "\n" }; + Ok(format!( + "[store]\ndir = \"{store}\"\n\n{base}{end}[profile.{profile}.junit]\npath = \"{GUESTS}/{slug}/junit.xml\"\n" + )) +} + +/// The guest's directory under `extensions/`, each `/` a `-`: `extensions/rust/test/Cargo.toml` is `rust-test`. +pub(crate) fn slug(manifest: &str) -> String { + let dir = manifest.strip_suffix("/Cargo.toml").unwrap_or(manifest); + dir.strip_prefix("extensions/") + .unwrap_or(dir) + .replace('/', "-") +} + +/// Each manifest with its [`slug`], in order; an error naming both manifests when two share a slug, since the second +/// run would overwrite the first's config and JUnit report. +pub(crate) fn slugged(manifests: Vec) -> Result, String> { + let mut out: Vec<(String, String)> = Vec::new(); + for manifest in manifests { + let slug = slug(&manifest); + if let Some((first, _)) = out.iter().find(|(_, s)| *s == slug) { + return Err(format!( + "{first} and {manifest} share the guest slug `{slug}`: one would overwrite the other's JUnit report" + )); + } + out.push((manifest, slug)); + } + Ok(out) +} + +/// The guests' and the extension libraries' manifests: `extensions//Cargo.toml` and +/// `extensions///Cargo.toml` (ADR 0328 D3). +pub(crate) fn guests_of(repo: &Repo) -> Vec { + EXTENSION_CRATES + .iter() + .flat_map(|dirs| crate::repo::expand(&repo.root, &format!("{dirs}/Cargo.toml"))) + .collect() +} + +#[cfg(test)] +mod tests; diff --git a/gate/src/guests/tests.rs b/gate/src/guests/tests.rs new file mode 100644 index 0000000000..43e1fd98d1 --- /dev/null +++ b/gate/src/guests/tests.rs @@ -0,0 +1,147 @@ +#![allow( + clippy::unwrap_used, + reason = "a test's unwrap is its assertion: a None or an Err fails the test" +)] + +use super::*; + +#[test] +fn a_guests_config_is_the_store_the_base_and_its_junit_path() { + let base = "[profile.gate]\nretries = 0\n"; + assert_eq!( + config(base, Path::new("/r/target/nextest"), "gate", "rust-test").unwrap(), + "[store]\ndir = \"/r/target/nextest\"\n\n[profile.gate]\nretries = 0\n\ + [profile.gate.junit]\npath = \"junit-guests/rust-test/junit.xml\"\n" + ); +} + +/// The store is a TOML basic string: an apostrophe needs nothing, a backslash and a double quote are escaped. +#[test] +fn any_store_path_is_written_as_an_escaped_basic_string() { + for (store, written) in [ + ("/Users/o'neil/r", "/Users/o'neil/r"), + (r"C:\r\target", r"C:\\r\\target"), + ("/r/a\"b", "/r/a\\\"b"), + ] { + let text = config("", Path::new(store), "gate", "checks").unwrap(); + assert!( + text.starts_with(&format!("[store]\ndir = \"{written}\"\n")), + "{text}" + ); + } +} + +#[test] +fn a_store_with_a_control_character_is_refused() { + for store in ["/r/a\nb", "/r/a\rb", "/r/a\tb"] { + let err = config("", Path::new(store), "gate", "checks").unwrap_err(); + assert!(err.contains(&format!("{store:?}")), "{err}"); + } +} + +#[test] +fn a_slug_outside_lowercase_digits_and_dashes_is_refused() { + for slug in ["", "Rust-test", "rust_test", "rust/test", "a b", "x\"y"] { + let err = config("", Path::new("/r"), "gate", slug).unwrap_err(); + assert!(err.contains(&format!("{slug:?}")), "{err}"); + } +} + +#[test] +fn a_guests_slug_is_its_directory_under_extensions() { + assert_eq!(slug("extensions/rust/test/Cargo.toml"), "rust-test"); + assert_eq!(slug("extensions/checks/Cargo.toml"), "checks"); +} + +/// Two guests whose directories slug alike are refused, naming both; distinct ones keep their order. +#[test] +fn two_guests_sharing_a_slug_are_refused() { + let manifests = |paths: &[&str]| paths.iter().map(|p| p.to_string()).collect::>(); + assert_eq!( + slugged(manifests(&[ + "extensions/rust/test/Cargo.toml", + "extensions/checks/Cargo.toml" + ])), + Ok(vec![ + ( + "extensions/rust/test/Cargo.toml".to_string(), + "rust-test".to_string() + ), + ( + "extensions/checks/Cargo.toml".to_string(), + "checks".to_string() + ), + ]) + ); + let err = slugged(manifests(&[ + "extensions/cargo-test/Cargo.toml", + "extensions/cargo/test/Cargo.toml", + ])) + .unwrap_err(); + assert!( + err.starts_with( + "extensions/cargo-test/Cargo.toml and extensions/cargo/test/Cargo.toml share the guest slug `cargo-test`" + ), + "{err}" + ); +} + +/// The real guests' slugs are distinct. +#[test] +fn the_repositorys_guests_have_distinct_slugs() { + let guests = slugged(guests_of(&crate::repo::this_repo())).unwrap(); + assert!(guests.len() > 1, "{guests:?}"); +} + +/// The body lines of `[profile.]` in `text`: each one neither blank nor a comment, up to the next table. +fn profile_body<'a>(text: &'a str, name: &str) -> Vec<&'a str> { + let header = format!("[profile.{name}]"); + text.lines() + .map(str::trim) + .skip_while(|line| *line != header) + .skip(1) + .take_while(|line| !line.starts_with('[')) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .collect() +} + +/// The guests' `default`, `ci` and `gate` profiles are the root's, line for line, so retries and slow-timeouts never +/// drift apart (the root's JUnit and override tables stay out of both bodies). +#[test] +fn the_guests_profiles_are_the_roots() { + let root = specforge_repo_root::repo_root(); + let read = |file: &str| std::fs::read_to_string(root.join(file)).unwrap(); + let (guests, workspace) = (read(BASE), read(".config/nextest.toml")); + for name in ["default", "ci", "gate"] { + let body = profile_body(&guests, name); + assert!(!body.is_empty(), "{BASE}: no [profile.{name}]"); + assert_eq!( + body, + profile_body(&workspace, name), + "{BASE}: [profile.{name}] differs from .config/nextest.toml's" + ); + } +} + +/// The committed base holds the gate and ci profiles and leaves the store, the JUnit path and the root's package +/// overrides out: the gate adds the first two, and nextest refuses the overrides against a guest manifest. +#[test] +fn the_committed_base_holds_the_profiles_and_no_store_junit_or_override() { + let path = specforge_repo_root::repo_root().join(BASE); + let text = std::fs::read_to_string(&path).unwrap(); + let lines: Vec<&str> = text + .lines() + .map(str::trim) + .filter(|line| !line.starts_with('#')) + .collect(); + for table in ["[profile.gate]", "[profile.ci]"] { + assert!(lines.contains(&table), "{}: no {table}", path.display()); + } + for line in &lines { + assert!( + !line.starts_with("[store]") && !line.contains("junit") && !line.contains("overrides"), + "{}: {line}", + path.display() + ); + } +} diff --git a/gate/src/judge.rs b/gate/src/judge.rs index 60c1d8f9b9..6c484931ef 100644 --- a/gate/src/judge.rs +++ b/gate/src/judge.rs @@ -126,9 +126,8 @@ const FAILED_NAMED: usize = 10; /// --kinds requirement`) and its computed `proof` (`@gsd/core`), a node with none counted under `none`. It fails /// when there is no requirement, when none is `proven` (a test run with an empty result shows red) or when any is /// `failed`, naming the first failed ones. It always prints `requirements proven: N of M` with the count of each -/// other state, and how many `no_test` requirements only guests' tests name (`guest_named`): guests run under -/// `cargo test` and write no JUnit, so what only they prove reads `no_test`. -pub fn requirement_verdict(export: &Value, guest_named: &BTreeSet) -> (Vec, bool) { +/// other state. +pub fn requirement_verdict(export: &Value) -> (Vec, bool) { let mut states: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); for node in export["nodes"] .as_array() @@ -144,17 +143,13 @@ pub fn requirement_verdict(export: &Value, guest_named: &BTreeSet) -> (V } let count = |state: &str| states.get(state).map_or(0, Vec::len); let total: usize = states.values().map(Vec::len).sum(); - let guests_only = states.get("no_test").map_or(0, |ids| { - ids.iter().filter(|id| guest_named.contains(**id)).count() - }); let others: String = states .iter() .filter(|(state, _)| !matches!(**state, "proven" | "failed" | "not_run" | "no_test")) .map(|(state, ids)| format!(", {state} {}", ids.len())) .collect(); let mut lines = vec![format!( - "requirements proven: {} of {total} (failed {}, not_run {}, no_test {}, of them {guests_only} named only by \ - guests' tests{others})", + "requirements proven: {} of {total} (failed {}, not_run {}, no_test {}{others})", count("proven"), count("failed"), count("not_run"), @@ -166,7 +161,7 @@ pub fn requirement_verdict(export: &Value, guest_named: &BTreeSet) -> (V failed = true; } else if count("proven") == 0 { lines.push( - "no requirement is proven: no passing test names one (run `cargo gate full --only tests` first)" + "no requirement is proven: no passing test names one (run `cargo gate full --only tests,guests,gsd,dogfood`)" .to_string(), ); failed = true; @@ -362,7 +357,7 @@ mod tests { fn requirement_verdict_fails_an_export_with_no_requirement() { let decision = json!({"nodes": [{"id": "D-001", "kind": "decision", "fields": {}}]}); for export in [json!({"nodes": []}), json!({}), decision] { - let (lines, failed) = requirement_verdict(&export, &BTreeSet::new()); + let (lines, failed) = requirement_verdict(&export); assert!(failed, "{lines:?}"); assert!( lines[1].starts_with("no requirement in the export"), @@ -377,12 +372,11 @@ mod tests { {"id": "A-01", "kind": "requirement", "fields": {}}, {"id": "A-02", "kind": "requirement", "fields": {"proof": "no_test"}}, ]}); - let (lines, failed) = requirement_verdict(&export, &BTreeSet::new()); + let (lines, failed) = requirement_verdict(&export); assert!(failed); assert_eq!( lines[0], - "requirements proven: 0 of 2 (failed 0, not_run 0, no_test 1, of them 0 named only by guests' tests, \ - none 1)" + "requirements proven: 0 of 2 (failed 0, not_run 0, no_test 1, none 1)" ); assert!( lines[1].starts_with("no requirement is proven"), @@ -394,12 +388,12 @@ mod tests { fn requirement_verdict_fails_a_failed_requirement_and_names_it() { let mut export = tracer_export(); export["nodes"][1]["fields"]["proof"] = json!("failed"); - let (lines, failed) = requirement_verdict(&export, &BTreeSet::new()); + let (lines, failed) = requirement_verdict(&export); assert!(failed); assert_eq!( lines, [ - "requirements proven: 1 of 3 (failed 1, not_run 0, no_test 1, of them 0 named only by guests' tests)", + "requirements proven: 1 of 3 (failed 1, not_run 0, no_test 1)", "TRACER-02 failed: a test that names it failed", ] ); @@ -412,7 +406,7 @@ mod tests { nodes.extend((1..=12).map(|n| { json!({"id": format!("BAD-{n:02}"), "kind": "requirement", "fields": {"proof": "failed"}}) })); - let (lines, failed) = requirement_verdict(&json!({ "nodes": nodes }), &BTreeSet::new()); + let (lines, failed) = requirement_verdict(&json!({ "nodes": nodes })); assert!(failed); assert_eq!(lines.len(), 1 + 10 + 1, "{lines:?}"); assert_eq!(lines.last().unwrap(), "and 2 more failed"); @@ -420,24 +414,11 @@ mod tests { #[test] fn requirement_verdict_passes_the_fixtures_export() { - let (lines, failed) = requirement_verdict(&tracer_export(), &BTreeSet::new()); + let (lines, failed) = requirement_verdict(&tracer_export()); assert!(!failed, "{lines:?}"); assert_eq!( lines, - [ - "requirements proven: 2 of 3 (failed 0, not_run 0, no_test 1, of them 0 named only by guests' tests)" - ] - ); - } - - #[test] - fn requirement_verdict_counts_the_no_test_requirements_only_guests_name() { - let guests = BTreeSet::from(["TRACER-03".to_string(), "TRACER-01".to_string()]); - let (lines, failed) = requirement_verdict(&tracer_export(), &guests); - assert!(!failed, "{lines:?}"); - assert!( - lines[0].contains("no_test 1, of them 1 named only by guests' tests"), - "{lines:?}" + ["requirements proven: 2 of 3 (failed 0, not_run 0, no_test 1)"] ); } diff --git a/gate/src/junit.rs b/gate/src/junit.rs index e42c78091d..b48e43d4f1 100644 --- a/gate/src/junit.rs +++ b/gate/src/junit.rs @@ -14,7 +14,7 @@ pub fn merge(reports: &[String]) -> Result { if reports.is_empty() { return Err( "no JUnit report to merge: nextest writes one under its `gate` and `ci` profiles \ - (run `cargo gate full --only tests` first)" + (run `cargo gate full --only tests,guests,gsd,dogfood`)" .to_string(), ); } diff --git a/gate/src/junit/tests.rs b/gate/src/junit/tests.rs index eb6a5547a4..c6f37c8715 100644 --- a/gate/src/junit/tests.rs +++ b/gate/src/junit/tests.rs @@ -27,5 +27,8 @@ fn a_report_with_no_testsuites_root_is_refused() { let refused = merge(&parts).expect_err("no root"); assert!(refused.contains("report 2"), "{refused}"); let none = merge(&[]).expect_err("nothing to merge"); - assert!(none.contains("cargo gate full --only tests"), "{none}"); + assert!( + none.contains("cargo gate full --only tests,guests,gsd,dogfood"), + "{none}" + ); } diff --git a/gate/src/lib.rs b/gate/src/lib.rs index 63425ce7b1..ee1e60ab5e 100644 --- a/gate/src/lib.rs +++ b/gate/src/lib.rs @@ -13,6 +13,7 @@ pub mod crate_map; mod doc_links; mod dogfood; mod gsd; +mod guests; pub mod judge; mod junit; pub mod layers; @@ -22,6 +23,7 @@ mod root_layout; mod run; mod size_cap; mod steps; +mod x2; pub use change_set::{ChangeSet, Pattern}; pub use checks::{CHECKS, Check, Reach, Selection, Trigger, render_list}; diff --git a/gate/src/run.rs b/gate/src/run.rs index 04d6c69558..903f32a03e 100644 --- a/gate/src/run.rs +++ b/gate/src/run.rs @@ -75,6 +75,26 @@ pub struct Ctx<'a> { specforge: &'a OnceLock>, } +impl<'a> Ctx<'a> { + /// A quick-mode context for a test, its log a new file at `log`; a `specforge` already filled is what + /// [`Ctx::specforge`] returns, with no build. + #[cfg(test)] + pub(crate) fn for_tests( + repo: &'a Repo, + changes: &'a ChangeSet, + specforge: &'a OnceLock>, + log: &Path, + ) -> Ctx<'a> { + Ctx { + repo, + mode: Mode::Quick, + changes, + log: File::create(log).expect("a test's log file is creatable"), + specforge, + } + } +} + impl Ctx<'_> { /// A command that runs in the repository root. pub fn cmd(&self, program: impl AsRef) -> Command { @@ -407,18 +427,42 @@ pub(crate) fn schedule(steps: &[Step], states: &[State]) -> Wave { } /// The file compiling checks take turns on, one per machine and user, whichever worktree they run from. -fn compile_lock_path() -> PathBuf { +pub(crate) fn compile_lock_path() -> PathBuf { std::env::temp_dir().join("specforge-gate-compile.lock") } /// Waits until no other gate on this machine compiles, and holds that turn until the file drops. The OS releases the /// lock when its holder dies, even a killed one. A lock that cannot be taken only loses the queueing, so the check runs. -fn compile_turn(path: &Path) -> Option { +pub(crate) fn compile_turn(path: &Path) -> Option { let file = File::create(path).ok()?; file.lock().ok()?; Some(file) } +/// Whether this run empties the nextest report dir before its checks, so that `dogfood` judges the reports this run +/// writes and no earlier run's (ADR 0374 D5, ADR 0393 D3): when `runs` (whether the run runs a check) holds `dogfood` +/// and every check that writes a report ([`crate::dogfood::REPORTERS`]). Any other run that runs `dogfood` is refused, +/// since it would judge reports of any age, perhaps another tree's; except in `ci`, whose `dogfood` job judges the +/// reports its shards uploaded in the same workflow, fresh by construction. +pub(crate) fn purges_reports(mode: Mode, runs: impl Fn(&str) -> bool) -> Result { + let reporters = crate::dogfood::REPORTERS; + if !runs("dogfood") { + return Ok(false); + } + let missing: Vec<&str> = reporters.into_iter().filter(|name| !runs(name)).collect(); + if missing.is_empty() { + Ok(true) + } else if mode == Mode::Ci { + Ok(false) + } else { + Err(format!( + "dogfood judges the JUnit reports this run writes, and {} would not run: cargo gate full --only {},dogfood", + missing.join(", "), + reporters.join(",") + )) + } +} + /// Whether `--only`'s comma-separated list (every name when `None`) names `check`. pub(crate) fn named(only: Option<&str>, check: &str) -> bool { only.is_none_or(|list| list.split(',').any(|name| name == check)) @@ -481,8 +525,13 @@ pub fn run( } let log_dir = repo.target_dir.join("gate"); std::fs::create_dir_all(&log_dir).map_err(|e| format!("{}: {e}", log_dir.display()))?; - // A full run's dogfood judges the JUnit reports this run's tests write, not an earlier run's (ADR 0374 D5). - if matches!(mode, Mode::Full | Mode::Ci) && only.is_none() { + let runs = |name: &str| { + CHECKS + .iter() + .zip(&selections) + .any(|(check, selection)| check.name == name && *selection != Selection::Skip) + }; + if purges_reports(mode, runs)? { for report in crate::dogfood::reports(&crate::dogfood::report_dir( &repo.root, mode.nextest_profile(), diff --git a/gate/src/run/tests.rs b/gate/src/run/tests.rs index 9112167eb6..d8f6bc9bf0 100644 --- a/gate/src/run/tests.rs +++ b/gate/src/run/tests.rs @@ -173,6 +173,31 @@ fn only_names_a_comma_separated_list_of_checks() { assert!(!named(Some("doc-links"), "links")); } +/// A run that runs dogfood with every report writer empties the report dir first; a full run that runs dogfood +/// without them is refused, naming what is missing and the command; CI's dogfood job runs it alone over fresh +/// artifacts; a run without dogfood leaves the reports alone (ADR 0393 D3). +#[test] +fn dogfood_judges_only_reports_this_run_writes() { + let runs = |only: &'static str| move |check: &str| named(Some(only), check); + for mode in [Mode::Full, Mode::Ci] { + assert_eq!(purges_reports(mode, |_| true), Ok(true)); + assert_eq!( + purges_reports(mode, runs("tests,guests,gsd,dogfood")), + Ok(true) + ); + assert_eq!(purges_reports(mode, runs("tests,guests,gsd")), Ok(false)); + } + assert_eq!(purges_reports(Mode::Ci, runs("dogfood")), Ok(false)); + assert_eq!( + purges_reports(Mode::Full, runs("tests,dogfood")), + Err( + "dogfood judges the JUnit reports this run writes, and guests, gsd would not run: \ + cargo gate full --only tests,guests,gsd,dogfood" + .to_string() + ) + ); +} + #[test] fn a_compile_turn_excludes_another_until_it_drops() { let dir = tempfile::tempdir().unwrap(); diff --git a/gate/src/steps.rs b/gate/src/steps.rs index 9bab21f595..89c7b586cd 100644 --- a/gate/src/steps.rs +++ b/gate/src/steps.rs @@ -11,13 +11,13 @@ use crate::checks::{self, Selection}; use crate::doc_links; use crate::judge; use crate::layers; -use crate::repo::{EXTENSION_CRATES, Repo, outside_workspace_patterns}; +use crate::repo::{Repo, outside_workspace_patterns}; use crate::root_layout; use crate::run::{CARGO_AUDIT, Ctx, Mode, TREE_SITTER}; use crate::size_cap; /// Ok when nothing failed; else every failure, one per line. -fn finish(failures: Vec) -> Result<(), String> { +pub(crate) fn finish(failures: Vec) -> Result<(), String> { if failures.is_empty() { Ok(()) } else { @@ -195,50 +195,6 @@ pub fn builtins(ctx: &Ctx, selection: &Selection) -> Result<(), String> { ])) } -pub fn guests(ctx: &Ctx, _: &Selection) -> Result<(), String> { - let target = ctx.ext_target(); - // (what, cargo arguments before the manifest, after it) - let passes: [(&str, &[&str], &[&str]); 3] = [ - ("tests", &["test", "-q"], &[]), - ( - "wasm clippy", - &["clippy", "-q", "--target", "wasm32-wasip2"], - &["--", "-D", "warnings"], - ), - ( - "native clippy", - &["clippy", "-q", "--all-targets"], - &["--", "-D", "warnings"], - ), - ]; - let mut failures = Vec::new(); - // An example project's extension gets the wasm clippy pass only: it has no tests and no native use. - let examples = crate::repo::expand(&ctx.repo.root, "examples/*/extension/Cargo.toml"); - let runs = guests_of(ctx.repo) - .into_iter() - .map(|manifest| (manifest, &passes[..])) - .chain( - examples - .into_iter() - .map(|manifest| (manifest, &passes[1..2])), - ); - for (manifest, passes) in runs { - for &(what, before, after) in passes { - let mut cmd = ctx.cmd("cargo"); - // What `build-blobs` does: an incremental guest is another build than CI's. - cmd.env("CARGO_TARGET_DIR", &target) - .env_remove("CARGO_INCREMENTAL"); - cmd.args(before) - .args(["--manifest-path", &manifest]) - .args(after); - if let Err(e) = ctx.sh(&mut cmd) { - failures.push(format!("{manifest} {what}: {e}")); - } - } - } - finish(failures) -} - pub fn audit(ctx: &Ctx, _: &Selection) -> Result<(), String> { ctx.tool(&CARGO_AUDIT)?; let (_, listed) = ctx.capture(ctx.cmd("git").args(["ls-files", "*Cargo.lock"]))?; @@ -562,12 +518,3 @@ pub(crate) fn outside_workspace(repo: &Repo) -> Vec { .flat_map(|pattern| crate::repo::expand(&repo.root, pattern)) .collect() } - -/// The guests' and the extension libraries' manifests: `extensions//Cargo.toml` and -/// `extensions///Cargo.toml` (ADR 0328 D3). -fn guests_of(repo: &Repo) -> Vec { - EXTENSION_CRATES - .iter() - .flat_map(|dirs| crate::repo::expand(&repo.root, &format!("{dirs}/Cargo.toml"))) - .collect() -} diff --git a/gate/src/x2.rs b/gate/src/x2.rs new file mode 100644 index 0000000000..ac7e1b4b41 --- /dev/null +++ b/gate/src/x2.rs @@ -0,0 +1,113 @@ +//! X2 (ADR 0388): of a project's `item` facts that carry a `test_id`, the share whose test id is the id of a +//! `test` fact, of any status. X2 is a floor every project the `dogfood` check collects must reach: 100%, and never +//! `0/0` (ADR 0393 D8). Pure functions the check calls; each is tested on literal input. + +use std::collections::BTreeSet; + +use serde_json::Value; + +/// X2 over one project: `present` of `total` items with a test id have a test fact; `missing` are the others' ids. +pub(crate) struct X2 { + pub present: usize, + pub total: usize, + pub missing: Vec, +} + +/// X2 over `items` (each an item id and its `test_id`) and the ids of the `test` facts: the missing item ids come +/// out sorted, once each. +pub(crate) fn ratio(items: &[(String, String)], tests: &BTreeSet) -> X2 { + let present = items + .iter() + .filter(|(_, test)| tests.contains(test)) + .count(); + let missing: BTreeSet = items + .iter() + .filter(|(_, test)| !tests.contains(test)) + .map(|(id, _)| id.clone()) + .collect(); + X2 { + present, + total: items.len(), + missing: missing.into_iter().collect(), + } +} + +/// What [`read`] reads of an export: each item id with its `test_id`, and the ids of the `test` facts. +pub(crate) type Read = (Vec<(String, String)>, BTreeSet); + +/// The `item` nodes of `export` (`specforge export --format graph --kinds item,test`) that carry a `test_id`, each +/// with it, and the ids of its `test` nodes, whatever their status. An error when the export is of another shape (no +/// `nodes` array, a node with no string `id` or `kind`): it would read as `0/0`, the line of a project whose items +/// carry no test id, and hide the change. +pub(crate) fn read(export: &Value) -> Result { + let nodes = export["nodes"] + .as_array() + .ok_or("the export has no `nodes` array: its shape changed")?; + let mut items = Vec::new(); + let mut tests = BTreeSet::new(); + for (n, node) in nodes.iter().enumerate() { + let (Some(id), Some(kind)) = (node["id"].as_str(), node["kind"].as_str()) else { + return Err(format!( + "the export's nodes[{n}] has no string `id` and `kind`: its shape changed" + )); + }; + match kind { + "item" => { + if let Some(test) = node["fields"]["test_id"].as_str() { + items.push((id.to_string(), test.to_string())); + } + } + "test" => { + tests.insert(id.to_string()); + } + _ => {} + } + } + Ok((items, tests)) +} + +/// `X2 : n/m (p%)`, the percent rounded down to one decimal so that `100.0%` means no item is missing, or +/// `X2 : 0/0 (no item has a test_id)` when no item has one, then each missing item id on its own line, +/// indented two spaces. +pub(crate) fn lines(project: &str, x2: &X2) -> Vec { + // Integer tenths of a percent: a float's 100 * 29 / 100 is 28.999…, which would floor to 28.9. + let head = match x2.present.saturating_mul(1000).checked_div(x2.total) { + None => format!("X2 {project}: 0/0 (no item has a test_id)"), + Some(tenths) => format!( + "X2 {project}: {}/{} ({}.{}%)", + x2.present, + x2.total, + tenths / 10, + tenths % 10 + ), + }; + std::iter::once(head) + .chain(x2.missing.iter().map(|id| format!(" {id}"))) + .collect() +} + +/// How many missing item ids [`floor`]'s error names; the log lists them all. +pub(crate) const MISSING_NAMED: usize = 10; + +/// The floor (ADR 0393 D8): Ok when every one of at least one item with a test id has a test fact. Otherwise the head +/// of [`lines`] (its rounded-down percent) and the first [`MISSING_NAMED`] missing ids, with how many more there are; +/// `X2 : no item has a test_id` on `0/0`. +pub(crate) fn floor(project: &str, x2: &X2) -> Result<(), String> { + if x2.total == 0 { + return Err(format!("X2 {project}: no item has a test_id")); + } + if x2.missing.is_empty() { + return Ok(()); + } + let head = lines(project, x2).swap_remove(0); + let named = x2.missing[..x2.missing.len().min(MISSING_NAMED)].join(", "); + let more = x2.missing.len().saturating_sub(MISSING_NAMED); + Err(if more == 0 { + format!("{head}: missing {named}") + } else { + format!("{head}: missing {named}, and {more} more (the log lists all)") + }) +} + +#[cfg(test)] +mod tests; diff --git a/gate/src/x2/tests.rs b/gate/src/x2/tests.rs new file mode 100644 index 0000000000..8c2fb15320 --- /dev/null +++ b/gate/src/x2/tests.rs @@ -0,0 +1,172 @@ +#![allow( + clippy::unwrap_used, + reason = "a test's unwrap is its assertion: a None or an Err fails the test" +)] + +use serde_json::json; + +use super::*; + +fn pairs(items: &[(&str, &str)]) -> Vec<(String, String)> { + items + .iter() + .map(|(id, test)| (id.to_string(), test.to_string())) + .collect() +} + +fn ids(tests: &[&str]) -> BTreeSet { + tests.iter().map(|id| id.to_string()).collect() +} + +#[test] +fn x2_counts_the_items_whose_test_id_a_test_fact_holds_and_names_the_rest() { + let items = pairs(&[ + ("rust:p::a", "rust:p::a"), + ("rust:p::b", "rust:p::b"), + ("rust:p::c", "rust:p::c"), + ("rust:p::d", "rust:p::d"), + ]); + let x2 = ratio(&items, &ids(&["rust:p::a", "rust:p::b", "rust:p::d"])); + assert_eq!( + lines("p", &x2), + ["X2 p: 3/4 (75.0%)", " rust:p::c"], + "the ratio, then the one item no test fact saw" + ); +} + +#[test] +fn x2_of_a_project_with_no_test_id_is_zero_of_zero_with_its_reason() { + let x2 = ratio(&[], &ids(&["js:t/a.test.js::adds"])); + assert_eq!( + lines("taskboard", &x2), + ["X2 taskboard: 0/0 (no item has a test_id)"], + "no percent and no line beneath" + ); +} + +#[test] +fn x2_counts_a_test_of_any_status_and_not_an_item_without_a_test_id() { + let export = json!({"nodes": [ + {"kind": "item", "id": "rust:p::skipped", "fields": {"test_id": "rust:p::skipped"}}, + {"kind": "item", "id": "rust:p::failed", "fields": {"test_id": "rust:p::failed"}}, + {"kind": "item", "id": "rust:p::helper", "fields": {"kind": "function"}}, + {"kind": "test", "id": "rust:p::skipped", "fields": {"status": "skipped"}}, + {"kind": "test", "id": "rust:p::failed", "fields": {"status": "failed"}}, + {"kind": "requirement", "id": "R-01", "fields": {"test_id": "rust:p::helper"}}, + ]}); + let (items, tests) = read(&export).unwrap(); + assert_eq!( + items, + pairs(&[ + ("rust:p::skipped", "rust:p::skipped"), + ("rust:p::failed", "rust:p::failed"), + ]), + "only items carry a counted test_id" + ); + let x2 = ratio(&items, &tests); + assert_eq!(lines("p", &x2), ["X2 p: 2/2 (100.0%)"]); +} + +#[test] +fn x2_lists_the_missing_items_sorted_once_each() { + let items = pairs(&[ + ("rust:p::z", "rust:p::z"), + ("rust:p::a", "rust:p::a"), + ("rust:p::m", "rust:p::m"), + ("rust:p::a", "rust:p::a"), + ]); + let x2 = ratio(&items, &ids(&[])); + assert_eq!(x2.missing, ["rust:p::a", "rust:p::m", "rust:p::z"]); + assert_eq!(lines("p", &x2)[0], "X2 p: 0/4 (0.0%)"); +} + +#[test] +fn x2_rounds_the_percent_down_to_one_decimal() { + let items = pairs(&[("a", "a"), ("b", "b"), ("c", "c")]); + assert_eq!( + lines("p", &ratio(&items, &ids(&["a"])))[0], + "X2 p: 1/3 (33.3%)" + ); + assert_eq!( + lines("p", &ratio(&items, &ids(&["a", "b"])))[0], + "X2 p: 2/3 (66.6%)" + ); +} + +/// `present` of `total` items with a test fact, the others missing. +fn of(present: usize, total: usize) -> X2 { + X2 { + present, + total, + missing: vec!["m".to_string(); total - present], + } +} + +#[test] +fn x2_never_prints_100_percent_while_an_item_is_missing() { + assert_eq!( + lines("p", &of(9_999, 10_000))[0], + "X2 p: 9999/10000 (99.9%)" + ); + assert_eq!(lines("p", &of(1_999, 2_000))[0], "X2 p: 1999/2000 (99.9%)"); + assert_eq!(lines("p", &of(29, 100))[0], "X2 p: 29/100 (29.0%)"); + assert_eq!(lines("p", &of(7, 7)), ["X2 p: 7/7 (100.0%)"]); +} + +#[test] +fn the_floor_passes_only_every_item_of_at_least_one() { + assert_eq!(floor("p", &of(7, 7)), Ok(())); + assert_eq!( + floor("p", &of(0, 0)), + Err("X2 p: no item has a test_id".to_string()) + ); + assert_eq!( + floor("p", &of(5, 6)), + Err("X2 p: 5/6 (83.3%): missing m".to_string()) + ); + let error = floor("p", &of(9_999, 10_000)).unwrap_err(); + assert!( + error.starts_with("X2 p: 9999/10000 (99.9%): missing m"), + "never rounds to a pass: {error}" + ); +} + +#[test] +fn the_floor_names_ten_missing_ids_in_order_and_counts_the_rest() { + let missing: Vec = (0..25).map(|n| format!("m{n:02}")).collect(); + let x2 = X2 { + present: 0, + total: 25, + missing: missing.clone(), + }; + let error = floor("p", &x2).unwrap_err(); + assert_eq!( + error, + format!( + "X2 p: 0/25 (0.0%): missing {}, and 15 more (the log lists all)", + missing[..10].join(", ") + ) + ); + assert_eq!(MISSING_NAMED, 10); + assert!(!error.contains("m10"), "an eleventh id named: {error}"); +} + +#[test] +fn x2_refuses_an_export_of_another_shape_rather_than_reading_0_of_0() { + for (export, named) in [ + (json!({}), "nodes"), + (json!({"nodes": {}}), "nodes"), + (json!({"entities": []}), "nodes"), + (json!({"nodes": [{"kind": "item"}]}), "nodes[0]"), + (json!({"nodes": [{"id": "x", "type": "item"}]}), "nodes[0]"), + (json!({"nodes": [{"id": 1, "kind": "item"}]}), "nodes[0]"), + ] { + let error = read(&export).expect_err(named); + assert!(error.contains(named), "{export}: {error}"); + } + let (items, tests) = read(&json!({"nodes": []})).unwrap(); + assert!( + items.is_empty() && tests.is_empty(), + "an empty graph is 0/0" + ); +} diff --git a/gsd/.config/nextest.toml b/gsd/.config/nextest.toml index 84c4a2d6a9..089b505853 100644 --- a/gsd/.config/nextest.toml +++ b/gsd/.config/nextest.toml @@ -6,3 +6,16 @@ [[profile.default.overrides]] filter = "package(gsd-core) & test(=hooks_guards::a_gsd_hook_is_within_the_latency_budget)" threads-required = "num-test-threads" + +# The workspace's JUnit report, read by the gate's `dogfood` check (ADR 0393 D2): the store is the repository root's +# `target/nextest` (relative to `gsd/`, the workspace root), so a plain `cargo nextest run` here stores under +# `target/nextest/default` there, and the `gate` and `ci` profiles (which inherit `default` and its override) write +# their report in `target/nextest//junit-gsd/`. +[store] +dir = "../target/nextest" + +[profile.gate.junit] +path = "junit-gsd/junit.xml" + +[profile.ci.junit] +path = "junit-gsd/junit.xml" diff --git a/gsd/Cargo.lock b/gsd/Cargo.lock index 98baf3de5f..0f0cb4472f 100644 --- a/gsd/Cargo.lock +++ b/gsd/Cargo.lock @@ -136,6 +136,21 @@ dependencies = [ "tempfile", ] +[[package]] +name = "gsd-import" +version = "1.0.0" +dependencies = [ + "gsd-core", + "gsd-kit", + "gsd-security", + "regex", + "rustix", + "serde_json", + "sha2", + "specforge-extension-sdk", + "tempfile", +] + [[package]] name = "gsd-kit" version = "1.0.0" diff --git a/gsd/Cargo.toml b/gsd/Cargo.toml index 183e372726..a6b1430f71 100644 --- a/gsd/Cargo.toml +++ b/gsd/Cargo.toml @@ -1,7 +1,7 @@ # The @gsd family: one Cargo workspace, one lockfile, one target (ADR gsd/0001). The root workspace excludes this folder. [workspace] resolver = "3" -members = ["kit", "core", "security"] +members = ["kit", "core", "security", "import"] [workspace.package] edition = "2024" diff --git a/gsd/README.md b/gsd/README.md index efc60157cc..5bf94ea7e9 100644 --- a/gsd/README.md +++ b/gsd/README.md @@ -1,6 +1,6 @@ # GSD in SpecForge (`@gsd/*`) -**Status: the kernel changes are built (protocol 1.15.0); `@gsd/core` 1.1.0 is built and tracks gsd-core 1.19.0: its model, checks, 15 agents, 51 commands, 44 prompts, 50 slash commands and 15 hooks, installed for Claude Code (verified) and Codex and Cursor (drafts), and three of the parity suite's four checks run in the gate; the fourth (upgrade) is a procedure ([acceptance checklist](parity/ACCEPTANCE.md), which lists the named gaps: hooks are 16 of 29, the `specforged` harness is later, Codex and Cursor are unrun). `@gsd/security` 1.0.0 is built on it (the threat model, `/gsd-secure-phase`, the auditor and the ship gate; [security/](security/)). The other `@gsd/*` extensions are not built. Tracking stays at gsd-core 1.19.0 while the extensions are redesigned; upgrades resume afterwards, each as its own round.** This folder holds the model, the contribution rosters and the parity +**Status: the kernel changes are built (protocol 1.15.0); `@gsd/core` 1.1.0 is built and tracks gsd-core 1.19.0: its model, checks, 15 agents, 51 commands, 44 prompts, 50 slash commands and 15 hooks, installed for Claude Code (verified) and Codex and Cursor (drafts), and three of the parity suite's four checks run in the gate; the fourth (upgrade) is a procedure ([acceptance checklist](parity/ACCEPTANCE.md), which lists the named gaps: hooks are 16 of 29, the `specforged` harness is later, Codex and Cursor are unrun). `@gsd/security` 1.0.0 is built on it (the threat model, `/gsd-secure-phase`, the auditor and the ship gate; [security/](security/)). `@gsd/import` 1.0.0 is built and vendored: `specforge gsd import` reads a `.planning/` folder once into one edit plan ([import/](import/)). The other `@gsd/*` extensions are not built. Tracking stays at gsd-core 1.19.0 while the extensions are redesigned; upgrades resume afterwards, each as its own round.** This folder holds the model, the contribution rosters and the parity plan for bringing the whole GSD framework ([open-gsd](https://github.com/open-gsd)) into SpecForge. It lives in this monorepo for now and moves to its own repository later; nothing in it may depend on a path outside `gsd/`. @@ -79,7 +79,7 @@ list fields as items, **K14** a writing call knows the time (`now`), **K15** a j | Parity and more | Parity is the floor. The default profile `gsd-compat` behaves as GSD does; `gsd-strict` and `gsd-plus` switch on what SpecForge can do beyond GSD. | | Versions | Our extensions keep their own semver and declare what they track: the crate's `[package.metadata.gsd] tracks = "gsd-core@1.19.0"` and the handshake keyword `tracks:gsd-core@1.19.0`. Only the latest tracked GSD is supported; projects move forward by migration. | | Upgrades | `gsd/parity/upgrade.sh []` diffs the tracked tag (or ``) against the new one (inventory manifest, capability ids, config manifest, changed files) and writes a parity backlog, `gsd/parity/backlog/.md`, one row per change with the table that owns it; `tracks` moves only when the [parity suite](parity/) passes. | -| Adoption | `specforge gsd import` reads an existing `.planning/` once and writes `.spec` (edit plans). The parity suite uses it too. | +| Adoption | `specforge gsd import` (`@gsd/import`) reads an existing `.planning/` once into one edit plan that writes `spec/gsd/`, with a report of everything it does not map; it is measured on the parity fixtures against their twins. See [import/](import/README.md). | ### Model diff --git a/gsd/core/README.md b/gsd/core/README.md index e6c9c45cda..d10f0f4e86 100644 --- a/gsd/core/README.md +++ b/gsd/core/README.md @@ -14,15 +14,15 @@ extensions and the profiles declare it as their peer. |---|---|---| | Kinds | `project` (one per repository: the kernel keeps `singleton` as metadata, `gsd/E108` enforces it), `requirement` (named by its GSD id), `milestone` (scoped by workstream), `phase` (scoped by milestone, named `03`, `03.1` or `999.1`), `workstream`, `retrospective`, `lesson`, `methodology`; `context` (named `02-CONTEXT`, scoped by its phase), `decision` (`D-01`, scoped by its phase or the project, a project decision is `/D-01` from inside a scope; from outside, a phase's is `v1.0/02/D-01`), `deferred_idea`, `phase_spec`, `locked_req`, `interview` (append-only), `edge` and `spec_prohibition` (a spec's edge-coverage rows), `discussion` (its entries append-only, its checkpoint set and cleared), `research` and its eight item kinds (`finding`, `stack_choice`, `pattern`, `pitfall`, `dont_hand_roll`, `open_question`, `source`, `package_audit`), each item scoped by its research; `plan` (named `03-02`, scoped by its phase; a quick plan by its quick id), `task` and `checkpoint` (scoped by their plan, `T1`, `C1`), the must-haves `truth`, `artifact`, `key_link` and `prohibition`, `disposition` (append-only), `user_setup` and `plan_start` (what `start_plan` recorded); `review` (a cross-AI review round, scoped by its phase), `review_concern` (append-only, scoped by its round) and `revision_conflict`; `summary` (scoped by its plan), `deliverable` (scoped by its summary, with computed check statuses), `deviation` (append-only), `commit` (written only by the git collector), `pause`, `handoff`, `blocker` (its `gate` names a tripped TDD gate's task) and `quick_batch`; `verification`, `verify_gap`, `override` (human-only), `human_item`, `uat_session`, `uat_test`, `uat_gap`, `validation`, `validation_row`, `wave0_item`, `manual_check`, `milestone_audit` (its `debt_accepted` only a human sets), `broken_window` and `refactor_proposal`: 61 kinds in all | `src/kinds/`, model in [spec/project.md](spec/project.md), [spec/discuss.md](spec/discuss.md), [spec/plan.md](spec/plan.md), [spec/execute.md](spec/execute.md) and [spec/verify.md](spec/verify.md) | | Agents | the 15 core agents of gsd-core 1.19.0, bodies ported under MIT (`assets/agents/`), their tools mapped to host tool classes, ten with a compact variant (`specforge.agent_variant`) and each with a model line from `model_overrides.`. `specforge install ` writes them; a judge's file also lists the rules it judges: `gsd-plan-checker` (`gsd/W311`, `W313`, `W315`, `W316`), `gsd-verifier` (`gsd/E501`), `gsd-phase-researcher` (`gsd/W205`), `gsd-integration-checker` (`gsd/E518`); the other eleven judge nothing. A judge's body ends with a section that names `record_verdict`. **The bodies are runnable:** every `specforge gsd ` a ported line names is a declared command (`tests/port_tools.rs`), and a judge's body ends with a section that names `record_verdict` and the refusals of K17. The attribution notice always names the full file `agents/.md`, also when the compact body renders | `src/agents/`, `src/judged.rs` | -| Commands, prompts | 51 commands (31 write; `reference` prints an embedded workflow, reference or template, and `smart_entry` is read-only: it answers what `/gsd-next` routes by): `record_verdict` records a judge's verdict through `set_verdict`, the read-only `re_verify` lists the verifier's verdicts of a phase or a plan that are not fresh, and the read-only `thread_plan` answers a phase's plans and tasks in order as the agent plan `specforge trace --plan` checks; the plan, summary, checkpoint, UAT, validation, pause, blocker, broken-window, refactor, milestone, review, revision-conflict, quick-batch, lesson and commit-waiver commands write the `H` fields (31 of the 44 have a command writer and 13 are the `gsd-git` collector's; `contributions/README.md`); `health`, `stats` and `progress_report` read the computed values of the graph a command receives (ADR 0299); `phase`, `workstreams`, `cleanup`, `help`, `health`, `stats` and `surface` are also slash commands. 44 prompts and 50 slash commands (43 prompt-backed and 7 command-backed; `execute_plan` has no slash command): the lifecycle prompts `new_project`, `new_milestone`, `discuss_phase`, `spec_phase`, `mvp_phase`, `plan_phase`, `plan_review_convergence`, `ultraplan_phase`, `execute_phase`, `execute_plan`, `verify_work`, `validate_phase`, `add_tests`, `audit_uat`, `audit_milestone`, `complete_milestone`, `ship`, then `next`, `progress`, `manager`, `quick`, `quick_batch`, `fast`, `autonomous`, `pause_work`, `resume_work`, `review`, `review_backlog`, `settings`, `config`, `undo`, `pr_branch`, `milestone_summary`, `extract_learnings`, `ingest_docs`, `onboard`, `workspace`, `update` and the routers `ns_context`, `ns_ideate`, `ns_manage`, `ns_project`, `ns_review`, `ns_workflow`. Each renders upstream's workflow (287 ported assets under `assets/`, byte-equal to the vendored v1.19.0 text except the lines that named `.planning` or `gsd-tools`; `update` renders a text of ours, because upstream's installs upstream GSD over this one, and a router adds the route table of this install) for claude-code, codex and cursor. A prompt with a subject is gated: `plan_phase` and `ultraplan_phase` by `gsd/E201`, `W204`, `E206`, `W406`, `E516`; `execute_phase` by `E301`, `W309`, `E310` (a half-planned phase), `W311`, `W313`, `W315`, `W318`, `E516`; `execute_plan` by `W318`, `E516`; `complete_milestone` by `E106`, `E511`, `E516`; `ship` by `E511`, `E512`, `E516`; the others by `E516`. `plan_phase` runs `thread_plan` as its step `thread`, between the planner and the plan checker, and feeds the answer to `specforge trace --plan`: an `ok: false` result is fixed, and the step run again, before the check. `gsd/W506` (a decision of a phase's context that no summary or commit mentions) gates `workflow.context_coverage_gate` | `src/commands/`, `src/prompts/` | -| Collectors | `gsd-git` records each commit that names a plan or task as a `commit` entity in its plan's file: `specforge collect --runner gsd-git --yes`, through the host's git port (no `git` program). Tests are not GSD's to collect: a runner pack (`@javascript/node-test`, `@rust/test`) records them as `@code/core`'s test facts (`specforge collect --runner node-test --no-run` reads node's JUnit report), a `[gsd:]` tag in a test's name names its entity, and a deliverable check's `ref` (GSD's `path#test name`, or a fact's id) names a fact | `src/collectors/` | -| Passes | `derive` (the computed fields: verification status, score and re-verification, UAT totals and status, validation coverage, audit status, the phase `completed` ladder and the window counts; plan, task, summary and deliverable-check status from the commits and the test facts; requirement, phase, milestone, project, workstream and context values), `execute` (`gsd/E401`, `gsd/W403`, `gsd/W407`, `gsd/W408`), `schema_drift` (`gsd/E405`), `roadmap` (`gsd/E101`, `gsd/E102`, `gsd/W103`, `gsd/W104`, `gsd/E108`, `gsd/W109`, `gsd/E206`), `research` (`gsd/W204`), `plan_shape` (`gsd/W323`, `gsd/E302`, `gsd/E303`, `gsd/W304`, `gsd/E307`, `gsd/W308`, `gsd/W309`, `gsd/E322`), `waves` (the computed `plan.wave`, `plan.autonomous` and `plan.strict_wave`), `file_scope` (`gsd/W305`, `gsd/W306`), `wave_collision` (`gsd/W526`), `scope` (`gsd/E312`, `gsd/W317`), `cross_plan` (`gsd/E301`, `gsd/E310`, `gsd/I321`), `scan` (computes the file facts: anti-patterns, debt markers, artifact and key-link states) with `scan_check` (`gsd/E505`), `nyquist` (`gsd/E314`, `gsd/W510`), `verify_rules` (`gsd/E503`, `gsd/W504`, `gsd/E509`), `stale_truths` (`gsd/I527`, from the graph delta), `windows` (`gsd/E513`, `gsd/W514`), `gates` (the guards `gsd/E106`, `gsd/E511`, `gsd/E512`, `gsd/W318`, `gsd/W404`, `gsd/E515`, `gsd/E516`, which answer at a gate trigger and are silent on a write) and `verify_paths` (`gsd/E320`, `gsd/W324`; computes `task.verify_paths`, which it reads through the project's files) `fails_when` (`gsd/E507`) and `traceability` (`gsd/W520`, `gsd/E521`, `gsd/W522`; reads the files a complete plan deletes), `decision_coverage` (`gsd/W506`), `probe_rows` (`gsd/E523`) and `workstreams` (`gsd/E517`) | `src/passes/` | +| Commands, prompts | 51 commands (31 write; `reference` prints an embedded workflow, reference or template, and `smart_entry` is read-only: it answers what `/gsd-next` routes by): `record_verdict` records a judge's verdict through `set_verdict`, the read-only `re_verify` lists the verifier's verdicts of a phase or a plan that are not fresh, and the read-only `thread_plan` answers a phase's plans and tasks in order as the agent plan `specforge trace --plan` checks; the plan, summary, checkpoint, UAT, validation, pause, blocker, broken-window, refactor, milestone, review, revision-conflict, quick-batch, lesson and commit-waiver commands write the `H` fields (31 of the 44 have a command writer and 13 are the `gsd-git` collector's; `contributions/README.md`); `health`, `stats` and `progress_report` read the computed values of the graph a command receives (ADR 0299); `phase`, `workstreams`, `cleanup`, `help`, `health`, `stats` and `surface` are also slash commands. 44 prompts and 50 slash commands (43 prompt-backed and 7 command-backed; `execute_plan` has no slash command): the lifecycle prompts `new_project`, `new_milestone`, `discuss_phase`, `spec_phase`, `mvp_phase`, `plan_phase`, `plan_review_convergence`, `ultraplan_phase`, `execute_phase`, `execute_plan`, `verify_work`, `validate_phase`, `add_tests`, `audit_uat`, `audit_milestone`, `complete_milestone`, `ship`, then `next`, `progress`, `manager`, `quick`, `quick_batch`, `fast`, `autonomous`, `pause_work`, `resume_work`, `review`, `review_backlog`, `settings`, `config`, `undo`, `pr_branch`, `milestone_summary`, `extract_learnings`, `ingest_docs`, `onboard`, `workspace`, `update` and the routers `ns_context`, `ns_ideate`, `ns_manage`, `ns_project`, `ns_review`, `ns_workflow`. Each renders upstream's workflow (287 ported assets under `assets/`, byte-equal to the vendored v1.19.0 text except the lines that named `.planning` or `gsd-tools`; `update` renders a text of ours, because upstream's installs upstream GSD over this one, and a router adds the route table of this install) for claude-code, codex and cursor. A prompt with a subject is gated: `plan_phase` and `ultraplan_phase` by `gsd/E201`, `W204`, `E206`, `W406`, `E516`; `execute_phase` by `E301`, `W309`, `E310` (a half-planned phase), `W311`, `W313`, `W315`, `W318`, `E516`; `execute_plan` by `W318`, `E516`; `complete_milestone` by `E106`, `E511`, `E516`, `E533`, `E535`; `ship` by `E511`, `E512`, `E516`; the others by `E516`. `plan_phase` runs `thread_plan` as its step `thread`, between the planner and the plan checker, and feeds the answer to `specforge trace --plan`: an `ok: false` result is fixed, and the step run again, before the check. `gsd/W506` (a decision of a phase's context that no summary or commit mentions) gates `workflow.context_coverage_gate` | `src/commands/`, `src/prompts/` | +| Collectors | `gsd-git` records each commit that names a plan or task as a `commit` entity in its plan's file: `specforge collect --runner gsd-git --yes`, through the host's git port (no `git` program), and whether each shipped milestone's release tag `v` resolves (`milestone.tag`). Tests are not GSD's to collect: a runner pack (`@javascript/node-test`, `@rust/test`) records them as `@code/core`'s test facts (`specforge collect --runner node-test --no-run` reads node's JUnit report), a `[gsd:]` tag in a test's name names its entity, and a deliverable check's `ref` (GSD's `path#test name`, or a fact's id) names a fact | `src/collectors/` | +| Passes | `derive` (the computed fields: verification status, score and re-verification, UAT totals and status, validation coverage, audit status, the phase `completed` ladder and the window counts; plan, task, summary and deliverable-check status from the commits and the test facts; requirement, phase, milestone, project, workstream and context values), `execute` (`gsd/E401`, `gsd/W403`, `gsd/W407`, `gsd/W408`), `schema_drift` (`gsd/E405`), `roadmap` (`gsd/E101`, `gsd/E102`, `gsd/W103`, `gsd/W104`, `gsd/E108`, `gsd/W109`, `gsd/E206`), `research` (`gsd/W204`), `plan_shape` (`gsd/W323`, `gsd/E302`, `gsd/E303`, `gsd/W304`, `gsd/E307`, `gsd/W308`, `gsd/W309`, `gsd/E322`), `waves` (the computed `plan.wave`, `plan.autonomous` and `plan.strict_wave`), `file_scope` (`gsd/W305`, `gsd/W306`), `wave_collision` (`gsd/W526`), `scope` (`gsd/E312`, `gsd/W317`), `cross_plan` (`gsd/E301`, `gsd/E310`, `gsd/I321`), `scan` (computes the file facts: anti-patterns, debt markers, artifact and key-link states) with `scan_check` (`gsd/E505`), `nyquist` (`gsd/E314`, `gsd/W510`), `verify_rules` (`gsd/E503`, `gsd/W504`, `gsd/E509`), `stale_truths` (`gsd/I527`, from the graph delta), `windows` (`gsd/E513`, `gsd/W514`), `gates` (the guards `gsd/E106`, `gsd/E511`, `gsd/E512`, `gsd/W318`, `gsd/W404`, `gsd/E515`, `gsd/E516`, `gsd/E533` (a breaking API change without a major version bump, from the milestone's computed `api_breaks`), `gsd/E535` (release evidence that does not match the milestone, from its computed `release`), which answer at a gate trigger and are silent on a write) and `verify_paths` (`gsd/E320`, `gsd/W324`; computes `task.verify_paths`, which it reads through the project's files) `fails_when` (`gsd/E507`) and `traceability` (`gsd/W520`, `gsd/E521`, `gsd/W522`; reads the files a complete plan deletes), `decision_coverage` (`gsd/W506`), `probe_rows` (`gsd/E523`) and `workstreams` (`gsd/E517`) | `src/passes/` | | Hooks | 15 hooks (r44, K20c): `read_guard`, `write_guard`, `secret_read_guard`, `injection_scanner`, `prompt_guard`, `worktree_path_guard`, `workflow_marker`, `workflow_guard`, `context_monitor`, `context_compacted`, `statusline`, `config_reload` and, under `hooks.community`, `validate_commit`, `phase_boundary`, `session_state`; what each does and does not do is in `contributions/README.md` | `src/hooks/` | | Rules | `gsd/E105` (an `out_of_scope` requirement has a reason), `gsd/E201` (a context has canonical refs: two declarative rules under one code), `gsd/E107` (generated for each authored timestamp field and block member: first `blocker.resolved.at`), `gsd/E402` (a halted summary says why), the seven declarative `gsd/E307` rules (what each checkpoint kind requires) and `gsd/E319` (a test-tier prohibition names a test) | `src/rules.rs`, `../kit/src/dsl.rs` | -| Code book | all 73 `gsd/` codes of [spec/rules.md](spec/rules.md), each with its `gsd-compat` severity and what `gsd-strict` raises it to; the rules of the others land with their kinds | `src/codes.rs` | -| Settings | the 181 GSD configuration keys `@gsd/core` declares (a count of declarations; ACCEPTANCE counts the inventory's 212 keys, 161 built here, on that basis), typed with GSD's default, and 12 families (`models.*`, `granularities.*`, …), `specforge.agent_variant`, the ten `specforge.surface.` settings that show or hide skills; the 15 `model_overrides.` keys belong to the `model_overrides.*` family and are set by a preset | `src/settings/keys.rs`, model in [spec/settings.md](spec/settings.md) | -| Profiles | `profile` (`gsd-compat` by default, `gsd-strict`, `gsd-plus`), presetting seven settings (`workflow.windows_enforce` and six `specforge.*` gates) and raising rule severities; `model_profile` presets the 15 `model_overrides.` and `workflow.compact_content` presets `specforge.agent_variant` | `src/settings/profiles.rs` | -| Gates | the six `specforge.*` settings and the `workflow.*` toggles switch off the rules [spec/rules.md](spec/rules.md#setting-gated-rules) lists | `src/settings/gates.rs` | +| Code book | all 75 `gsd/` codes of [spec/rules.md](spec/rules.md), each with its `gsd-compat` severity and what `gsd-strict` raises it to; the rules of the others land with their kinds | `src/codes.rs` | +| Settings | the 181 GSD configuration keys `@gsd/core` declares (a count of declarations; ACCEPTANCE counts the inventory's 212 keys, 161 built here, on that basis), typed with GSD's default, and 12 families (`models.*`, `granularities.*`, …), `specforge.agent_variant`, `specforge.release_exempt` (the package names gsd/E535 does not judge), the ten `specforge.surface.` settings that show or hide skills; the 15 `model_overrides.` keys belong to the `model_overrides.*` family and are set by a preset | `src/settings/keys.rs`, model in [spec/settings.md](spec/settings.md) | +| Profiles | `profile` (`gsd-compat` by default, `gsd-strict`, `gsd-plus`), presetting nine settings (`workflow.windows_enforce` and eight `specforge.*` gates, among them `specforge.interface_gate` and `specforge.release_gate`) and raising rule severities; `model_profile` presets the 15 `model_overrides.` and `workflow.compact_content` presets `specforge.agent_variant` | `src/settings/profiles.rs` | +| Gates | the eight `specforge.*` gate settings and the `workflow.*` toggles switch off the rules [spec/rules.md](spec/rules.md#setting-gated-rules) lists | `src/settings/gates.rs` | | Secrets | the key half of the seven search flags (`brave_search_key` … `jina_key`), read from `BRAVE_API_KEY` … `JINA_API_KEY`; `github_token`, read from `GH_TOKEN`, for the pull requests ship and pr-branch open | `src/settings/profiles.rs` | A setting is declared before the round that reads it, so most are inert today; `specforge settings` lists what a diff --git a/gsd/core/assets/gsd-core/workflows/complete-milestone.md b/gsd/core/assets/gsd-core/workflows/complete-milestone.md index 5f859931d5..a807b4c5d8 100644 --- a/gsd/core/assets/gsd-core/workflows/complete-milestone.md +++ b/gsd/core/assets/gsd-core/workflows/complete-milestone.md @@ -59,7 +59,7 @@ These items are open. Choose an action: [C] Cancel — exit without closing ``` -**If user chooses [A] (Accept the tech debt):** the open items are `specforge check` findings, and an agent cannot suppress them. A person accepts the latest milestone audit's tech debt: they write its `debt_accepted` (`by`, `at`) by hand or from an interactive `specforge set`, which clears gsd/E106 alone. Ask the person to do it, wait for their answer, and re-run `specforge check --format json`. The close's gate is gsd/E106, gsd/E511, gsd/E515 and gsd/E516: proceed with `specforge gsd close-milestone` only when none of them is reported; an open UAT or verification item (gsd/E511, gsd/E515, gsd/E516) still blocks, and is resolved through [R]. The audit's `tech_debt` entries are the disclosure record; nothing else is written. +**If user chooses [A] (Accept the tech debt):** the open items are `specforge check` findings, and an agent cannot suppress them. A person accepts the latest milestone audit's tech debt: they write its `debt_accepted` (`by`, `at`) by hand or from an interactive `specforge set`, which clears gsd/E106 alone. Ask the person to do it, wait for their answer, and re-run `specforge check --format json`. The close's gate is gsd/E106, gsd/E511, gsd/E515, gsd/E516, gsd/E533 (a breaking API change without a major version bump) and gsd/E535 (release evidence that does not match the milestone): proceed with `specforge gsd close-milestone` only when none of them is reported; an open UAT or verification item (gsd/E511, gsd/E515, gsd/E516) still blocks, and is resolved through [R], a breaking API change (gsd/E533) is resolved by a major bump, by restoring the item or by committing the accepted API report, and a release mismatch (gsd/E535) by setting the package versions, naming a later version or tagging the last release, then collecting again. The audit's `tech_debt` entries are the disclosure record; nothing else is written. If output shows all clear (no open items): proceed with the close. A close that passes because a person accepted the audit's tech debt says so: name the audit and its `debt_accepted.by`. diff --git a/gsd/core/assets/gsd-core/workflows/complete-milestone/detail/elaboration.md b/gsd/core/assets/gsd-core/workflows/complete-milestone/detail/elaboration.md index 48656986ef..183559aaaf 100644 --- a/gsd/core/assets/gsd-core/workflows/complete-milestone/detail/elaboration.md +++ b/gsd/core/assets/gsd-core/workflows/complete-milestone/detail/elaboration.md @@ -12,7 +12,7 @@ If user chooses [A] (Acknowledge): the open items are `specforge check` findings 1. Ask the person to accept the latest milestone audit's tech debt: they write its `debt_accepted` (`by`, `at`) by hand or from an interactive `specforge set`. The host refuses that field in every plan and MCP write, so the agent never writes it. 2. Wait for their answer. 3. Re-run `specforge check --format json`: gsd/E106 passes once the milestone's latest audit is `passed`, or `tech_debt` with a `debt_accepted`; that is all [A] clears. -4. Proceed with the close (`specforge gsd close-milestone`) only when none of its gate codes is reported (gsd/E106, gsd/E511, gsd/E515 and gsd/E516); an open UAT or verification item (gsd/E511, gsd/E515, gsd/E516) still blocks: stop, report it and resolve it through [R]. The audit's `tech_debt` entries are the disclosure record: no other file is written. +4. Proceed with the close (`specforge gsd close-milestone`) only when none of its gate codes is reported (gsd/E106, gsd/E511, gsd/E515, gsd/E516, gsd/E533, a breaking API change without a major version bump, and gsd/E535, release evidence that does not match the milestone); an open UAT or verification item (gsd/E511, gsd/E515, gsd/E516) still blocks: stop, report it and resolve it through [R]; a breaking API change (gsd/E533) or a release mismatch (gsd/E535) still blocks too: stop and report it. The audit's `tech_debt` entries are the disclosure record: no other file is written. Accepting is a person's act on one audit: a later audit of the milestone carries no `debt_accepted` until a person writes one again. diff --git a/gsd/core/spec/README.md b/gsd/core/spec/README.md index 637a67cff9..4df4c721aa 100644 --- a/gsd/core/spec/README.md +++ b/gsd/core/spec/README.md @@ -150,9 +150,9 @@ task T1 "Issue a token on sign-in" { Nothing in it is computed: `wave`, `autonomous` and `status` are derived (`specforge query 03-02` shows them), and the plan's summary, written by the executor at the end, lands in the same file. -## Route +## Routes -`@gsd/core` declares one route, `gsd/requirement-thread` (ADR 0331 D8, ADR 0352 D3, ADR 0371 D7): `specforge trace +`@gsd/core` declares two routes. The first is `gsd/requirement-thread` (ADR 0331 D8, ADR 0352 D3, ADR 0371 D7): `specforge trace ` follows it and prints the requirement's thread on one line, or as a tree when a step has several matches. It reads GSD's own fields and collected data alone: no truth names a requirement for it, and no truth's `proof` is read. @@ -186,8 +186,16 @@ TASK-01 (proven) → deliverable D1 (test/tasks.test.js#a task is added with the next id) ``` +The second is `gsd/milestone-release` ([ADR 0390](../../../docs/adr/0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md) +D10): `specforge trace ` prints the milestone with the evidence gsd/E533 and gsd/E535 read, its computed +`api_breaks` and `release` (`tag`, `commit`, `packages`) and the `tag` `gsd-git` recorded ([project.md](project.md#milestone)), +then one `phase ` step for each of its phases (`-*`. N | git_range | str | C | `**Git range:**`: the first and last recorded `feat` commit as `` `feat(01-01)` → `feat(01-02)` `` (the scope is the name of the plan the commit names); absent with none | | progress | {phases int, phases_complete int, plans int, plans_complete int, percent int} | C | `STATE.md`'s `progress`, per milestone: `percent` is the smaller of plans_complete/plans and phases_complete/phases (a side with nothing counts 1, `state-document.cts:861-878`); `phases_complete` counts the phases whose verification passed, which needs r40's verdicts. `plans_complete` counts every plan with a summary, a halted one too (#2830), and the sentinel `999.x` backlog phases are left out (#3167) | | branch | str | C | the branch it is executed on, from `git.branching_strategy` and its template (`{milestone}`, `{slug}`: its title's slug); under the `milestone` strategy, else absent | +| api_breaks | strs | C | (new, ADR 0390 D4) the API items the last collect found changed, narrowed or removed against the committed accepted report, one ` ` line each from the `@code/core` `api_item` facts, sorted by id, at most 50 then `more `; on a milestone neither shipped nor abandoned; absent when no API fact carries a change, empty when none breaks; gsd/E533 reads it at the close | +| release | {tag str, commit str, packages [{name str, version str}], more int} | C | (new, ADR 0390 D6) the release evidence gsd/E535 reads: on a shipped milestone, `tag` and `commit` copy the `tag` `gsd-git` recorded (not while `git.create_tag` is false); on a milestone neither shipped nor abandoned whose name is a version, `packages` holds the `name` and `version` of each `@code/core` `package` fact whose version is not the milestone's and whose name is not in `specforge.release_exempt`, sorted, at most 50, and `more` the count past them (absent when none), so no package name reads as the count; absent when nothing was observed | +| tag | {name str, commit str} | H | (new, ADR 0390 D6) written by `gsd-git` from `refs/tags/v` for a shipped milestone named by its version: the tag's `name`, and the `commit` it resolves to, absent when it resolves to none; not written on a shallow clone or while `git.create_tag` is false | GSD's archive copies (`milestones/-ROADMAP.md` …) have no counterpart: a shipped milestone's entities stay where they are, and `specforge query` answers what an archive answered. diff --git a/gsd/core/spec/rules.md b/gsd/core/spec/rules.md index 24ed40dcab..66ddea53d9 100644 --- a/gsd/core/spec/rules.md +++ b/gsd/core/spec/rules.md @@ -33,6 +33,8 @@ every profile, while that setting is false; its letter is still the severity it | gsd/E107 | a timestamp field holds an RFC 3339 UTC time (every authored `ts` field, and every authored `ts` member of an authored block, is a `str` that `matches` `YYYY-MM-DDTHH:MM:SS[.f]Z` with ASCII digits and RFC 3339's ranges for month, day, hour, minute and second; the day is not checked against the month; generated per field and member. `project.updated` is computed, so the first is `blocker.resolved.at` (r38, fired by a black-box test); `answer.at`, `done.at`, `pause.at` and `blocker.raised` are harness values and get none) | decl | E | E | (new: SpecForge has no timestamp type) | | gsd/E108 | a repository has one `project` (the kernel keeps `singleton` as metadata, so the second and later `project` entities, by id, are reported) | pass | E | E | (new: `PROJECT.md` is one file) | | gsd/W109 | a phase's title does not begin with a phase number: `Phase` (any case) and a number in GSD's grammar, `\d+[A-Z]?(\.\d+)*`, then no letter or digit (`Phase 12: Core`, `phase 03.1 - Core`, `PHASE 12A: Core`, `Phase 3:Core`, `Phase 4`), or a bare number of digits and dots before `:` or `.` and a space, `)` or a spaced dash (`03: Core`, `3. Core`, `2) Core`, `04 - Core`). The rule reads that label grammar and no wider: a number inside the title (`HTTP 2 support`, `2FA login`, `v2.0 migration`, `3:00 standup`), a number joined to a word by a dash, a colon or a dot with no space (`03-Core`, `3-way merge`, `03:Core`, `3.Core`), a bare number before a word (`3 Core`, `#3 Core`, `(3) Core`), another word before a number (`Step 3: Core`, `Phase-3 cleanup`) and a lower-case letter after the number (`Phase 3a rollout`) are not one. A phase is labelled `Phase : ` (ADR 0387), so a numbered title prints a second number, which a renumber leaves behind. A `999.x` backlog phase is read too | pass | W | E | (new: GSD's heading `### Phase N: Name` keeps the number out of the name) | +| gsd/E533 | a milestone that is neither shipped nor abandoned, whose computed `api_breaks` ([project.md](project.md#milestone)) is not empty, is closed while its version is still API-compatible with (no major bump over) the last shipped milestone of its workstream scope (the other shipped milestones whose name is a version, latest by `shipped`, ties by the higher version; a shipped `mvp` or `v1.7-rc1` is no release and is skipped): Cargo's rule, two versions are compatible when they agree up to and including the first non-zero part of the older one, so for `0.x` a minor bump counts as major ([ADR 0390](../../../docs/adr/0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md) D5). A version is the milestone's name, `v1.7`, `1.7` or `v1.7.2` (one to three numeric parts); a subject name that is not one fires one error saying no major bump can be shown. No shipped milestone in the scope is a first release: allowed. At the gate, one error per `<change> <id>` line, on the gate's subject, at most 25, then one summary error; each echoed id is escaped. `api_breaks` is computed from the `@code/core` `api_item` facts of the last `specforge collect`, so the remedy (a major bump, restoring the item, or committing the updated accepted report) says to collect again. A guard, not a check (a write is never refused by it); a gate code of `close_milestone` and `/gsd-complete-milestone`. Silent outside a gate and at a phase gate. The setting `specforge.interface_gate` (on in gsd-strict and gsd-plus) gates it | guard | — | E | (new: the API packs' accepted report) | +| gsd/E535 | a milestone whose name is a version is closed while its release evidence does not match it ([ADR 0390](../../../docs/adr/0390-a-milestone-computes-its-api-breaks-and-release-evidence-and-two-guards-read-them.md) D6), read from its computed `release` ([project.md](project.md#milestone)): while it is unshipped, a package of `release.packages`, a `package` fact whose `version` is not the milestone's (the first max(2, the milestone's written parts) numeric parts agree; a `+build` suffix is ignored; a pre-release is not equal) and whose name is not in `specforge.release_exempt`; while it is unshipped, a version not later than the last shipped milestone of its workstream scope (E533's rule for "last shipped"; a backport reads as backwards); and the tag of the last shipped milestone of its scope, or its own once shipped, that `gsd-git` looked up as `refs/tags/v<version>` and found resolving to no commit. At the gate, one error per package, at most 25, then one summary error counting the rest and `release.more`, each echoed name and version escaped. No observation is silence: no `package` fact with a version, no repository, a shallow clone, `git.create_tag` false, or a name that is not a version. The package versions and the tag are read at the last `specforge collect`, so the remedy says to collect again. A guard, not a check; a gate code of `close_milestone` and `/gsd-complete-milestone`. Silent outside a gate and at a phase gate. The setting `specforge.release_gate` (on in gsd-strict and gsd-plus) gates it | guard | — | E | (new: GSD tags the release and reads no package version) | ## Discuss, spec, research @@ -172,6 +174,8 @@ is off while the setting is false, whatever the profile; a profile only presets | `specforge.cross_workstream_conflicts` | false | false (gsd-plus: true) | gsd/E517 | | `specforge.plan_paths_touched` | false | true | gsd/W520 | | `specforge.task_trailers` | false | true | gsd/E521 | +| `specforge.interface_gate` | false | true | gsd/E533 | +| `specforge.release_gate` | false | true | gsd/E535 | `gsd/W514` is gated the other way (`gates_when_on`, ADR 0305): `workflow.windows_enforce` silences it while it is on, and it is reported while the setting is off. diff --git a/gsd/core/spec/settings.md b/gsd/core/spec/settings.md index 62b2133edf..9fdb555115 100644 --- a/gsd/core/spec/settings.md +++ b/gsd/core/spec/settings.md @@ -40,7 +40,7 @@ Typed as GSD types them (K6 takes K3's field types), with three shapes GSD's JSO | GSD key | Declared as | |---|---| -| `brave_search`, `firecrawl`, `exa_search`, `tavily_search`, `ref_search`, `perplexity`, `jina` (`string \| boolean \| null`) | a bool setting that forces the source on or off, with no default under any of the seven (unset: detected from the key's presence, as GSD does at `config-new-project`; GSD also detects from `~/.gsd/<name>_api_key` files, which the environment-only secrets do not read), and a secret read from `BRAVE_API_KEY`, `FIRECRAWL_API_KEY`, `EXA_API_KEY`, `TAVILY_API_KEY`, `REF_API_KEY`, `PERPLEXITY_API_KEY`, `JINA_API_KEY`, named `<flag>_key` (`brave_search_key`, `firecrawl_key`, `exa_search_key`, `tavily_search_key`, `ref_search_key`, `perplexity_key`, `jina_key`) because the kernel refuses a secret that shares a setting's name; `specforge gsd import` moves a string value out to the environment and reports it | +| `brave_search`, `firecrawl`, `exa_search`, `tavily_search`, `ref_search`, `perplexity`, `jina` (`string \| boolean \| null`) | a bool setting that forces the source on or off, with no default under any of the seven (unset: detected from the key's presence, as GSD does at `config-new-project`; GSD also detects from `~/.gsd/<name>_api_key` files, which the environment-only secrets do not read), and a secret read from `BRAVE_API_KEY`, `FIRECRAWL_API_KEY`, `EXA_API_KEY`, `TAVILY_API_KEY`, `REF_API_KEY`, `PERPLEXITY_API_KEY`, `JINA_API_KEY`, named `<flag>_key` (`brave_search_key`, `firecrawl_key`, `exa_search_key`, `tavily_search_key`, `ref_search_key`, `perplexity_key`, `jina_key`) because the kernel refuses a secret that shares a setting's name; `specforge gsd import` prints the flag and reports the variable to export, never the value | | `model_profile_overrides.<runtime>.<tier>` (`string \| object`) | the block `{model str R, reasoning_effort enum}`; the import rewrites a bare string to `{model}` | | a key GSD leaves unset (`(none)`, `null`, _unset_, or a capability's empty string or `-1`) | no default; `null` is unset | | `resolve_model_ids` (`false \| true \| "omit"`) | an enum `aliases \| ids \| omit`, default `aliases`; the import maps `false`, `true` and `"omit"` | @@ -56,7 +56,7 @@ partner could satisfy `critical < warning`; the pair itself is not checked, as G (the model leaves them unset; GSD treats any non-positive value as unset too, and only `-1` is accepted here). A `number` setting (ADR 0305) takes a whole or a decimal number within whole-number bounds: `hooks.context_warning_threshold` (1-100) and `hooks.context_critical_threshold` (0-99) are numbers. The other settings GSD's capabilities declare as `number` (`7.5`, `1.5` seconds) are whole numbers here; the bounds of a number are whole, so `99.5` is within the critical bound. `worktree.baseRef` is declared here, but GSD keeps it in `.claude/settings.local.json`, not `.planning/config.json` -(`docs/CONFIGURATION.md`), so `specforge gsd import` reads it from there. +(`docs/CONFIGURATION.md`), outside `.planning/`, so `specforge gsd import` reports it and does not read it. Where `docs/CONFIGURATION.md` and the defaults manifest disagree, the manifest wins (`workflow.inline_plan_threshold` is 2, the docs say 3). A host URL whose capability default is empty and whose documented default is a URL (`review.ollama_host`) takes the documented one. @@ -86,7 +86,7 @@ setting. | Profile | Behaves as | |---|---| | `gsd-compat` (default) | GSD at the tracked version: every rule GSD only warns about warns, every check GSD leaves to a prompt is still judged but does not block. The parity suite runs on it. | -| `gsd-strict` | the same rules, blocking where GSD warns: same-wave file conflicts, a stale plan-check verdict, a backstop truth without evidence, and an open broken window at ship; and, beyond GSD, a verdict that is not fresh at any step (gsd/E516), a complete requirement no commit and passing test trace (gsd/E515) and a task commit without its `Gsd-Task:` trailer (gsd/E521). | +| `gsd-strict` | the same rules, blocking where GSD warns: same-wave file conflicts, a stale plan-check verdict, a backstop truth without evidence, and an open broken window at ship; and, beyond GSD, a verdict that is not fresh at any step (gsd/E516), a complete requirement no commit and passing test trace (gsd/E515), a task commit without its `Gsd-Task:` trailer (gsd/E521), and, at the milestone close, a breaking API change without a major version bump (gsd/E533) and release evidence that does not match the milestone (gsd/E535). | | `gsd-plus` | strict, and cross-workstream conflict detection (gsd/E517). | A profile presets these settings: @@ -100,6 +100,8 @@ A profile presets these settings: | `specforge.cross_workstream_conflicts` | false | false | true | | `specforge.plan_paths_touched` | false | true | true | | `specforge.task_trailers` | false | true | true | +| `specforge.interface_gate` | false | true | true | +| `specforge.release_gate` | false | true | true | ## Other presets @@ -118,7 +120,9 @@ below are bool, default false, and each gates rules ([rules.md](rules.md#setting `specforge.agent_variant`, gates none: it is an enum, `full` (the default) or `compact`, that picks the body of the ten agents that have a compact variant (codex and cursor; Claude Code always renders the full body, as upstream installs no compact agent for it). It is an enum -because the host takes a variant setting only as a string or enum; `workflow.compact_content` presets it. +because the host takes a variant setting only as a string or enum; `workflow.compact_content` presets it. Another, +`specforge.release_exempt`, gates none either: a string list, empty by default, of the package names gsd/E535 does +not judge (packages the milestone does not release, such as a workspace's internal crates). | Setting | Switches on | |---|---| @@ -128,6 +132,8 @@ because the host takes a variant setting only as a string or enum; `workflow.com | `specforge.cross_workstream_conflicts` | active plans of different workstreams share no file (gsd/E517) | | `specforge.plan_paths_touched` | a complete plan's commits touched every path it planned, and the files it deletes are gone (gsd/W520) | | `specforge.task_trailers` | a task commit names its task by its `Gsd-Task:` trailer (gsd/E521) | +| `specforge.interface_gate` | a milestone that changes, narrows or removes an API item bumps its major version over the last shipped one (gsd/E533) | +| `specforge.release_gate` | a milestone's packages are at its version, its version is later than the last shipped one, and that one's tag resolves (gsd/E535) | Ten more are bool, default **true**, and show or hide skills: `specforge.surface.<cluster>` for each of GSD's skill clusters (`core_loop`, `audit_review`, `milestone`, `research_ideate`, `workspace_state`, `docs`, `ui`, `ai_eval`, diff --git a/gsd/core/src/codes.rs b/gsd/core/src/codes.rs index 5bdc5b2195..6bd48c66b3 100644 --- a/gsd/core/src/codes.rs +++ b/gsd/core/src/codes.rs @@ -694,6 +694,22 @@ pub static CODES: &[Code] = &[ Severity::Warning, Severity::Error, ), + code( + "E533", + "Breaking API change without a major version bump", + "A milestone whose API facts show a changed, narrowed or removed item is closed while its version is API-compatible with the last shipped milestone of its workstream scope (Cargo's rule: for 0.x the minor counts as major), or while its name is not a version, so no major bump can be shown", + "project-and-roadmap", + Severity::Error, + Severity::Error, + ), + code( + "E535", + "Release evidence does not match the milestone", + "A milestone named by its version is closed while a package fact's version is not its version, while its version is not later than the last shipped milestone of its workstream scope, or while the last shipped milestone's tag does not resolve to a commit", + "project-and-roadmap", + Severity::Error, + Severity::Error, + ), ]; pub fn declare(c: &mut ContributionsBuilder) { diff --git a/gsd/core/src/collectors/git.rs b/gsd/core/src/collectors/git.rs index e5432d643a..8ff706eb43 100644 --- a/gsd/core/src/collectors/git.rs +++ b/gsd/core/src/collectors/git.rs @@ -30,6 +30,8 @@ //! lines no answer holds, the field is left unwritten (the plan's title names the commit), never written short: it is //! immutable once written. //! +//! It also records whether each shipped milestone's release tag `v<version>` resolves (`milestone.tag`, see [`tags`]). +//! //! What a commit says is untrusted: control characters in a subject or a path become U+FFFD, and a commit whose time //! is out of range is skipped and named in the plan's title. The host refuses a whole plan for one value it cannot //! write, so one bad commit must never reach it. @@ -38,6 +40,7 @@ mod items; mod subject; +mod tags; #[cfg(test)] mod tests; mod trailer; @@ -663,9 +666,10 @@ fn collect(input: &CollectInput) -> Result<CollectOutput, String> { ); recorded += 1; } + let tagged = tags::plan(nodes, &repo, &mut builder)?; skipped.dedup(); let mut output = CollectOutput::default(); - if recorded > 0 || backfilled > 0 { + if recorded > 0 || backfilled > 0 || tagged > 0 { let mut note = if skipped.is_empty() { String::new() } else { @@ -695,6 +699,12 @@ fn collect(input: &CollectInput) -> Result<CollectOutput, String> { plural(backfilled) )); } + if tagged > 0 { + title.push(format!( + "record the tag of {tagged} shipped milestone{}", + plural(tagged) + )); + } let mut title = title.join("; "); title[..1].make_ascii_uppercase(); builder.title(&format!("{title}{note}")); diff --git a/gsd/core/src/collectors/git/tags.rs b/gsd/core/src/collectors/git/tags.rs new file mode 100644 index 0000000000..ea4b3aa093 --- /dev/null +++ b/gsd/core/src/collectors/git/tags.rs @@ -0,0 +1,62 @@ +//! A shipped milestone's `tag` (ADR 0390 D6): GSD tags a release `v<version>` after its close, and `gsd-git` records +//! whether that tag resolves, for `derive` to copy into `milestone.release` and `gsd/E535` to judge. A pass never asks +//! the git port (ADR 0335 D4): this collector does, once per shipped milestone whose name is a version, with the port's +//! `commit` verb on `refs/tags/v<version>` (an annotated tag resolves to its commit), the version as the name wrote it +//! (`v2026.01`, the tag GSD creates). The revision is built from the parsed version alone, digits and dots, so no +//! other text of a milestone's name reaches the port. +//! +//! No observation writes nothing: a shallow clone holds no tags, and with `git.create_tag` false GSD tags no release. + +use serde_json::{Value, json}; +use specforge_extension_sdk::host::{GitRepo, git}; +use specforge_extension_sdk::prelude::*; + +use super::said; +use crate::passes::plans::name_of; +use crate::release::parse; + +/// Sets each shipped milestone's `tag` where it changed; the count set. +pub(super) fn plan( + nodes: &[GraphNode], + repo: &GitRepo, + builder: &mut PlanBuilder, +) -> Result<usize, String> { + let create_tag = Settings::current().bool("git.create_tag") != Some(false); + let sets = tags(nodes, repo.shallow, create_tag)?; + for (milestone, tag) in &sets { + builder.set(milestone, "tag", tag.clone()); + } + Ok(sets.len()) +} + +/// The `tag` of each shipped milestone whose name is a version, `{name, commit}` with `commit` absent when the tag +/// resolves to none, where it differs from the one the milestone holds. +pub(super) fn tags( + nodes: &[GraphNode], + shallow: bool, + create_tag: bool, +) -> Result<Vec<(String, Value)>, String> { + if shallow || !create_tag { + return Ok(Vec::new()); + } + let mut sets = Vec::new(); + for node in nodes + .iter() + .filter(|n| n.kind == "milestone" && n.fields.contains_key("completion")) + { + let Some(version) = parse(name_of(&node.id)) else { + continue; + }; + let name = format!("v{version}"); + let commit = git::commit(&format!("refs/tags/v{version}")) + .map_err(|e| said(&format!("read the tag {name}"), &e))?; + let tag = match commit { + Some(commit) => json!({ "name": name, "commit": commit }), + None => json!({ "name": name }), + }; + if node.fields.get("tag") != Some(&tag) { + sets.push((node.id.clone(), tag)); + } + } + Ok(sets) +} diff --git a/gsd/core/src/collectors/git/tests.rs b/gsd/core/src/collectors/git/tests.rs index 2c7a04576d..16b0508c78 100644 --- a/gsd/core/src/collectors/git/tests.rs +++ b/gsd/core/src/collectors/git/tests.rs @@ -12,6 +12,7 @@ use super::*; mod items; mod port; mod serve; +mod tags; mod trailers; pub(super) use serve::served; @@ -126,6 +127,9 @@ pub(super) struct Repo { pub(super) room: Option<usize>, pub(super) logs: std::cell::Cell<usize>, pub(super) asked: std::cell::RefCell<Vec<GitDiffQuery>>, + /// Each tag's commit, by its name (`v1.7`), and whether the clone is shallow. + pub(super) tags: HashMap<String, String>, + pub(super) shallow: bool, } impl InProcessHost for Repo { @@ -135,10 +139,13 @@ impl InProcessHost for Repo { } Ok(Some(GitRepo { toplevel: self.top.clone(), - shallow: false, + shallow: self.shallow, })) } fn git_commit(&self, revision: &str) -> Result<Option<String>, HostError> { + if let Some(tag) = revision.strip_prefix("refs/tags/") { + return Ok(self.tags.get(tag).cloned()); + } assert_eq!(revision, "HEAD"); Ok(self.log.first().map(|c| c.sha.clone())) } diff --git a/gsd/core/src/collectors/git/tests/tags.rs b/gsd/core/src/collectors/git/tests/tags.rs new file mode 100644 index 0000000000..9eb19cc75c --- /dev/null +++ b/gsd/core/src/collectors/git/tests/tags.rs @@ -0,0 +1,131 @@ +//! A shipped milestone's `tag`, read from `refs/tags/v<version>` (ADR 0390 D6). + +use super::super::tags::tags; +use super::*; + +const SHA: &str = "1111111111111111111111111111111111111111"; + +/// A milestone, shipped when `shipped`. +fn milestone(id: &str, shipped: bool) -> GraphNode { + let mut node = node(id, "milestone", id); + if shipped { + node.fields + .insert("completion".into(), json!({ "at": "2026-02-01" })); + } + node +} + +/// The `tag` each milestone is set to, collecting over `repo` (one commit no plan names) and `milestones`. +fn tagged(repo: Repo, milestones: Vec<GraphNode>) -> Vec<(String, Value)> { + let mut graph = plan_graph().expect("a graph"); + graph.nodes.extend(milestones); + let input = CollectInput { + graph: Some(graph), + ..Default::default() + }; + let repo = Repo { + log: vec![logged(&"a".repeat(40), &[], 10, "chore: tidy", &[])], + ..repo + }; + let output = served(repo, &input).0.expect("an answer"); + output + .plan + .iter() + .flat_map(|plan| &plan.ops) + .filter_map(|op| match op { + PlanOp::Set { + entity, + field, + value, + .. + } if field == "tag" => Some((entity.clone(), value.clone())), + _ => None, + }) + .collect() +} + +fn tagged_v17() -> Repo { + Repo { + tags: HashMap::from([("v1.7".to_string(), SHA.to_string())]), + ..Repo::default() + } +} + +#[test] +fn tags_of_a_shipped_version_record_the_commit_it_resolves_to() { + let set = tagged( + tagged_v17(), + vec![ + milestone("v1.7", true), + milestone("v1.8", false), + milestone("mvp", true), + ], + ); + assert_eq!( + set, + [("v1.7".to_string(), json!({ "name": "v1.7", "commit": SHA }))] + ); +} + +#[test] +fn tags_that_do_not_resolve_are_recorded_without_a_commit() { + let set = tagged( + Repo::default(), + vec![milestone("v1.7", true), milestone("a/1.7.2", true)], + ); + assert_eq!( + set, + [ + ("v1.7".to_string(), json!({ "name": "v1.7" })), + ("a/1.7.2".to_string(), json!({ "name": "v1.7.2" })), + ] + ); +} + +#[test] +fn tags_of_a_zero_padded_version_look_up_the_name_as_written() { + let repo = Repo { + tags: HashMap::from([("v2026.01".to_string(), SHA.to_string())]), + ..Repo::default() + }; + let set = tagged(repo, vec![milestone("v2026.01", true)]); + assert_eq!( + set, + [( + "v2026.01".to_string(), + json!({ "name": "v2026.01", "commit": SHA }) + )] + ); +} + +#[test] +fn tags_already_held_are_not_set_again() { + let mut held = milestone("v1.7", true); + held.fields + .insert("tag".into(), json!({ "name": "v1.7", "commit": SHA })); + assert!(tagged(tagged_v17(), vec![held]).is_empty()); +} + +#[test] +fn tags_are_not_read_on_a_shallow_clone_or_while_git_create_tag_is_false() { + let shallow = Repo { + shallow: true, + ..tagged_v17() + }; + assert!(tagged(shallow, vec![milestone("v1.7", true)]).is_empty()); + // No port is asked: this runs with no host. + assert_eq!( + tags(&[milestone("v1.7", true)], false, false), + Ok(Vec::new()) + ); +} + +#[test] +fn tags_ask_nothing_for_a_name_that_is_no_version() { + // The fake repository answers `refs/tags/<t>` for any `t`: a name that does not parse asks nothing at all. + let names = ["v1.7;rm -rf", "v1.7^{tree}", "--all", "v1.7 HEAD", "mvp"]; + let milestones = names.iter().map(|n| milestone(n, true)).collect(); + assert!(tagged(tagged_v17(), milestones).is_empty()); + let nodes: Vec<GraphNode> = names.iter().map(|n| milestone(n, true)).collect(); + assert_eq!(tags(&nodes, false, true), Ok(Vec::new())); +} diff --git a/gsd/core/src/commands/milestone.rs b/gsd/core/src/commands/milestone.rs index 0e654d780b..734e4b8fcb 100644 --- a/gsd/core/src/commands/milestone.rs +++ b/gsd/core/src/commands/milestone.rs @@ -91,6 +91,8 @@ pub fn declare(c: &mut ContributionsBuilder) { .gate("E511") .gate("E515") .gate("E516") + .gate("E533") + .gate("E535") .subject("milestone") .arg("milestone", |a| { a.required().description("the milestone (its id, or a short form that is not ambiguous)"); diff --git a/gsd/core/src/commands/mod.rs b/gsd/core/src/commands/mod.rs index 15afc39160..99d9e3bde8 100644 --- a/gsd/core/src/commands/mod.rs +++ b/gsd/core/src/commands/mod.rs @@ -39,11 +39,12 @@ use specforge_extension_sdk::prelude::*; /// The harness fields and the one thing that writes each: `(kind, field, writer)`. A writer is a writing command, or /// the collector `gsd-git` for a commit's fields but its `waiver`, which `waive_trailer` writes (a person's, never the -/// collector's). `tests/writer_roster.rs` pins the table against the `H` fields the kinds declare. `record_window` is -/// the writer of a window's `recorded_at`; `propose_refactor` also stamps it on the deviation window it creates under -/// `refactor.trigger_strict`. +/// collector's), and for a milestone's `tag` (ADR 0390 D6). `tests/writer_roster.rs` pins the table against the `H` +/// fields the kinds declare. `record_window` is the writer of a window's `recorded_at`; `propose_refactor` also stamps +/// it on the deviation window it creates under `refactor.trigger_strict`. pub const WRITERS: &[(&str, &str, &str)] = &[ ("milestone", "completion", "close_milestone"), + ("milestone", "tag", "gsd-git"), ("checkpoint", "answer", "answer_checkpoint"), ("user_setup", "done", "confirm_setup"), ("plan_start", "at", "start_plan"), diff --git a/gsd/core/src/kinds/roadmap.rs b/gsd/core/src/kinds/roadmap.rs index 59b218b175..ee55f32fea 100644 --- a/gsd/core/src/kinds/roadmap.rs +++ b/gsd/core/src/kinds/roadmap.rs @@ -19,6 +19,14 @@ const PROGRESS: &[Field] = &[ int("plans_complete"), int("percent"), ]; +const OFF_PACKAGE: &[Field] = &[str("name"), str("version")]; +const RELEASE: &[Field] = &[ + str("tag"), + str("commit"), + blocks("packages", OFF_PACKAGE), + int("more"), +]; +const TAG: &[Field] = &[str("name"), str("commit")]; const MILESTONE_STATE: &[&str] = &["planned", "in_progress", "shipped", "abandoned"]; /// A milestone section of `ROADMAP.md`, named `v1.0` and scoped by its workstream when it has one. Its title is its @@ -61,6 +69,19 @@ pub const MILESTONE: Kind = Kind::new( str("branch") .c() .doc("the branch it is executed on: git.branching_strategy and its template"), + strs("api_breaks").c().doc( + "the API items the last collect found changed, narrowed or removed against the committed accepted \ + report: `<change> <id>`; absent when no API fact carries a change; gsd/E533 reads it", + ), + block("release", RELEASE).c().doc( + "the release evidence gsd/E535 reads: `tag` and `commit` the recorded tag of a shipped milestone, \ + `packages` the `name` and `version` of each package fact not at an open milestone's version, at most 50, \ + and `more` the count past them; absent when nothing was observed", + ), + block("tag", TAG).h().doc( + "written by gsd-git from `refs/tags/v<version>` for a shipped milestone named by its version: the tag's \ + `name`, and the `commit` it resolves to, absent when it resolves to none", + ), ], ) .scoped_by("workstream"); diff --git a/gsd/core/src/lib.rs b/gsd/core/src/lib.rs index b8523f1a60..bba5833f30 100644 --- a/gsd/core/src/lib.rs +++ b/gsd/core/src/lib.rs @@ -16,6 +16,7 @@ mod passes; mod probe; pub mod prompts; mod quick_id; +mod release; mod relocation; mod route; mod rules; diff --git a/gsd/core/src/passes/derive/interface.rs b/gsd/core/src/passes/derive/interface.rs new file mode 100644 index 0000000000..a67bd6816d --- /dev/null +++ b/gsd/core/src/passes/derive/interface.rs @@ -0,0 +1,52 @@ +//! A milestone's `api_breaks` (ADR 0390 D4): a selection of the `@code/core` `api_item` facts, which the API packs +//! classified against the committed accepted report. Each fact whose `change` is `changed`, `narrowed` or `removed` +//! is one `<change> <id>` line, the id as the fact holds it (the guard escapes what it prints), sorted by id, at most +//! [`LINES`] then one `more <N>` line; `added`, `unchanged` and any later value never count. Written on each milestone neither shipped nor abandoned, and only when some fact carries +//! a `change` at all: absent means never observed, empty means clean. It reflects the facts of the last collect; +//! `gsd/E533` reads it at the close. + +use specforge_extension_sdk::prelude::*; + +use super::execute::value; +use crate::passes::plans::{of_kind, text}; + +/// `@code/core`'s kind, named once as `thread.rs` names `test`. +pub const API_ITEM: &str = "api_item"; +const LINES: usize = 50; + +/// How the packs judged an item against the accepted report; `None` when no accepted report covered it. +fn change(item: &PassEntity) -> Option<&str> { + text(item, "change") +} + +pub fn values(input: &PassInput) -> Vec<PassValue> { + let items: Vec<&PassEntity> = of_kind(input, API_ITEM).collect(); + if !items.iter().any(|i| change(i).is_some()) { + return Vec::new(); + } + let mut broken: Vec<(&str, &str)> = items + .iter() + .filter_map(|i| { + change(i) + .filter(|c| matches!(*c, "changed" | "narrowed" | "removed")) + .map(|c| (i.id.as_str(), c)) + }) + .collect(); + broken.sort(); + let more = broken.len().saturating_sub(LINES); + let mut lines: Vec<String> = broken + .iter() + .take(LINES) + .map(|(id, c)| format!("{c} {id}")) + .collect(); + if more > 0 { + lines.push(format!("more {more}")); + } + of_kind(input, "milestone") + .filter(|m| !m.fields.contains_key("abandoned") && !m.fields.contains_key("completion")) + .map(|m| value(&m.id, "api_breaks", lines.clone())) + .collect() +} + +#[cfg(test)] +mod tests; diff --git a/gsd/core/src/passes/derive/interface/tests.rs b/gsd/core/src/passes/derive/interface/tests.rs new file mode 100644 index 0000000000..db99d9c8c2 --- /dev/null +++ b/gsd/core/src/passes/derive/interface/tests.rs @@ -0,0 +1,95 @@ +use serde_json::{Value, json}; + +use super::*; + +fn item(id: &str, change: Option<&str>) -> Value { + let fields = change.map_or_else(|| json!({ "item": id }), |c| json!({ "change": c })); + json!({ "id": id, "kind": "api_item", "fields": fields }) +} + +/// v1.7 shipped, v1.8 open, v1.9 abandoned, then `items`. +fn input(items: Vec<Value>) -> PassInput { + let mut entities = vec![ + json!({ "id": "v1.7", "kind": "milestone", "fields": { "completion": "at 2026-02-01" }, + "values": { "completion": { "at": "2026-02-01" } } }), + json!({ "id": "v1.8", "kind": "milestone" }), + json!({ "id": "v1.9", "kind": "milestone", "fields": { "abandoned": "reason gone" } }), + ]; + entities.extend(items); + serde_json::from_value(json!({ "entities": entities, "edges": [] })).expect("a pass input") +} + +fn breaks(found: &[PassValue]) -> Vec<(&str, Value)> { + found + .iter() + .map(|v| (v.entity.as_str(), v.value.clone())) + .collect() +} + +#[test] +fn api_breaks_of_e533_lists_a_removed_item_on_the_open_milestone_only() { + let found = values(&input(vec![ + item("api:rust:a::f", Some("removed")), + item("api:rust:a::g", Some("unchanged")), + item("api:rust:a::h", Some("added")), + ])); + assert_eq!(breaks(&found), [("v1.8", json!(["removed api:rust:a::f"]))]); +} + +#[test] +fn api_breaks_of_e533_is_empty_when_every_judged_item_is_clean() { + let found = values(&input(vec![ + item("api:rust:a::f", Some("unchanged")), + item("api:rust:a::g", None), + ])); + assert_eq!(breaks(&found), [("v1.8", json!([]))]); +} + +#[test] +fn api_breaks_of_e533_is_absent_without_an_accepted_side() { + assert!(values(&input(vec![item("api:rust:a::f", None)])).is_empty()); + assert!(values(&input(vec![])).is_empty()); +} + +#[test] +fn api_breaks_of_e533_sorts_by_id_and_keeps_the_three_breaking_changes() { + let found = values(&input(vec![ + item("api:rust:a::z", Some("narrowed")), + item("api:rust:a::b", Some("changed")), + item("api:rust:a::m", Some("removed")), + item("api:rust:a::q", Some("renamed")), + ])); + assert_eq!( + breaks(&found), + [( + "v1.8", + json!([ + "changed api:rust:a::b", + "removed api:rust:a::m", + "narrowed api:rust:a::z" + ]) + )] + ); +} + +#[test] +fn api_breaks_of_e533_caps_at_50_lines_then_one_more_line() { + let items = (0..60) + .map(|i| item(&format!("api:rust:a::f{i:02}"), Some("removed"))) + .collect(); + let found = values(&input(items)); + let lines = found[0].value.as_array().expect("a list"); + assert_eq!(lines.len(), 51); + assert_eq!(lines[49], "removed api:rust:a::f49"); + assert_eq!(lines[50], "more 10"); +} + +#[test] +fn api_breaks_of_e533_keeps_each_id_as_the_fact_holds_it() { + // Escaped once, by the guard that prints it (`gates/release/tests.rs`). + let found = values(&input(vec![item("api:rust:a::f\nb`'", Some("changed"))])); + assert_eq!( + breaks(&found), + [("v1.8", json!(["changed api:rust:a::f\nb`'"]))] + ); +} diff --git a/gsd/core/src/passes/derive/mod.rs b/gsd/core/src/passes/derive/mod.rs index 0adbbfb8ae..11b43c9183 100644 --- a/gsd/core/src/passes/derive/mod.rs +++ b/gsd/core/src/passes/derive/mod.rs @@ -12,8 +12,9 @@ //! answers a plan's slices under the smart-zone budget, `estimate_error` how far a completed plan's estimate was from //! what it took, and `critical_path` a phase's heaviest chain of plans along the //! strict waves (`passes::waves`) and its weight. `review` answers a review concern's status, a round's open -//! counts and a revision conflict's status, `batch` a quick batch's status and eligible items, and `learning` a -//! lesson's status. +//! counts and a revision conflict's status, `batch` a quick batch's status and eligible items, `learning` a +//! lesson's status, `interface` a milestone's `api_breaks` from the `@code/core` `api_item` facts, and `release` its +//! release evidence from the `package` facts. //! //! Not answered, by design: `phase.frontend` (`@gsd/ui`'s detection) and `retrospective.sessions` (no harness). @@ -25,9 +26,11 @@ mod estimate; mod estimate_error; mod execute; mod halt; +pub(crate) mod interface; pub mod ladder; mod learning; mod progress; +pub(crate) mod release; mod requirement; mod review; pub(crate) mod uat; @@ -52,7 +55,11 @@ pub fn declare(c: &mut ContributionsBuilder) { "verify_gap", "override", ]) - .input(Input::facts(&[crate::passes::thread::TEST])) + .input(Input::facts(&[ + crate::passes::thread::TEST, + interface::API_ITEM, + release::PACKAGE, + ])) .run(derive); }); } @@ -82,6 +89,8 @@ fn derive(input: &PassInput) -> PassOutput { values.extend(estimate_error::values(input)); values.extend(critical_path::values(input)); values.extend(review::values(input)); + values.extend(interface::values(input)); + values.extend(release::values(input)); let diagnostics = branch::diagnostics(input); PassOutput { values, diff --git a/gsd/core/src/passes/derive/release.rs b/gsd/core/src/passes/derive/release.rs new file mode 100644 index 0000000000..cdbf93d4e2 --- /dev/null +++ b/gsd/core/src/passes/derive/release.rs @@ -0,0 +1,84 @@ +//! A milestone's `release` (ADR 0390 D6): the release evidence `gsd/E535` reads. On each milestone neither shipped nor +//! abandoned whose name is a version, `packages` holds the `name` and `version` of every `@code/core` `package` fact +//! whose version is not the milestone's ([`crate::release::matches`]) and whose name is not in +//! `specforge.release_exempt`, sorted, at most [`LINES`], and `more` counts the rest (absent when none): two +//! members, so no package name, not even `more` or one with a space, reads as the count. Name and version are as the +//! facts hold them (the guard escapes what it prints). Written only when some package fact carries a version: absent +//! means never observed, empty means clean. A package with no version is not judged. It reflects the facts of the last +//! collect. On a shipped milestone, `tag` and `commit` copy the `tag` `gsd-git` recorded, unless `git.create_tag` is +//! false (GSD then tags no release). + +use serde_json::{Value, json}; +use specforge_extension_sdk::prelude::*; + +use super::execute::value; +use crate::passes::plans::{name_of, of_kind, text}; +use crate::release::{matches, parse}; + +/// `@code/core`'s kind, named once as `thread.rs` names `test`. +pub const PACKAGE: &str = "package"; +const LINES: usize = 50; + +pub fn values(input: &PassInput) -> Vec<PassValue> { + let settings = Settings::current(); + let exempt: Vec<&str> = settings + .get("specforge.release_exempt") + .and_then(Value::as_array) + .map(|names| names.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + let mut values = release(input, &exempt); + if settings.bool("git.create_tag") != Some(false) { + values.extend(tagged(input)); + } + values +} + +/// A shipped milestone's `release` copies the tag `gsd-git` recorded (`milestone.tag`): its `name` as `tag`, and its +/// `commit`, absent when the tag resolves to none. Absent when no tag was recorded. +fn tagged(input: &PassInput) -> Vec<PassValue> { + of_kind(input, "milestone") + .filter(|m| !m.fields.contains_key("abandoned") && m.fields.contains_key("completion")) + .filter_map(|m| { + let tag = m.values.get("tag")?; + let name = tag.get("name")?.as_str()?; + let mut release = json!({ "tag": name }); + if let Some(commit) = tag.get("commit").and_then(Value::as_str) { + release["commit"] = json!(commit); + } + Some(value(&m.id, "release", release)) + }) + .collect() +} + +fn release(input: &PassInput, exempt: &[&str]) -> Vec<PassValue> { + let packages: Vec<(&str, &str)> = of_kind(input, PACKAGE) + .filter_map(|p| Some((text(p, "name").unwrap_or(&p.id), text(p, "version")?))) + .collect(); + if packages.is_empty() { + return Vec::new(); + } + of_kind(input, "milestone") + .filter(|m| !m.fields.contains_key("abandoned") && !m.fields.contains_key("completion")) + .filter_map(|m| { + let version = parse(name_of(&m.id))?; + let mut off: Vec<&(&str, &str)> = packages + .iter() + .filter(|(name, v)| !matches(&version, v) && !exempt.contains(name)) + .collect(); + off.sort(); + let listed: Vec<Value> = off + .iter() + .take(LINES) + .map(|(name, v)| json!({ "name": name, "version": v })) + .collect(); + let mut release = json!({ "packages": listed }); + if off.len() > LINES { + release["more"] = json!(off.len() - LINES); + } + Some(value(&m.id, "release", release)) + }) + .collect() +} + +#[cfg(test)] +mod tests; diff --git a/gsd/core/src/passes/derive/release/tests.rs b/gsd/core/src/passes/derive/release/tests.rs new file mode 100644 index 0000000000..3fc39e1960 --- /dev/null +++ b/gsd/core/src/passes/derive/release/tests.rs @@ -0,0 +1,171 @@ +use serde_json::{Value, json}; + +use super::*; + +fn package(name: &str, version: Option<&str>) -> Value { + let fields = version.map_or_else( + || json!({ "name": name }), + |v| json!({ "name": name, "version": v }), + ); + json!({ "id": format!("pkg:cargo/{name}"), "kind": "package", "fields": fields }) +} + +/// v1.7 shipped, v1.8 open, v1.9 abandoned, `mvp` open, then `facts`. +fn input(facts: Vec<Value>) -> PassInput { + let mut entities = vec![ + json!({ "id": "v1.7", "kind": "milestone", "fields": { "completion": "at 2026-02-01" } }), + json!({ "id": "v1.8", "kind": "milestone" }), + json!({ "id": "v1.9", "kind": "milestone", "fields": { "abandoned": "reason gone" } }), + json!({ "id": "mvp", "kind": "milestone" }), + ]; + entities.extend(facts); + serde_json::from_value(json!({ "entities": entities, "edges": [] })).expect("a pass input") +} + +fn released(found: &[PassValue]) -> Vec<(&str, Value)> { + found + .iter() + .map(|v| (v.entity.as_str(), v.value.clone())) + .collect() +} + +fn packages() -> Vec<Value> { + vec![ + package("a", Some("1.8.0")), + package("b", Some("1.7.0")), + package("c", None), + ] +} + +#[test] +fn release_of_e535_lists_the_package_not_at_the_open_milestones_version() { + let found = release(&input(packages()), &[]); + assert_eq!( + released(&found), + [( + "v1.8", + json!({ "packages": [{ "name": "b", "version": "1.7.0" }] }) + )] + ); +} + +#[test] +fn release_of_e535_skips_an_exempt_package() { + let found = release(&input(packages()), &["b"]); + assert_eq!(released(&found), [("v1.8", json!({ "packages": [] }))]); +} + +#[test] +fn release_of_e535_is_absent_without_a_versioned_package() { + assert!(release(&input(vec![package("c", None)]), &[]).is_empty()); + assert!(release(&input(vec![]), &[]).is_empty()); +} + +#[test] +fn release_of_e535_caps_its_lines_and_keeps_them_raw() { + let mut facts: Vec<Value> = (0..53) + .map(|n| package(&format!("p{n:02}"), Some("0.1.0"))) + .collect(); + facts.push(package("z\u{1b}[2J", Some("1.0"))); + let found = release(&input(facts), &[]); + let listed = found[0].value["packages"] + .as_array() + .expect("a list") + .clone(); + assert_eq!(listed.len(), 50); + assert_eq!(listed[0], json!({ "name": "p00", "version": "0.1.0" })); + assert_eq!(found[0].value["more"], 4); + let found = release(&input(vec![package("z\u{1b}", Some("1.\u{7}0"))]), &[]); + assert_eq!( + found[0].value, + json!({ "packages": [{ "name": "z\u{1b}", "version": "1.\u{7}0" }] }) + ); +} + +#[test] +fn release_of_e535_holds_a_package_named_more_or_with_a_space_as_a_package() { + let found = release( + &input(vec![ + package("more", Some("5")), + package("my crate", Some("0.1.0")), + ]), + &[], + ); + assert_eq!( + found[0].value, + json!({ "packages": [ + { "name": "more", "version": "5" }, + { "name": "my crate", "version": "0.1.0" }, + ] }) + ); +} + +/// The `release` values the `derive` pass answers over v1.7, shipped with a recorded tag, and the package `b` at +/// 1.7.0, under the `@gsd/core` `settings` the call carries. +fn derived_release(settings: Value) -> Vec<(String, Value)> { + let call = json!({ + "entities": [ + { "id": "v1.7", "kind": "milestone", "fields": { "completion": "at 2026-02-01", "tag": "name" }, + "values": { "tag": { "name": "v1.7" } } }, + { "id": "v1.8", "kind": "milestone" }, + package("b", Some("1.7.0")), + ], + "edges": [], + "settings": settings, + }); + let answer = crate::build() + .dispatch_export("__pass_derive", call.to_string().as_bytes()) + .expect("the derive pass") + .expect("an answer"); + let output: Value = serde_json::from_slice(&answer).expect("JSON"); + output["values"] + .as_array() + .expect("values") + .iter() + .filter(|v| v["field"] == "release") + .map(|v| { + ( + v["entity"].as_str().expect("an id").to_string(), + v["value"].clone(), + ) + }) + .collect() +} + +#[test] +fn release_values_copy_no_tag_while_git_create_tag_is_false() { + let package = json!({ "packages": [{ "name": "b", "version": "1.7.0" }] }); + assert_eq!( + derived_release(json!({})), + [ + ("v1.8".to_string(), package.clone()), + ("v1.7".to_string(), json!({ "tag": "v1.7" })), + ] + ); + assert_eq!( + derived_release(json!({ "git.create_tag": false })), + [("v1.8".to_string(), package)] + ); +} + +#[test] +fn release_of_e535_copies_a_shipped_milestones_recorded_tag() { + let entities = vec![ + json!({ "id": "v1.6", "kind": "milestone", "fields": { "completion": "at 2026-01-01", "tag": "name, commit" }, + "values": { "tag": { "name": "v1.6", "commit": "abc" } } }), + json!({ "id": "v1.7", "kind": "milestone", "fields": { "completion": "at 2026-02-01", "tag": "name" }, + "values": { "tag": { "name": "v1.7" } } }), + json!({ "id": "v1.5", "kind": "milestone", "fields": { "completion": "at 2025-12-01" } }), + json!({ "id": "v1.8", "kind": "milestone", "fields": { "tag": "name" }, + "values": { "tag": { "name": "v1.8" } } }), + ]; + let input: PassInput = + serde_json::from_value(json!({ "entities": entities, "edges": [] })).expect("a pass input"); + assert_eq!( + released(&tagged(&input)), + [ + ("v1.6", json!({ "tag": "v1.6", "commit": "abc" })), + ("v1.7", json!({ "tag": "v1.7" })), + ] + ); +} diff --git a/gsd/core/src/passes/gates.rs b/gsd/core/src/passes/gates.rs index 6448580d4f..ec87f14f69 100644 --- a/gsd/core/src/passes/gates.rs +++ b/gsd/core/src/passes/gates.rs @@ -1,5 +1,5 @@ -//! The gate guards: `gsd/E106`, `E511`, `E512`, `W318`, `W404`, `E515` and `E516` (D-r39-12, D-K20a-7). A command's or prompt's -//! gate runs the guard passes that report its codes; a gate fails only on an Error. +//! The gate guards: `gsd/E106`, `E511`, `E512`, `W318`, `W404`, `E515`, `E516` (D-r39-12, D-K20a-7), `E533` and `E535` +//! (ADR 0390). A command's or prompt's gate runs the guard passes that report its codes; a gate fails only on an Error. //! //! A guard also runs on every judged write, with no trigger. Every guard here answers nothing unless its trigger is a //! gate (its trigger kind), so a write is never refused by one: an agent's plan, and `gsd-git`'s, stay free @@ -12,7 +12,8 @@ //! W318 and E516 read the settled judgements alone: a judged target declares when its verdict is owed (a plan check //! while its plan is open, a must-have once its plan is complete), and the host settles away the rest, so no guard //! decides for itself whether a plan was executed. E516, which also reads the workflow a gate is for, lives in -//! `gates/e516.rs`. +//! `gates/e516.rs`; E533 and E535, which read a milestone's computed `api_breaks` and `release` and its version, in +//! `gates/release.rs`. use std::collections::BTreeSet; @@ -24,7 +25,9 @@ use super::thread::{Proof, requirement_proven}; use crate::scope::scope_of; mod e516; +mod release; use e516::e516; +use release::{e533, e535}; type Check = fn(&PassInput) -> Vec<PassDiagnostic>; @@ -38,6 +41,8 @@ const GUARDS: &[(&str, &str, Check)] = &[ ("gate_w404", "W404", w404), ("gate_e515", "E515", e515), ("gate_e516", "E516", e516), + ("gate_e533", "E533", e533), + ("gate_e535", "E535", e535), ]; pub fn declare(c: &mut ContributionsBuilder) { diff --git a/gsd/core/src/passes/gates/release.rs b/gsd/core/src/passes/gates/release.rs new file mode 100644 index 0000000000..8374a85e92 --- /dev/null +++ b/gsd/core/src/passes/gates/release.rs @@ -0,0 +1,253 @@ +//! E533: a breaking API change the milestone's version does not allow (ADR 0390 D5), and E535: release evidence that +//! does not match the milestone ([`e535`], D6). Both share the baseline, [`last_shipped`]. +//! +//! At a gate on an unshipped milestone whose computed `api_breaks` is not empty, the baseline is the last shipped +//! other milestone of the same workstream scope whose name is a version (latest by `shipped`, ties by the higher +//! version); a shipped milestone whose name is not one (`mvp`, `v1.7-rc1`) is skipped by both guards. No baseline is a +//! first release: nothing to refuse. A subject name that is not a version fails closed (one error). When +//! the subject's version is API-compatible with the baseline's (Cargo's rule, [`crate::release::compatible`]), each +//! break is one error, at most [`ERRORS`], then one summary error. The guard reads the computed field alone, never the +//! `api_item` facts (ADR 0353), so it judges the facts of the last `specforge collect`. Every echoed id is [`quoted`]. + +use serde_json::Value; +use specforge_extension_sdk::prelude::*; + +use super::{gate, refuse}; +use crate::passes::plans::{link, name_of, of_kind, strings, text}; +use crate::passes::{one_line, quoted}; +use crate::release::{Version, compatible, parse}; + +const ERRORS: usize = 25; +const COLLECT: &str = + "then run `specforge collect` again: this check reads the API facts of the last collect"; + +fn shipped(milestone: &PassEntity) -> bool { + milestone.fields.contains_key("completion") +} + +fn version(milestone: &PassEntity) -> Option<Version<'_>> { + parse(name_of(&milestone.id)) +} + +/// The first [`ERRORS`] of `items`, and how many more there are: past them, plus `more` that `derive` counted past its +/// own cap. +fn capped<T>(mut items: Vec<T>, more: usize) -> (Vec<T>, usize) { + let more = more + items.len().saturating_sub(ERRORS); + items.truncate(ERRORS); + (items, more) +} + +/// The `<change> <id>` lines of `api_breaks`, and the count of the `more <N>` line `derive` caps it with. No id line +/// reads `more <N>`: each starts with its change. +fn breaks_of(lines: &[String]) -> (Vec<&str>, usize) { + let mut more = 0; + let mut named = Vec::new(); + for line in lines { + match line + .strip_prefix("more ") + .and_then(|n| n.parse::<usize>().ok()) + { + Some(n) => more += n, + None => named.push(line.as_str()), + } + } + capped(named, more) +} + +/// The `name` and `version` of each package of a milestone's computed `release.packages`, and its `more` count. +fn packages_of(milestone: &PassEntity) -> (Vec<(&str, &str)>, usize) { + let release = milestone.values.get("release"); + let packages = release + .and_then(|r| r.get("packages")) + .and_then(Value::as_array) + .map(|list| { + list.iter() + .filter_map(|p| Some((p.get("name")?.as_str()?, p.get("version")?.as_str()?))) + .collect() + }) + .unwrap_or_default(); + let more = release + .and_then(|r| r.get("more")) + .and_then(Value::as_u64) + .and_then(|n| usize::try_from(n).ok()) + .unwrap_or(0); + capped(packages, more) +} + +/// The last shipped milestone of `milestone`'s workstream scope whose name is a version, itself excluded: latest by +/// `shipped`, ties by the higher version, with that version. A shipped `mvp` or `v1.7-rc1` is no release to compare +/// with: skipped. +fn last_shipped<'a>( + input: &'a PassInput, + milestone: &PassEntity, +) -> Option<(&'a PassEntity, Version<'a>)> { + let scope = link(input, milestone, "workstream"); + of_kind(input, "milestone") + .filter(|m| m.id != milestone.id && shipped(m) && link(input, m, "workstream") == scope) + .filter_map(|m| Some((text(m, "shipped"), version(m)?, m))) + .max_by(|(at_a, a, _), (at_b, b, _)| (at_a, a).cmp(&(at_b, b))) + .map(|(_, v, m)| (m, v)) +} + +pub(super) fn e533(input: &PassInput) -> Vec<PassDiagnostic> { + let Some(subject) = gate(input).flatten() else { + return Vec::new(); + }; + let Some(milestone) = of_kind(input, "milestone").find(|m| m.id == subject) else { + return Vec::new(); + }; + let breaks = strings(milestone, "api_breaks"); + if shipped(milestone) || breaks.is_empty() { + return Vec::new(); + } + let Some((baseline, older)) = last_shipped(input, milestone) else { + return Vec::new(); + }; + let named = quoted(subject); + let last = quoted(&baseline.id); + let Some(newer) = version(milestone) else { + return vec![refuse( + "E533", + PassSeverity::Error, + subject, + format!( + "milestone {named} has API breaks and no major version bump over the last shipped {last} can be \ + shown: {named} is not a version" + ), + &format!( + "name the milestone by its version (`v1.7`, `1.7` or `v1.7.2`), or restore the items, or commit the \ + updated accepted report when the change is accepted; {COLLECT}" + ), + )]; + }; + if !compatible(&older, &newer) { + return Vec::new(); + } + let how = format!( + "bump the milestone's major version (Cargo's rule: for 0.x the minor), or restore the item, or commit the \ + updated accepted report when the change is accepted; {COLLECT}" + ); + let (items, more) = breaks_of(&breaks); + let mut found: Vec<PassDiagnostic> = items + .into_iter() + .map(|line| line.split_once(' ').unwrap_or(("changed", line))) + .map(|(change, id)| { + refuse( + "E533", + PassSeverity::Error, + subject, + format!( + "API item {} is {} without a major version bump: milestone {named} is compatible with the last \ + shipped {last}", + quoted(id), + one_line(change) + ), + &how, + ) + }) + .collect(); + if more > 0 { + found.push(refuse( + "E533", + PassSeverity::Error, + subject, + format!( + "{more} more API items broken without a major version bump: milestone {named} is compatible with \ + the last shipped {last}" + ), + &how, + )); + } + found +} + +/// A text member of a milestone's computed `release`. +fn release_of<'a>(milestone: &'a PassEntity, member: &str) -> Option<&'a str> { + milestone.values.get("release")?.get(member)?.as_str() +} + +/// E535: release evidence that does not match the milestone (ADR 0390 D6). At a gate on a milestone whose name is a +/// version: one error when the recorded tag of the subject once shipped, else of the last shipped milestone of its +/// scope ([`last_shipped`]), resolves to no commit; while the subject is unshipped, one error per package of its +/// computed `release.packages` (a package not at its version), at most [`ERRORS`] then one summary counting the rest +/// and `release.more`, and one error when its +/// version is not later than the last shipped one. Absent evidence is no observation, never a failure. +pub(super) fn e535(input: &PassInput) -> Vec<PassDiagnostic> { + let Some(subject) = gate(input).flatten() else { + return Vec::new(); + }; + let Some(milestone) = of_kind(input, "milestone").find(|m| m.id == subject) else { + return Vec::new(); + }; + let Some(own) = version(milestone) else { + return Vec::new(); + }; + let named = quoted(subject); + let mut found = Vec::new(); + let baseline = last_shipped(input, milestone); + // GSD tags after the close: the release judged is the subject once shipped, else the last one before it. + let released = if shipped(milestone) { + Some(milestone) + } else { + baseline.map(|(last, _)| last) + }; + if let Some(released) = released + && let Some(tag) = release_of(released, "tag") + && release_of(released, "commit").is_none() + { + found.push(refuse( + "E535", + PassSeverity::Error, + subject, + format!( + "the tag {} of the shipped milestone {} resolves to no commit", + quoted(tag), + quoted(&released.id) + ), + "create and push the tag, then run `specforge collect` again: the tag is observed only at collect", + )); + } + if shipped(milestone) { + return found; + } + if let Some((last, _)) = baseline.filter(|(_, older)| own <= *older) { + let last = quoted(&last.id); + found.push(refuse( + "E535", + PassSeverity::Error, + subject, + format!("milestone {named} goes backwards from the last shipped {last}: its version is not later"), + &format!("name the milestone by a version later than the last shipped {last}"), + )); + } + let how = "set the package's version to the milestone's, or list the package in `specforge.release_exempt` when \ + the milestone does not release it; then run `specforge collect` again: this check reads the package \ + versions of the last collect"; + let (packages, more) = packages_of(milestone); + for (name, at) in packages { + found.push(refuse( + "E535", + PassSeverity::Error, + subject, + format!( + "package {} is at version {}, not at the version of milestone {named}", + quoted(name), + quoted(at) + ), + how, + )); + } + if more > 0 { + found.push(refuse( + "E535", + PassSeverity::Error, + subject, + format!("{more} more packages are not at the version of milestone {named}"), + how, + )); + } + found +} + +#[cfg(test)] +mod tests; diff --git a/gsd/core/src/passes/gates/release/tests.rs b/gsd/core/src/passes/gates/release/tests.rs new file mode 100644 index 0000000000..49fc2b0149 --- /dev/null +++ b/gsd/core/src/passes/gates/release/tests.rs @@ -0,0 +1,355 @@ +use serde_json::{Value, json}; + +use super::*; +use crate::passes::gates::tests::{gate_of, input}; + +const HOW: &str = "bump the milestone's major version (Cargo's rule: for 0.x the minor), or restore the item, or \ + commit the updated accepted report when the change is accepted; then run `specforge collect` again: this check \ + reads the API facts of the last collect"; + +fn shipped(id: &str, at: &str) -> Value { + json!({ "id": id, "kind": "milestone", "fields": { "completion": format!("at {at}"), "shipped": at } }) +} + +fn open(id: &str, breaks: &[&str]) -> Value { + json!({ "id": id, "kind": "milestone", "values": { "api_breaks": breaks } }) +} + +fn close(subject: &str, entities: Vec<Value>) -> PassInput { + input( + gate_of("complete_milestone", Some(subject)), + entities, + vec![], + ) +} + +#[test] +fn e533_refuses_a_removed_item_without_a_major_bump() { + let found = e533(&close( + "v1.8", + vec![ + shipped("v1.7", "2026-02-01"), + open("v1.8", &["removed api:rust:a::f"]), + ], + )); + assert_eq!(found.len(), 1); + assert_eq!(found[0].code, "E533"); + assert_eq!(found[0].severity, PassSeverity::Error); + assert_eq!(found[0].entity.as_deref(), Some("v1.8")); + assert_eq!( + found[0].message, + "API item 'api:rust:a::f' is removed without a major version bump: milestone 'v1.8' is compatible with the \ + last shipped 'v1.7'" + ); + assert_eq!(found[0].suggestion.as_deref(), Some(HOW)); +} + +#[test] +fn e533_allows_a_break_at_a_major_bump() { + let found = e533(&close( + "v2.0", + vec![ + shipped("v1.7", "2026-02-01"), + open("v2.0", &["removed api:rust:a::f"]), + ], + )); + assert!(found.is_empty()); +} + +#[test] +fn e533_is_silent_outside_a_gate() { + let mut found = close( + "v1.8", + vec![ + shipped("v1.7", "2026-02-01"), + open("v1.8", &["removed api:rust:a::f"]), + ], + ); + found.trigger = None; + assert!(e533(&found).is_empty()); +} + +/// The E533 messages of closing `subject` (open, with `breaks`) after `baseline` shipped on 2026-02-01. +fn refused(baseline: &str, subject: &str, breaks: &[&str]) -> Vec<String> { + let found = e533(&close( + subject, + vec![shipped(baseline, "2026-02-01"), open(subject, breaks)], + )); + assert!( + found + .iter() + .all(|d| d.code == "E533" && d.entity.as_deref() == Some(subject)) + ); + found.into_iter().map(|d| d.message).collect() +} + +#[test] +fn e533_fires_on_each_breaking_change_alone() { + for change in ["removed", "changed", "narrowed"] { + let line = format!("{change} api:js:p::f"); + assert_eq!( + refused("v1.7", "v1.8", &[&line]), + [format!( + "API item 'api:js:p::f' is {change} without a major version bump: milestone 'v1.8' is compatible \ + with the last shipped 'v1.7'" + )] + ); + } +} + +#[test] +fn e533_fires_on_a_patch_bump_of_a_0x_minor() { + assert_eq!(refused("v0.7.1", "v0.7.2", &["removed a"]).len(), 1); +} + +#[test] +fn e533_fires_on_a_minor_bump_of_a_one_part_version() { + assert_eq!(refused("v1", "v1.1", &["removed a"]).len(), 1); +} + +#[test] +fn e533_allows_a_break_at_a_0x_minor_bump() { + assert!(refused("v0.7", "v0.8", &["removed a"]).is_empty()); +} + +#[test] +fn e533_allows_a_break_at_a_first_release() { + let found = e533(&close("v1.8", vec![open("v1.8", &["removed a"])])); + assert!(found.is_empty()); +} + +#[test] +fn e533_is_silent_when_api_breaks_is_empty_or_absent() { + assert!(refused("v1.7", "v1.8", &[]).is_empty()); + let absent = json!({ "id": "v1.8", "kind": "milestone" }); + let found = e533(&close("v1.8", vec![shipped("v1.7", "2026-02-01"), absent])); + assert!(found.is_empty()); +} + +#[test] +fn e533_is_silent_on_a_shipped_subject() { + let mut subject = shipped("v1.8", "2026-03-01"); + subject["values"] = json!({ "api_breaks": ["removed a"] }); + let found = e533(&close("v1.8", vec![shipped("v1.7", "2026-02-01"), subject])); + assert!(found.is_empty()); +} + +#[test] +fn e533_is_silent_at_a_phase_gate_and_on_a_write() { + let entities = vec![ + shipped("v1.7", "2026-02-01"), + open("v1.8", &["removed a"]), + json!({ "id": "v1.8/01", "kind": "phase" }), + ]; + let phase = input(gate_of("ship", Some("v1.8/01")), entities.clone(), vec![]); + assert!(e533(&phase).is_empty()); + let write = input( + json!({ "kind": "write", "subject": "v1.8" }), + entities, + vec![], + ); + assert!(e533(&write).is_empty()); +} + +#[test] +fn e533_takes_no_baseline_from_another_workstream() { + let edges = vec![json!({ "source": "a/v1.8", "target": "a", "label": "workstream" })]; + let found = e533(&input( + gate_of("complete_milestone", Some("a/v1.8")), + vec![ + shipped("v1.7", "2026-02-01"), + open("a/v1.8", &["removed a"]), + ], + edges.clone(), + )); + assert!(found.is_empty()); + // The same milestone in workstream `a` is the baseline. + let mut edges = edges; + edges.push(json!({ "source": "a/v1.7", "target": "a", "label": "workstream" })); + let found = e533(&input( + gate_of("complete_milestone", Some("a/v1.8")), + vec![ + shipped("a/v1.7", "2026-02-01"), + open("a/v1.8", &["removed a"]), + ], + edges, + )); + assert_eq!(found.len(), 1); + assert!(found[0].message.ends_with("the last shipped 'a/v1.7'")); +} + +#[test] +fn e533_takes_the_latest_shipped_milestone_as_the_baseline() { + // v2.0 shipped last: compatible with v2.1, so it fires; v1.9 would allow the break. + let found = e533(&close( + "v2.1", + vec![ + shipped("v2.0", "2026-02-01"), + shipped("v1.9", "2026-01-01"), + open("v2.1", &["removed a"]), + ], + )); + assert_eq!(found.len(), 1); + assert!(found[0].message.ends_with("the last shipped 'v2.0'")); + // v1.9 shipped after v2.0 (a backport): it is the baseline, and v2.1 is a major bump over it. + let found = e533(&close( + "v2.1", + vec![ + shipped("v2.0", "2026-01-01"), + shipped("v1.9", "2026-02-01"), + open("v2.1", &["removed a"]), + ], + )); + assert!(found.is_empty()); +} + +#[test] +fn e533_breaks_a_tie_of_dates_by_the_higher_version() { + for order in [["v2.0", "v1.9"], ["v1.9", "v2.0"]] { + let found = e533(&close( + "v2.1", + vec![ + shipped(order[0], "2026-02-01"), + shipped(order[1], "2026-02-01"), + open("v2.1", &["removed a"]), + ], + )); + assert_eq!(found.len(), 1, "{order:?}"); + assert!(found[0].message.ends_with("the last shipped 'v2.0'")); + } +} + +#[test] +fn e533_fires_once_on_a_subject_that_is_not_a_version() { + let found = e533(&close( + "mvp", + vec![ + shipped("v1.7", "2026-02-01"), + open("mvp", &["removed a", "changed b"]), + ], + )); + assert_eq!(found.len(), 1); + assert_eq!( + found[0].message, + "milestone 'mvp' has API breaks and no major version bump over the last shipped 'v1.7' can be shown: 'mvp' \ + is not a version" + ); + assert!( + found[0] + .suggestion + .as_deref() + .is_some_and(|s| s.contains("run `specforge collect` again")) + ); +} + +#[test] +fn e533_takes_no_baseline_whose_name_is_not_a_version() { + // A release candidate or an `mvp` that shipped last is skipped: v1.7 is the baseline. + for skipped in ["mvp", "v1.8-rc1"] { + let found = e533(&close( + "v1.8", + vec![ + shipped("v1.7", "2026-01-01"), + shipped(skipped, "2026-02-01"), + open("v1.8", &["removed a"]), + ], + )); + assert_eq!(found.len(), 1, "{skipped}"); + assert!(found[0].message.ends_with("the last shipped 'v1.7'")); + } + // With no shipped version at all, it is a first release. + let found = e533(&close( + "v2.0", + vec![shipped("mvp", "2026-02-01"), open("v2.0", &["removed a"])], + )); + assert!(found.is_empty()); +} + +#[test] +fn e533_bounds_its_errors_at_25_and_one_summary() { + let lines: Vec<String> = (0..60) + .map(|i| format!("removed api:rust:a::f{i:02}")) + .collect(); + let lines: Vec<&str> = lines.iter().map(String::as_str).collect(); + let found = refused("v1.7", "v1.8", &lines); + assert_eq!(found.len(), 26); + assert_eq!( + found[25], + "35 more API items broken without a major version bump: milestone 'v1.8' is compatible with the last \ + shipped 'v1.7'" + ); +} + +#[test] +fn e533_counts_the_more_line_of_a_capped_field() { + let mut lines: Vec<String> = (0..50) + .map(|i| format!("removed api:rust:a::f{i:02}")) + .collect(); + lines.push("more 10".to_string()); + let lines: Vec<&str> = lines.iter().map(String::as_str).collect(); + let found = refused("v1.7", "v1.8", &lines); + assert_eq!(found.len(), 26); + assert!(found[25].starts_with("35 more API items")); +} + +#[test] +fn e533_escapes_every_id_it_echoes() { + let found = e533(&close( + "v1.8\n", + vec![ + shipped("v1.7", "2026-02-01"), + open("v1.8\n", &["removed a\nb'`c"]), + ], + )); + assert_eq!(found.len(), 1); + assert!(found[0].message.ends_with("'v1.8\\n' is not a version")); + for d in &found { + assert!(!d.message.contains('\n'), "{:?}", d.message); + assert!(d.suggestion.as_deref().is_some_and(|s| !s.contains('\n'))); + } + let found = refused("v1.7", "v1.8", &["removed a\nb'`c"]); + assert_eq!( + found, + [ + "API item 'a\\nb\\'`c' is removed without a major version bump: milestone 'v1.8' is compatible with the \ + last shipped 'v1.7'" + ] + ); +} + +#[test] +fn a_subject_part_past_u64_fails_e533_closed_and_leaves_e535_silent() { + // Not a version: E533 cannot show a major bump, and E535 has no version to release. + let subject = "v1.99999999999999999999"; + let entities = vec![shipped("v1.7", "2026-02-01"), open(subject, &["removed a"])]; + let found = e533(&close(subject, entities.clone())); + assert_eq!(found.len(), 1); + assert!(found[0].message.ends_with("is not a version")); + assert!(e535(&close(subject, entities)).is_empty()); +} + +#[test] +fn e533_escapes_an_id_derive_kept_raw_once() { + let id = "api:rust:a::f\u{7}\n'"; + let derived = crate::passes::derive::interface::values(&close( + "v1.8", + vec![ + shipped("v1.7", "2026-02-01"), + json!({ "id": "v1.8", "kind": "milestone" }), + json!({ "id": id, "kind": "api_item", "fields": { "change": "removed" } }), + ], + )); + assert_eq!(derived.len(), 1); + let mut subject = json!({ "id": "v1.8", "kind": "milestone" }); + subject["values"] = json!({ "api_breaks": derived[0].value }); + let found = e533(&close("v1.8", vec![shipped("v1.7", "2026-02-01"), subject])); + assert_eq!( + found.iter().map(|d| d.message.as_str()).collect::<Vec<_>>(), + [ + "API item 'api:rust:a::f\\u{7}\\n\\'' is removed without a major version bump: milestone 'v1.8' is \ + compatible with the last shipped 'v1.7'" + ] + ); +} + +mod e535; diff --git a/gsd/core/src/passes/gates/release/tests/e535.rs b/gsd/core/src/passes/gates/release/tests/e535.rs new file mode 100644 index 0000000000..74f9e7467b --- /dev/null +++ b/gsd/core/src/passes/gates/release/tests/e535.rs @@ -0,0 +1,280 @@ +//! E535's package and backwards parts (ADR 0390 D6). + +use serde_json::{Value, json}; + +use super::{close, shipped}; +use crate::passes::gates::release::e535; +use crate::passes::gates::tests::{gate_of, input}; +use specforge_extension_sdk::prelude::*; + +const PACKAGES: &str = "set the package's version to the milestone's, or list the package in \ + `specforge.release_exempt` when the milestone does not release it; then run `specforge collect` again: this check \ + reads the package versions of the last collect"; + +/// An open milestone whose computed `release.packages` is `packages`, each written `<name> <version>` and split at +/// its last space. +fn releasing(id: &str, packages: &[&str]) -> Value { + let packages: Vec<Value> = packages + .iter() + .map(|p| { + let (name, version) = p.rsplit_once(' ').expect("<name> <version>"); + json!({ "name": name, "version": version }) + }) + .collect(); + json!({ "id": id, "kind": "milestone", "values": { "release": { "packages": packages } } }) +} + +fn messages(found: &[PassDiagnostic]) -> Vec<&str> { + found.iter().map(|d| d.message.as_str()).collect() +} + +#[test] +fn e535_refuses_a_package_not_at_the_milestones_version() { + let found = e535(&close( + "v1.8", + vec![ + shipped("v1.7", "2026-02-01"), + releasing("v1.8", &["b 1.7.0"]), + ], + )); + assert_eq!( + messages(&found), + ["package 'b' is at version '1.7.0', not at the version of milestone 'v1.8'"] + ); + assert_eq!(found[0].code, "E535"); + assert_eq!(found[0].severity, PassSeverity::Error); + assert_eq!(found[0].entity.as_deref(), Some("v1.8")); + assert_eq!(found[0].suggestion.as_deref(), Some(PACKAGES)); +} + +#[test] +fn e535_allows_a_release_whose_packages_match() { + let found = e535(&close( + "v1.8", + vec![shipped("v1.7", "2026-02-01"), releasing("v1.8", &[])], + )); + assert!(found.is_empty()); + // Nothing observed: no `release` at all. + let found = e535(&close( + "v1.8", + vec![ + shipped("v1.7", "2026-02-01"), + json!({ "id": "v1.8", "kind": "milestone" }), + ], + )); + assert!(found.is_empty()); +} + +#[test] +fn e535_refuses_a_version_that_goes_backwards() { + let found = e535(&close( + "v1.6", + vec![shipped("v1.7", "2026-02-01"), releasing("v1.6", &[])], + )); + assert_eq!( + messages(&found), + ["milestone 'v1.6' goes backwards from the last shipped 'v1.7': its version is not later"] + ); + assert_eq!( + found[0].suggestion.as_deref(), + Some("name the milestone by a version later than the last shipped 'v1.7'") + ); + // The same version is not later either. + let found = e535(&close( + "v1.7.0", + vec![shipped("v1.7", "2026-02-01"), releasing("v1.7.0", &[])], + )); + assert_eq!(found.len(), 1); +} + +#[test] +fn e535_allows_a_later_version_and_a_first_release() { + let found = e535(&close( + "v1.8", + vec![shipped("v1.7", "2026-02-01"), releasing("v1.8", &[])], + )); + assert!(found.is_empty()); + let found = e535(&close("v0.1", vec![releasing("v0.1", &[])])); + assert!(found.is_empty()); +} + +#[test] +fn e535_takes_no_baseline_from_another_workstream() { + let edges = vec![json!({ "source": "a/v1.6", "target": "a", "label": "workstream" })]; + let found = e535(&input( + gate_of("complete_milestone", Some("a/v1.6")), + vec![shipped("v1.7", "2026-02-01"), releasing("a/v1.6", &[])], + edges, + )); + assert!(found.is_empty()); +} + +#[test] +fn e535_is_silent_outside_a_gate_and_for_a_name_that_is_no_version() { + let mut write = close( + "v1.6", + vec![ + shipped("v1.7", "2026-02-01"), + releasing("v1.6", &["b 1.7.0"]), + ], + ); + write.trigger = None; + assert!(e535(&write).is_empty()); + let found = e535(&close( + "mvp", + vec![ + shipped("v1.7", "2026-02-01"), + releasing("mvp", &["b 1.7.0"]), + ], + )); + assert!(found.is_empty()); +} + +#[test] +fn e535_names_at_most_25_packages_then_counts_the_rest() { + let lines: Vec<String> = (0..30).map(|n| format!("p{n:02} 0.1.0")).collect(); + let lines: Vec<&str> = lines.iter().map(String::as_str).collect(); + // 30 listed, and 5 more `derive` counted past its own cap. + let mut milestone = releasing("v1.8", &lines); + milestone["values"]["release"]["more"] = json!(5); + let found = e535(&close("v1.8", vec![milestone])); + assert_eq!(found.len(), 26); + assert_eq!( + found[25].message, + "10 more packages are not at the version of milestone 'v1.8'" + ); + assert!( + found + .iter() + .all(|d| d.suggestion.as_deref() == Some(PACKAGES)) + ); +} + +#[test] +fn e535_reads_a_package_named_more_or_with_a_space_as_a_package() { + let found = e535(&close( + "v1.8", + vec![releasing("v1.8", &["more 5", "my crate 0.1.0"])], + )); + assert_eq!( + messages(&found), + [ + "package 'more' is at version '5', not at the version of milestone 'v1.8'", + "package 'my crate' is at version '0.1.0', not at the version of milestone 'v1.8'" + ] + ); +} + +#[test] +fn e535_escapes_what_it_echoes() { + let found = e535(&close("v1.8", vec![releasing("v1.8", &["a\nb'c 1\t0"])])); + assert_eq!( + messages(&found), + ["package 'a\\nb\\'c' is at version '1\\t0', not at the version of milestone 'v1.8'"] + ); +} + +#[test] +fn e535_escapes_a_name_and_version_derive_kept_raw_once() { + let derived = crate::passes::derive::release::values(&close( + "v1.8", + vec![ + json!({ "id": "v1.8", "kind": "milestone" }), + json!({ "id": "pkg:cargo/a", "kind": "package", + "fields": { "name": "a\u{1b}'b", "version": "1.\u{7}7" } }), + ], + )); + assert_eq!(derived.len(), 1); + let mut subject = json!({ "id": "v1.8", "kind": "milestone" }); + subject["values"] = json!({ "release": derived[0].value }); + let found = e535(&close("v1.8", vec![subject])); + assert_eq!( + messages(&found), + [ + "package 'a\\u{1b}\\'b' is at version '1.\\u{7}7', not at the version of milestone 'v1.8'" + ] + ); +} + +/// A shipped milestone whose computed `release` copies the recorded tag `tag`, with `commit` when it resolves. +fn tagged(id: &str, at: &str, tag: &str, commit: Option<&str>) -> Value { + let mut milestone = shipped(id, at); + let release = commit.map_or_else( + || json!({ "tag": tag }), + |c| json!({ "tag": tag, "commit": c }), + ); + milestone["values"] = json!({ "release": release }); + milestone +} + +const TAG: &str = "create and push the tag, then run `specforge collect` again: the tag is observed only at collect"; + +#[test] +fn e535_refuses_closing_the_next_milestone_while_the_last_tag_resolves_to_no_commit() { + let found = e535(&close( + "v1.8", + vec![ + tagged("v1.7", "2026-02-01", "v1.7", None), + releasing("v1.8", &[]), + ], + )); + assert_eq!( + messages(&found), + ["the tag 'v1.7' of the shipped milestone 'v1.7' resolves to no commit"] + ); + assert_eq!(found[0].suggestion.as_deref(), Some(TAG)); + assert_eq!(found[0].entity.as_deref(), Some("v1.8")); +} + +#[test] +fn e535_allows_a_last_tag_that_resolves() { + let found = e535(&close( + "v1.8", + vec![ + tagged("v1.7", "2026-02-01", "v1.7", Some("abc")), + releasing("v1.8", &[]), + ], + )); + assert!(found.is_empty()); + // No tag recorded (no repository, a shallow clone, `git.create_tag` false): no observation, silent. + let found = e535(&close( + "v1.8", + vec![shipped("v1.7", "2026-02-01"), releasing("v1.8", &[])], + )); + assert!(found.is_empty()); +} + +#[test] +fn e535_takes_no_baseline_whose_name_is_not_a_version() { + // `mvp` shipped last and is skipped, as E533 skips it: v1.7's tag and version are judged. + let found = e535(&close( + "v1.6", + vec![ + tagged("v1.7", "2026-01-01", "v1.7", None), + shipped("mvp", "2026-02-01"), + releasing("v1.6", &[]), + ], + )); + assert_eq!( + messages(&found), + [ + "the tag 'v1.7' of the shipped milestone 'v1.7' resolves to no commit", + "milestone 'v1.6' goes backwards from the last shipped 'v1.7': its version is not later" + ] + ); +} + +#[test] +fn e535_judges_a_shipped_subjects_own_tag() { + let found = e535(&close( + "v1.8", + vec![ + tagged("v1.7", "2026-02-01", "v1.7", Some("abc")), + tagged("v1.8", "2026-03-01", "v1.8", None), + ], + )); + assert_eq!( + messages(&found), + ["the tag 'v1.8' of the shipped milestone 'v1.8' resolves to no commit"] + ); +} diff --git a/gsd/core/src/passes/gates/tests.rs b/gsd/core/src/passes/gates/tests.rs index 5bf82c78b1..26543397f8 100644 --- a/gsd/core/src/passes/gates/tests.rs +++ b/gsd/core/src/passes/gates/tests.rs @@ -339,10 +339,13 @@ fn a_stale_verdict_is_e516_and_a_fresh_one_is_not() { /// A project every guard has something to say about at a gate on milestone v1.0: no audit (E106), an unverified /// phase (E511), an open window (E512), a stale plan-check (W318), a tdd plan with a summary and no review (W404), a -/// complete requirement no task traces (E515) and a stale verdict (E516). +/// complete requirement no task traces (E515), a stale verdict (E516) and an API break without a major bump over the +/// shipped v1 (E533), and a package not at the milestone's version (E535). fn everything_wrong() -> (Vec<Value>, Vec<Value>) { let entities = vec![ - json!({ "id": "v1.0", "kind": "milestone" }), + json!({ "id": "v1.0", "kind": "milestone", "values": { + "api_breaks": ["removed api:rust:a::f"], "release": { "packages": [{ "name": "b", "version": "0.9.0" }] } } }), + json!({ "id": "v1", "kind": "milestone", "fields": { "completion": "at 2026-01-01" } }), json!({ "id": "v1.0/01", "kind": "phase", "values": { "requirements": ["R1"] } }), json!({ "id": "R1", "kind": "requirement", "fields": { "status": "complete" } }), window("BW1", json!({})), diff --git a/gsd/core/src/passes/thread/tests.rs b/gsd/core/src/passes/thread/tests.rs index 5d22f78e1f..f5bd5fee56 100644 --- a/gsd/core/src/passes/thread/tests.rs +++ b/gsd/core/src/passes/thread/tests.rs @@ -268,6 +268,15 @@ fn every_pass_that_reads_the_thread_declares_test_facts() { match facts(&pass.inputs).as_slice() { [] => {} [only] if only == TEST => reading.push(&pass.name), + // derive also reads the API and package facts for a milestone's `api_breaks` and `release` (ADR 0390). + [test, api, package] + if test == TEST + && api == "api_item" + && package == "package" + && pass.name == "derive" => + { + reading.push(&pass.name); + } other => panic!("pass '{}' declares the facts {other:?}", pass.name), } } diff --git a/gsd/core/src/prompts/ship.rs b/gsd/core/src/prompts/ship.rs index 56fc1f1cae..384a4c7cba 100644 --- a/gsd/core/src/prompts/ship.rs +++ b/gsd/core/src/prompts/ship.rs @@ -30,7 +30,7 @@ static COMPLETE_MILESTONE: Spec = Spec { command: "complete-milestone", args: &[Arg::reference("milestone", "milestone")], subject: Some("milestone"), - gates: &["E106", "E511", "E515", "E516"], + gates: &["E106", "E511", "E515", "E516", "E533", "E535"], steps: COMPLETE_STEPS, slash: Some(Slash { hint: "<milestone>", diff --git a/gsd/core/src/release.rs b/gsd/core/src/release.rs new file mode 100644 index 0000000000..06416d07a0 --- /dev/null +++ b/gsd/core/src/release.rs @@ -0,0 +1,88 @@ +//! A milestone's version, read from its name (`v1.7`, `1.7`, `v1.7.2`), Cargo's compatibility rule between two +//! (ADR 0390 D5), and whether a package's version is the milestone's (D6). Hand-written on purpose: no version library +//! accepts `v1.7`. + +use std::cmp::Ordering; +use std::fmt; + +/// One to three numeric parts; a part not written reads as 0, so `v1.0` and `v1.0.0` are one version, ordered and +/// compared by its parts alone. `written` counts the parts the name wrote: it decides how many a package must match. +/// `text` is the name without its `v`, as written (`2026.01`): the version prints it. +#[derive(Debug, Clone, Copy)] +pub struct Version<'a> { + pub parts: [u64; 3], + pub written: usize, + text: &'a str, +} + +impl PartialEq for Version<'_> { + fn eq(&self, other: &Self) -> bool { + self.parts == other.parts + } +} + +impl Eq for Version<'_> {} + +impl PartialOrd for Version<'_> { + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for Version<'_> { + fn cmp(&self, other: &Self) -> Ordering { + self.parts.cmp(&other.parts) + } +} + +/// The version as the name wrote it, digits and dots only (`2026.01` for `v2026.01`): a tag name is `v` and this, the +/// tag GSD creates, and never other text of the name. +impl fmt::Display for Version<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.text) + } +} + +/// The version a name writes: one leading `v` stripped, then one to three dot-separated decimal parts, each within +/// `u64`; anything else (`mvp`, `v1.7-rc1`, `v1.2.3.4`) is not a version. +pub fn parse(name: &str) -> Option<Version<'_>> { + let digits = name.strip_prefix('v').unwrap_or(name); + let mut parts = [0u64; 3]; + let mut written = 0; + for (index, part) in digits.split('.').enumerate() { + if index == 3 || part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + parts[index] = part.parse().ok()?; + written = index + 1; + } + Some(Version { + parts, + written, + text: digits, + }) +} + +/// Cargo's rule: `newer` is API-compatible with `older` when they agree up to and including the first non-zero part +/// of `older` (`1.7` to `1.8` yes, `1.7` to `2.0` no; for `0.x` the minor counts as major). +pub fn compatible(older: &Version, newer: &Version) -> bool { + let first = older.parts.iter().position(|p| *p != 0).unwrap_or(2); + older.parts[..=first] == newer.parts[..=first] +} + +/// Whether a package's version is the milestone's: their first max(2, the milestone's written parts) parts agree +/// (`v1.7` takes `1.7.0` and `1.7.3`, `v1.7.2` only `1.7.2`). A `+build` suffix is ignored; a pre-release +/// (`1.7.0-rc.1`) and anything that is no version is not equal. +pub fn matches(milestone: &Version, package_version: &str) -> bool { + let bare = package_version + .split_once('+') + .map_or(package_version, |(v, _)| v); + let Some(package) = parse(bare) else { + return false; + }; + let compared = milestone.written.max(2); + milestone.parts[..compared] == package.parts[..compared] +} + +#[cfg(test)] +mod tests; diff --git a/gsd/core/src/release/tests.rs b/gsd/core/src/release/tests.rs new file mode 100644 index 0000000000..e08f76e518 --- /dev/null +++ b/gsd/core/src/release/tests.rs @@ -0,0 +1,98 @@ +use super::*; + +fn v(name: &str) -> Version<'_> { + parse(name).expect("a version") +} + +#[test] +fn a_milestone_name_with_one_to_three_numeric_parts_is_a_version() { + assert_eq!(v("v1.7").parts, [1, 7, 0]); + assert_eq!(v("1.7").parts, [1, 7, 0]); + assert_eq!(v("v1.7.2").parts, [1, 7, 2]); + assert_eq!(v("v1").parts, [1, 0, 0]); +} + +#[test] +fn any_other_name_is_not_a_version() { + for name in [ + "mvp", + "v1.7-rc1", + "v1.2.3.4", + "", + "v", + "v1..2", + "vv1.7", + "v1.7.", + " v1.7", + "v+1", + // git revision syntax (`@{`, `:`), a control character and a non-ASCII digit (ARABIC-INDIC ONE) + "v1@{", + "v1:0", + "v1\u{7}", + "v\u{661}.0", + ] { + assert!(parse(name).is_none(), "{name:?}"); + } +} + +#[test] +fn a_part_not_written_reads_as_zero() { + assert_eq!(v("v1.0"), v("v1.0.0")); + assert!(v("v1.7") < v("v1.7.1")); + assert!(v("v1.10") > v("v1.9")); +} + +#[test] +fn compatibility_is_cargos_rule() { + assert!(compatible(&v("1.7"), &v("1.8"))); + assert!(!compatible(&v("1.7"), &v("2.0"))); + assert!(!compatible(&v("0.7"), &v("0.8"))); + assert!(compatible(&v("0.7.1"), &v("0.7.2"))); + assert!(!compatible(&v("0.0.3"), &v("0.0.4"))); + assert!(compatible(&v("v1"), &v("v1.1"))); +} + +#[test] +fn a_package_matches_the_milestones_first_two_or_written_parts() { + for same in ["1.7.0", "1.7.0+b5", "1.7", "1.7.1"] { + assert!(matches(&v("v1.7"), same), "{same}"); + } + for other in ["1.7.0-rc.1", "1.8.0", "x", "", "1.7.0.1"] { + assert!(!matches(&v("v1.7"), other), "{other}"); + } + assert!(!matches(&v("v1.7.2"), "1.7.0")); + assert!(matches(&v("v1.7.2"), "1.7.2+build")); + assert!(matches(&v("v1"), "1.0.4")); + assert!(!matches(&v("v1"), "1.1.0")); +} + +#[test] +fn a_version_prints_as_written_without_its_v() { + assert_eq!(v("v1.7").to_string(), "1.7"); + assert_eq!(v("1.7.2").to_string(), "1.7.2"); + // CalVer keeps its zero: the tag GSD creates for `v2026.01` is `v2026.01`. + assert_eq!(v("v2026.01").to_string(), "2026.01"); + assert_eq!(v("v01.7").to_string(), "01.7"); +} + +#[test] +fn a_part_past_u64_is_not_a_version() { + assert!(parse("v18446744073709551615").is_some()); + assert!(parse("v18446744073709551616").is_none()); + assert!(parse("v1.99999999999999999999").is_none()); +} + +#[test] +fn an_all_zero_older_version_is_compatible_with_itself_alone() { + assert!(compatible(&v("0.0.0"), &v("0.0.0"))); + assert!(compatible(&v("0"), &v("0.0"))); + assert!(!compatible(&v("0.0.0"), &v("0.0.1"))); + assert!(!compatible(&v("0.0"), &v("0.1"))); +} + +#[test] +fn a_zero_padded_version_compares_by_its_numbers() { + assert_eq!(v("v1.07"), v("v1.7")); + assert!(v("v2026.01") < v("v2026.2")); + assert!(matches(&v("v2026.01"), "2026.1.0")); +} diff --git a/gsd/core/src/route.rs b/gsd/core/src/route.rs index 261075ed08..e086fcc7d5 100644 --- a/gsd/core/src/route.rs +++ b/gsd/core/src/route.rs @@ -1,6 +1,6 @@ -//! The route `specforge trace` follows from a requirement (ADR 0330, ADR 0331 D8, ADR 0371 D7), read from GSD's own -//! fields and collected data alone: the requirement with its computed `proof` and the status of each test whose tag -//! names it; its plans (`requirements`), their tasks, the commits that name those tasks (with how each is linked), the +//! The routes `specforge trace` follows. The first, from a requirement (ADR 0330, ADR 0331 D8, ADR 0371 D7), is read +//! from GSD's own fields and collected data alone: the requirement with its computed `proof` and the status of each +//! test whose tag names it; its plans (`requirements`), their tasks, the commits that name those tasks (with how each is linked), the //! code items each commit changed (ADR 0352 D3), the plans' truths (with their E501 judgement), and the coverage items //! of its summaries (`deliverable`, with each check's `ref`). //! @@ -9,10 +9,13 @@ //! is an annotation of the start, not a step, since every step is required: a requirement no test tags would never //! read whole. Without `@code/core` the `item` step and the tests' annotation are inert, as every selector into an //! unloaded optional peer's kind. +//! +//! The second, `milestone-release` (ADR 0390 D10), starts at a milestone: its computed `api_breaks` and `release` +//! (gsd/E533's and gsd/E535's evidence) and the `tag` `gsd-git` recorded, then its phases (a route needs a step). use specforge_extension_sdk::prelude::*; -/// Declare `requirement-thread` (`gsd/requirement-thread` once qualified). +/// Declare `requirement-thread` and `milestone-release` (`gsd/<name>` once qualified). pub fn declare(c: &mut ContributionsBuilder) { c.route("requirement-thread", |r| { r.start("requirement") @@ -39,4 +42,17 @@ pub fn declare(c: &mut ContributionsBuilder) { s.from_start().label("deliverable").field("checks.ref"); }); }); + c.route("milestone-release", |r| { + r.start("milestone") + .description( + "A milestone's release evidence: its API breaks, its release (tag, commit, packages) and its \ + recorded tag, and its phases", + ) + .field("api_breaks") + .field("release") + .field("tag") + .step("phase", "<phase.milestone", |s| { + s.label("phase"); + }); + }); } diff --git a/gsd/core/src/settings/gates.rs b/gsd/core/src/settings/gates.rs index 2b0577891a..ae2d24d453 100644 --- a/gsd/core/src/settings/gates.rs +++ b/gsd/core/src/settings/gates.rs @@ -55,8 +55,22 @@ pub const SPECFORGE: &[(&str, &str, &str)] = &[ "E521", "A task commit names its task by its Gsd-Task trailer.", ), + ( + "specforge.interface_gate", + "E533", + "A milestone that changes, narrows or removes an API item bumps its major version over the last shipped one.", + ), + ( + "specforge.release_gate", + "E535", + "A milestone's packages are at its version, its version is later than the last shipped one, and that one's tag resolves.", + ), ]; +/// `specforge.release_exempt`: the package names E535 does not judge (ADR 0390 D8). +const RELEASE_EXEMPT: &str = + "The package names gsd/E535 does not judge: packages the milestone does not release."; + /// The codes `setting` gates, if it is a GSD key that gates any. pub fn of(setting: &str) -> Option<&'static [&'static str]> { GATES.iter().find(|(s, _)| *s == setting).map(|(_, c)| *c) @@ -76,4 +90,9 @@ pub fn declare(c: &mut ContributionsBuilder) { s.bool().default(false).describe(about).gates(&[code]); }); } + c.setting("specforge.release_exempt", |s| { + s.string_list() + .default(Vec::<String>::new()) + .describe(RELEASE_EXEMPT); + }); } diff --git a/gsd/core/src/settings/profiles.rs b/gsd/core/src/settings/profiles.rs index 70d14b8f9d..8a7c42639b 100644 --- a/gsd/core/src/settings/profiles.rs +++ b/gsd/core/src/settings/profiles.rs @@ -19,6 +19,8 @@ const PRESETS: &[(&str, [bool; 3])] = &[ ("specforge.cross_workstream_conflicts", [false, false, true]), ("specforge.plan_paths_touched", [false, true, true]), ("specforge.task_trailers", [false, true, true]), + ("specforge.interface_gate", [false, true, true]), + ("specforge.release_gate", [false, true, true]), ]; /// `(setting, environment variable)`: the key half of each search availability flag. A secret may not share a diff --git a/gsd/core/tests/cli/harness.rs b/gsd/core/tests/cli/harness.rs index 5810be02bd..a2a983a097 100644 --- a/gsd/core/tests/cli/harness.rs +++ b/gsd/core/tests/cli/harness.rs @@ -106,6 +106,9 @@ pub struct Project { /// The loaded extensions as `(name, component)`, `@gsd/core` first; a builtin has no component. A cell: /// [`Project::node_tests`] loads the test packs on a shared project. extensions: RefCell<Vec<(String, Option<PathBuf>)>>, + /// The `@gsd/core` block of the fixture's own committed `specforge.json` (`Null` without one), which + /// [`Project::settings_in`] keeps under a test's settings. + own_settings: serde_json::Value, } pub fn project(name: &str) -> Project { @@ -124,16 +127,17 @@ pub const TWIN_BUILTINS: [&str; 3] = ["@code/core", "@javascript/node-test", "@j /// The parity suite's taskboard fixture: its `spec/` twin of the GSD project beside its `.planning/`, loading /// [`TWIN_BUILTINS`]. +/// +/// Each twin keeps its own committed `specforge.json` settings under a test's (ADR 0390 D9): the twins record no +/// commits, so `specforge.task_commits: false` silences gsd/W407; and the ledger's crate is `0.1.0` under milestone +/// v1.0, so it lists `ledger` in `specforge.release_exempt` rather than move its source (neither choice moves a +/// golden). A test's own key wins. pub fn taskboard() -> Project { from_dir(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../parity/fixtures/taskboard")).twin() } /// The security parity suite's vault fixture: its `spec/` twin of the GSD project beside its `.planning/`, loading -/// [`TWIN_BUILTINS`] as the taskboard does. -#[allow( - dead_code, - reason = "core's own tests do not use it; @gsd/security's include this harness" -)] +/// [`TWIN_BUILTINS`] as the taskboard does, its own settings kept as [`taskboard`]'s are. pub fn vault() -> Project { from_dir(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../parity/fixtures/vault")).twin() } @@ -144,7 +148,8 @@ pub const RUST_TEST_COLLECTORS: [&str; 2] = ["rust-cargo", "rust-source"]; /// The parity suite's ledger fixture: a Rust project whose CI is red, its `spec/` twin beside its `.planning/`, /// loading beside `@gsd/core` the builtins `evaluation/gsd-ab/tasks.json` names as the ledger's `thread` (the code -/// facts and the Rust packs whose collectors read its manifest, its items and a nextest report). +/// facts and the Rust packs whose collectors read its manifest, its items and a nextest report). Its own settings are +/// kept as [`taskboard`]'s are. #[allow( dead_code, reason = "@gsd/security's tests include this harness and do not use it" @@ -219,7 +224,7 @@ fn from_dir_at(source: &Path, inside: &str) -> Project { let root = dir.path().join(inside); std::fs::create_dir_all(&root).expect("the project's directory"); copy_dir(source, &root); - let p = Project { + let mut p = Project { _dir: dir, root, source: Some(source.to_path_buf()), @@ -228,7 +233,12 @@ fn from_dir_at(source: &Path, inside: &str) -> Project { ("@gsd/core".to_string(), None), ("@specforge/checks".to_string(), None), ]), + own_settings: serde_json::Value::Null, }; + // Read before the first rewrite replaces the fixture's manifest; `Null` when the fixture commits none. + if source.join("specforge.json").is_file() { + p.own_settings = p.manifest()["settings"]["@gsd/core"].clone(); + } p.settings(serde_json::json!({})); p } @@ -239,7 +249,10 @@ impl Project { self.settings_in("spec", settings); } - /// [`Self::settings`] with the manifest's `spec_root` (`.`: the spec root is the project root). + /// [`Self::settings`] with the manifest's `spec_root` (`.`: the spec root is the project root). Only a fixture that + /// commits a `specforge.json` (today the taskboard, ledger and vault twins) has its own `@gsd/core` settings: they + /// stay under `settings`, whose keys win. The merge is shallow, by top-level key (settings are dotted flat keys), + /// so `settings(json!({}))` resets to the fixture's own settings, not to the defaults. pub fn settings_in(&self, spec_root: &str, settings: serde_json::Value) { // another extension's block survives a rewrite of core's let mut manifest = self.manifest(); @@ -247,7 +260,12 @@ impl Project { if !blocks.is_object() { blocks = serde_json::json!({}); } - blocks["@gsd/core"] = settings; + let mut core = self.own_settings.clone(); + match (core.as_object_mut(), settings.as_object()) { + (Some(own), Some(test)) => own.extend(test.clone()), + _ => core = settings, + } + blocks["@gsd/core"] = core; let extensions: Vec<String> = self .extensions .borrow() @@ -280,6 +298,46 @@ impl Project { self } + /// The state a GSD project is in before its import: every `.spec` file under the spec root and the fixture's + /// `specforge-harness` removed; `.planning/`, `specforge.json` and the sources kept. + #[allow( + dead_code, + reason = "@gsd/import's tests include this file and use it; core's do not" + )] + pub fn without_spec(self) -> Self { + fn remove_specs(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries { + let entry = entry.expect("a directory entry"); + let path = entry.path(); + // The entry's own type: a symlinked directory is not followed (a loop, or a tree outside the project). + if entry.file_type().expect("a file type").is_dir() { + remove_specs(&path); + } else if path.extension().is_some_and(|ext| ext == "spec") { + std::fs::remove_file(&path).expect("remove a .spec file"); + } + } + } + let spec_root = self.manifest()["spec_root"] + .as_str() + .unwrap_or("spec") + .to_string(); + assert!( + Path::new(&spec_root) + .components() + .all(|c| matches!(c, std::path::Component::Normal(_))), + "spec_root {spec_root:?} leaves the project" + ); + remove_specs(&self.root.join(spec_root)); + let harness = self.root.join("specforge-harness"); + if harness.is_file() { + std::fs::remove_file(harness).expect("remove specforge-harness"); + } + self + } + /// The taskboard twin's setup: [`TWIN_BUILTINS`] loaded. fn twin(self) -> Self { self.with_builtins(&TWIN_BUILTINS) diff --git a/gsd/core/tests/cli/harness_ab.rs b/gsd/core/tests/cli/harness_ab.rs index 8105d28086..de53ee12f0 100644 --- a/gsd/core/tests/cli/harness_ab.rs +++ b/gsd/core/tests/cli/harness_ab.rs @@ -169,6 +169,8 @@ pub fn seeded(task: &str, arm: &str, flags: &[&str]) -> Result<Project, String> root, source: None, extensions: RefCell::new(extensions), + // The arm's `specforge.json` is the copy's own: a test's settings replace it. + own_settings: serde_json::Value::Null, }) } diff --git a/gsd/core/tests/cli/interface_gate.rs b/gsd/core/tests/cli/interface_gate.rs new file mode 100644 index 0000000000..1a3bddf9af --- /dev/null +++ b/gsd/core/tests/cli/interface_gate.rs @@ -0,0 +1,172 @@ +//! gsd/E533 end to end (ADR 0390 D3 to D5, D7): the `release` project, a crate `adder` whose committed accepted +//! `tests/public-api.txt` lists `ops::add` and `ops::sub`, is collected over a saved cargo public-api capture +//! (`fresh-public-api.txt`) that lacks `ops::sub`. `@rust/api` marks the item `removed`, `derive` lists it in the open +//! milestone v1.8's `api_breaks`, and the close of v1.8 after the shipped v1.7 is refused under gsd-strict and gsd-plus. +//! Accepting the capture, a major bump and a first release each clear it. + +use serde_json::{Value, json}; + +use super::harness::{Project, RUST_TEST_COLLECTORS, project}; +use super::prompts_gates::{gate_failed, refused_by}; +use super::prompts_support::prompt; + +/// `(profile, blocks)`: the profiles that turn the release gates on (ADR 0390 D8). +pub(super) const PROFILES: [(&str, bool); 3] = [ + ("gsd-compat", false), + ("gsd-strict", true), + ("gsd-plus", true), +]; + +/// The builtins the `release` project loads beside `@gsd/core`: the code facts and the Rust packs whose collectors +/// read its manifest, its items and its public API. +const RUST_API: [&str; 4] = ["@code/core", "@rust/cargo", "@rust/source", "@rust/api"]; + +/// The saved capture of cargo public-api over the crate once `ops::sub` is dropped. +pub(super) const FRESH: &str = "fresh-public-api.txt"; + +const REMOVED: &str = "api:rust:adder::ops::sub"; + +/// The `release` project with [`RUST_API`] loaded and `settings` under `@gsd/core`; v1.7's `completion` is recorded +/// as `close_milestone` writes it, so v1.7 is shipped. +pub(super) fn release(settings: Value) -> Project { + let p = project("release").with_builtins(&RUST_API); + p.record_harness("v1.7", "completion", r#"{"at":"2026-10-01"}"#); + p.settings(settings); + p +} + +/// `collect` of the manifest and the items, then of the API over the saved `capture`. +pub(super) fn collect_api(p: &Project, capture: &str) { + let run = p.collect_report(&RUST_TEST_COLLECTORS, "rust-api", &p.root().join(capture)); + assert_eq!(run.code, 0, "{}", run.all()); +} + +/// `(code, message)` of each diagnostic the `complete_milestone` gate of `milestone` fails on; none when it renders. +pub(super) fn close(p: &Project, milestone: &str) -> Vec<(String, String)> { + let run = prompt(p, "complete_milestone", &[milestone], "claude-code"); + if run.code == 0 { + return Vec::new(); + } + gate_failed(&run)["data"]["failing"] + .as_array() + .expect("failing") + .iter() + .map(|d| { + let text = |key: &str| d[key].as_str().unwrap_or_default().to_string(); + (text("code"), text("message")) + }) + .collect() +} + +/// The messages of `code` (`gsd/E533`) at the close of `milestone`. +pub(super) fn named(p: &Project, milestone: &str, code: &str) -> Vec<String> { + close(p, milestone) + .into_iter() + .filter(|(c, _)| c == code) + .map(|(_, message)| message) + .collect() +} + +#[test] +fn e533_refuses_the_close_after_a_collected_removal_under_strict_and_plus() { + for (profile, blocks) in PROFILES { + let p = release(json!({ "profile": profile })); + collect_api(&p, FRESH); + let removed: Vec<Value> = p + .nodes_of("api_item") + .into_iter() + .filter(|n| n["id"] == REMOVED) + .collect(); + assert_eq!(removed.len(), 1, "{profile}: {removed:?}"); + assert_eq!(removed[0]["fields"]["change"], "removed", "{profile}"); + assert_eq!( + p.fields_of("v1.8")["api_breaks"], + json!([format!("removed {REMOVED}")]), + "{profile}" + ); + if blocks { + refused_by(&p, "complete_milestone", &["v1.8"], "E533"); + let found = named(&p, "v1.8", "gsd/E533"); + assert_eq!(found.len(), 1, "{profile}: {found:?}"); + assert!( + found[0].contains(REMOVED) && found[0].contains("'v1.7'"), + "{profile}: {found:?}" + ); + } else { + assert_eq!(named(&p, "v1.8", "gsd/E533"), Vec::<String>::new()); + } + } +} + +#[test] +fn e533_refuses_each_break_of_a_close_once() { + let p = release(json!({ "profile": "gsd-strict" })); + // `ops::add` widened to i64 and `ops::sub` dropped: two breaks, one error each, sorted by id. + p.write( + "two-breaks.txt", + "pub mod adder\npub mod adder::ops\npub fn adder::ops::add(a: i64, b: i64) -> i64\n", + ); + collect_api(&p, "two-breaks.txt"); + assert_eq!( + p.fields_of("v1.8")["api_breaks"], + json!([ + "changed api:rust:adder::ops::add", + format!("removed {REMOVED}") + ]) + ); + assert_eq!( + named(&p, "v1.8", "gsd/E533"), + [ + "API item 'api:rust:adder::ops::add' is changed without a major version bump: milestone 'v1.8' is \ + compatible with the last shipped 'v1.7'", + "API item 'api:rust:adder::ops::sub' is removed without a major version bump: milestone 'v1.8' is \ + compatible with the last shipped 'v1.7'" + ] + ); +} + +#[test] +fn e533_is_silent_once_the_fresh_api_is_committed_as_accepted() { + let p = release(json!({ "profile": "gsd-strict" })); + collect_api(&p, FRESH); + assert_eq!(named(&p, "v1.8", "gsd/E533").len(), 1); + // Accepting the break: the updated report committed in place of the old one, then collected again. + p.write("tests/public-api.txt", &p.read(FRESH)); + collect_api(&p, FRESH); + assert_eq!(p.fields_of("v1.8")["api_breaks"], json!([])); + assert_eq!(named(&p, "v1.8", "gsd/E533"), Vec::<String>::new()); +} + +#[test] +fn e533_is_silent_for_a_major_bump() { + let p = release(json!({ "profile": "gsd-strict" })); + collect_api(&p, FRESH); + assert_eq!(named(&p, "v1.8", "gsd/E533").len(), 1); + p.edit("spec/milestones.spec", "milestone v1.8 ", "milestone v2.0 "); + p.edit( + "spec/milestones.spec", + "milestone v1.8", + "milestone v2.0", + ); + // The break is still there; v2.0 is not compatible with v1.7, so it is allowed. + assert_eq!( + p.fields_of("v2.0")["api_breaks"], + json!([format!("removed {REMOVED}")]) + ); + assert_eq!(named(&p, "v2.0", "gsd/E533"), Vec::<String>::new()); +} + +#[test] +fn e533_is_silent_for_a_first_release() { + let p = release(json!({ "profile": "gsd-strict" })); + collect_api(&p, FRESH); + assert_eq!(named(&p, "v1.8", "gsd/E533").len(), 1); + // v1.7 not shipped: there is no release before v1.8 to break. + p.edit( + "spec/milestones.spec", + " completion {\n at 2026-10-01\n }\n", + "", + ); + assert_eq!(p.fields_of("v1.7")["state"], "planned"); + assert_eq!(named(&p, "v1.8", "gsd/E533"), Vec::<String>::new()); +} diff --git a/gsd/core/tests/cli/main.rs b/gsd/core/tests/cli/main.rs index e2d98ccd6c..48749d648a 100644 --- a/gsd/core/tests/cli/main.rs +++ b/gsd/core/tests/cli/main.rs @@ -77,6 +77,7 @@ mod host_options; mod install_agents; mod install_hosts; mod install_skills; +mod interface_gate; mod judged; mod judged_flow; mod judged_prohibition; @@ -133,6 +134,7 @@ mod quick_context; mod re_verify; mod reference; mod rejudge_scope; +mod release_gate; mod render_prompts; mod rendered_lines; mod roadmap; diff --git a/gsd/core/tests/cli/parity_scenario.rs b/gsd/core/tests/cli/parity_scenario.rs index d7f06582c0..45ccf5c35d 100644 --- a/gsd/core/tests/cli/parity_scenario.rs +++ b/gsd/core/tests/cli/parity_scenario.rs @@ -157,6 +157,8 @@ fn every_taskboard_golden_is_compared_once() { name.rsplit_once('.') .map_or(name.clone(), |(stem, _)| stem.to_string()) }) + // Recorded tool reports, compared by the gate's dogfood check, not the scenario (CONTEXT D-15). + .filter(|name| name != "reports") .collect(); assert_eq!(on_disk.len(), 19, "the recorded goldens"); let listed: Vec<&str> = SCENARIO.iter().map(|(g, ..)| *g).collect(); diff --git a/gsd/core/tests/cli/release_gate.rs b/gsd/core/tests/cli/release_gate.rs new file mode 100644 index 0000000000..bfd26547b9 --- /dev/null +++ b/gsd/core/tests/cli/release_gate.rs @@ -0,0 +1,195 @@ +//! gsd/E535 end to end (ADR 0390 D6, D7) on the `release` project of [`super::interface_gate`]: the close of the open +//! milestone v1.8 after the shipped v1.7 is refused for a package not at the milestone's version, for a version that +//! goes backwards, and for a last release whose tag resolves to no commit; an exempt package, a lightweight or an +//! annotated tag, and `git.create_tag: false` are not. Each silent case follows the same project firing. The trace +//! route shows the evidence. + +use serde_json::{Value, json}; + +use super::harness::Project; +use super::interface_gate::{FRESH, PROFILES, collect_api, named, release}; +use super::prompts_gates::refused_by; + +const E535: &str = "gsd/E535"; + +/// Sets the crate's version in `Cargo.toml` (it is `1.8.0`), then collects the manifest. +fn at_version(p: &Project, version: &str) { + let text = p.read("Cargo.toml"); + let from = text + .lines() + .find(|l| l.starts_with("version = ")) + .expect("the package version") + .to_string(); + p.write( + "Cargo.toml", + &text.replacen(&from, &format!("version = \"{version}\""), 1), + ); + let run = p.collect(&["--runner", "rust-cargo"]); + assert_eq!(run.code, 0, "{}", run.all()); +} + +/// The project committed in a repository of its own, its tags collected by `gsd-git`. +fn tags_collected(p: &Project) { + p.commit(); + collect_tags(p); +} + +fn collect_tags(p: &Project) { + let run = p.collect(&["--runner", "gsd-git"]); + assert_eq!(run.code, 0, "{}", run.all()); +} + +#[test] +fn e535_refuses_a_package_not_at_the_milestones_version_under_strict_and_plus() { + for (profile, blocks) in PROFILES { + let p = release(json!({ "profile": profile })); + at_version(&p, "1.7.0"); + assert_eq!( + p.fields_of("v1.8")["release"]["packages"], + json!([{ "name": "adder", "version": "1.7.0" }]), + "{profile}" + ); + let found = named(&p, "v1.8", E535); + if blocks { + refused_by(&p, "complete_milestone", &["v1.8"], "E535"); + assert_eq!( + found, + ["package 'adder' is at version '1.7.0', not at the version of milestone 'v1.8'"], + "{profile}" + ); + } else { + assert_eq!(found, Vec::<String>::new(), "{profile}"); + } + } +} + +#[test] +fn e535_is_silent_for_a_package_at_the_milestones_version() { + let p = release(json!({ "profile": "gsd-strict" })); + at_version(&p, "1.7.0"); + assert_eq!(named(&p, "v1.8", E535).len(), 1); + at_version(&p, "1.8.0"); + assert_eq!(p.fields_of("v1.8")["release"]["packages"], json!([])); + assert_eq!(named(&p, "v1.8", E535), Vec::<String>::new()); +} + +#[test] +fn e535_is_silent_for_an_exempt_package() { + let p = release(json!({ "profile": "gsd-strict" })); + at_version(&p, "1.7.0"); + assert_eq!(named(&p, "v1.8", E535).len(), 1); + p.settings(json!({ "profile": "gsd-strict", "specforge.release_exempt": ["adder"] })); + assert_eq!(named(&p, "v1.8", E535), Vec::<String>::new()); +} + +#[test] +fn e535_refuses_a_milestone_that_goes_backwards() { + let p = release(json!({ "profile": "gsd-strict" })); + at_version(&p, "1.8.0"); + assert_eq!(named(&p, "v1.8", E535), Vec::<String>::new()); + // The open milestone renamed v1.6 beside the shipped v1.7, its package at its own version. + p.edit("spec/milestones.spec", "milestone v1.8 ", "milestone v1.6 "); + p.edit( + "spec/milestones.spec", + "milestone v1.8", + "milestone v1.6", + ); + at_version(&p, "1.6.0"); + refused_by(&p, "complete_milestone", &["v1.6"], "E535"); + assert_eq!( + named(&p, "v1.6", E535), + ["milestone 'v1.6' goes backwards from the last shipped 'v1.7': its version is not later"] + ); +} + +/// The message of the tag part, naming the last shipped release. +const UNTAGGED: &str = "the tag 'v1.7' of the shipped milestone 'v1.7' resolves to no commit"; + +#[test] +fn e535_refuses_until_the_last_release_is_tagged() { + for (profile, blocks) in PROFILES { + let p = release(json!({ "profile": profile })); + tags_collected(&p); + assert_eq!(p.fields_of("v1.7")["tag"], json!({ "name": "v1.7" })); + if !blocks { + assert_eq!(named(&p, "v1.8", E535), Vec::<String>::new(), "{profile}"); + continue; + } + refused_by(&p, "complete_milestone", &["v1.8"], "E535"); + assert_eq!(named(&p, "v1.8", E535), [UNTAGGED], "{profile}"); + p.git(&["tag", "v1.7"], "2026-10-01T12:00:00Z"); + collect_tags(&p); + let head = p.head(); + assert_eq!(p.fields_of("v1.7")["tag"]["commit"], json!(head)); + assert_eq!(named(&p, "v1.8", E535), Vec::<String>::new(), "{profile}"); + } +} + +#[test] +fn e535_is_silent_for_an_annotated_tag() { + let p = release(json!({ "profile": "gsd-strict" })); + tags_collected(&p); + assert_eq!(named(&p, "v1.8", E535), [UNTAGGED]); + // An annotated tag resolves to the commit it tags, not to the tag object. + p.git( + &["tag", "-a", "v1.7", "-m", "release"], + "2026-10-01T12:00:00Z", + ); + collect_tags(&p); + assert_eq!(p.fields_of("v1.7")["tag"]["commit"], json!(p.head())); + assert_eq!(named(&p, "v1.8", E535), Vec::<String>::new()); +} + +#[test] +fn e535_is_silent_when_the_project_creates_no_tag() { + let p = release(json!({ "profile": "gsd-strict" })); + tags_collected(&p); + assert_eq!(named(&p, "v1.8", E535), [UNTAGGED]); + p.settings(json!({ "profile": "gsd-strict", "git.create_tag": false })); + collect_tags(&p); + assert_eq!(named(&p, "v1.8", E535), Vec::<String>::new()); +} + +/// `specforge trace <milestone> --format json`. +fn trace(p: &Project, milestone: &str) -> Value { + let run = p.run(&["trace", milestone, "--format", "json"]); + serde_json::from_str(&run.stdout) + .unwrap_or_else(|e| panic!("trace prints JSON ({e}): {}", run.all())) +} + +/// The start's annotation `name`'s values. +fn annotation(trace: &Value, name: &str) -> Value { + trace["annotations"] + .as_array() + .expect("the start's annotations") + .iter() + .find(|a| a["name"] == name) + .unwrap_or_else(|| panic!("no annotation {name}: {trace:#}"))["values"] + .clone() +} + +#[test] +fn trace_follows_the_milestone_release_route() { + let p = release(json!({ "profile": "gsd-strict" })); + at_version(&p, "1.7.0"); + collect_api(&p, FRESH); + let found = trace(&p, "v1.8"); + assert_eq!(found["route"], "gsd/milestone-release", "{found:#}"); + assert_eq!( + annotation(&found, "api_breaks"), + json!(["removed api:rust:adder::ops::sub"]), + "{found:#}" + ); + let release: Value = serde_json::from_str( + annotation(&found, "release")[0] + .as_str() + .expect("the release, as JSON text"), + ) + .expect("JSON"); + assert_eq!( + release, + json!({ "packages": [{ "name": "adder", "version": "1.7.0" }] }), + "{found:#}" + ); + assert_eq!(found["steps"][0]["matches"][0]["entity_id"], "v1.8/01"); +} diff --git a/gsd/core/tests/cli/rules_silent.rs b/gsd/core/tests/cli/rules_silent.rs index 976122b373..287a33e791 100644 --- a/gsd/core/tests/cli/rules_silent.rs +++ b/gsd/core/tests/cli/rules_silent.rs @@ -4,19 +4,22 @@ use serde_json::json; -use super::harness::{judged, project, taskboard}; +use super::harness::{Project, judged, ledger, project, taskboard, vault}; +use super::interface_gate::{PROFILES, close, named}; #[test] fn the_clean_twin_is_silent_for_the_unjudged_codes() { - /// The unjudged codes the taskboard twin must never report, under any of the three profiles. `W407` is the one the - /// twin reports under strict and plus (its tasks carry no commit), so `task_without_commit_is_w407_...` holds it. - const SILENT_ON_THE_TWIN: [&str; 61] = [ + /// The unjudged codes the taskboard twin must never report, under any of the three profiles. `W407` is among them: + /// the twin records no commits, and its own `specforge.json` says so (`specforge.task_commits: false`, ADR 0390 D9). + /// E533 and E535 are not here: a guard answers only at a gate, never in `codes()`; the twins' close gate is + /// [`the_twins_are_clean_under_every_profile`]. + const SILENT_ON_THE_TWIN: [&str; 62] = [ "E101", "E102", "W103", "W104", "E105", "E106", "E107", "E108", "E201", "W204", "E206", "E301", "E302", "E303", "W304", "W305", "W306", "E307", "W308", "W309", "E310", "E312", "E314", "W317", "W318", "E319", "E320", "I321", "E322", "W323", "W324", "E507", "E401", - "E402", "W403", "W404", "E405", "W406", "W408", "W409", "E502", "E503", "W504", "E505", - "W506", "E509", "W510", "E511", "E512", "E513", "E515", "E516", "E517", "W520", "E521", - "W522", "E523", "W524", "W526", "I527", "W109", + "E402", "W403", "W404", "E405", "W406", "W407", "W408", "W409", "E502", "E503", "W504", + "E505", "W506", "E509", "W510", "E511", "E512", "E513", "E515", "E516", "E517", "W520", + "E521", "W522", "E523", "W524", "W526", "I527", "W109", ]; for profile in ["gsd-compat", "gsd-strict", "gsd-plus"] { let p = taskboard(); @@ -31,6 +34,98 @@ fn the_clean_twin_is_silent_for_the_unjudged_codes() { } } +/// What the vault twin carries by design under every profile (its README), sorted: `@gsd/security`'s undeclared peer +/// `@specforge/checks` (W019), phase 02's one success criterion (gsd/W103), the duplicate threat ID the fixture exists +/// to carry (gsd.security/E101, once per claim), and the security workflow's owed verdicts (gsd.security/W302 on each +/// closed threat, W303 on the audit), which `@gsd/security`'s book judges and core's harness does not know. +const VAULT_CARRIES: [&str; 10] = [ + "W019", + "gsd.security/E101", + "gsd.security/E101", + "gsd.security/W302", + "gsd.security/W302", + "gsd.security/W302", + "gsd.security/W302", + "gsd.security/W302", + "gsd.security/W303", + "gsd/W103", +]; + +/// A twin's name, its constructor, the collector that reads its manifest into package facts, and what it reports by +/// design. +type Twin = ( + &'static str, + fn() -> Project, + &'static str, + &'static [&'static str], +); + +const TWINS: [Twin; 3] = [ + ("taskboard", taskboard, "javascript-source", &[]), + ("ledger", ledger, "rust-cargo", &[]), + ("vault", secured_vault, "javascript-source", &VAULT_CARRIES), +]; + +/// The vault twin as its parity suite loads it: its `spec/` holds `@gsd/security`'s kinds. +fn secured_vault() -> Project { + vault().with_extension("@gsd/security", "GSD_SECURITY_WASM") +} + +/// Success criterion 5 of the release guards (ADR 0390 D9): taskboard and ledger report no code under each profile, +/// and the vault only what it carries by design ([`VAULT_CARRIES`]); once each twin's package facts are collected, +/// the close gate of its milestone v1.0 names none of gsd/W407, gsd/E533 and gsd/E535 (it may name other gate codes: +/// the twins' milestones are not audited). E535 is judged over the package versions. E533 is silent for want of input: +/// no twin loads an API pack, so v1.0's `api_breaks` is absent, which the test asserts. +#[test] +fn the_twins_are_clean_under_every_profile() { + for (name, twin, collector, carries) in TWINS { + for (profile, _) in PROFILES { + let p = twin(); + p.settings(json!({ "profile": profile })); + let mut codes = p.codes(); + codes.sort(); + assert_eq!(codes, carries, "{name} {profile}"); + let run = p.collect(&["--runner", collector]); + assert_eq!(run.code, 0, "{name} {profile}: {}", run.all()); + let versions: Vec<_> = p + .nodes_of("package") + .into_iter() + .filter(|n| n["fields"]["version"].is_string()) + .collect(); + assert!( + !versions.is_empty(), + "{name}: no package fact with a version" + ); + assert!( + p.fields_of("v1.0")["api_breaks"].is_null(), + "{name} {profile}: an API break was observed" + ); + let closed: Vec<String> = close(&p, "v1.0").into_iter().map(|(c, _)| c).collect(); + for code in ["gsd/W407", "gsd/E533", "gsd/E535"] { + assert!( + !closed.contains(&code.to_string()), + "{name} {profile}: {closed:?}" + ); + } + } + } +} + +/// The ledger's crate is `0.1.0` under milestone v1.0: its own `specforge.release_exempt` is what keeps gsd/E535 silent. +#[test] +fn e535_on_the_ledger_is_silenced_by_its_own_exemption() { + let p = ledger(); + p.settings(json!({ "profile": "gsd-strict", "specforge.release_exempt": [] })); + let run = p.collect(&["--runner", "rust-cargo"]); + assert_eq!(run.code, 0, "{}", run.all()); + assert_eq!( + named(&p, "v1.0", "gsd/E535"), + ["package 'ledger' is at version '0.1.0', not at the version of milestone 'v1.0'"] + ); + p.settings(json!({ "profile": "gsd-strict" })); + assert_eq!(named(&p, "v1.0", "gsd/E535"), Vec::<String>::new()); +} + /// Whether the report has a judged diagnostic of `code` on `entity`. fn owed(p: &super::harness::Project, code: &str, entity: &str) -> bool { judged(&p.report_all()) diff --git a/gsd/core/tests/cli/settings.rs b/gsd/core/tests/cli/settings.rs index 7446c40f9f..50e868d274 100644 --- a/gsd/core/tests/cli/settings.rs +++ b/gsd/core/tests/cli/settings.rs @@ -33,7 +33,7 @@ fn specforge_settings_lists_gsd_core_defaults() { let defaults = listed(&p, false); assert_eq!( defaults.len(), - 147, + 150, "settings with a default (15 of them the balanced profile's model_overrides, 10 the surface clusters)" ); for detected in ["brave_search", "firecrawl", "exa_search"] { @@ -64,8 +64,8 @@ fn specforge_settings_lists_gsd_core_defaults() { let all = listed(&p, true); assert_eq!( all.len(), - 220, - "194 keys (the 10 surface clusters among them), 11 families and the 15 model_overrides the profile presets (listed in place of the family)" + 223, + "197 keys (the 10 surface clusters among them), 11 families and the 15 model_overrides the profile presets (listed in place of the family)" ); assert!(all.contains_key("models.*") && all.contains_key("review.reviewer_instances.*.*")); } @@ -135,7 +135,7 @@ fn gsd_strict_raises_w103_to_an_error() { } /// The SpecForge gates each profile switches on, as `specforge settings` lists the codes it leaves gated off: none -/// under gsd-compat, all but cross-workstream conflicts (gsd/E517) under gsd-strict, all six under gsd-plus; and an +/// under gsd-compat, all but cross-workstream conflicts (gsd/E517) under gsd-strict, all eight under gsd-plus; and an /// explicit setting beside the profile beats its preset. #[test] fn each_profile_switches_on_its_specforge_gates_and_an_explicit_setting_wins() { @@ -144,23 +144,24 @@ fn each_profile_switches_on_its_specforge_gates_and_an_explicit_setting_wins() { let r = resolved(p, &[]); let all = strings(&r["gated"]); [ - "gsd/W407", "gsd/E515", "gsd/E516", "gsd/E517", "gsd/W520", "gsd/E521", + "gsd/W407", "gsd/E515", "gsd/E516", "gsd/E517", "gsd/W520", "gsd/E521", "gsd/E533", + "gsd/E535", ] .map(|code| all.contains(&code)) }; - assert_eq!(gated(&p), [true; 6], "gsd-compat gates all six"); + assert_eq!(gated(&p), [true; 8], "gsd-compat gates all eight"); p.settings(serde_json::json!({ "profile": "gsd-strict" })); assert_eq!( gated(&p), - [false, false, false, true, false, false], + [false, false, false, true, false, false, false, false], "strict switches on all but cross-workstream conflicts" ); p.settings(serde_json::json!({ "profile": "gsd-plus" })); - assert_eq!(gated(&p), [false; 6], "plus switches on all six"); + assert_eq!(gated(&p), [false; 8], "plus switches on all eight"); p.settings(serde_json::json!({ "profile": "gsd-plus", "specforge.task_commits": false })); assert_eq!( gated(&p), - [true, false, false, false, false, false], + [true, false, false, false, false, false, false, false], "an explicit setting beats the profile" ); } diff --git a/gsd/core/tests/cli/source_items.rs b/gsd/core/tests/cli/source_items.rs index 440ea365c1..9b2877eaea 100644 --- a/gsd/core/tests/cli/source_items.rs +++ b/gsd/core/tests/cli/source_items.rs @@ -60,8 +60,26 @@ fn the_twins_sources_collect_as_item_facts() { "public", 3 ), + item( + "js:taskboard/test/tasks.test.js::a task is added with the next id", + "function", + "private", + 6 + ), + item( + "js:taskboard/test/tasks.test.js::a task is completed by its id", + "function", + "private", + 13 + ), + item( + "js:taskboard/test/tasks.test.js::completing an unknown id throws", + "function", + "private", + 20 + ), ], - "nothing from test/tasks.test.js" + "from test/tasks.test.js only its three test calls (ADR 0393 D4)" ); let packages: Vec<String> = p .nodes_of("package") diff --git a/gsd/core/tests/declaration.rs b/gsd/core/tests/declaration.rs index c81a7b2aeb..73d158a396 100644 --- a/gsd/core/tests/declaration.rs +++ b/gsd/core/tests/declaration.rs @@ -162,7 +162,7 @@ fn the_code_book_matches_rules_md() { from_book, from_md, "the code book and rules.md list different codes" ); - assert_eq!(book.len(), 73); + assert_eq!(book.len(), 75); for row in &rows { let code = book .iter() @@ -263,10 +263,10 @@ fn the_kinds_golden() { ); } -/// ADR 0331 D8, ADR 0371 D7: the one route, `gsd/requirement-thread` once qualified by the short name, as `specforge trace` follows -/// it from a requirement. +/// ADR 0331 D8, ADR 0371 D7: `gsd/requirement-thread` once qualified by the short name, as `specforge trace` follows +/// it from a requirement; ADR 0390 D10: `gsd/milestone-release`, a milestone's release evidence and its phases. #[test] -fn the_requirement_route_is_declared() { +fn the_routes_are_declared() { assert_eq!( describe("routes")["items"], serde_json::json!([{ @@ -288,6 +288,18 @@ fn the_requirement_route_is_declared() { {"name": "deliverable", "via": "<deliverable.requirement", "from": "start", "label": "deliverable", "annotations": [{"field": "checks.ref"}]}, ] + }, { + "name": "milestone-release", + "description": "A milestone's release evidence: its API breaks, its release (tag, commit, packages) and its recorded tag, and its phases", + "start": "milestone", + "annotations": [ + {"field": "api_breaks"}, + {"field": "release"}, + {"field": "tag"}, + ], + "steps": [ + {"name": "phase", "via": "<phase.milestone", "label": "phase"}, + ] }]) ); } diff --git a/gsd/core/tests/declaration_project.rs b/gsd/core/tests/declaration_project.rs index 989efdd363..1c97aa4d5a 100644 --- a/gsd/core/tests/declaration_project.rs +++ b/gsd/core/tests/declaration_project.rs @@ -65,7 +65,7 @@ fn phase_and_milestone_are_named_by_their_title() { #[test] fn milestone_and_phase_declare_the_fields_of_the_model() { let milestone = "delivered accomplishments whats_next goal target_features abandoned workstream completion \ - state first_commit shipped stats git_range progress branch"; + state first_commit shipped stats git_range progress branch api_breaks release tag"; let milestone: Vec<&str> = milestone.split_whitespace().collect(); assert_eq!(fields_of("milestone"), milestone); assert_eq!( @@ -156,9 +156,12 @@ fn the_roadmap_kinds_declare_every_field_of_project_md() { // + 2: the requirement's computed `proof` (its thread's state) and `satisfied_by` (the items its tasks' commits changed). // + 2: the phase's computed `critical_path` and `critical_weight` (its heaviest chain of plans). // - 2: the milestone's and the phase's `name`: each is named by its title (ADR 0387). + // + 1: the milestone's computed `api_breaks` (ADR 0390 D4). + // + 1: the milestone's computed `release` (ADR 0390 D6). + // + 1: the milestone's harness `tag`, written by gsd-git (ADR 0390 D6). assert_eq!( total, - 68 + 3 - 2 + 1 + 2 + 2 + 2 + 2 + 2 + 2 - 2, + 68 + 3 - 2 + 1 + 2 + 2 + 2 + 2 + 2 + 2 - 2 + 1 + 1 + 1, "the kinds' fields" ); } diff --git a/gsd/core/tests/declaration_verify.rs b/gsd/core/tests/declaration_verify.rs index 2fec1788a8..e752004fa0 100644 --- a/gsd/core/tests/declaration_verify.rs +++ b/gsd/core/tests/declaration_verify.rs @@ -88,7 +88,9 @@ fn the_guards_are_declared_with_their_reports() { reported.sort(); assert_eq!( reported, - ["E106", "E511", "E512", "E515", "E516", "W318", "W404"], + [ + "E106", "E511", "E512", "E515", "E516", "E533", "E535", "W318", "W404" + ], "{passes}" ); // A guard answers no values. diff --git a/gsd/core/tests/golden/codebook.json b/gsd/core/tests/golden/codebook.json index 1e507b0158..ed1e461f18 100644 --- a/gsd/core/tests/golden/codebook.json +++ b/gsd/core/tests/golden/codebook.json @@ -442,6 +442,18 @@ "docs": "https://github.com/leaderiop/SpecForge/blob/main/gsd/core/spec/rules.md#project-and-roadmap", "explanation": "A phase's title does not begin with a phase number: its label reads the number from its id. It is a warning, and an error under gsd-strict and gsd-plus.", "title": "Phase title embeds a number" + }, + { + "code": "E533", + "docs": "https://github.com/leaderiop/SpecForge/blob/main/gsd/core/spec/rules.md#project-and-roadmap", + "explanation": "A milestone whose API facts show a changed, narrowed or removed item is closed while its version is API-compatible with the last shipped milestone of its workstream scope (Cargo's rule: for 0.x the minor counts as major), or while its name is not a version, so no major bump can be shown. It is an error.", + "title": "Breaking API change without a major version bump" + }, + { + "code": "E535", + "docs": "https://github.com/leaderiop/SpecForge/blob/main/gsd/core/spec/rules.md#project-and-roadmap", + "explanation": "A milestone named by its version is closed while a package fact's version is not its version, while its version is not later than the last shipped milestone of its workstream scope, or while the last shipped milestone's tag does not resolve to a commit. It is an error.", + "title": "Release evidence does not match the milestone" } ] } diff --git a/gsd/core/tests/golden/kinds.json b/gsd/core/tests/golden/kinds.json index 7dafe8e6dc..65d23d33a8 100644 --- a/gsd/core/tests/golden/kinds.json +++ b/gsd/core/tests/golden/kinds.json @@ -1820,6 +1820,125 @@ "required": false, "target_kind": null, "writer": "computed" + }, + { + "default_value": null, + "description": "the API items the last collect found changed, narrowed or removed against the committed accepted report: `<change> <id>`; absent when no API fact carries a change; gsd/E533 reads it", + "edge": null, + "field_type": "string_list", + "inverse_of": null, + "name": "api_breaks", + "required": false, + "target_kind": null, + "writer": "computed" + }, + { + "default_value": null, + "description": "the release evidence gsd/E535 reads: `tag` and `commit` the recorded tag of a shipped milestone, `packages` the `name` and `version` of each package fact not at an open milestone's version, at most 50, and `more` the count past them; absent when nothing was observed", + "edge": null, + "field_type": "block", + "inverse_of": null, + "members": [ + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "tag", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "commit", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "block_list", + "inverse_of": null, + "members": [ + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "name", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "version", + "required": false, + "target_kind": null + } + ], + "name": "packages", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "integer", + "inverse_of": null, + "name": "more", + "required": false, + "target_kind": null + } + ], + "name": "release", + "required": false, + "target_kind": null, + "writer": "computed" + }, + { + "default_value": null, + "description": "written by gsd-git from `refs/tags/v<version>` for a shipped milestone named by its version: the tag's `name`, and the `commit` it resolves to, absent when it resolves to none", + "edge": null, + "field_type": "block", + "inverse_of": null, + "members": [ + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "name", + "required": false, + "target_kind": null + }, + { + "default_value": null, + "description": null, + "edge": null, + "field_type": "string", + "inverse_of": null, + "name": "commit", + "required": false, + "target_kind": null + } + ], + "name": "tag", + "required": false, + "target_kind": null, + "writer": "harness" } ], "has_body_parser": false, diff --git a/gsd/core/tests/golden/prompts/claude-code/complete_milestone.json b/gsd/core/tests/golden/prompts/claude-code/complete_milestone.json index 6b6fe1d1fa..62060930de 100644 --- a/gsd/core/tests/golden/prompts/claude-code/complete_milestone.json +++ b/gsd/core/tests/golden/prompts/claude-code/complete_milestone.json @@ -220,6 +220,16 @@ "code": "gsd/E516", "off": true, "passes": true + }, + { + "code": "gsd/E533", + "off": true, + "passes": true + }, + { + "code": "gsd/E535", + "off": true, + "passes": true } ], "id": "close", diff --git a/gsd/core/tests/golden/prompts/codex/complete_milestone.json b/gsd/core/tests/golden/prompts/codex/complete_milestone.json index 0c7a4450ad..458a8c809c 100644 --- a/gsd/core/tests/golden/prompts/codex/complete_milestone.json +++ b/gsd/core/tests/golden/prompts/codex/complete_milestone.json @@ -220,6 +220,16 @@ "code": "gsd/E516", "off": true, "passes": true + }, + { + "code": "gsd/E533", + "off": true, + "passes": true + }, + { + "code": "gsd/E535", + "off": true, + "passes": true } ], "id": "close", diff --git a/gsd/core/tests/golden/prompts/cursor/complete_milestone.json b/gsd/core/tests/golden/prompts/cursor/complete_milestone.json index c8824498e0..215c498703 100644 --- a/gsd/core/tests/golden/prompts/cursor/complete_milestone.json +++ b/gsd/core/tests/golden/prompts/cursor/complete_milestone.json @@ -220,6 +220,16 @@ "code": "gsd/E516", "off": true, "passes": true + }, + { + "code": "gsd/E533", + "off": true, + "passes": true + }, + { + "code": "gsd/E535", + "off": true, + "passes": true } ], "id": "close", diff --git a/gsd/core/tests/one_reader.rs b/gsd/core/tests/one_reader.rs index 35043a95b1..541abc689d 100644 --- a/gsd/core/tests/one_reader.rs +++ b/gsd/core/tests/one_reader.rs @@ -40,7 +40,7 @@ fn no_gsd_code_splits_a_markdown_table_row_by_hand() { let mut found = Vec::new(); let mut exempt_hit = vec![false; EXEMPT.len()]; let mut scanned = 0; - for dir in ["kit", "core", "security"] { + for dir in ["kit", "core", "security", "import"] { for path in files::under(&root.join(dir)) { let relative = path .strip_prefix(&root) diff --git a/gsd/core/tests/parity_roster.rs b/gsd/core/tests/parity_roster.rs index 97f7efc0c1..21a92f7282 100644 --- a/gsd/core/tests/parity_roster.rs +++ b/gsd/core/tests/parity_roster.rs @@ -466,7 +466,7 @@ fn the_acceptance_counts_match() { assert_eq!(accept::hooks(), [29, 16, 0, 11, 2]); assert_eq!(accept::capabilities(), [45, 17, 10, 0, 18]); assert_eq!(accept::gate_cutover(), [171, 93, 51, 14, 13]); - assert_eq!(accept::codes(), [73, 73, 0, 0, 0]); + assert_eq!(accept::codes(), [75, 75, 0, 0, 0]); assert_eq!(accept::config_keys()[0], 212); } diff --git a/gsd/core/tests/parity_rules.rs b/gsd/core/tests/parity_rules.rs index 72b3772ca9..f8c053a81e 100644 --- a/gsd/core/tests/parity_rules.rs +++ b/gsd/core/tests/parity_rules.rs @@ -1,6 +1,6 @@ //! The parity rules check (D-r44-3, D-r44-22): the code book and the gate-cutover verdicts are accounted in one place. //! -//! `evidence.rs` names, for each of the code book's 73 codes, a test that makes it fire and a test that keeps it +//! `evidence.rs` names, for each of the code book's 75 codes, a test that makes it fire and a test that keeps it //! silent; `cutover.rs` classifies each of the 171 recorded verdicts of gsd-core's `gate-cutover` fixtures. The //! black-box half, which runs the twin projects, is `tests/cli/parity_gate_cutover.rs`. @@ -100,7 +100,7 @@ fn names_code(fns: &[(String, String)], name: &str, code: &str) -> bool { fn every_code_fires_and_stays_silent() { let fns = test_fns(); let book = codes(); - assert_eq!(book.len(), 73, "the code book has 73 codes"); + assert_eq!(book.len(), 75, "the code book has 75 codes"); let listed: Vec<&str> = RULE_EVIDENCE.iter().map(|(c, _)| *c).collect(); assert_eq!(listed, book, "RULE_EVIDENCE lists the code book, in order"); let mut bad = Vec::new(); diff --git a/gsd/core/tests/parity_rules/evidence.rs b/gsd/core/tests/parity_rules/evidence.rs index 64f087ad8d..6c73fa56ca 100644 --- a/gsd/core/tests/parity_rules/evidence.rs +++ b/gsd/core/tests/parity_rules/evidence.rs @@ -9,7 +9,7 @@ pub enum Evidence { }, } -pub const RULE_EVIDENCE: [(&str, Evidence); 73] = [ +pub const RULE_EVIDENCE: [(&str, Evidence); 75] = [ ( "E101", Evidence::Tests { @@ -521,4 +521,18 @@ pub const RULE_EVIDENCE: [(&str, Evidence); 73] = [ silent: "the_clean_twin_is_silent_for_the_unjudged_codes", }, ), + ( + "E533", + Evidence::Tests { + fires: "e533_refuses_a_removed_item_without_a_major_bump", + silent: "e533_allows_a_break_at_a_major_bump", + }, + ), + ( + "E535", + Evidence::Tests { + fires: "e535_refuses_a_package_not_at_the_milestones_version", + silent: "e535_allows_a_release_whose_packages_match", + }, + ), ]; diff --git a/gsd/core/tests/port.lock b/gsd/core/tests/port.lock index eacad39b6f..fd240785b3 100644 --- a/gsd/core/tests/port.lock +++ b/gsd/core/tests/port.lock @@ -2397,7 +2397,7 @@ gsd-core/workflows/complete-milestone.md own 46+3 3 a01dd0c4f6b0 099c9aa598ee po gsd-core/workflows/complete-milestone.md kept 49+12 06f6928b1eda gsd-core/workflows/complete-milestone.md own 61+1 1 9ed72da09648 a3e5342b200e prose gsd-core/workflows/complete-milestone.md kept 62+3 3ebf27bb6494 -gsd-core/workflows/complete-milestone.md own 65+3 3 09a6bd3df91f e173d06f99db typed-edit +gsd-core/workflows/complete-milestone.md own 65+3 3 09a6bd3df91f dbf53e0438c0 typed-edit gsd-core/workflows/complete-milestone.md kept 68+2 d3325a506fe8 gsd-core/workflows/complete-milestone.md own 70+3 3 da61c80be615 8de42b67479e ported-name gsd-core/workflows/complete-milestone.md kept 73+7 7b995ce7ecb1 @@ -2474,7 +2474,7 @@ gsd-core/workflows/complete-milestone.md kept 635+3 9293e0db8d3c gsd-core/workflows/complete-milestone.md own 638+2 2 a7d12d5b7b3f 459cf8709810 prose gsd-core/workflows/complete-milestone.md kept 640+5 2a328612a480 gsd-core/workflows/complete-milestone/detail/elaboration.md kept 1+9 f11312356871 -gsd-core/workflows/complete-milestone/detail/elaboration.md own 10+131 11 55c4aabce7c0 714a4bf300e2 ported-name +gsd-core/workflows/complete-milestone/detail/elaboration.md own 10+131 11 55c4aabce7c0 d0c84a922351 ported-name gsd-core/workflows/complete-milestone/detail/elaboration.md kept 141+8 6258f4cf20a3 gsd-core/workflows/complete-milestone/detail/elaboration.md own 149+12 8 7f5360d7cb28 0b16221dab4d ported-name gsd-core/workflows/complete-milestone/detail/elaboration.md kept 161+8 15e5dca451dc diff --git a/gsd/core/tests/profiles.rs b/gsd/core/tests/profiles.rs index bb8ab165ca..c31933d8b1 100644 --- a/gsd/core/tests/profiles.rs +++ b/gsd/core/tests/profiles.rs @@ -119,7 +119,7 @@ fn md_presets() -> Vec<(String, [bool; 3])> { fn the_profile_presets_are_the_settings_md_table() { let items = items(); let table = md_presets(); - assert_eq!(table.len(), 7); + assert_eq!(table.len(), 9); for (setting, values) in table { for (index, profile) in PROFILES.iter().enumerate() { let entry = preset(&items, profile); diff --git a/gsd/core/tests/projects/release/Cargo.toml b/gsd/core/tests/projects/release/Cargo.toml new file mode 100644 index 0000000000..1bdb11a81c --- /dev/null +++ b/gsd/core/tests/projects/release/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "adder" +version = "1.8.0" +edition = "2021" +description = "Adds and subtracts integers: the crate the release gates (gsd/E533, gsd/E535) are proved on" +license = "MIT" + +[dependencies] + +# Its own workspace: the test project is no member of the repository's. +[workspace] diff --git a/gsd/core/tests/projects/release/fresh-public-api.txt b/gsd/core/tests/projects/release/fresh-public-api.txt new file mode 100644 index 0000000000..1c99d0afc6 --- /dev/null +++ b/gsd/core/tests/projects/release/fresh-public-api.txt @@ -0,0 +1,3 @@ +pub mod adder +pub mod adder::ops +pub fn adder::ops::add(a: i32, b: i32) -> i32 diff --git a/gsd/core/tests/projects/release/spec/milestones.spec b/gsd/core/tests/projects/release/spec/milestones.spec new file mode 100644 index 0000000000..8f1bf0295d --- /dev/null +++ b/gsd/core/tests/projects/release/spec/milestones.spec @@ -0,0 +1,15 @@ +milestone v1.7 "Addition" { + completion { + at 2026-10-01 + } +} + +milestone v1.8 "Trim" { +} + +phase 01 "Drop subtraction" { + milestone v1.8 + slug "drop-subtraction" + goal "The crate keeps addition only" + success_criteria ["`ops::add` adds", "`ops::sub` is gone"] +} diff --git a/gsd/core/tests/projects/release/src/lib.rs b/gsd/core/tests/projects/release/src/lib.rs new file mode 100644 index 0000000000..4f746ded5c --- /dev/null +++ b/gsd/core/tests/projects/release/src/lib.rs @@ -0,0 +1,14 @@ +//! Adds and subtracts integers. + +/// The two operations. +pub mod ops { + /// `a + b`. + pub fn add(a: i32, b: i32) -> i32 { + a + b + } + + /// `a - b`. + pub fn sub(a: i32, b: i32) -> i32 { + a - b + } +} diff --git a/gsd/core/tests/projects/release/tests/public-api.txt b/gsd/core/tests/projects/release/tests/public-api.txt new file mode 100644 index 0000000000..8cf7b555e1 --- /dev/null +++ b/gsd/core/tests/projects/release/tests/public-api.txt @@ -0,0 +1,4 @@ +pub mod adder +pub mod adder::ops +pub fn adder::ops::add(a: i32, b: i32) -> i32 +pub fn adder::ops::sub(a: i32, b: i32) -> i32 diff --git a/gsd/core/tests/record_script.rs b/gsd/core/tests/record_script.rs index 2cca517e29..78165bb37d 100644 --- a/gsd/core/tests/record_script.rs +++ b/gsd/core/tests/record_script.rs @@ -1,26 +1,35 @@ //! `gsd/parity/record.sh`, `record-security.sh` and `record-ledger.sh` record a golden only from a `gsd-tools` run //! that succeeded: each runs a fake `gsd-tools` that prints JSON and fails, and must fail there, writing nothing. +//! `record-reports.sh` needs Docker, so it never runs here: its isolation is read from its text. use std::path::Path; use std::process::Command; +use regex::Regex; + #[path = "common/node.rs"] mod node; +/// Every file under `dir`, at any depth (the recorded tool reports sit in `reports/`), with its text, by path. fn goldens(dir: &Path) -> Vec<(String, String)> { - let mut found: Vec<(String, String)> = std::fs::read_dir(dir) - .expect("goldens") - .map(|e| { - let path = e.expect("entry").path(); - ( - path.file_name() - .expect("name") - .to_string_lossy() - .into_owned(), - std::fs::read_to_string(&path).expect("read"), - ) - }) - .collect(); + let mut found = Vec::new(); + for entry in std::fs::read_dir(dir).expect("goldens") { + let path = entry.expect("entry").path(); + let name = path + .file_name() + .expect("name") + .to_string_lossy() + .into_owned(); + if path.is_dir() { + found.extend( + goldens(&path) + .into_iter() + .map(|(file, text)| (format!("{name}/{file}"), text)), + ); + } else { + found.push((name, std::fs::read_to_string(&path).expect("read"))); + } + } found.sort(); found } @@ -80,3 +89,125 @@ fn record_ledger_records_nothing_from_a_failing_gsd_tools_either() { // The verbs run before the tests, so the script stops at the fake gsd-tools, before any cargo-nextest run. check("record-ledger.sh", "goldens/ledger"); } + +/// `record-reports.sh`'s text with its comment lines dropped and each `\` continuation joined to its line. +fn record_reports() -> String { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../parity/record-reports.sh"); + let text = std::fs::read_to_string(path).expect("read record-reports.sh"); + let code: Vec<&str> = text + .lines() + .filter(|line| !line.trim_start().starts_with('#')) + .collect(); + code.join("\n").replace("\\\n", " ") +} + +#[test] +fn record_reports_pins_every_image_by_digest() { + let script = record_reports(); + let assigned = Regex::new(r"(?m)^([A-Z_]+_IMAGE)=(.*)$").expect("regex"); + let pinned = Regex::new(r"^[^@\s]+@sha256:[0-9a-f]{64}$").expect("regex"); + let images: Vec<&str> = assigned + .captures_iter(&script) + .map(|image| { + let (name, value) = (image.get(1).expect("name"), image.get(2).expect("value")); + assert!( + pinned.is_match(value.as_str()), + "{} is not pinned by digest: {}", + name.as_str(), + value.as_str() + ); + name.as_str() + }) + .collect(); + assert_eq!(images.len(), 3, "the node, rust and osv-scanner images"); + // Every container runs one of them: `container`'s first argument is the image `docker run` gets. + let calls = Regex::new(r#"(?m)^\s*container "\$([A-Za-z_]+)""#).expect("regex"); + let used: Vec<&str> = calls + .captures_iter(&script) + .map(|call| call.get(1).expect("name").as_str()) + .collect(); + assert_eq!( + used.len(), + 3, + "the javascript, ledger and osv-scanner containers" + ); + for image in used { + assert!( + images.contains(&image), + "container runs ${image}, no pinned image" + ); + } +} + +#[test] +fn record_reports_runs_one_container_with_no_mount_privilege_or_host_network() { + let script = record_reports(); + assert_eq!(script.matches("docker").count(), 1, "one docker call"); + let run = script + .lines() + .find(|line| line.contains("docker run")) + .expect("a docker run"); + // Docker's options are the tokens before the image; what follows is the container's command. + let tokens: Vec<&str> = run.split_whitespace().collect(); + let docker = tokens.iter().position(|t| *t == "docker").expect("docker"); + let image = tokens + .iter() + .position(|t| *t == "\"$image\"") + .expect("docker run takes container's \"$image\""); + let options = &tokens[docker + 2..image]; + for (at, option) in options.iter().enumerate() { + let short = option.starts_with('-') && !option.starts_with("--"); + assert!(!(short && option.contains('v')), "a volume: {option}"); + for refused in [ + "--volume", + "--mount", + "--privileged", + "--cap-add", + "--volumes-from", + ] { + assert!( + *option != refused && !option.starts_with(&format!("{refused}=")), + "docker run takes {option}" + ); + } + let host_network = matches!(*option, "--network=host" | "--net=host") + || (matches!(*option, "--network" | "--net") && options.get(at + 1) == Some(&"host")); + assert!(!host_network, "docker run joins the host network"); + } +} + +#[test] +fn record_reports_refuses_any_fixture_but_the_three_before_running_one() { + let script = record_reports(); + assert!(script.contains("\n[ ${#fixtures[@]} -gt 0 ] || fixtures=(taskboard vault ledger)\n")); + let allowlist = "for fixture in \"${fixtures[@]}\"; do + case $fixture in + taskboard | vault | ledger) ;; + *) echo \"record-reports.sh: no fixture '$fixture' (taskboard, vault, ledger)\" >&2; exit 1 ;; + esac +"; + let checked = script.find(allowlist).expect("the fixture allowlist"); + let ran = script + .find("\n \"$fixture\"\n") + .expect("each fixture's run"); + assert!( + checked < ran, + "the allowlist is checked before any fixture runs" + ); +} + +#[test] +fn record_reports_refuses_a_non_regular_report_before_copying_without_following_links() { + let script = record_reports(); + let refusal = "odd=$(find \"$staged\" -mindepth 2 ! -type f) +if [ -n \"$odd\" ]; then"; + let refused = script.find(refusal).expect("the non-regular file refusal"); + let exits = script[refused..].find("exit 1").expect("the refusal exits") + refused; + let copies: Vec<usize> = script.match_indices("cp ").map(|(at, _)| at).collect(); + assert_eq!(copies.len(), 1, "one copy into the reports directory"); + assert!(exits < copies[0], "the refusal runs before the copy"); + assert!( + script[copies[0]..].starts_with("cp -P \"$staged/$fixture\"/* \"$out\"/"), + "the copy follows no symlink: cp -P" + ); +} diff --git a/gsd/core/tests/settings_roster.rs b/gsd/core/tests/settings_roster.rs index 2daa99ec7d..cf48db280e 100644 --- a/gsd/core/tests/settings_roster.rs +++ b/gsd/core/tests/settings_roster.rs @@ -158,15 +158,15 @@ fn family_matches(family: &Declared, key: &str) -> bool { fn every_core_key_of_the_manifest_is_declared_with_its_default() { let (universe, capabilities) = upstream(); let settings = declared(); - // `profile`, the seven `specforge.` settings and the ten `specforge.surface.` ones are SpecForge's, not GSD's. + // `profile`, the ten `specforge.` settings and the ten `specforge.surface.` ones are SpecForge's, not GSD's. let (ours, statics): (Vec<&Declared>, Vec<&Declared>) = settings .iter() .filter(|s| !s.name.contains('*')) .partition(|s| s.name == "profile" || s.name.starts_with("specforge.")); assert_eq!( ours.len(), - 18, - "profile, seven specforge. settings and ten specforge.surface. clusters" + 21, + "profile, ten specforge. settings and ten specforge.surface. clusters" ); let families: Vec<&Declared> = settings.iter().filter(|s| s.name.contains('*')).collect(); let owners = other_owners(); diff --git a/gsd/core/tests/writer_roster.rs b/gsd/core/tests/writer_roster.rs index 68716a54d2..44b9074bb0 100644 --- a/gsd/core/tests/writer_roster.rs +++ b/gsd/core/tests/writer_roster.rs @@ -37,7 +37,7 @@ fn fields_written(writer: &str) -> BTreeSet<(String, String)> { #[test] fn every_h_field_has_one_writer() { let declared = fields_written("harness"); - assert_eq!(declared.len(), 44, "the 44 harness fields of the model"); + assert_eq!(declared.len(), 45, "the 45 harness fields of the model"); let rows: Vec<(String, String)> = WRITERS .iter() .map(|(k, f, _)| (k.to_string(), f.to_string())) @@ -45,7 +45,7 @@ fn every_h_field_has_one_writer() { let listed: BTreeSet<(String, String)> = rows.iter().cloned().collect(); assert_eq!(listed.len(), rows.len(), "a field has two writer rows"); assert_eq!(listed, declared, "the rows and the H fields differ"); - assert_eq!(WRITERS.len(), 44, "every H field has a writer"); + assert_eq!(WRITERS.len(), 45, "every H field has a writer"); } /// Every context field (ADR 0356) is a row of `RECORDS`, and the row's route records it: a field no route records could diff --git a/gsd/core/wasm/gsd_core.wasm b/gsd/core/wasm/gsd_core.wasm index 27b7b1230c..4de9e7a475 100644 Binary files a/gsd/core/wasm/gsd_core.wasm and b/gsd/core/wasm/gsd_core.wasm differ diff --git a/gsd/core/wasm/inputs.json b/gsd/core/wasm/inputs.json index c129f0f6ae..0324fd196c 100644 --- a/gsd/core/wasm/inputs.json +++ b/gsd/core/wasm/inputs.json @@ -1,17 +1,17 @@ { "artifact": "gsd_core.wasm", - "artifact_sha256": "4852d627412b4c8694f31fdd97d0db73bac35de8fcd02be688efd56f74c28813", + "artifact_sha256": "c0699b5f36b72cc74c376d3077f597520f80c50b88c857f8d42ee8b219b093c3", "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", "inputs": { "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", - "crates/leaf/protocol-types/src/calls/collect.rs": "0c3c76ea80dd4c6a05396627fc20a209022ae8dbe34640be3790fd4f06269b50", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", - "crates/leaf/protocol-types/src/code_catalog.rs": "cc778e521f7d531d586495b6b3635d010335074d86a5648264cca8288df95008", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", @@ -21,29 +21,29 @@ "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", - "crates/leaf/protocol-types/src/inputs.rs": "34c3b44c76880bc1f3aa1cbe94b11962cf51a8430a9e533c9ed3d15b52fb6d08", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", - "crates/leaf/protocol-types/src/lib.rs": "44361061188f992f56bec699d749a431997c10309622246bc9ae714e42649d43", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", - "crates/leaf/protocol-types/src/reads.rs": "f9fd2b408d3946551bbbe8bcdd6c29e985216512d839967ef384b7c70317c772", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", - "crates/leaf/protocol-types/src/surface.rs": "cbfff5216d0c63ecd8ca9a6e55dd1a130942c30ab91718ddbd5898955a623a98", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", - "crates/leaf/protocol-types/src/version.rs": "83c7e996a370da5fe1ad1966521d6a67803a5d8e0a62b3dee6ce4ccf00e3fe1e", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", - "crates/runtime/extension-sdk/src/builders.rs": "712ce82c6d226ff013d182d06e5fe6c64eafd2bf262bf12b24ff491828cbfe0a", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", @@ -55,19 +55,19 @@ "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", - "crates/runtime/extension-sdk/src/lib.rs": "73ea8baf8b13f290a8161e1328ba7c1bdb3335ab036a2fea234340fa5aaf3ba4", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", - "crates/runtime/extension-sdk/src/reads.rs": "41f590418a4571c222647aa1e3ff3c5f54d2aa59c92bbd4c251f3450b908195d", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", - "crates/runtime/extension-sdk/src/surface.rs": "43b00053ed3dc4f4022608b75a39f6a9a5110ad23d6dc4f45d5cfedc257c2a98", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", "gsd/.cargo/config.toml": "746bbb5a5d288839f912d2560de084edb16df1e63508fd815e1ff81f3a894ef6", - "gsd/Cargo.lock": "e054b78688ed1f7993769899fd45db787357282cc915037e2e32c290868545ec", + "gsd/Cargo.lock": "17cd94254b2c7dc2e6dc04245e6bc391ab87a3db043aaff232371e49973b1f03", "gsd/core/Cargo.toml": "8d35e71e2c19e4872688c5f926bcecf97789291a6cb553dfda7e21003dc40b85", "gsd/core/assets/agents/gsd-advisor-researcher.compact.md": "fad37c2e9c45b1722fa2b8c9e884d050db85fcc949b523dfa4bee4e3e00cdcfc", "gsd/core/assets/agents/gsd-advisor-researcher.md": "0cb9228f1b86a15032b8e39919ebdc96c6b0749565550a3dfb850926fadde41d", @@ -259,8 +259,8 @@ "gsd/core/assets/gsd-core/workflows/autonomous/steps/converge-fail-fast.md": "58adde31e7147daca8064bbe59ba8c4bbedd719b1d3d37cf85c4bc961f374a0b", "gsd/core/assets/gsd-core/workflows/autonomous/steps/converge-loop.md": "f4af5e69b726a77156275d5d92336f3901cf572de93216a8eef1d800309eca7e", "gsd/core/assets/gsd-core/workflows/autonomous/templates/minimal-context.md": "2119bf1b3fd7fb7b53b1a5bc6ee3a9bbd31c4f8bb0505482ac28b580043d80cd", - "gsd/core/assets/gsd-core/workflows/complete-milestone.md": "54efe7361746b62d28d9e2f3bd63fa3d72bf8a619ab2f307fdb6c53af7aaa262", - "gsd/core/assets/gsd-core/workflows/complete-milestone/detail/elaboration.md": "40c2addaa6574b5168e0ac4adc1394aee9949189e4d8ea070160e04809d7716f", + "gsd/core/assets/gsd-core/workflows/complete-milestone.md": "7aaef02221eccecba8bafc3a59ddcd28a00a042ae7eb6e7139beac350d5815d1", + "gsd/core/assets/gsd-core/workflows/complete-milestone/detail/elaboration.md": "058fae4b2c4d6b1949e49e08b01fd7918ce0575c14a99c1b2cff1f9b27308837", "gsd/core/assets/gsd-core/workflows/complete-milestone/steps/git-tag.md": "a5bc22f85803f45c9875704d3f8e09e6c457a073c1be4d3262103aa6bc0109b5", "gsd/core/assets/gsd-core/workflows/complete-milestone/steps/project-md-evolution-review.md": "0727c707c8377a19ccc0567b066d59ed00d9e23f6d33faef63d2e288229dcf77", "gsd/core/assets/gsd-core/workflows/diagnose-issues.md": "f49f924e86debddd0f29b2dc2579a4a86be76f4e859ffe6458b38efdee8eb235", @@ -383,10 +383,11 @@ "gsd/core/src/agents/mod.rs": "a3a1648efda60e64639788cd08daab705d55a5b44d9fbccd1ac7988d4fe06d58", "gsd/core/src/agents/roster.rs": "e82db6b21ce7e570e7ecc48b1d278bffcbd80d427e96ac1d648f322964592e58", "gsd/core/src/branch.rs": "3fcd8200fd2849bac0a8bee40bf87c9bb213b4cf57798605f2c985c89c67abc5", - "gsd/core/src/codes.rs": "332ff92af8165c6672b58057185e42162f02a22d75cafbc903e4cef2a1ccaae8", - "gsd/core/src/collectors/git.rs": "0eb9d845dbd70a30d861292a07c8671d9dbc4d1ab413c2a8322793662ac6ba24", + "gsd/core/src/codes.rs": "d506f51d91c5ec6112d79a833d95bc22887bcf10e4e3790042f2365bc424f778", + "gsd/core/src/collectors/git.rs": "ecd3df550833cfb7e97f6d36b808a60f9ccea5b45f94474d02401e0fe8ab6719", "gsd/core/src/collectors/git/items.rs": "36e68c3b0283a258f68330fb54a4c86121c92eb653a9a854dd802cd70fa8f4ab", "gsd/core/src/collectors/git/subject.rs": "e0bba2609da4dc8cffd9b13218c2cd8950b162489b7b38254605dc90877e621c", + "gsd/core/src/collectors/git/tags.rs": "dc9dd2768bdaf53a5d7d18a166ec38eafd58b0f7c39d768d1c94f8178e7aec36", "gsd/core/src/collectors/git/trailer.rs": "f325e109430c5ed7f665d79a54150539f68dc7ff1a0d6191a5f17f532994b431", "gsd/core/src/collectors/graph.rs": "957e9494ffa9b1c70cf589b011d9e98d5d93ef8dc7ada42fbc82dd77b0ad016e", "gsd/core/src/collectors/mod.rs": "9be733fc844c367945bd13f81e77add6ccc53a3f26201fdeaf58d022417b4076", @@ -401,9 +402,9 @@ "gsd/core/src/commands/gate.rs": "a70bf0ba8d6bd6d3a583786937006d4bf900f07728f297687493cf942b955cb1", "gsd/core/src/commands/help.rs": "2158488d83ebdb03d6575862d0376c9b9bcc84e9830da77a3307edd25006b269", "gsd/core/src/commands/learning.rs": "607f54bfa6bb7ccaca92ed136ee10fb70c6db9839e65602f6e6b079cc31a0754", - "gsd/core/src/commands/milestone.rs": "bc377fa59ecbe395bee6ba31f410b99c492cbfd08e14d9527f9db92b9ab1adc4", + "gsd/core/src/commands/milestone.rs": "ee20defafb14a53b43775618f1de69c8d7b47835b90ab81e53516df53805b3d3", "gsd/core/src/commands/milestone_branches.rs": "b133e0e00127dc68d308217d65ac19d1420a1c6f838117a9a32ac9e2c54b381d", - "gsd/core/src/commands/mod.rs": "d8c2a8d3bdcde880ea84f73cf0c429e2215aa6b5d347fa0fe362f21de444adba", + "gsd/core/src/commands/mod.rs": "97571a1d616c256fc164116334d6fec3f3d86f1b33809785bda16a7b33ab68a5", "gsd/core/src/commands/phase.rs": "c1da17c86d52ec7cf486c092cadae62f7a441f641d93e656df36ca9e3dd1e973", "gsd/core/src/commands/phase/promote.rs": "5cf1c306432caf436b49888813f11490610305bc27c9105dde3ec1b4797bc1b7", "gsd/core/src/commands/phase/remove.rs": "054b9b4008b13f79e2d34488d822ded5f63805f54496c48c1c82951a19a3a117", @@ -460,13 +461,13 @@ "gsd/core/src/kinds/project.rs": "96d0005834ad81e760dd29d821a726b8d3824783391f51006c1522b8c8e6f03d", "gsd/core/src/kinds/research.rs": "a76b2e7a7378f241dbbc19295fc5e563360ca1d99193f2234a959f29c38f5bd6", "gsd/core/src/kinds/review.rs": "777a3ffad104e9651e97dab67e8c037b56440bcd587a45ca66c37597d9a8df9b", - "gsd/core/src/kinds/roadmap.rs": "aa7271bf87cc9ce0f6de774c7d3d50690b5282fe3b3ebfe0c38cde891d84b3f0", + "gsd/core/src/kinds/roadmap.rs": "10ce8509a50964efaee6a137ef898122e57064db8a84df1303ed5cf67f21e924", "gsd/core/src/kinds/spec.rs": "d22993f109eeb3936953ef12f4ac98f5dc4f0c4d26768d6019779b275c4a32f4", "gsd/core/src/kinds/uat.rs": "6cec431c4c37a404fe24a2bbc7d62f9a5113fc289e8ae47e721bce6f12a5b4c8", "gsd/core/src/kinds/validation.rs": "60c8ce7adb6d1e7523bb1dab6005b2bb71f344d690b0e5ef563cf4fc15717b9f", "gsd/core/src/kinds/verify.rs": "1e9212cc2836344d89cfe3489d486ca45f5fd5da665f53f2297a8ed274d9d643", "gsd/core/src/kinds/windows.rs": "cbe296e9f9288e41b91d701a82d99f2b3fb5a3ff32b3f98457a555d37eef9dce", - "gsd/core/src/lib.rs": "7c349cea36d6072cdbcf3576ae86cfc72e178751736136abbd236728d67ea266", + "gsd/core/src/lib.rs": "fd1b22e811a05dc37cf9cee908801ab88b9e40489338016061ff0e88833bfedb", "gsd/core/src/passes/citations.rs": "844de1439dbe1e785d203d7ba5a9a827286e5d1ebe5447ef67e22752851a9475", "gsd/core/src/passes/commits.rs": "ac5fc9d2419a60734be3530dfd557c499f7cf4bab159aa2e694dbc1a27ea6a9e", "gsd/core/src/passes/cross_plan.rs": "ac874654262ee5523a16881c8c2da24973956ff68be3ac7e205735d608c1725a", @@ -479,10 +480,12 @@ "gsd/core/src/passes/derive/estimate_error.rs": "d05b67f4ee9199beb44e67145e43a9a6be5d07b6c79237eb4b690ccd421b806c", "gsd/core/src/passes/derive/execute.rs": "1251dd9cdc2feb4447fe2a771a371f569165670c919c0d2ccb7863fc95b270c8", "gsd/core/src/passes/derive/halt.rs": "4246044153f375a64c94a7b4dbc2780d86405fc5ba6fbac50738bca1aa6f51cf", + "gsd/core/src/passes/derive/interface.rs": "940428d14372790770f8d1b943ec319e624be2bb1867cf9720a7a0d451d6f673", "gsd/core/src/passes/derive/ladder.rs": "0c2df7616760dca604181d5935a965dc00f0e801140109a474831b262f92ef92", "gsd/core/src/passes/derive/learning.rs": "dc5ff8d0cb54a636ad7b610fc02c08b7b35007fb1dad44c25d13b6e58347273d", - "gsd/core/src/passes/derive/mod.rs": "1de2628af4b91f990c694db2ad4ed2cc0be36af18a146030a0b57006143c620a", + "gsd/core/src/passes/derive/mod.rs": "330f38adaaed2f318e588802c0ea655e452cccefa30d07546d94c51e6670977a", "gsd/core/src/passes/derive/progress.rs": "07af6c53b75b6f0a65217563d8ccc992da5b29077279bf4da3b90eac35ce26c9", + "gsd/core/src/passes/derive/release.rs": "277febeaf441f0d7ef86c04a7c1a0a754e3ef3b0c41f2421974c49b09af14220", "gsd/core/src/passes/derive/requirement.rs": "d98524a381650746adac99471b6b1f636392bf9c561859f5e0b58da88c0b7d2b", "gsd/core/src/passes/derive/review.rs": "75955d7754df10bfe4226beaeb450b0bfa58d9abdcc345b9369affe88c2f034c", "gsd/core/src/passes/derive/uat.rs": "ad9b19674be18383248922394bb376e8c766f126fc59a89851aecfbd5989af2c", @@ -490,8 +493,9 @@ "gsd/core/src/passes/execute.rs": "ebb39aaa1e663188a09a066effe5c19971485df27249ef6ed8eb37e59c2a86cb", "gsd/core/src/passes/fails_when.rs": "07023030831ddf8f3f7773ae79cb19e4404eb721468575ab92f0fbf9ea16cc8c", "gsd/core/src/passes/file_scope.rs": "d1dffbc91ac4a03088c801493db76448f4d35b62c2cf40d39b4058b30adfa001", - "gsd/core/src/passes/gates.rs": "b7232e5f078d357c7ad12d4a5ac12b898555e8f5d207024470f26182a2a1b81a", + "gsd/core/src/passes/gates.rs": "3eba0821dd397d98bfbda23532aff907f4783f3048b3ecf1bd95e1eec14a4df3", "gsd/core/src/passes/gates/e516.rs": "d920528d39e0fe95f0dbeb9ae7c5fcaaff9a30c0ad961e5da6de21e8cbbca19c", + "gsd/core/src/passes/gates/release.rs": "1f7f4a37ebebe3431260c02b8dbe00f009056dc678ddacbd87cfd1602dbfdc40", "gsd/core/src/passes/mod.rs": "779604aafaed2c7bc09110516e6dd2d85b81199a6de3f4beee2de973e6c11cd0", "gsd/core/src/passes/nyquist.rs": "4e7c5c01988561f121ff449c6e0ce1ee8c6bf34ef6e7e4714fbde658b03f98e8", "gsd/core/src/passes/plan_shape.rs": "a4d08d1052633e254c82dfd5c443f786be9b4081e76434f984ece4ae6db4bb4e", @@ -543,7 +547,7 @@ "gsd/core/src/prompts/repoint.rs": "3ed348fe77c1b8c927449c7341297a1f85d1010a142eed2519449513b6182ac5", "gsd/core/src/prompts/review.rs": "7f95ab9a1a4965f9958e64ac1b9c1d22441deaea923e0e87d27498e5106dc636", "gsd/core/src/prompts/session.rs": "18b9f2b7d1669b5b1bcf648377ae671b774896cc8324b169e5ac525137c8eb2f", - "gsd/core/src/prompts/ship.rs": "6abb0d4603aec8975e905d30c8215d623ea20b0eed54cdb16cf203298499b881", + "gsd/core/src/prompts/ship.rs": "df41e0437b8929d8421e286b0a8274b48ba4ec7821fede764f44372d40ea6550", "gsd/core/src/prompts/slash.rs": "8ca241cebb5305394edf783533f874ac37196ac678fffbadc86cee85de619c3c", "gsd/core/src/prompts/spec.rs": "c66ee46fd91ddede8332b29439976736c46a214e346331b518cc9c9db9219176", "gsd/core/src/prompts/update.rs": "e012196181d7440ab163672d397556112e61d7ac3e582943fc97215e285d48ea", @@ -551,15 +555,16 @@ "gsd/core/src/prompts/workflow.rs": "78eef61afc73c8f95c8d2413c4c773057b544dc6b6747c5dab574c7294eba033", "gsd/core/src/prompts/workspace.rs": "f43f5f9c0c102837d99111f335864517479f0a55037f4752bc3ec6d26883406c", "gsd/core/src/quick_id.rs": "a90ab314e8a2adc7adbba2637fdd80612269ba692f63b469702700d75419fafa", + "gsd/core/src/release.rs": "2c67c2e08a7e44271279954d80a8538781db19e466302b04583bd53ca4d8c268", "gsd/core/src/relocation.rs": "456c9ec541ddaa65434bb1a888968a6e8f87be6f2196f0ae853ba3d3c0c86a9b", - "gsd/core/src/route.rs": "0bcf3040adb64877dede4376bc2bbc2c685b80cdf97b194a81a04da4eb2f527b", + "gsd/core/src/route.rs": "9b654138486a0641bcc01022091f3d259eb58567d17c832c2752b0ab3ed8ef7d", "gsd/core/src/rules.rs": "32c852f74579133e8cf12c7bbda41ed334065362dcc5bea9d4d8096739e18980", "gsd/core/src/scope.rs": "9b324678c615b6f1c1e0e614f2ab77fba626db5e512e7bc3157a1e6245db2e4a", - "gsd/core/src/settings/gates.rs": "b9b8b041e54845796a495c2f2b0b4c92ccb9b1b545c7e1cebc6459792ba2e41c", + "gsd/core/src/settings/gates.rs": "996d8d5bf576c027805dcad1f75b14c91ccb646dc094dc9d9153c7187e6706a8", "gsd/core/src/settings/keys.rs": "d8b4ed23b60fa5b7c6e8f0eb744a4f4417711fb2aee1547b37f86ee8d0fdf574", "gsd/core/src/settings/mod.rs": "71f5510e9e44eb22a3da9d4a12141fff972163cfbce0add9f37a5f08dbe01909", "gsd/core/src/settings/models.rs": "9585db498106c907690cba0a249e60c61e31427db06a49c2decde77140806e8d", - "gsd/core/src/settings/profiles.rs": "542b54e27a0224a2f3d2cfbbbe6197d686bc7a987745d6ff7ba558d97f23162c", + "gsd/core/src/settings/profiles.rs": "595b0804f5ad1e8b7fba5b641b2c5ad69b1e83e9a8dbc80423aa3208d80e1a18", "gsd/core/src/settings/surface.rs": "ca0ac28d23292be8eb7529d2d3c72f34c973fb596c36a28044fbe9f40372942f", "gsd/core/src/slash.rs": "85fdacd9307106d93c412cffe47ca41a9b9912889cd8d1d74b0b8329d9286b8c", "gsd/core/src/time.rs": "c3b745804fe5046328bb891e95c85a953046d5783267e26d132ebeaf4ff29248", @@ -571,7 +576,7 @@ "gsd/kit/src/judged.rs": "5dede3d81904cd2e03c759c263743f146000da1b982160a071d4cb42c3be0a82", "gsd/kit/src/judged/record.rs": "13ad01c1c91949dc241fb349e95af9f1124a0feacb175a7a572f1cad446593e0", "gsd/kit/src/lib.rs": "6972cba47d094891c80c5d846eafd097bdd48e6a4776acf1e7c17a5079308c1f", - "gsd/kit/src/markdown.rs": "0f6450c1b13d5943d9dda96b851532838cfdea64871c7249636c842e4c3b6980", + "gsd/kit/src/markdown.rs": "a1544e5bd0041256ea527ef07b10f87949b697d8d293e892250854ddb2e8d5f1", "gsd/kit/src/prompt/args.rs": "a0eff63b22fae5fc16ecb4b0defb3c07783eae3048740b439bda5d3949a83b18", "gsd/kit/src/prompt/compose.rs": "929f8737d33d410d27f480b65e909712040278ec9aeccce52d5e034d6ff88bdb", "gsd/kit/src/prompt/host.rs": "3fcf9c030703485679c5bb7bac15a8803ca9e61d97e4314d08b6ec780f822e0f", diff --git a/gsd/import/Cargo.toml b/gsd/import/Cargo.toml new file mode 100644 index 0000000000..f134b97667 --- /dev/null +++ b/gsd/import/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "gsd-import" +version = "1.0.0" +edition.workspace = true +license.workspace = true +description = "@gsd/import: reads a GSD project's .planning/ folder once into one edit plan that writes spec/gsd/ for SpecForge" +publish = false + +# `rlib` lets the native tests link the crate; the wasm component is the cdylib. +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +specforge-extension-sdk = "0.3.0" +gsd-kit = { path = "../kit" } +serde_json = "1.0" + +[dev-dependencies] +specforge-extension-sdk = { version = "0.3.0", features = ["testing"] } +# The black-box harness is core's (`#[path]`), and the tests read core's declared kinds; never a `src` dependency (ADR 0391 D12). +gsd-core = { path = "../core" } +gsd-security = { path = "../security" } +serde_json = "1.0" +tempfile = "3" +regex = "1" +sha2 = "0.10" +# The harness's pty for stdin. +rustix = { version = "1", features = ["pty", "fs"] } + +# The gsd-core release this crate tracks (the handshake carries it as the keyword `tracks:gsd-core@<version>`). +[package.metadata.gsd] +tracks = "gsd-core@1.19.0" + +[lints] +workspace = true diff --git a/gsd/import/README.md b/gsd/import/README.md index 292d717d13..66d2e86b91 100644 --- a/gsd/import/README.md +++ b/gsd/import/README.md @@ -1,6 +1,127 @@ # `@gsd/import` -**Status: being designed; nothing is built yet.** `specforge gsd import`: reads an existing `.planning/` once and returns edit plans that write -`spec/gsd/` (K5). One way only; after the import no Markdown is read again. The parity suite imports real GSD -output with it to compare graphs. Every GSD file it reads maps to kinds in -[the file table](../core/spec/README.md#every-gsd-file-maps-to-a-kind); a file it cannot map is reported, never dropped. +**Status: built, 1.0.0, a vendored builtin** ([ADR 0391](../../docs/adr/0391-gsd-import-reads-a-planning-folder-once-into-one-edit-plan.md), +amended by [ADR 0392](../../docs/adr/0392-an-import-commands-plan-is-judged-for-host-errors-only.md)). One command, +`specforge gsd import`, reads a GSD project's `.planning/` folder once and answers one edit plan that writes +`spec/gsd/`, with a report of every file, section and row it did not map and why. One way only: after the import +`.spec` is the only state, no Markdown is read again, and nothing under `.planning/` is written. It declares no kind; +its peers are `@gsd/core` (required) and `@gsd/security` (optional). + +## Running it + +```sh +specforge add @gsd/core +specforge add @gsd/import +specforge add @gsd/security # optional: threats, trust boundaries, security audits +specforge gsd import --dry-run # the report, nothing written +specforge gsd import # the plan, applied all or nothing, and the report +specforge check # exits 1 until the owed verdicts are recorded (below) +``` + +- **No positional.** The command reads the project root's `.planning/**` (text, up to the 4 MiB read ceiling) and + `specforge.json`, the two static globs it declares (ADR 0391 D2). The host's `--path` picks another project root. +- **`--dry-run`** prints the report and writes nothing. **`--format json`** gives the report as JSON beside the plan, + in the host's `{output, plan, files_written}`. +- The same folder gives the same plan and the same report, byte for byte: files are read in path order, and the report + is sorted, with no clock and no absolute path (D8). + +## What it writes + +One all-or-nothing edit plan under `spec/gsd/`; every file name is built from validated ids (D4): + +| File | Holds | +|---|---| +| `spec/gsd/project.spec` | the project and its decisions (`PROJECT.md`) | +| `spec/gsd/requirements.spec` | the requirements, out-of-scope rows `OOS-<NN>` (`REQUIREMENTS.md`) | +| `spec/gsd/<milestone>.spec` | a milestone and its phases (`ROADMAP.md`); `v1.0` when the roadmap names none, reported `filled` | +| `spec/gsd/phases/<NN>.spec` | everything under one phase: contexts, discussions, research, plans and tasks, summaries, verifications, UAT sessions, threats and security audits | +| `spec/gsd/quick.spec` | quick plans and their summaries (`quick/*`) | + +Ids are GSD's own (`TASK-01`, `D-01`, phase `02.1`, plan `01-02`, task `T1`, threat `T-01-02`). A value that is not +a valid id is reported at its `file:line` and the entity is not created. A record missing a required field is +dropped and reported, and its children are reported "parent not imported", never written with a dangling reference +(D9). The host also writes the `specforge-harness` ledger lines for the harness fields the import sets (a UAT result, +a threat's status, a security audit's level and date) and the `.gitattributes` merge line for that ledger (D7). + +What the [file table](../core/spec/README.md#every-gsd-file-maps-to-a-kind) maps, the fate table +(`src/table.rs`) gives every known file, section, key and row exactly one outcome, and a test counts it (D3). +Threat models, `NN-SECURITY.md` and audit runs map only when `specforge.json` lists `@gsd/security` (a text check of +the file, which the report says); otherwise they are `needs-extension` (D11). + +## The report + +One line per file, section or row: `<file>:<line> <section> <outcome> <reason>`. The ten outcomes are `mapped`, +`computed`, `redundant`, `runtime`, `ignored`, `unmapped`, `needs-extension`, `setting`, `authored-after-import` and +`filled`. Every echoed string is escaped (C0, C1, DEL and the bidi and format controls as `\u{..}`) and capped; an +`unmapped` file's content is never echoed, only its name and reason (D8). A title or value holding a control or bidi +character no `.spec` file can hold drops its record, reported. Then, each under its heading: + +- **settings: run each line to keep the setting.** `config.json` is never written into `specforge.json` (D6). Each + mappable key gets one `specforge settings set <extension> <key> <value>` line, the value POSIX single-quoted; a value + holding a control character is reported, not printed. A search provider's API key is never printed: the line turns + the provider on, and the report names the environment variable to export (`BRAVE_API_KEY`, …). A key of an + extension the project does not load is `needs-extension`. `worktree.baseRef` lives in + `.claude/settings.local.json`, outside `.planning/`, so it is reported, not read. +- **owed: record each verdict anew.** Verdicts are never imported (D5): `.planning/` records results, and a legacy + `passed` is no judgement of today's code. Every imported entity a judged rule of `@gsd/core` or `@gsd/security` + judges is listed, grouped by phase under the slash command that judges it (`/gsd-verify-work <NN>`, + `/gsd-secure-phase <NN>`, `/gsd-plan-phase <NN>`, `/gsd-spec-phase <NN>`, `/gsd-audit-milestone`), each followed by + `specforge query '<entity>' --inputs <code> --format json`, whose `basis` the recording command takes. The count line + says whether `specforge check` exits 1 (an error rule such as `gsd/E501` is owed) or warns. +- **authored after import:** fields no `.planning` file gives, such as a vault threat's `files`. + +The last line counts the entities per kind and the report entries. + +## After the import, `check` exits 1 + +`specforge check` reports the owed judged codes until each verdict is recorded, so it exits 1 on any project with an +executed plan. That is the expected result. It also reports any rule error the imported records carry: the import is +an importing command (ADR 0392), so a namespaced rule error of a third-party extension, such as `gsd.security/E101` (a +threat id claimed by two plans), `gsd/E201` or `gsd/E312`, is written rather than refused, and the user fixes it in +`spec/gsd/` with SpecForge's own tools. + +## Refusals + +A refusal writes nothing and answers no plan: + +- **Re-import.** Any `@gsd/core` entity already in the project, named by kind, path and file. There is no `--force`: + delete those entities (by default `spec/gsd/`) and run it again. Two imports at once cannot both land: the host's + revision check refuses the second (D10). +- **Another spec root.** `specforge.json` naming a `spec_root` other than `spec`. +- **Truncated.** "truncated at N": the host's read of `.planning/` stopped early, or the plan would pass its caps + (2,000 operations, 20,000 report entries). Nothing is written in part (D9). +- **A read error** on a mapped file, which would leave its entities missing; no `.planning/` at the root; a + `specforge.json` that is missing or not JSON. +- **A host error, E080.** The host still refuses a plan that adds a first-party error (ADR 0392): a path that no longer + exists (E016 on a complete plan's `files_modified`, a done task's `files`, any `context_refs`), an unresolved + reference. The message names each path; fix it in `.planning/` and run the import again. + +## Never imported + +Verdicts and scores (D5); computed, context, human and verdict fields, which the host refuses from any command (D7); +`config.json` into the manifest (D6); `state.json` (`runtime`); `.gitkeep` (`ignored`); Tier 2 sections (key decisions, +deviations, checkpoints, prohibitions, user setup), which are reported. + +## The measure + +Taskboard, ledger and vault ([../parity/fixtures/](../parity/fixtures/)), imported from `.planning/` alone, are held +against their hand-written twins (D13, `tests/cli/parity_import.rs`): the entity sets equal, with computed fields, +`context_pack` and verdicts left out, except 49 field differences listed with a reason each, and the list fails both +ways. Each fixture's harness codes are pinned under `gsd-compat`, `gsd-strict` and `gsd-plus`; the vault gives two +`gsd.security/W302`, not the twin's five (no `.planning` source gives the other statuses), and carries its two +`gsd.security/E101`. `check` owes exactly the pairs the report lists. The vault imports in under 30 s. + +## What stays open + +- The host's apply cost grows about quadratically with the plan: 2,000 creates applied in 38 s and 5,000 in 218 s on + an idle machine, and 960 creates took 286 s under a loaded gate. `MAX_OPS` (2,000) caps one import; a larger + `.planning/` is refused "truncated at 2000". +- Upstream's `/gsd-import` slash command is not contributed. + +## Layout + +`src/command.rs` (the command), `src/preflight.rs` (refusals before reading), `src/read/` (one reader per file), +`src/records.rs` and `src/emit.rs` (the plan), `src/table.rs` (the fate table), `src/report.rs`, `src/settings.rs`, +`src/owed.rs`, `src/limits.rs`. Tests: native under `tests/`, through the `specforge` binary under `tests/cli/`, which +loads the vendored builtin by name. The blob is `wasm/gsd_import.wasm`, rebuilt only by the re-vendor +([docs/agents/revendor.md](../../docs/agents/revendor.md)). diff --git a/gsd/import/src/command.rs b/gsd/import/src/command.rs new file mode 100644 index 0000000000..558664ed51 --- /dev/null +++ b/gsd/import/src/command.rs @@ -0,0 +1,134 @@ +//! `specforge gsd import` (ADR 0391 D2): no positional; the host serves the project root's `.planning/**` and its +//! `specforge.json`, and the command answers one edit plan that writes `spec/gsd/`, with the report as its output. + +use serde_json::{Value, json}; +use specforge_extension_sdk::prelude::*; + +use crate::preflight::Manifest; +use crate::read::{self, Served}; +use crate::records::Records; +use crate::report::Report; +use crate::{emit, owed, preflight}; + +pub const INVALID: &str = "invalid_input"; + +/// The read of the `.planning/` folder. +pub const PLANNING: &str = "planning"; +/// The read of `specforge.json`. +pub const MANIFEST: &str = "manifest"; + +pub fn declare(c: &mut ContributionsBuilder) { + c.command("import", |cmd| { + cmd.description("Import a GSD project once: read the project root's .planning/ folder into one edit plan that writes spec/gsd/, and report every file, section and row it did not map, with the reason") + // History, not authoring: a rule error the `.planning/` carries lands and `check` reports it (ADR 0392). + .imports() + .input(Input::files( + PLANNING, + FileReadSpec::glob(".planning/**").text_up_to(TEXT_MAX_CEILING_BYTES), + )) + .input(Input::files( + MANIFEST, + FileReadSpec::glob("specforge.json").text(), + )) + .handler(|call| run(call, import)); + }); +} + +/// The served files of the read `name`, sorted by path as the host sends a glob's, and whether the read stopped early. +fn served(call: &CommandCall<'_>, name: &str) -> (Vec<Served>, bool) { + call.files(name) + .map(|files| { + let served = files + .facts + .iter() + .map(|fact| Served { + path: fact.path.clone(), + text: fact.text.clone(), + error: fact.error.clone(), + }) + .collect(); + (served, files.truncated) + }) + .unwrap_or_default() +} + +/// Preflight, read, emit, answer: a refusal anywhere answers no plan. +fn import(call: &CommandCall<'_>) -> Result<CommandOutput, String> { + let graph = call.graph(); + preflight::refuse_reimport(graph)?; + let manifest = preflight::manifest(&served(call, MANIFEST).0)?; + let (planning, truncated) = served(call, PLANNING); + preflight::check_reads(&planning, truncated, manifest.security)?; + let imported = imported(planning, &manifest, graph, call.plan())?; + Ok(answer( + call, + imported.payload, + imported.text, + Some(&imported.plan), + )) +} + +/// What one import answers: its plan, and its report as JSON and as text. +pub struct Imported { + pub plan: PlanBuilder, + pub payload: Value, + pub text: String, +} + +/// Reads `planning`, in path order whatever the order it is given in (an import is deterministic, ADR 0391 D8), into +/// a plan built on `plan` over `graph`, with its report and the verdicts it owes. +pub fn imported( + mut planning: Vec<Served>, + manifest: &Manifest, + graph: &CommandGraph, + plan: PlanBuilder, +) -> Result<Imported, String> { + planning.sort_by(|a, b| a.path.cmp(&b.path)); + let mut records = Records::default(); + let mut report = Report::default(); + read::all(&planning, manifest, &mut records, &mut report); + let (plan, counts, kept) = emit::emit(&records, graph, plan, &mut report)?; + for owed in owed::owed(kept.iter().copied()) { + report.owed(owed); + } + let mut payload = report.payload(&counts); + payload["security"] = json!({ "loaded": manifest.security, "check": SECURITY_CHECK }); + let mut text = report.text(&counts); + text.push_str(&format!( + "@gsd/security {}loaded ({SECURITY_CHECK})\n", + if manifest.security { "" } else { "not " } + )); + Ok(Imported { + plan, + payload, + text, + }) +} + +/// How the import knows the project loads `@gsd/security` (ADR 0391 D11). +const SECURITY_CHECK: &str = "a text check of specforge.json's extensions, not a registry query"; + +/// Runs a command's body: its `Err` is the refusal, reported as `invalid_input` (core's `support::run`). +pub fn run( + call: &CommandCall<'_>, + body: impl FnOnce(&CommandCall<'_>) -> Result<CommandOutput, String>, +) -> CommandOutput { + match body(call) { + Ok(out) => out, + Err(why) => call.fail(&CommandError::new(INVALID, why), 1), + } +} + +/// `payload` through `render`, with `human` as the text form, and `plan` as the edit plan (core's `support::answer`). +pub fn answer( + call: &CommandCall<'_>, + payload: Value, + human: String, + plan: Option<&PlanBuilder>, +) -> CommandOutput { + let out = call.render(&payload, |text| text.push_str(&human)); + match plan { + Some(plan) => out.with_plan(plan.finish()), + None => out, + } +} diff --git a/gsd/import/src/emit.rs b/gsd/import/src/emit.rs new file mode 100644 index 0000000000..ccde1c1a7f --- /dev/null +++ b/gsd/import/src/emit.rs @@ -0,0 +1,552 @@ +//! The records to one edit plan (ADR 0391 D9). The guest refuses what the host would, and reports it, before it +//! answers: a host refusal of the plan (E080) would drop the JSON report. A record is dropped, never stubbed: an id the +//! grammar refuses, an id given twice, a reference to nothing, a file outside `spec/gsd/`, a required field with no +//! source (`kinds::REQUIRED`: a reader puts each `filled` value in the fields first), a field no table row writes for +//! its kind or a block item without a required member (`kinds::REQUIRED_MEMBERS`), a title or field holding a +//! character no `.spec` file holds; a record whose scope or required reference names a dropped one is reported "parent +//! not imported", as is one whose reference list that must keep an item keeps none (`kinds::NON_EMPTY`), while a link +//! (an item of a reference list, an optional reference) naming one is left out of its field and reported, the record +//! kept. Past a cap the plan is refused "truncated at N". +//! +//! A record's id is its graph path (`v1.0/01`): records, references and collisions key by it, and the create takes its +//! last segment. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::Value; +use specforge_extension_sdk::prelude::*; + +use crate::kinds::{non_empty, rank, required, required_members}; +use crate::limits::{MAX_ENTRIES, MAX_OPS}; +use crate::records::{Record, Records}; +use crate::report::{Entry, Outcome, Report, hidden}; +use crate::{ids, table}; + +/// What [`emit`] answers: the plan, how many entities of each kind it creates, and the records it creates. +pub type Emitted<'r> = (PlanBuilder, BTreeMap<&'static str, usize>, Vec<&'r Record>); + +/// The plan built on `plan` from what of `records` passes, how many entities of each kind it creates, and the records +/// it creates. +pub fn emit<'r>( + records: &'r Records, + graph: &CommandGraph, + mut plan: PlanBuilder, + report: &mut Report, +) -> Result<Emitted<'r>, String> { + if records.len() > MAX_OPS { + return Err(format!( + "truncated at {MAX_OPS}: .planning/ gives {} entities, more than one plan holds; nothing is imported", + records.len() + )); + } + let mut ordered: Vec<&Record> = records.iter().collect(); + ordered.sort_by(|a, b| (rank(a.kind), a.kind, &a.id).cmp(&(rank(b.kind), b.kind, &b.id))); + let every: BTreeSet<&str> = ordered.iter().map(|r| r.id.as_str()).collect(); + let refuse = |record: &Record, why: String, report: &mut Report| { + report.push(Entry::at( + &record.source, + record.kind, + Outcome::Unmapped, + format!("{} {}: {why}: not imported", record.kind, record.id), + )); + }; + // The ids, files, fields and collisions: what a record is alone. + let written = table::written(); + let mut kept: Vec<&Record> = Vec::new(); + let mut taken: BTreeMap<&str, &Record> = BTreeMap::new(); + for record in ordered { + let missing = required(record.kind) + .iter() + .find(|field| !record.fields.contains_key(**field)); + // A scope prefix is the path of an entity the record names, never text a document wrote (`A/B-01`). + let scoped = record + .id + .rsplit_once('/') + .is_none_or(|(scope, _)| record.refs.iter().any(|r| r == scope)); + if !(scoped + && ids::valid(record.kind, local(&record.id)) + && record.id.split('/').all(ids::name)) + { + refuse(record, format!("not an id a {} takes", record.kind), report); + } else if !ids::file(&record.file) { + refuse( + record, + format!("its file {} is not under spec/gsd/", record.file), + report, + ); + } else if let Some(field) = missing { + refuse(record, format!("required {field} has no source"), report); + } else if let Some(why) = outside(record, &written) { + refuse(record, why, report); + } else if let Some(field) = unwritable(record) { + refuse( + record, + format!( + "its {field} holds a control or bidirectional character, which no .spec file holds" + ), + report, + ); + } else if let Some(first) = taken.get(record.id.as_str()) { + refuse( + record, + format!( + "the id is {} {}'s already (at {})", + first.kind, first.id, first.source + ), + report, + ); + } else if let Some(node) = graph.node(&record.id) { + refuse( + record, + format!("the graph already holds {} {}", node.kind, node.id), + report, + ); + } else { + taken.insert(&record.id, record); + kept.push(record); + } + } + // The references, until no drop leaves another record naming nothing. + loop { + let alive: BTreeSet<&str> = kept.iter().map(|&r| r.id.as_str()).collect(); + let before = kept.len(); + kept.retain(|record| { + let lives = |id: &String| alive.contains(id.as_str()) || graph.node(id).is_some(); + let missing = record.refs.iter().find(|id| !lives(id)); + let emptied = non_empty(record.kind) + .find(|field| !record.links.iter().any(|(f, id)| f == field && lives(id))); + match (missing, emptied) { + (None, None) => true, + (None, Some(field)) => { + refuse( + record, + format!("no item of its {field} is imported"), + report, + ); + false + } + (Some(id), _) if every.contains(id.as_str()) => { + refuse(record, format!("parent not imported ({})", id), report); + false + } + (Some(id), _) => { + refuse( + record, + format!( + "it names {}, which neither the import nor the graph holds", + id + ), + report, + ); + false + } + } + }); + if kept.len() == before { + break; + } + } + // The links: an item naming nothing is left out of its field, the record kept (the readers' per-item rule). + let alive: BTreeSet<&str> = kept.iter().map(|&r| r.id.as_str()).collect(); + let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new(); + for record in &kept { + let mut fields = record.fields.clone(); + for (field, id) in &record.links { + if alive.contains(id.as_str()) || graph.node(id).is_some() { + continue; + } + let why = if every.contains(id.as_str()) { + "which is not imported" + } else { + "which neither the import nor the graph holds" + }; + report.push(Entry::at( + &record.source, + record.kind, + Outcome::Unmapped, + format!( + "{} {}: its {field} names {id}, {why}: left out", + record.kind, record.id + ), + )); + unlink( + &mut fields, + field, + id, + required(record.kind).contains(field), + ); + } + report.push(Entry::at( + &record.source, + record.kind, + Outcome::Mapped, + format!("{} {}", record.kind, record.id), + )); + plan.create( + record.kind, + local(&record.id), + &record.title, + &record.file, + fields, + Vec::new(), + ); + *counts.entry(record.kind).or_default() += 1; + } + if report.len() > MAX_ENTRIES { + return Err(format!( + "truncated at {MAX_ENTRIES}: the report would hold {} lines; nothing is imported", + report.len() + )); + } + Ok((plan, counts, kept)) +} + +/// Why the host would refuse what `record` writes, at runtime rather than only through the table's static check: a +/// field no table row writes for its kind (a computed, context, human or verdict field, `table::written`), or a block +/// item without a required member (`kinds::REQUIRED_MEMBERS`, E006). +fn outside(record: &Record, written: &BTreeSet<(&str, &str)>) -> Option<String> { + for (field, value) in &record.fields { + if !written.contains(&(record.kind, field.as_str())) { + return Some(format!( + "its {field} is no field the import writes for a {}", + record.kind + )); + } + let items = match value { + Value::Array(items) => items.as_slice(), + one => std::slice::from_ref(one), + }; + for member in required_members(record.kind, field) { + if items.iter().any(|item| item.get(member).is_none()) { + return Some(format!( + "an item of its {field} has no {member}, which a {} requires", + record.kind + )); + } + } + } + None +} + +/// The title, or the first field, of `record` whose text holds a character no `.spec` file holds: a control or +/// bidirectional character but a tab, a line feed and a carriage return before one. The parser refuses such a file, +/// so the host would refuse the whole plan (`block_unreadable`). +fn unwritable(record: &Record) -> Option<&str> { + fn bad(text: &str) -> bool { + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + let line_break = c == '\n' || (c == '\r' && chars.peek() == Some(&'\n')); + if hidden(c) && c != '\t' && !line_break { + return true; + } + } + false + } + fn holds(value: &Value) -> bool { + match value { + Value::String(text) => bad(text), + Value::Array(items) => items.iter().any(holds), + Value::Object(map) => map.iter().any(|(key, value)| bad(key) || holds(value)), + _ => false, + } + } + if bad(&record.title) { + return Some("title"); + } + record + .fields + .iter() + .find(|(_, value)| holds(value)) + .map(|(field, _)| field.as_str()) +} + +/// `fields[field]` without what names `id`: the item `id` or an item block holding it (`requires: {phase, provides}`) +/// of a list, or the field when it is `id`. An optional list left empty goes; a required one stays written, empty, as +/// a reader writes it when it keeps no item (`requirements_completed: []`). +fn unlink(fields: &mut BTreeMap<String, Value>, field: &str, id: &str, required: bool) { + let names = |v: &Value| match v { + Value::String(s) => s == id, + Value::Object(map) => map.values().any(|v| v.as_str() == Some(id)), + _ => false, + }; + match fields.get_mut(field) { + Some(Value::Array(items)) => { + items.retain(|item| !names(item)); + if items.is_empty() && !required { + fields.remove(field); + } + } + Some(value) if names(value) => { + fields.remove(field); + } + _ => {} + } +} + +/// A record's own id, the last segment of its path: a scoped entity is created with it and its scope field +/// (`phase 01` with `milestone v1.0` is `v1.0/01`). +fn local(id: &str) -> &str { + id.rsplit('/').next().unwrap_or(id) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use specforge_extension_sdk::PlanOp; + + use super::*; + use crate::records::Source; + + /// A record of `kind` holding each of its required fields, naming `refs` and linking `links`. + fn record( + kind: &'static str, + id: &str, + refs: &[&str], + links: &[(&'static str, &str)], + ) -> Record { + Record { + kind, + id: id.to_string(), + title: id.to_string(), + file: "spec/gsd/x.spec".to_string(), + fields: required(kind) + .iter() + .map(|f| (f.to_string(), json!("x"))) + .collect(), + refs: refs.iter().map(|r| r.to_string()).collect(), + links: links.iter().map(|(f, id)| (*f, id.to_string())).collect(), + source: Source { + file: ".planning/x.md".to_string(), + line: 1, + }, + } + } + + /// The creates of `records` on an empty graph, each id with its fields. + fn created( + records: &Records, + report: &mut Report, + ) -> BTreeMap<String, BTreeMap<String, Value>> { + let plan = PlanBuilder::new(Default::default(), Default::default()); + let (plan, _, _) = + emit(records, &CommandGraph::default(), plan, report).expect("not refused"); + plan.finish() + .ops + .into_iter() + .filter_map(|op| match op { + PlanOp::Create { id, fields, .. } => Some((id, fields)), + _ => None, + }) + .collect() + } + + fn reasons(report: &Report) -> Vec<String> { + report + .entries() + .into_iter() + .map(|e| e.reason.clone()) + .collect() + } + + #[test] + fn a_dropped_list_item_is_left_out_and_its_holder_kept() { + let mut records = Records::default(); + let mut report = Report::default(); + // A-01's text holds U+200F, which the parser refuses: it is dropped, and the phase naming it is kept. + let mut rlm = record("requirement", "A-01", &[], &[]); + rlm.fields.insert("text".to_string(), json!("x\u{200F}")); + records.add(rlm, &mut report); + records.add(record("requirement", "A-02", &[], &[]), &mut report); + records.add(record("milestone", "v1.0", &[], &[]), &mut report); + let mut phase = record( + "phase", + "v1.0/01", + &["v1.0"], + &[("requirements", "A-01"), ("requirements", "A-02")], + ); + phase + .fields + .insert("requirements".to_string(), json!(["A-01", "A-02"])); + records.add(phase, &mut report); + let mut plan = record( + "plan", + "v1.0/01/01-01", + &["v1.0/01"], + &[("requirements", "A-01")], + ); + plan.fields + .insert("requirements".to_string(), json!(["A-01"])); + records.add(plan, &mut report); + let created = created(&records, &mut report); + assert_eq!( + created.keys().map(String::as_str).collect::<Vec<_>>(), + ["01", "01-01", "A-02", "v1.0"] + ); + assert_eq!(created["01"]["requirements"], json!(["A-02"])); + // An optional list left empty goes. + assert!(!created["01-01"].contains_key("requirements")); + let said = reasons(&report); + assert!( + said.iter().any(|r| r + == "phase v1.0/01: its requirements names A-01, which is not imported: left out"), + "{said:#?}" + ); + assert!( + !said.iter().any(|r| r.contains("parent not imported")), + "{said:#?}" + ); + } + + #[test] + fn a_session_with_no_imported_source_is_dropped_with_its_tests() { + let mut records = Records::default(); + let mut report = Report::default(); + records.add(record("milestone", "v1.0", &[], &[]), &mut report); + for phase in ["01", "02", "03"] { + let id = format!("v1.0/{phase}"); + records.add(record("phase", &id, &["v1.0"], &[]), &mut report); + } + let (gone, kept) = ("v1.0/01/01-01/01-01-SUMMARY", "v1.0/01/01-02/01-02-SUMMARY"); + for (plan, summary) in [("v1.0/01/01-01", gone), ("v1.0/01/01-02", kept)] { + records.add(record("plan", plan, &["v1.0/01"], &[]), &mut report); + let mut s = record("summary", summary, &[plan], &[]); + if summary == gone { + // U+202E, which the parser refuses: the summary is dropped. + s.title = "x\u{202E}".to_string(); + } + records.add(s, &mut report); + } + let session = |id: &str, phase: &str, names: &[&'static str]| { + let links: Vec<(&'static str, &str)> = names.iter().map(|n| ("source", *n)).collect(); + let mut r = record("uat_session", id, &[phase], &links); + r.fields.insert("source".to_string(), json!(names)); + r + }; + // Every summary it names is dropped; it names none; it keeps one of two. + records.add(session("v1.0/01/01-UAT", "v1.0/01", &[gone]), &mut report); + records.add(session("v1.0/02/02-UAT", "v1.0/02", &[]), &mut report); + records.add( + session("v1.0/03/03-UAT", "v1.0/03", &[gone, kept]), + &mut report, + ); + records.add( + record("uat_test", "v1.0/01/01-UAT/U1", &["v1.0/01/01-UAT"], &[]), + &mut report, + ); + let created = created(&records, &mut report); + assert!(!created.contains_key("01-UAT") && !created.contains_key("02-UAT")); + assert!(!created.contains_key("U1"), "{created:#?}"); + assert_eq!(created["03-UAT"]["source"], json!([kept])); + let said = reasons(&report); + for says in [ + "uat_session v1.0/01/01-UAT: no item of its source is imported: not imported", + "uat_session v1.0/02/02-UAT: no item of its source is imported: not imported", + "uat_test v1.0/01/01-UAT/U1: parent not imported (v1.0/01/01-UAT): not imported", + ] { + assert!(said.iter().any(|r| r == says), "{says}: {said:#?}"); + } + } + + #[test] + fn a_dropped_parent_still_drops_its_children() { + let mut records = Records::default(); + let mut report = Report::default(); + let mut milestone = record("milestone", "v1.0", &[], &[]); + milestone.title = "x\u{202E}".to_string(); + records.add(milestone, &mut report); + records.add(record("phase", "v1.0/01", &["v1.0"], &[]), &mut report); + records.add( + record("plan", "v1.0/01/01-01", &["v1.0/01"], &[]), + &mut report, + ); + assert!(created(&records, &mut report).is_empty()); + let said = reasons(&report); + assert!( + said.iter() + .any(|r| r.contains("v1.0/01: parent not imported (v1.0)")), + "{said:#?}" + ); + } + + #[test] + fn settings_lines_and_minted_ids_count_toward_the_report_cap() { + let mut report = Report::default(); + for n in 0..MAX_ENTRIES / 2 { + report.setting(format!("specforge settings set @gsd/core k{n} 'x'")); + } + for n in 0..=MAX_ENTRIES / 2 { + report.minted(crate::report::Minted { + kind: "requirement".to_string(), + old: format!("row {n}"), + new: format!("OOS-{n}"), + }); + } + let plan = PlanBuilder::new(Default::default(), Default::default()); + let Err(refused) = emit( + &Records::default(), + &CommandGraph::default(), + plan, + &mut report, + ) else { + panic!("a report past the cap is refused"); + }; + assert!( + refused.starts_with(&format!("truncated at {MAX_ENTRIES}")), + "{refused}" + ); + } + + #[test] + fn a_field_outside_the_table_or_a_block_without_its_member_drops_the_record() { + let mut records = Records::default(); + let mut report = Report::default(); + records.add(record("milestone", "v1.0", &[], &[]), &mut report); + records.add(record("phase", "v1.0/01", &["v1.0"], &[]), &mut report); + // `status` is computed: no row writes it. + let mut computed = record("plan", "v1.0/01/01-01", &["v1.0/01"], &[]); + computed.fields.insert("status".to_string(), json!("done")); + records.add(computed, &mut report); + let mut plan = record("plan", "v1.0/01/01-02", &["v1.0/01"], &[]); + plan.fields.insert("phase".to_string(), json!("v1.0/01")); + records.add(plan, &mut report); + let mut task = record("task", "v1.0/01/01-02/T1", &["v1.0/01/01-02"], &[]); + task.fields.insert( + "verify".to_string(), + json!([{"automated": "npm test"}, {"fails_when": "x"}]), + ); + records.add(task, &mut report); + let created = created(&records, &mut report); + assert_eq!( + created.keys().map(String::as_str).collect::<Vec<_>>(), + ["01", "01-02", "v1.0"] + ); + let said = reasons(&report); + for says in [ + "plan v1.0/01/01-01: its status is no field the import writes for a plan: not imported", + "task v1.0/01/01-02/T1: an item of its verify has no automated, which a task requires: not imported", + ] { + assert!(said.iter().any(|r| r == says), "{says}: {said:#?}"); + } + } + + #[test] + fn unlink_leaves_out_what_names_the_id() { + let mut fields: BTreeMap<String, Value> = BTreeMap::from([ + ("completed".to_string(), json!(["A"])), + ("optional".to_string(), json!(["A"])), + ("one".to_string(), json!("A")), + ( + "requires".to_string(), + json!([{"phase": "A", "provides": "p"}, {"phase": "B", "provides": "q"}]), + ), + ]); + unlink(&mut fields, "completed", "A", true); + unlink(&mut fields, "optional", "A", false); + unlink(&mut fields, "one", "A", false); + unlink(&mut fields, "requires", "A", false); + assert_eq!( + Value::Object(fields.into_iter().collect()), + json!({"completed": [], "requires": [{"phase": "B", "provides": "q"}]}) + ); + } +} diff --git a/gsd/import/src/frontmatter.rs b/gsd/import/src/frontmatter.rs new file mode 100644 index 0000000000..85a7c6d6fe --- /dev/null +++ b/gsd/import/src/frontmatter.rs @@ -0,0 +1,596 @@ +//! A file's frontmatter (ADR 0391 D9, 13-RESEARCH Pitfall 3): split off by hand (a first line `---` up to the next line +//! that is exactly `---`), since CommonMark reads it as a thematic break and a setext heading, and read as the small +//! YAML subset GSD writes. No YAML crate (ADR 0391 Rejected): a bounded, line-driven reader that refuses what it does +//! not read, at its line. +//! +//! Read: plain, single- and double-quoted scalars; flow lists and flow maps of scalars; block lists, nested maps and +//! lists of maps; `|` and `>` block scalars with `-` / `+` chomping; `#` comments; empty values. A scalar is never +//! typed: `01` stays the text `01`, `true` the text `true`, for the reader to interpret. +//! +//! Refused, mapping nothing of the frontmatter: an anchor, an alias, a tag, a merge key, a second document, a tab in an +//! indentation, nesting deeper than [`MAX_DEPTH`], a line longer than [`MAX_LINE`], a key given twice, a +//! double-quoted escape YAML does not define. A block scalar's lines are text: a tab, `%` or `...` in one is kept. +//! +//! Lines are 1-based over the whole file, frontmatter lines included. + +use std::collections::BTreeSet; + +/// The deepest nesting read: the frontmatter's own map is depth 1. +pub const MAX_DEPTH: usize = 8; + +/// The longest frontmatter line read, in bytes. +pub const MAX_LINE: usize = 64 * 1024; + +/// A value and the 1-based line it starts on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Located<T> { + pub line: usize, + pub value: T, +} + +/// A frontmatter value: text, a list or a map (keys in the order written). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Value { + Str(String), + List(Vec<Located<Value>>), + Map(Vec<(String, Located<Value>)>), +} + +impl Value { + /// The value of `key`, when this is a map holding it. + pub fn get(&self, key: &str) -> Option<&Located<Value>> { + match self { + Value::Map(entries) => entries.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + + /// The text, when this is a scalar. + pub fn as_str(&self) -> Option<&str> { + match self { + Value::Str(text) => Some(text), + _ => None, + } + } +} + +/// What a reader refused, and the 1-based line it refused at. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refused { + pub line: usize, + pub reason: String, +} + +fn refused<T>(line: usize, reason: impl Into<String>) -> Result<T, Refused> { + Err(Refused { + line, + reason: reason.into(), + }) +} + +/// A frontmatter: its lines, without the two `---` marks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Front<'a> { + pub lines: Vec<&'a str>, + /// The 1-based line of `lines[0]` in the file. + pub line: usize, +} + +/// The frontmatter of `text`, if its first line is exactly `---`, and the 0-based index of the body's first line. With +/// no closing `---` the frontmatter is refused at line 1 and the whole file is the body. +pub fn split(text: &str) -> (Result<Option<Front<'_>>, Refused>, usize) { + let lines: Vec<&str> = text.split('\n').map(|l| l.trim_end_matches('\r')).collect(); + if lines.first() != Some(&"---") { + return (Ok(None), 0); + } + match lines.iter().skip(1).position(|l| *l == "---") { + Some(n) => ( + Ok(Some(Front { + lines: lines[1..=n].to_vec(), + line: 2, + })), + n + 2, + ), + None => ( + refused(1, "frontmatter not closed: no line `---` ends it"), + 0, + ), + } +} + +/// `text` with its first `start` lines emptied: the body, at its own line numbers, for the Markdown readers. +pub fn body(text: &str, start: usize) -> String { + text.split('\n') + .enumerate() + .map(|(n, line)| if n < start { "" } else { line }) + .collect::<Vec<_>>() + .join("\n") +} + +/// A map's entries, in the order written. +pub type Entries = Vec<(String, Located<Value>)>; + +/// The frontmatter's entries, at the line of its first key, or the first thing it refuses: a frontmatter is a map, so +/// a reader gets its keys and has no other shape to handle. +pub fn read(front: &Front<'_>) -> Result<Located<Entries>, Refused> { + let mut lines = Vec::with_capacity(front.lines.len()); + for (n, raw) in front.lines.iter().enumerate() { + let no = front.line + n; + if raw.len() > MAX_LINE { + return refused(no, format!("a line longer than {MAX_LINE} bytes")); + } + let content = raw.trim_start_matches(' ').trim_end(); + // Refused only where the parser reads the line as a key or an item: a block scalar's line is text. + let refusal = if content.starts_with('\t') { + Some("a tab indents this line") + } else if content == "..." || content.starts_with("--- ") || content.starts_with('%') { + Some("a second YAML document or a directive") + } else { + None + }; + lines.push(Line { + no, + indent: raw.len() - raw.trim_start_matches(' ').len(), + content, + refusal, + }); + } + let mut parser = Parser { lines, at: 0 }; + parser.skip(); + let Some(first) = parser.peek() else { + return Ok(Located { + line: front.line, + value: Vec::new(), + }); + }; + first.read()?; + if first.content.starts_with('-') + && (first.content.len() == 1 || first.content[1..].starts_with(' ')) + { + return refused(first.no, "a frontmatter is a map, not a list"); + } + let map = parser.entries(first.indent, 1)?; + match parser.peek() { + None => Ok(map), + Some(rest) => { + rest.read()?; + refused(rest.no, "a line outside the frontmatter's map") + } + } +} + +#[derive(Debug, Clone, Copy)] +struct Line<'a> { + no: usize, + indent: usize, + /// The line without its indentation and trailing white space. + content: &'a str, + /// Why the line is refused when read as a key or an item: a tab indenting it, a document mark or a directive. + refusal: Option<&'static str>, +} + +impl Line<'_> { + /// The line, read as a key or an item: refused when it carries a [`Line::refusal`]. + fn read(&self) -> Result<(), Refused> { + match self.refusal { + Some(why) => refused(self.no, why), + None => Ok(()), + } + } +} + +struct Parser<'a> { + lines: Vec<Line<'a>>, + at: usize, +} + +fn item(content: &str) -> Option<&str> { + match content.strip_prefix('-') { + Some("") => Some(""), + Some(rest) if rest.starts_with(' ') => Some(rest.trim_start()), + _ => None, + } +} + +impl<'a> Parser<'a> { + /// Moves past blank and comment lines. + fn skip(&mut self) { + while self + .lines + .get(self.at) + .is_some_and(|l| l.content.is_empty() || l.content.starts_with('#')) + { + self.at += 1; + } + } + + fn peek(&mut self) -> Option<Line<'a>> { + self.skip(); + self.lines.get(self.at).copied() + } + + fn deep(line: usize, depth: usize) -> Result<(), Refused> { + if depth > MAX_DEPTH { + return refused(line, format!("nesting deeper than {MAX_DEPTH}")); + } + Ok(()) + } + + /// The map whose keys stand at `indent`. + fn map(&mut self, indent: usize, depth: usize) -> Result<Located<Value>, Refused> { + let entries = self.entries(indent, depth)?; + Ok(Located { + line: entries.line, + value: Value::Map(entries.value), + }) + } + + /// The entries of the map whose keys stand at `indent`, at the line of its first key. + fn entries(&mut self, indent: usize, depth: usize) -> Result<Located<Entries>, Refused> { + let start = self.peek().map_or(0, |l| l.no); + Self::deep(start, depth)?; + let mut entries: Vec<(String, Located<Value>)> = Vec::new(); + // The keys seen, so a key given twice is found in linear time over a frontmatter of any size. + let mut seen: BTreeSet<String> = BTreeSet::new(); + while let Some(line) = self.peek() { + line.read()?; + if line.indent < indent || (line.indent == indent && item(line.content).is_some()) { + break; + } + if line.indent > indent { + return refused(line.no, "an indentation no key opens"); + } + let Some((key, rest)) = key(line.content) else { + return refused(line.no, "not a `key: value` line"); + }; + if key == "<<" { + return refused(line.no, "a merge key `<<`"); + } + if !seen.insert(key.clone()) { + return refused(line.no, format!("the key `{key}` is given twice")); + } + self.at += 1; + let value = self.value(rest, line.no, indent, depth, true)?; + entries.push((key, value)); + } + Ok(Located { + line: start, + value: entries, + }) + } + + /// The list whose `- ` marks stand at `indent`. + fn list(&mut self, indent: usize, depth: usize) -> Result<Located<Value>, Refused> { + let start = self.peek().map_or(0, |l| l.no); + Self::deep(start, depth)?; + let mut items = Vec::new(); + while let Some(line) = self.peek() { + line.read()?; + if line.indent < indent { + break; + } + if line.indent > indent { + return refused(line.no, "an indentation no list item opens"); + } + let Some(rest) = item(line.content) else { + break; + }; + if !rest.is_empty() && !rest.starts_with(['"', '\'', '[', '{']) && key(rest).is_some() { + // `- key: value`: a map whose keys stand at the column of `key`. + let column = indent + line.content.len() - rest.len(); + self.lines[self.at] = Line { + indent: column, + content: rest, + ..line + }; + items.push(self.map(column, depth + 1)?); + } else { + self.at += 1; + items.push(self.value(rest, line.no, indent, depth, false)?); + } + } + Ok(Located { + line: start, + value: Value::List(items), + }) + } + + /// The value written `rest` after a key or a list mark at `indent`, on line `no`, inside a collection of `depth`. + fn value( + &mut self, + rest: &'a str, + no: usize, + indent: usize, + depth: usize, + in_map: bool, + ) -> Result<Located<Value>, Refused> { + if rest.is_empty() || rest.starts_with('#') { + return match self.peek() { + Some(next) if next.indent > indent => { + if item(next.content).is_some() { + self.list(next.indent, depth + 1) + } else { + self.map(next.indent, depth + 1) + } + } + // `key:` then `- a` at the key's own column: YAML's compact list. + Some(next) if in_map && next.indent == indent && item(next.content).is_some() => { + self.list(indent, depth + 1) + } + _ => Ok(Located { + line: no, + value: Value::Str(String::new()), + }), + }; + } + if let Some(header) = rest.strip_prefix('|') { + return self.block(header, no, indent, false); + } + if let Some(header) = rest.strip_prefix('>') { + return self.block(header, no, indent, true); + } + Ok(Located { + line: no, + value: inline(rest, no, depth)?, + }) + } + + /// A `|` or `>` block scalar: the lines indented past `indent` after its header. + fn block( + &mut self, + header: &str, + no: usize, + indent: usize, + folded: bool, + ) -> Result<Located<Value>, Refused> { + let header = header.trim(); + let (chomp, rest) = match header.chars().next() { + Some(c @ ('-' | '+')) => (c, header[1..].trim_start()), + _ => (' ', header), + }; + if !(rest.is_empty() || rest.starts_with('#')) { + return refused(no, "a block scalar header this reader does not read"); + } + let mut lines: Vec<String> = Vec::new(); + let mut column: Option<usize> = None; + while let Some(line) = self.lines.get(self.at) { + if !line.content.is_empty() && line.indent <= indent { + break; + } + if line.content.is_empty() { + lines.push(String::new()); + } else { + let c = *column.get_or_insert(line.indent); + if line.indent < c { + return refused(line.no, "a block scalar line less indented than its first"); + } + lines.push(format!("{}{}", " ".repeat(line.indent - c), line.content)); + } + self.at += 1; + } + let kept = lines + .iter() + .rposition(|l| !l.is_empty()) + .map_or(0, |i| i + 1); + let trailing = lines.len() - kept; + lines.truncate(kept); + let mut text = if folded { + fold(&lines) + } else { + lines.join("\n") + }; + match chomp { + '-' => {} + '+' => text.push_str(&"\n".repeat(trailing + 1)), + _ if !text.is_empty() => text.push('\n'), + _ => {} + } + Ok(Located { + line: no, + value: Value::Str(text), + }) + } +} + +/// `>`'s folding: the lines of a paragraph joined by a space, each blank line a line break. +fn fold(lines: &[String]) -> String { + let mut out = String::new(); + let mut blank = 0; + for (n, line) in lines.iter().enumerate() { + if line.is_empty() { + blank += 1; + continue; + } + if n > 0 { + out.push_str(&if blank == 0 { + " ".to_string() + } else { + "\n".repeat(blank) + }); + } + blank = 0; + out.push_str(line); + } + out +} + +/// The key of a `key: value` line, unquoted, and the text after it. +fn key(content: &str) -> Option<(String, &str)> { + let (key, after) = match content.chars().next()? { + q @ ('"' | '\'') => { + let end = content[1..].find(q)? + 1; + (content[1..end].to_string(), &content[end + 1..]) + } + '[' | '{' | '#' | '&' | '*' | '!' | '?' => return None, + _ => { + let end = content + .find(": ") + .or_else(|| content.strip_suffix(':').map(str::len))?; + (content[..end].trim_end().to_string(), &content[end..]) + } + }; + let rest = after.strip_prefix(':')?; + if !(rest.is_empty() || rest.starts_with(' ')) || key.is_empty() { + return None; + } + Some((key, rest.trim())) +} + +/// A value written on its key's line: a scalar, a flow list or a flow map of scalars. +fn inline(text: &str, no: usize, depth: usize) -> Result<Value, Refused> { + let text = text.trim(); + match text.chars().next() { + Some('[') | Some('{') => { + Parser::deep(no, depth + 1)?; + let (open, close) = if text.starts_with('[') { + ('[', ']') + } else { + ('{', '}') + }; + let inner = uncomment(text) + .strip_prefix(open) + .and_then(|t| t.strip_suffix(close)) + .ok_or_else(|| Refused { + line: no, + reason: format!("a flow collection not closed by `{close}` on its line"), + })?; + let parts = commas(inner, no)?.into_iter().filter(|p| !p.is_empty()); + if open == '[' { + return Ok(Value::List( + parts.map(|p| scalar(p, no)).collect::<Result<_, _>>()?, + )); + } + let mut entries = Vec::new(); + for part in parts { + let (k, v) = key(part).ok_or_else(|| Refused { + line: no, + reason: "a flow map item is not `key: value`".to_string(), + })?; + entries.push((k, scalar(v, no)?)); + } + Ok(Value::Map(entries)) + } + _ => Ok(scalar(text, no)?.value), + } +} + +/// `text` split at the commas outside quotes; a flow collection inside one is refused. +fn commas(text: &str, no: usize) -> Result<Vec<&str>, Refused> { + let mut parts = Vec::new(); + let (mut start, mut quote) = (0, None::<char>); + for (i, c) in text.char_indices() { + match (quote, c) { + (Some(q), c) if c == q => quote = None, + (Some(_), _) => {} + (None, '"' | '\'') => quote = Some(c), + (None, '[' | '{') => return refused(no, "a flow collection inside a flow collection"), + (None, ',') => { + parts.push(text[start..i].trim()); + start = i + 1; + } + _ => {} + } + } + parts.push(text[start..].trim()); + Ok(parts) +} + +/// `text` without a trailing ` #` comment outside quotes. +fn uncomment(text: &str) -> &str { + let mut quote = None::<char>; + let mut prev = ' '; + for (i, c) in text.char_indices() { + match (quote, c) { + (Some(q), c) if c == q => quote = None, + (Some(_), _) => {} + (None, '"' | '\'') if prev == ' ' || prev == '[' || prev == '{' || prev == ',' => { + quote = Some(c); + } + (None, '#') if prev == ' ' || prev == '\t' => return text[..i].trim_end(), + _ => {} + } + prev = c; + } + text.trim_end() +} + +/// One scalar, unquoted. +fn scalar(text: &str, no: usize) -> Result<Located<Value>, Refused> { + let text = text.trim(); + let value = match text.chars().next() { + Some('&') => return refused(no, "an anchor `&`"), + Some('*') => return refused(no, "an alias `*`"), + Some('!') => return refused(no, "a tag `!`"), + Some('[' | '{') => return refused(no, "a flow collection inside a flow collection"), + Some(q @ ('"' | '\'')) => quoted(text, q, no)?, + _ => uncomment(text).to_string(), + }; + Ok(Located { + line: no, + value: Value::Str(value), + }) +} + +/// A quoted scalar's text; it ends on its line, then only a comment may follow. +fn quoted(text: &str, q: char, no: usize) -> Result<String, Refused> { + let mut out = String::new(); + let mut chars = text[1..].char_indices(); + while let Some((i, c)) = chars.next() { + match c { + '\\' if q == '"' => { + let Some((_, e)) = chars.next() else { break }; + let mut hex = |digits: usize| { + let code: String = chars.by_ref().take(digits).map(|(_, c)| c).collect(); + (code.len() == digits && code.chars().all(|c| c.is_ascii_hexdigit())) + .then(|| u32::from_str_radix(&code, 16).ok()) + .flatten() + .and_then(char::from_u32) + }; + // YAML 1.2's double-quoted escapes (5.7); any other is refused, never read as its letter. + let decoded = match e { + '0' => Some('\0'), + 'a' => Some('\u{7}'), + 'b' => Some('\u{8}'), + 't' | '\t' => Some('\t'), + 'n' => Some('\n'), + 'v' => Some('\u{b}'), + 'f' => Some('\u{c}'), + 'r' => Some('\r'), + 'e' => Some('\u{1b}'), + ' ' | '"' | '/' | '\\' => Some(e), + 'N' => Some('\u{85}'), + '_' => Some('\u{a0}'), + 'L' => Some('\u{2028}'), + 'P' => Some('\u{2029}'), + 'x' => hex(2), + 'u' => hex(4), + 'U' => hex(8), + _ => None, + }; + match decoded { + Some(c) => out.push(c), + None => { + return refused(no, format!("an escape `\\{e}` this reader does not read")); + } + } + } + c if c == q => { + if q == '\'' && text[1 + i + 1..].starts_with('\'') { + out.push('\''); + chars.next(); + continue; + } + let after = text[1 + i + 1..].trim(); + if !(after.is_empty() || after.starts_with('#')) { + return refused(no, "text after a quoted value"); + } + return Ok(out); + } + c => out.push(c), + } + } + refused(no, "a quoted value runs past its line") +} + +#[cfg(test)] +mod tests; diff --git a/gsd/import/src/frontmatter/tests.rs b/gsd/import/src/frontmatter/tests.rs new file mode 100644 index 0000000000..b39a5ea5c6 --- /dev/null +++ b/gsd/import/src/frontmatter/tests.rs @@ -0,0 +1,304 @@ +use super::*; + +fn front(text: &str) -> Result<Located<Value>, Refused> { + let (front, _) = split(text); + read(&front.expect("closed").expect("a frontmatter")).map(|m| Located { + line: m.line, + value: Value::Map(m.value), + }) +} + +fn s(line: usize, text: &str) -> Located<Value> { + Located { + line, + value: Value::Str(text.to_string()), + } +} + +fn refused_at(text: &str) -> (usize, String) { + let r = front(text).expect_err("refused"); + (r.line, r.reason) +} + +#[test] +fn split_keeps_the_body_at_its_lines() { + let text = "---\na: 1\n---\n# Title\n"; + let (front, start) = split(text); + let front = front.expect("closed").expect("a frontmatter"); + assert_eq!((front.lines, front.line, start), (vec!["a: 1"], 2, 3)); + assert_eq!(body(text, start), "\n\n\n# Title\n"); + assert_eq!(split("# No front\n---\n"), (Ok(None), 0)); +} + +#[test] +fn an_unclosed_frontmatter_is_refused_at_line_one() { + let (front, start) = split("---\na: 1\n# Title\n"); + let refusal = front.expect_err("refused"); + assert_eq!((refusal.line, start), (1, 0)); + assert!(refusal.reason.contains("not closed"), "{}", refusal.reason); +} + +#[test] +fn scalars_are_never_typed_and_keep_their_lines() { + let map = front( + "---\nphase: \"01\"\nplan: 01\nauto: true\nempty:\nq: 'it''s'\nc: text # a note\n---\n", + ) + .expect("read"); + assert_eq!(map.line, 2); + let Value::Map(entries) = &map.value else { + panic!("a map") + }; + let got: Vec<(&str, &Located<Value>)> = entries.iter().map(|(k, v)| (k.as_str(), v)).collect(); + assert_eq!( + got, + [ + ("phase", &s(2, "01")), + ("plan", &s(3, "01")), + ("auto", &s(4, "true")), + ("empty", &s(5, "")), + ("q", &s(6, "it's")), + ("c", &s(7, "text")), + ] + ); + let escaped = front("---\nv: \"a \\\"b\\\" \\\\ c\"\n---\n").expect("read"); + assert_eq!(escaped.value.get("v"), Some(&s(2, "a \"b\" \\ c"))); +} + +#[test] +fn flow_lists_and_maps_hold_scalars() { + let map = + front("---\nfiles: [package.json, \"a, b\", 'c']\nnone: []\nm: {a: 1, b: \"x y\"}\n---\n") + .expect("read"); + assert_eq!( + map.value.get("files").map(|v| &v.value), + Some(&Value::List(vec![ + s(2, "package.json"), + s(2, "a, b"), + s(2, "c") + ])) + ); + assert_eq!( + map.value.get("none").map(|v| &v.value), + Some(&Value::List(vec![])) + ); + assert_eq!( + map.value.get("m").map(|v| &v.value), + Some(&Value::Map(vec![ + ("a".into(), s(4, "1")), + ("b".into(), s(4, "x y")) + ])) + ); +} + +#[test] +fn a_plans_must_haves_read_as_lists_of_maps() { + let text = std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../parity/fixtures/taskboard/.planning/phases/01-core/01-01-PLAN.md" + )) + .expect("the fixture"); + let map = front(&text).expect("read"); + assert_eq!(map.value.get("phase"), Some(&s(2, "01-core"))); + assert_eq!( + map.value.get("files_modified").map(|v| &v.value), + Some(&Value::List(vec![ + s(7, "package.json"), + s(7, "src/tasks.js"), + s(7, "test/tasks.test.js") + ])) + ); + let must = &map.value.get("must_haves").expect("must_haves").value; + let truths = must.get("truths").expect("truths"); + assert_eq!( + truths.value, + Value::List(vec![s( + 12, + "A task added to a board has the next integer id and keeps its title" + )]) + ); + let artifact = match &must.get("artifacts").expect("artifacts").value { + Value::List(items) => items[0].clone(), + other => panic!("{other:?}"), + }; + assert_eq!(artifact.line, 14); + assert_eq!(artifact.value.get("path"), Some(&s(14, "src/tasks.js"))); + assert_eq!( + artifact.value.get("contains"), + Some(&s(16, "export function addTask")) + ); + let link = match &must.get("key_links").expect("key_links").value { + Value::List(items) => items[0].clone(), + other => panic!("{other:?}"), + }; + assert_eq!(link.value.get("via"), Some(&s(20, "import { addTask }"))); +} + +#[test] +fn the_fixtures_security_and_state_frontmatters_read() { + let fixture = |path: &str| { + std::fs::read_to_string(format!( + "{}/../parity/fixtures/{path}", + env!("CARGO_MANIFEST_DIR") + )) + .expect("the fixture") + }; + let security = front(&fixture("vault/.planning/phases/01-core/01-SECURITY.md")).expect("read"); + assert_eq!(security.value.get("phase"), Some(&s(2, "01"))); + assert_eq!(security.value.get("created"), Some(&s(8, "2026-10-30"))); + let state = front(&fixture("taskboard/.planning/STATE.md")).expect("read"); + assert_eq!(state.value.get("current_phase"), Some(&s(3, "02"))); + let progress = &state.value.get("progress").expect("progress").value; + assert_eq!(progress.get("percent"), Some(&s(16, "33"))); +} + +#[test] +fn nested_maps_and_compact_lists_read() { + let map = front("---\nprogress:\n total: 4\n done: 1\nlist:\n- a\n- b\nafter: x\n---\n") + .expect("read"); + assert_eq!( + map.value.get("progress").map(|v| &v.value), + Some(&Value::Map(vec![ + ("total".into(), s(3, "4")), + ("done".into(), s(4, "1")) + ])) + ); + assert_eq!( + map.value.get("list").map(|v| &v.value), + Some(&Value::List(vec![s(6, "a"), s(7, "b")])) + ); + assert_eq!(map.value.get("after"), Some(&s(8, "x"))); +} + +#[test] +fn block_scalars_fold_and_chomp() { + let text = "---\nlit: |\n one\n two\n\nclip: |-\n a\n b\nkeep: |+\n k\n\nfold: >\n a\n b\n\n c\nend: x\n---\n"; + let map = front(text).expect("read"); + let get = |k: &str| { + map.value + .get(k) + .and_then(|v| v.value.as_str()) + .map(str::to_string) + }; + assert_eq!(get("lit").as_deref(), Some("one\n two\n")); + assert_eq!(get("clip").as_deref(), Some("a\nb")); + assert_eq!(get("keep").as_deref(), Some("k\n\n")); + assert_eq!(get("fold").as_deref(), Some("a b\nc\n")); + assert_eq!(get("end").as_deref(), Some("x")); +} + +#[test] +fn every_unread_yaml_feature_is_refused_at_its_line() { + for (text, line, why) in [ + ("---\na: &x 1\n---\n", 2, "anchor"), + ("---\na: 1\nb: *x\n---\n", 3, "alias"), + ("---\na: !tag 1\n---\n", 2, "tag"), + ("---\nb:\n <<: {a: 1}\n---\n", 3, "merge"), + ("---\na: 1\n...\nb: 2\n---\n", 3, "second YAML document"), + ("---\na: 1\n--- b\n---\n", 3, "second YAML document"), + ("---\na:\n\tb: 1\n---\n", 3, "tab"), + ("---\na: 1\na: 2\n---\n", 3, "twice"), + ("---\na: [1, [2]]\n---\n", 2, "inside a flow"), + ("---\na: \"open\n---\n", 2, "past its line"), + ] { + let (at, reason) = refused_at(text); + assert_eq!(at, line, "{text:?}: {reason}"); + assert!(reason.contains(why), "{text:?}: {reason}"); + } +} + +#[test] +fn a_line_past_the_cap_is_refused() { + let text = format!("---\na: {}\n---\n", "x".repeat(MAX_LINE)); + let (at, reason) = refused_at(&text); + assert_eq!(at, 2); + assert!(reason.contains("longer than"), "{reason}"); +} + +/// `a1:` holding `a2:` ... to `aN: x`: N maps nested. +fn nest(n: usize) -> String { + let mut text = "---\n".to_string(); + for i in 1..n { + text.push_str(&format!("{}a{i}:\n", " ".repeat(i - 1))); + } + text.push_str(&format!("{}a{n}: x\n---\n", " ".repeat(n - 1))); + text +} + +#[test] +fn nesting_stops_at_the_depth_cap() { + assert_eq!(MAX_DEPTH, 8); + assert!(front(&nest(MAX_DEPTH)).is_ok()); + let (at, reason) = refused_at(&nest(MAX_DEPTH + 1)); + // `a9` opens the ninth map, on the file's line 10. + assert_eq!(at, MAX_DEPTH + 2, "{reason}"); + assert!(reason.contains("deeper than 8"), "{reason}"); + // A flow collection is one level more. + let mut flow = nest(MAX_DEPTH); + flow = flow.replace(&format!("a{MAX_DEPTH}: x"), &format!("a{MAX_DEPTH}: [x]")); + assert!(refused_at(&flow).1.contains("deeper")); +} + +#[test] +fn a_block_scalars_lines_are_text_not_structure() { + let map = + front("---\ncode: |\n \tindented\n % not a directive\n ...\n --- x\nnext: y\n---\n") + .expect("read"); + assert_eq!( + map.value.get("code"), + Some(&s(2, "\tindented\n% not a directive\n...\n--- x\n")) + ); + assert_eq!(map.value.get("next"), Some(&s(7, "y"))); + // Outside a block the same lines are refused at their line. + assert_eq!(refused_at("---\na: 1\n% x\n---\n").0, 3); + assert_eq!(refused_at("---\na:\n\t- x\n---\n").0, 3); +} + +#[test] +fn double_quoted_escapes_are_decoded_or_refused() { + let map = front( + "---\nu: \"caf\\u00e9\"\nx: \"\\x41\\r\\0\"\nbig: \"\\U0001F600\"\nkept: \"a\\\\b \\\"q\\\" \\/\"\n---\n", + ) + .expect("read"); + assert_eq!(map.value.get("u"), Some(&s(2, "café"))); + assert_eq!(map.value.get("x"), Some(&s(3, "A\r\0"))); + assert_eq!(map.value.get("big"), Some(&s(4, "😀"))); + assert_eq!(map.value.get("kept"), Some(&s(5, "a\\b \"q\" /"))); + for (text, says) in [ + ("---\nv: \"C:\\path\"\n---\n", "an escape `\\p`"), + ("---\nv: \"\\u00\"\n---\n", "an escape `\\u`"), + ("---\nv: \"\\uD800\"\n---\n", "an escape `\\u`"), + ] { + let (at, reason) = refused_at(text); + assert_eq!(at, 2, "{text}"); + assert!(reason.contains(says), "{text}: {reason}"); + } +} + +#[test] +fn a_key_given_twice_is_found_in_linear_time() { + // 200,000 keys: a scan of the earlier keys per key is 2e10 comparisons; a set is well under a second. + let n = 200_000; + let mut text = "---\n".to_string(); + for k in 0..n { + text.push_str(&format!("k{k}: x\n")); + } + text.push_str("k7: again\n---\n"); + let started = std::time::Instant::now(); + let (at, reason) = refused_at(&text); + assert!( + started.elapsed() < std::time::Duration::from_secs(10), + "{:?}", + started.elapsed() + ); + assert_eq!( + (at, reason.as_str()), + (n + 2, "the key `k7` is given twice") + ); +} + +#[test] +fn an_empty_frontmatter_is_an_empty_map() { + let (front, start) = split("---\n---\nbody\n"); + let map = read(&front.expect("closed").expect("a frontmatter")).expect("read"); + assert_eq!((map.value, start), (Vec::new(), 2)); +} diff --git a/gsd/import/src/ids.rs b/gsd/import/src/ids.rs new file mode 100644 index 0000000000..5ca302dbe6 --- /dev/null +++ b/gsd/import/src/ids.rs @@ -0,0 +1,189 @@ +//! The ids the import writes (ADR 0391 D4, 13-RESEARCH Part B "Id rules"), each checked before it is used in an op or +//! a file path. Every check is over ASCII bytes: a space, a `/`, `..`, a control character or a non-ASCII digit fails. + +/// The grammar's `_name`, which the host's create takes as an id: runs of ASCII letters, digits and `_`, joined by +/// one `-` or `.` (`AUTH-01`, `02.1`, `v1.0`). +pub fn name(id: &str) -> bool { + let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_'; + let bytes = id.as_bytes(); + !bytes.is_empty() + && word(bytes[0]) + && word(bytes[bytes.len() - 1]) + && bytes + .windows(2) + .all(|w| word(w[0]) || (word(w[1]) && (w[0] == b'-' || w[0] == b'.'))) + && bytes.iter().all(|&b| word(b) || b == b'-' || b == b'.') +} + +fn digits(s: &str) -> bool { + !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) +} + +/// `<CAT>-<NN>`: an upper-case category, then a number (`TASK-01`, the minted `OOS-01`). +pub fn requirement(id: &str) -> bool { + id.split_once('-').is_some_and(|(cat, n)| { + cat.as_bytes().first().is_some_and(u8::is_ascii_uppercase) + && cat + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()) + && digits(n) + }) +} + +/// `D-<NN>`, two digits at least. +pub fn decision(id: &str) -> bool { + id.strip_prefix("D-") + .is_some_and(|n| n.len() >= 2 && digits(n)) +} + +/// `v<version>`: `v1`, `v1.0`, `v2.3.1`. +pub fn milestone(id: &str) -> bool { + id.strip_prefix('v') + .is_some_and(|v| v.split('.').all(digits)) +} + +/// A phase: its integer part on two digits at least (no leading zero past two), a decimal kept (`01`, `02.1`, `100`). +pub fn phase(id: &str) -> bool { + let (int, dec) = match id.split_once('.') { + Some((int, dec)) => (int, Some(dec)), + None => (id, None), + }; + digits(int) + && (int.len() == 2 || int.len() > 2 && !int.starts_with('0')) + && dec.is_none_or(digits) +} + +/// GSD's phase number with its integer part on two digits (`2` is `02`, `2.1` is `02.1`); none for anything else. +pub fn padded(number: &str) -> Option<String> { + let (int, dec) = match number.split_once('.') { + Some((int, dec)) => (int, Some(dec)), + None => (number, None), + }; + if !digits(int) || dec.is_some_and(|d| !digits(d)) { + return None; + } + Some(match dec { + Some(dec) => format!("{int:0>2}.{dec}"), + None => format!("{int:0>2}"), + }) +} + +/// A phase's plan `<NN>-<MM>` (`01-02`, `02.1-01`). +pub fn plan(id: &str) -> bool { + id.rsplit_once('-') + .is_some_and(|(p, m)| phase(p) && m.len() >= 2 && digits(m)) +} + +/// A quick plan's id: its date `YYMMDD`, `-`, then lower-case letters and digits (`261105-tcl`). +pub fn quick(id: &str) -> bool { + id.split_once('-').is_some_and(|(day, tail)| { + day.len() == 6 + && digits(day) + && !tail.is_empty() + && tail + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) + }) +} + +/// A minted id: `prefix` then a number from 1, with no leading zero (`T1`, `TR12`, `KL3`). +pub fn minted(prefix: &str, id: &str) -> bool { + id.strip_prefix(prefix) + .is_some_and(|n| digits(n) && !n.starts_with('0')) +} + +/// Whether `id` is an id the import may write for `kind`: the host's `_name` and the family of the kind. +pub fn valid(kind: &str, id: &str) -> bool { + let family = match kind { + "requirement" => requirement(id), + "decision" => decision(id), + "milestone" => milestone(id), + "phase" => phase(id), + "plan" => plan(id) || quick(id), + "task" => minted("T", id), + "truth" => minted("TR", id), + "artifact" => minted("AR", id), + "key_link" => minted("KL", id), + "uat_test" => minted("U", id), + "uat_gap" => minted("G", id), + "deferred_idea" => minted("DI", id), + "source" => minted("SRC", id), + "finding" => minted("F", id), + "stack_choice" => minted("SC", id), + "pattern" => minted("P", id), + "pitfall" => minted("PF", id), + "dont_hand_roll" => minted("DH", id), + "open_question" => minted("OQ", id), + "trust_boundary" => minted("TB", id), + "audit_run" => minted("AU", id), + "accepted_risk" => minted("AR", id), + // File stems (`01-01-SUMMARY`), coverage ids (`D1`), threat ids (`T-01-SC`): the grammar alone. + _ => true, + }; + name(id) && family +} + +/// Whether `file` is a path the import may write: `spec/gsd/`, then names joined by `/`, then `.spec`. +pub fn file(file: &str) -> bool { + file.strip_prefix("spec/gsd/") + .and_then(|rest| rest.strip_suffix(".spec")) + .is_some_and(|rest| rest.split('/').all(name)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_name_is_the_grammars() { + for ok in ["TASK-01", "02.1", "v1.0", "01-01-SUMMARY", "T_1"] { + assert!(name(ok), "{ok}"); + } + for bad in [ + "", + "TASK 01", + "A/B-01", + "..", + "a..b", + "-a", + "a-", + "a.", + "T\u{7}-01", + "TASK-\u{661}", + "é", + "a--b", + ] { + assert!(!name(bad), "{bad:?}"); + } + } + + #[test] + fn each_family_has_its_shape() { + assert!(valid("requirement", "TASK-01") && valid("requirement", "OOS-01")); + assert!(!valid("requirement", "task-01") && !valid("requirement", "TASK-")); + assert!(valid("decision", "D-01") && !valid("decision", "D-1")); + assert!(valid("milestone", "v1.0") && !valid("milestone", "v1..0")); + assert!(valid("phase", "01") && valid("phase", "02.1") && valid("phase", "100")); + assert!(!valid("phase", "1") && !valid("phase", "001")); + assert!(valid("plan", "01-02") && valid("plan", "02.1-01") && valid("plan", "261105-tcl")); + assert!(!valid("plan", "01-2") && !valid("plan", "1-02")); + assert!(valid("task", "T1") && !valid("task", "T01") && !valid("task", "TR1")); + assert!(valid("truth", "TR1") && valid("key_link", "KL3")); + assert!(valid("summary", "01-01-SUMMARY") && !valid("summary", "01 SUMMARY")); + } + + #[test] + fn a_file_is_built_from_names_under_spec_gsd() { + assert!(file("spec/gsd/requirements.spec")); + assert!(file("spec/gsd/phases/01.spec")); + for bad in [ + "spec/requirements.spec", + "spec/gsd/../x.spec", + "spec/gsd/a b.spec", + "spec/gsd/req.txt", + "spec/gsd//x.spec", + ] { + assert!(!file(bad), "{bad}"); + } + } +} diff --git a/gsd/import/src/kinds.rs b/gsd/import/src/kinds.rs new file mode 100644 index 0000000000..9b7956e538 --- /dev/null +++ b/gsd/import/src/kinds.rs @@ -0,0 +1,238 @@ +//! `@gsd/core`'s kind names, which the re-import refusal looks for (ADR 0391 D10). A test holds the list equal to what +//! `@gsd/core` declares; the crate does not depend on `gsd-core` (D12). + +/// Every kind `@gsd/core` declares, sorted. +pub const CORE_KINDS: &[&str] = &[ + "artifact", + "blocker", + "broken_window", + "checkpoint", + "commit", + "context", + "decision", + "deferred_idea", + "deliverable", + "deviation", + "discussion", + "disposition", + "dont_hand_roll", + "edge", + "finding", + "handoff", + "human_item", + "interview", + "key_link", + "lesson", + "locked_req", + "manual_check", + "methodology", + "milestone", + "milestone_audit", + "open_question", + "override", + "package_audit", + "pattern", + "pause", + "phase", + "phase_spec", + "pitfall", + "plan", + "plan_start", + "prohibition", + "project", + "quick_batch", + "refactor_proposal", + "requirement", + "research", + "retrospective", + "review", + "review_concern", + "revision_conflict", + "source", + "spec_prohibition", + "stack_choice", + "summary", + "task", + "truth", + "uat_gap", + "uat_session", + "uat_test", + "user_setup", + "validation", + "validation_row", + "verification", + "verify_gap", + "wave0_item", + "workstream", +]; + +/// The order the plan creates kinds in, so an entity is created before one that names it; a kind not listed comes +/// after these, by name. +pub const CREATE_ORDER: &[&str] = &[ + "milestone", + "requirement", + "project", + "decision", + "phase", + "plan", + "task", + "truth", + "artifact", + "key_link", + "summary", + "deliverable", + "context", + "discussion", + "deferred_idea", + "research", + "source", + "finding", + "stack_choice", + "pattern", + "pitfall", + "dont_hand_roll", + "open_question", + "uat_session", + "uat_test", + "uat_gap", + "verification", + "verify_gap", + "human_item", + "security_audit", + "trust_boundary", + "threat", + "accepted_risk", + "audit_run", +]; + +/// Each `@gsd/core` and `@gsd/security` kind's required fields that an author writes (neither computed nor harness), +/// in declaration order; a kind with none is not listed. A test holds it equal to both declarations. A record missing +/// one is dropped before the plan is built (ADR 0391 D9): the host would refuse the whole plan for it. +#[rustfmt::skip] +pub const REQUIRED: &[(&str, &[&str])] = &[ + ("project", &["name", "what", "core_value", "context", "constraints"]), + ("requirement", &["text", "category", "tier"]), + ("phase", &["milestone", "slug", "goal", "success_criteria"]), + ("workstream", &["purpose"]), + ("retrospective", &["milestone"]), + ("lesson", &["text"]), + ("methodology", &["name"]), + ("context", &["boundary"]), + ("decision", &["text", "origin"]), + ("deferred_idea", &["text", "phase", "origin"]), + ("phase_spec", &["phase", "goal"]), + ("locked_req", &["spec", "title", "current", "target", "acceptance"]), + ("interview", &["spec", "round", "perspective", "question"]), + ("edge", &["spec", "requirement", "category", "status"]), + ("spec_prohibition", &["spec", "requirement", "statement", "status"]), + ("discussion", &["phase"]), + ("research", &["confidence", "summary"]), + ("finding", &["research", "text", "confidence"]), + ("stack_choice", &["research", "name", "purpose"]), + ("pattern", &["research", "name", "what"]), + ("pitfall", &["research", "name", "goes_wrong", "why", "avoid"]), + ("dont_hand_roll", &["research", "problem", "instead", "why"]), + ("open_question", &["research", "question", "unclear"]), + ("source", &["research", "url", "tier"]), + ("package_audit", &["research", "package", "registry"]), + ("plan", &["type", "files_modified", "objective"]), + ("task", &["plan", "type", "action", "done"]), + ("checkpoint", &["plan", "kind", "resume_signal"]), + ("truth", &["plan", "text"]), + ("artifact", &["plan", "path", "provides"]), + ("key_link", &["plan", "from", "to", "via"]), + ("prohibition", &["plan", "statement", "verification"]), + ("disposition", &["plan", "round", "feedback", "outcome"]), + ("review", &["phase", "plans"]), + ("review_concern", &["review", "severity", "text"]), + ("revision_conflict", &["phase", "plan", "dimension", "property", "conflicts_with"]), + ("user_setup", &["plan", "service", "why"]), + ("plan_start", &["plan"]), + ("summary", &["plan", "status", "one_liner", "subsystem", "requirements_completed"]), + ("deliverable", &["summary", "description", "human_judgment"]), + ("deviation", &["summary", "kind", "text"]), + ("pause", &["reason"]), + ("handoff", &["state", "current_state", "next_action"]), + ("blocker", &["text"]), + ("quick_batch", &["items"]), + ("verification", &["phase"]), + ("verify_gap", &["verification", "truth", "reason"]), + ("override", &["verification", "truth", "reason"]), + ("human_item", &["verification", "test", "expected", "why_human"]), + ("uat_session", &["phase", "source"]), + ("uat_test", &["session", "expected"]), + ("uat_gap", &["test", "truth"]), + ("validation", &["phase"]), + ("validation_row", &["validation", "task", "test_type"]), + ("wave0_item", &["validation", "path", "kind"]), + ("manual_check", &["validation", "behavior", "why_manual", "instructions"]), + ("milestone_audit", &["milestone"]), + ("broken_window", &["kind", "phase", "description"]), + ("refactor_proposal", &["phase", "target_file", "target_function"]), + // @gsd/security + ("trust_boundary", &["plan", "boundary", "description"]), + ("threat", &["plan", "category", "component", "severity", "disposition", "mitigation"]), + ("security_audit", &["phase"]), + ("accepted_risk", &["audit", "threat", "rationale", "accepted_by"]), + ("audit_run", &["audit"]), +]; + +/// Each `@gsd/core` and `@gsd/security` block field's required, author-written members, as `(kind, block, members)` in +/// declaration order. A test holds it equal to both declarations. A record writing a block item without one is dropped +/// before the plan is built: the host would refuse the whole plan for it (E006 on a member). +#[rustfmt::skip] +pub const REQUIRED_MEMBERS: &[(&str, &str, &[&str])] = &[ + ("project", "out_of_scope", &["why"]), + ("milestone", "abandoned", &["reason", "ruled_by", "at"]), + ("plan", "coupling_justified", &["peer", "reason"]), + ("task", "reversibility", &["rating"]), + ("task", "verify", &["automated"]), + ("checkpoint", "options", &["name"]), + ("review", "reviewers", &["name", "model", "source"]), + ("review", "lanes", &["reviewer", "summary"]), + ("review", "coverage", &["reviewer"]), + ("review", "unchecked", &["symbol", "why"]), + ("user_setup", "env_vars", &["name"]), + ("summary", "requires", &["phase", "provides"]), + ("deliverable", "checks", &["kind", "ref"]), + ("verification", "deferred", &["truth", "addressed_in", "evidence"]), + ("milestone_audit", "tech_debt", &["item"]), + ("milestone_audit", "debt_accepted", &["by", "at"]), +]; + +/// Each `(kind, field)` reference list that must keep an item: a record none of whose `field` items is imported (it +/// names none, or each one it names is dropped) is dropped and reported, and its children with it. A UAT session tests +/// summaries: with none it is no session. A reader writes the list it read, empty or not; `emit` alone holds the rule. +pub const NON_EMPTY: &[(&str, &str)] = &[("uat_session", "source")]; + +/// The reference lists of `kind` that must keep an item ([`NON_EMPTY`]). +pub fn non_empty(kind: &str) -> impl Iterator<Item = &'static str> + '_ { + NON_EMPTY + .iter() + .filter(move |(k, _)| *k == kind) + .map(|(_, field)| *field) +} + +/// The required, author-written members of the block field `block` of `kind` ([`REQUIRED_MEMBERS`]). +pub fn required_members(kind: &str, block: &str) -> &'static [&'static str] { + REQUIRED_MEMBERS + .iter() + .find(|(k, b, _)| *k == kind && *b == block) + .map_or(&[], |(_, _, members)| members) +} + +/// The required, author-written fields of `kind` ([`REQUIRED`]); none for a kind not listed. +pub fn required(kind: &str) -> &'static [&'static str] { + REQUIRED + .iter() + .find(|(k, _)| *k == kind) + .map_or(&[], |(_, fields)| fields) +} + +/// Where `kind` stands in [`CREATE_ORDER`]. +pub fn rank(kind: &str) -> usize { + CREATE_ORDER + .iter() + .position(|k| *k == kind) + .unwrap_or(CREATE_ORDER.len()) +} diff --git a/gsd/import/src/lib.rs b/gsd/import/src/lib.rs new file mode 100644 index 0000000000..4a22e4eff6 --- /dev/null +++ b/gsd/import/src/lib.rs @@ -0,0 +1,55 @@ +//! `@gsd/import`: `specforge gsd import` reads a GSD project's `.planning/` folder once and answers one edit plan +//! that writes `spec/gsd/`, plus a report naming every file it did not map, with a reason (ADR 0391). + +pub mod command; +pub mod emit; +pub mod frontmatter; +pub mod ids; +pub mod kinds; +pub mod limits; +pub mod owed; +pub mod paths; +pub mod preflight; +pub mod read; +pub mod records; +pub mod report; +pub mod sections; +pub mod settings; +pub mod table; +pub mod xmltags; + +use specforge_extension_sdk::prelude::*; + +/// The gsd-core release this crate tracks; `[package.metadata.gsd] tracks` in `Cargo.toml` says the same. +pub const TRACKS: &str = concat!("gsd-core@", gsd_kit::tracked_version!()); + +/// The `@gsd/core` releases this extension writes for: the range `@gsd/security` declares. +pub const CORE_RANGE: &str = "^1.1.0"; + +/// The `@gsd/security` releases whose kinds a threat model maps to when the project loads it (ADR 0391 D11). +pub const SECURITY_RANGE: &str = "^1.0.0"; + +#[specforge_extension_sdk::extension( + name = "@gsd/import", + short = "gsd", + description = "Import a GSD project: its .planning/ folder, read once, into one edit plan that writes spec/gsd/" +)] +struct GsdImport; + +impl Contributions for GsdImport { + fn contribute(c: &mut ContributionsBuilder) { + c.meta.keywords.push(format!("tracks:{TRACKS}")); + c.peer("@gsd/core", CORE_RANGE); + c.optional_peer("@gsd/security", SECURITY_RANGE); + command::declare(c); + } +} + +/// The extension's contributions, as its guest builds them per call (tests serve the same declaration). +pub fn build() -> ContributionsBuilder { + specforge_extension_build() +} + +// Only the component exports `call`: a native test binary links `@gsd/core` too, whose guest exports the same symbol. +#[cfg(target_arch = "wasm32")] +specforge_extension_sdk::component_guest!(build = build); diff --git a/gsd/import/src/limits.rs b/gsd/import/src/limits.rs new file mode 100644 index 0000000000..cea85da2dd --- /dev/null +++ b/gsd/import/src/limits.rs @@ -0,0 +1,8 @@ +//! The import's caps (ADR 0391 D9): past either, the plan is refused "truncated at N", never answered in part. + +/// The most operations one plan holds: 13-02 measured one plan of 2,000 creates applying in about 38 s, and the host's +/// apply cost grows about quadratically (5,000 took 218 s). +pub const MAX_OPS: usize = 2_000; + +/// The most report entries: ten per operation, room for every file, section and row of a folder at the op cap. +pub const MAX_ENTRIES: usize = 10 * MAX_OPS; diff --git a/gsd/import/src/owed.rs b/gsd/import/src/owed.rs new file mode 100644 index 0000000000..b0673ed65c --- /dev/null +++ b/gsd/import/src/owed.rs @@ -0,0 +1,379 @@ +//! The verdicts an import owes (ADR 0391 D5): `.planning/` records results, never a verdict, so every imported entity a +//! judged rule judges is listed with the commands that record its verdict. The targets mirror the rules' own: +//! +//! - `gsd/E501` (`gsd/core/src/judged.rs`): each truth, artifact and key link without a `pattern` of a complete plan, +//! and a plan is complete when its summary's `status` is `complete` (`passes::derive::execute::plan_statuses`); +//! - `gsd/W525`: each prohibition without a `test` of a complete plan; +//! - `gsd/W311`, `W313`, `W315`, `W316`, the plan checks: each plan that is not complete; +//! - `gsd/E518`, `gsd/E202`, `gsd/W203`, `gsd/W205`: each milestone audit, phase spec, locked requirement and package +//! audit, owed from its creation; +//! - `gsd.security/W302`: each threat whose `status` is `closed` (`complete_when status closed`); +//! - `gsd.security/W303`: each security audit, owed from its creation. +//! +//! 13-10 holds this prediction equal to what `specforge check` reports on the imported fixtures. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; + +use crate::paths; +use crate::records::Record; +use crate::settings::shell_quote; + +pub const E501: &str = "gsd/E501"; +pub const W525: &str = "gsd/W525"; +pub const E518: &str = "gsd/E518"; +pub const E202: &str = "gsd/E202"; +pub const W203: &str = "gsd/W203"; +pub const W205: &str = "gsd/W205"; +/// The plan checks, owed while a plan is open (no complete summary). +pub const PLAN_CHECKS: [&str; 4] = ["gsd/W311", "gsd/W313", "gsd/W315", "gsd/W316"]; +pub const W302: &str = "gsd.security/W302"; +pub const W303: &str = "gsd.security/W303"; + +/// One verdict owed: on `entity` (its graph path), by the rule `code`, in the phase `phase` (none for a quick plan's). +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct Owed { + pub phase: Option<String>, + pub code: &'static str, + pub entity: String, +} + +impl Owed { + /// `{"code", "entity", "phase"}`. + pub fn json(&self) -> Value { + json!({ "code": self.code, "entity": self.entity, "phase": self.phase }) + } +} + +/// The verdicts `kept`, the records the plan creates, owe, sorted by phase, code and entity. +pub fn owed<'r>(kept: impl IntoIterator<Item = &'r Record> + Clone) -> Vec<Owed> { + let text = |r: &Record, field: &str| { + r.fields + .get(field) + .and_then(Value::as_str) + .map(str::to_string) + }; + let complete: BTreeSet<String> = kept + .clone() + .into_iter() + .filter(|r| r.kind == "summary" && text(r, "status").as_deref() == Some("complete")) + .filter_map(|r| text(r, "plan")) + .collect(); + let plan_done = |r: &Record| text(r, "plan").is_some_and(|p| complete.contains(&p)); + let mut out: Vec<Owed> = kept + .into_iter() + .flat_map(|r| { + let codes: &[&'static str] = match r.kind { + "truth" | "artifact" if plan_done(r) => &[E501], + "key_link" if plan_done(r) && !r.fields.contains_key("pattern") => &[E501], + "prohibition" if plan_done(r) && !r.fields.contains_key("test") => &[W525], + "plan" if !complete.contains(&r.id) => &PLAN_CHECKS, + "milestone_audit" => &[E518], + "phase_spec" => &[E202], + "locked_req" => &[W203], + "package_audit" => &[W205], + "threat" if text(r, "status").as_deref() == Some("closed") => &[W302], + "security_audit" => &[W303], + _ => &[], + }; + let phase = r + .file + .strip_prefix(&format!("{}/phases/", paths::ROOT)) + .and_then(|f| f.strip_suffix(".spec")) + .map(str::to_string); + codes.iter().map(move |&code| Owed { + phase: phase.clone(), + code, + entity: r.id.clone(), + }) + }) + .collect(); + out.sort(); + out +} + +/// The slash command that records a verdict of `code`: the workflow that runs its judge. +fn command(code: &str) -> &'static str { + match code { + E501 | W525 => "/gsd-verify-work", + E518 => "/gsd-audit-milestone", + E202 | W203 => "/gsd-spec-phase", + W302 | W303 => "/gsd-secure-phase", + // The plan checks and the package audit: the plan checker and the phase researcher. + _ => "/gsd-plan-phase", + } +} + +/// The report's owed lines for `owed`: per phase and slash command that records its verdicts ([`command`]), then per +/// entity the query that shows what its judge reads, then the count; `check` exits 1 while an error rule is owed. +pub fn lines(owed: &[Owed]) -> Vec<String> { + let mut sorted: Vec<(&str, &Owed)> = owed.iter().map(|o| (command(o.code), o)).collect(); + sorted.sort_by(|(a, x), (b, y)| (&x.phase, a, *x).cmp(&(&y.phase, b, *y))); + let mut out = Vec::new(); + let mut group = None; + for (command, o) in sorted { + if group != Some((&o.phase, command)) { + group = Some((&o.phase, command)); + out.push(match &o.phase { + Some(phase) => format!("{command} {phase}"), + None if command == "/gsd-verify-work" => { + "quick plans (no phase): ask the verifier to judge each".to_string() + } + // `/gsd-plan-phase` names a phase, and none plans a quick plan. + None if command == "/gsd-plan-phase" => { + "quick plans (no phase): ask the plan checker to judge each".to_string() + } + // A milestone audit: its command names no phase. + None => command.to_string(), + }); + } + out.push(format!( + " specforge query {} --inputs {} --format json", + shell_quote(&o.entity), + o.code + )); + } + if !owed.is_empty() { + let check = if owed.iter().any(|o| { + o.code + .rsplit('/') + .next() + .is_some_and(|c| c.starts_with('E')) + }) { + "exits 1" + } else { + "warns" + }; + out.push(format!( + "{} verdicts owed: `specforge check` {check} until these verdicts are recorded", + owed.len() + )); + } + out +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use super::*; + use crate::records::Source; + + fn record(kind: &'static str, id: &str, file: &str, fields: Value) -> Record { + Record { + kind, + id: id.to_string(), + title: String::new(), + file: file.to_string(), + fields: serde_json::from_value::<BTreeMap<String, Value>>(fields).unwrap_or_default(), + refs: Vec::new(), + links: Vec::new(), + source: Source { + file: String::new(), + line: 1, + }, + } + } + + #[test] + fn owed_mirrors_each_rules_targets() { + let phase = "spec/gsd/phases/01.spec"; + let records = [ + record( + "summary", + "v1.0/01/01-01/01-01-SUMMARY", + phase, + json!({"plan": "v1.0/01/01-01", "status": "complete"}), + ), + record( + "summary", + "v1.0/01/01-02/01-02-SUMMARY", + phase, + json!({"plan": "v1.0/01/01-02", "status": "halted"}), + ), + record( + "truth", + "v1.0/01/01-01/TR1", + phase, + json!({"plan": "v1.0/01/01-01"}), + ), + record( + "artifact", + "v1.0/01/01-01/AR1", + phase, + json!({"plan": "v1.0/01/01-01"}), + ), + record( + "key_link", + "v1.0/01/01-01/KL1", + phase, + json!({"plan": "v1.0/01/01-01"}), + ), + record( + "key_link", + "v1.0/01/01-01/KL2", + phase, + json!({"plan": "v1.0/01/01-01", "pattern": "x"}), + ), + record( + "truth", + "v1.0/01/01-02/TR1", + phase, + json!({"plan": "v1.0/01/01-02"}), + ), + record( + "threat", + "v1.0/01/01-01/T-01-01", + phase, + json!({"status": "closed"}), + ), + record( + "threat", + "v1.0/01/01-02/T-01-02", + phase, + json!({"status": "open"}), + ), + record("security_audit", "v1.0/01/01-SECURITY", phase, json!({})), + record( + "summary", + "261105-tcl/261105-tcl-SUMMARY", + "spec/gsd/quick.spec", + json!({"plan": "261105-tcl", "status": "complete"}), + ), + record( + "truth", + "261105-tcl/TR1", + "spec/gsd/quick.spec", + json!({"plan": "261105-tcl"}), + ), + ]; + let owed = owed(&records); + let found: Vec<(Option<&str>, &str, &str)> = owed + .iter() + .map(|o| (o.phase.as_deref(), o.code, o.entity.as_str())) + .collect(); + assert_eq!( + found, + // Codes sort as text: `gsd.security/` before `gsd/`. + [ + (None, E501, "261105-tcl/TR1"), + (Some("01"), W302, "v1.0/01/01-01/T-01-01"), + (Some("01"), W303, "v1.0/01/01-SECURITY"), + (Some("01"), E501, "v1.0/01/01-01/AR1"), + (Some("01"), E501, "v1.0/01/01-01/KL1"), + (Some("01"), E501, "v1.0/01/01-01/TR1"), + ] + ); + assert_eq!( + lines(&owed), + [ + "quick plans (no phase): ask the verifier to judge each", + " specforge query '261105-tcl/TR1' --inputs gsd/E501 --format json", + "/gsd-secure-phase 01", + " specforge query 'v1.0/01/01-01/T-01-01' --inputs gsd.security/W302 --format json", + " specforge query 'v1.0/01/01-SECURITY' --inputs gsd.security/W303 --format json", + "/gsd-verify-work 01", + " specforge query 'v1.0/01/01-01/AR1' --inputs gsd/E501 --format json", + " specforge query 'v1.0/01/01-01/KL1' --inputs gsd/E501 --format json", + " specforge query 'v1.0/01/01-01/TR1' --inputs gsd/E501 --format json", + "6 verdicts owed: `specforge check` exits 1 until these verdicts are recorded", + ] + ); + assert_eq!( + lines(&owed[1..3]).last().map(String::as_str), + Some("2 verdicts owed: `specforge check` warns until these verdicts are recorded") + ); + } + + /// Core's other judged rules: the plan checks on an open plan, W525 on a complete plan's untested prohibition, and + /// the rules owed from creation. + #[test] + fn owed_mirrors_cores_other_judged_rules() { + let phase = "spec/gsd/phases/01.spec"; + let plan = |id: &str| record("plan", id, phase, json!({})); + let records = [ + record( + "summary", + "v1.0/01/01-01/01-01-SUMMARY", + phase, + json!({"plan": "v1.0/01/01-01", "status": "complete"}), + ), + plan("v1.0/01/01-01"), + plan("v1.0/01/01-02"), + record( + "prohibition", + "v1.0/01/01-01/P1", + phase, + json!({"plan": "v1.0/01/01-01"}), + ), + record( + "prohibition", + "v1.0/01/01-01/P2", + phase, + json!({"plan": "v1.0/01/01-01", "test": "t"}), + ), + record( + "prohibition", + "v1.0/01/01-02/P1", + phase, + json!({"plan": "v1.0/01/01-02"}), + ), + record("phase_spec", "v1.0/01/01-SPEC", phase, json!({})), + record("package_audit", "v1.0/01/01-RESEARCH/PA1", phase, json!({})), + record( + "milestone_audit", + "v1.0-MILESTONE-AUDIT", + "spec/gsd/milestones.spec", + json!({}), + ), + ]; + let owed = owed(&records); + let found: Vec<(&str, &str)> = owed.iter().map(|o| (o.code, o.entity.as_str())).collect(); + assert_eq!( + found, + [ + (E518, "v1.0-MILESTONE-AUDIT"), + (E202, "v1.0/01/01-SPEC"), + (W205, "v1.0/01/01-RESEARCH/PA1"), + ("gsd/W311", "v1.0/01/01-02"), + ("gsd/W313", "v1.0/01/01-02"), + ("gsd/W315", "v1.0/01/01-02"), + ("gsd/W316", "v1.0/01/01-02"), + (W525, "v1.0/01/01-01/P1"), + ] + ); + let lines = lines(&owed); + let headers: Vec<&str> = lines + .iter() + .filter(|l| !l.starts_with(' ')) + .map(String::as_str) + .collect(); + assert_eq!( + headers, + [ + "/gsd-audit-milestone", + "/gsd-plan-phase 01", + "/gsd-spec-phase 01", + "/gsd-verify-work 01", + "8 verdicts owed: `specforge check` exits 1 until these verdicts are recorded", + ] + ); + } + + #[test] + fn an_open_quick_plans_checks_name_no_bare_plan_phase() { + let records = [record( + "plan", + "261105-tcl", + "spec/gsd/quick.spec", + json!({}), + )]; + let lines = lines(&owed(&records)); + assert_eq!( + lines[0], + "quick plans (no phase): ask the plan checker to judge each" + ); + assert!(!lines.iter().any(|l| l == "/gsd-plan-phase"), "{lines:#?}"); + } +} diff --git a/gsd/import/src/paths.rs b/gsd/import/src/paths.rs new file mode 100644 index 0000000000..4fdeae8780 --- /dev/null +++ b/gsd/import/src/paths.rs @@ -0,0 +1,59 @@ +//! The `spec/gsd/` file of each record (ADR 0391 D4): `project.spec` (the project and its decisions), +//! `requirements.spec`, `<milestone>.spec` (a milestone and its phases), `phases/<phase>.spec` (everything scoped under +//! one phase) and `quick.spec` (quick plans and their summaries). +//! +//! A name is built from ids the readers validated; `emit` refuses any record whose file `ids::file` does not take, so a +//! `/`, a space or `..` from a document never becomes a path. + +/// The folder every imported entity is written under. +pub const ROOT: &str = "spec/gsd"; + +pub fn project() -> String { + format!("{ROOT}/project.spec") +} + +pub fn requirements() -> String { + format!("{ROOT}/requirements.spec") +} + +/// The file of the milestone `id` and its phases. +pub fn milestone(id: &str) -> String { + format!("{ROOT}/{id}.spec") +} + +/// The file of everything scoped under the phase `id`. +pub fn phase(id: &str) -> String { + format!("{ROOT}/phases/{id}.spec") +} + +pub fn quick() -> String { + format!("{ROOT}/quick.spec") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ids; + + #[test] + fn each_record_has_its_file() { + assert_eq!(phase("02.1"), "spec/gsd/phases/02.1.spec"); + assert_eq!(milestone("v1.0"), "spec/gsd/v1.0.spec"); + for file in [ + project(), + requirements(), + milestone("v1.0"), + phase("02.1"), + quick(), + ] { + assert!(ids::file(&file), "{file}"); + } + } + + #[test] + fn a_name_no_id_takes_makes_no_file_emit_writes() { + for bad in [phase(".."), phase("a b"), milestone("../x"), phase("")] { + assert!(!ids::file(&bad), "{bad}"); + } + } +} diff --git a/gsd/import/src/preflight.rs b/gsd/import/src/preflight.rs new file mode 100644 index 0000000000..d6cf4a8e09 --- /dev/null +++ b/gsd/import/src/preflight.rs @@ -0,0 +1,196 @@ +//! What the import refuses before it reads a line (ADR 0391 D4, D9, D10): a project that already holds `@gsd/core` +//! entities, a spec root other than `spec`, no `.planning/`, and a host read that stopped early or failed on a file +//! that maps to entities. + +use serde_json::Value; +use specforge_extension_sdk::prelude::*; + +use crate::kinds::CORE_KINDS; +use crate::read::Served; +use crate::table; + +/// What `specforge.json` says that the import needs, read as text (D11: not a registry query). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Manifest { + /// `extensions` lists `@gsd/security`. + pub security: bool, + /// The extensions it lists, each by the name its text gives ([`entry_name`]). + pub loaded: Vec<String>, +} + +/// The manifest the `manifest` read served; refused when it is missing, not JSON, or names a spec root other than +/// `spec` (D4: the twins and the fixtures use `spec`, and the spec root is no input a command is given). An absent +/// spec root and `.` both mean the project root to the host (`ProjectConfig::sources`), which holds `spec/gsd/`: both +/// are accepted. +pub fn manifest(served: &[Served]) -> Result<Manifest, String> { + let file = served + .iter() + .find(|f| f.path == "specforge.json") + .ok_or("specforge.json was not read: the import needs the project's manifest")?; + let text = file.text.as_deref().ok_or_else(|| { + format!( + "specforge.json was not read ({})", + file.error.as_deref().unwrap_or("no text") + ) + })?; + let json: Value = + serde_json::from_str(text).map_err(|e| format!("specforge.json is not JSON: {e}"))?; + match json.get("spec_root") { + None => {} + Some(Value::String(root)) if root == "spec" || root == "." => {} + Some(Value::String(root)) => { + return Err(format!( + "specforge.json names the spec root '{}': the import writes spec/gsd/ and needs the spec root 'spec'", + crate::report::escape(root) + )); + } + Some(other) => { + return Err(format!( + "specforge.json: spec_root is not a string: {other}" + )); + } + } + let loaded: Vec<String> = json + .get("extensions") + .and_then(Value::as_array) + .map(|list| { + list.iter() + .filter_map(Value::as_str) + .filter_map(entry_name) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(); + Ok(Manifest { + security: loaded.iter().any(|name| name == "@gsd/security"), + loaded, + }) +} + +/// The extension one `extensions` entry names by its text, read as the host's `ExtensionEntry::parse` reads it (the +/// guest cannot depend on the host crate): trimmed; an entry ending `.wasm` is a file, named by the text before `=` +/// (which the load holds equal to the component's name) and by nothing when bare; any other is `name` or the legacy +/// `name@requirement` (`split_requirement`: the text before the last `@` but a leading one). +fn entry_name(entry: &str) -> Option<&str> { + let entry = entry.trim(); + if entry.ends_with(".wasm") { + return entry.split_once('=').map(|(name, _)| name.trim()); + } + match entry.rfind('@') { + Some(at) if at > 0 => Some(&entry[..at]), + _ => Some(entry), + } +} + +/// Refuses a graph that holds any `@gsd/core` entity (D10), naming the first by id: its kind, path and file. +pub fn refuse_reimport(graph: &CommandGraph) -> Result<(), String> { + match graph + .nodes() + .iter() + .find(|node| CORE_KINDS.contains(&node.kind.as_str())) + { + None => Ok(()), + Some(node) => Err(format!( + "the project already holds @gsd/core entities, such as {} {} in {}: an import starts from none; delete them (by default spec/gsd/) and run the import again", + node.kind, + node.id, + node.file.as_deref().unwrap_or("an unknown file") + )), + } +} + +/// Refuses a `.planning/` read the import cannot trust whole (D9): none at all, one that stopped early, or one that +/// failed on a file that maps to entities (a `SECURITY.md` only when the project loads `@gsd/security`, `security`). +/// A failed read of any other file is the reader's to report. +pub fn check_reads(planning: &[Served], truncated: bool, security: bool) -> Result<(), String> { + if truncated { + return Err(format!( + "truncated at {FILE_READ_MAX}: the host's read of .planning/ stopped early (more than {FILE_READ_MAX} files, or a walk past {GLOB_VISITS_MAX} entries); nothing is imported" + )); + } + if planning.is_empty() { + return Err("no .planning/ at the project root".to_string()); + } + for file in planning { + let rel = file.path.strip_prefix(".planning/").unwrap_or(&file.path); + if let (Some(error), true) = (&file.error, table::maps(rel, security)) { + return Err(format!( + "{} was not read ({error}): its entities would be missing, so nothing is imported", + crate::report::escape(&file.path) + )); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_entry_is_named_as_the_host_names_it() { + for (entry, name) in [ + ("@gsd/security", Some("@gsd/security")), + ("@gsd/security@^1.0", Some("@gsd/security")), + ("@gsd/security@1.0.0", Some("@gsd/security")), + (" @gsd/security ", Some("@gsd/security")), + ("@gsd/security = ../s.wasm", Some("@gsd/security")), + ("../s.wasm", None), + // `=` splits a `.wasm` entry only: `x=y` names the extension `x=y`. + ("x=y", Some("x=y")), + ("plain", Some("plain")), + ] { + assert_eq!(entry_name(entry), name, "{entry:?}"); + } + } + + fn read(text: &str) -> Result<Manifest, String> { + manifest(&[Served { + path: "specforge.json".to_string(), + text: Some(text.to_string()), + error: None, + }]) + } + + #[test] + fn a_legacy_or_padded_entry_loads_security() { + let text = r#"{"extensions": ["@gsd/core@^1.1", " @gsd/security@^1.0 "]}"#; + let manifest = read(text).expect("a manifest"); + assert!(manifest.security); + assert_eq!(manifest.loaded, ["@gsd/core", "@gsd/security"]); + } + + #[test] + fn a_security_read_error_refuses_only_when_security_is_loaded() { + let failed = |path: &str| Served { + path: path.to_string(), + text: None, + error: Some("too_large".to_string()), + }; + let security = [failed(".planning/phases/01-core/01-SECURITY.md")]; + assert!(check_reads(&security, false, false).is_ok()); + let why = check_reads(&security, false, true).expect_err("refused"); + assert!( + why.contains("01-SECURITY.md was not read (too_large)"), + "{why}" + ); + // A plan maps whatever the manifest says. + let plan = [failed(".planning/phases/01-core/01-01-PLAN.md")]; + assert!(check_reads(&plan, false, false).is_err()); + } + + #[test] + fn a_spec_root_holding_spec_gsd_is_accepted_and_any_other_refused() { + // Absent and `.` are the project root to the host, which holds spec/gsd/ as `spec` does. + for text in ["{}", r#"{"spec_root": "spec"}"#, r#"{"spec_root": "."}"#] { + assert!(read(text).is_ok(), "{text}"); + } + for (text, says) in [ + (r#"{"spec_root": "specs"}"#, "the spec root 'specs'"), + (r#"{"spec_root": 1}"#, "spec_root is not a string"), + ] { + let why = read(text).expect_err("refused"); + assert!(why.contains(says), "{text}: {why}"); + } + } +} diff --git a/gsd/import/src/read/context.rs b/gsd/import/src/read/context.rs new file mode 100644 index 0000000000..3c65f6345d --- /dev/null +++ b/gsd/import/src/read/context.rs @@ -0,0 +1,388 @@ +//! `NN-CONTEXT.md` to a `context`, its phase's decisions and its deferred ideas (13-RESEARCH Part B, the CONTEXT table; +//! the rows are `table::sections::CONTEXT`): the file stem is the context's id, its sections its fields, each +//! `- **D-NN:** text` under a `### <Area>` of `## Implementation Decisions` a `decision D-NN` and each `## Deferred Ideas` +//! bullet a `deferred_idea DI<n>`, all scoped by the phase. Values are kept as written (trimmed). + +use std::collections::BTreeMap; +use std::ops::Range; + +use gsd_kit::markdown::{self, InlineBlock}; +use serde_json::{Value, json}; + +use super::{ + Context, PhaseFile, Rest, blocks_in, bullets_in, is_bold_only, is_date, is_footer, is_tag, + mapped, own, phase_file, prose, +}; +use crate::ids; +use crate::records::Records; +use crate::report::Report; +use crate::sections::{self, Section}; + +/// The fate table's name of a phase context. +pub const CX: &str = "NN-CONTEXT.md"; + +/// What a section no row names becomes. +const UNKNOWN: &str = "a section no row of the NN-CONTEXT.md table names: no field holds it"; + +const DECISIONS: &str = "Implementation Decisions"; +const INSIGHTS: &str = "Existing Code Insights"; + +/// Whether `title` is `Claude's Discretion`, with either apostrophe. +pub fn discretion(title: &str) -> bool { + matches!(title, "Claude's Discretion" | "Claude’s Discretion") +} + +/// One file's raw lines, their fence marks and its leaf blocks less the template's own lines. +pub struct Text<'t> { + pub lines: Vec<&'t str>, + pub fenced: Vec<bool>, + pub blocks: Vec<InlineBlock>, +} + +impl<'t> Text<'t> { + pub fn new(text: &'t str) -> Self { + let lines: Vec<&str> = text.split('\n').map(|l| l.trim_end_matches('\r')).collect(); + // A heading is a section, read by its title, never a block of the section over it. + let headings: Vec<usize> = markdown::headings(text).iter().map(|h| h.line).collect(); + let blocks = markdown::inline_blocks(text) + .into_iter() + .filter(|b| !headings.contains(&b.lines[0])) + .filter_map(|mut b| { + // A closing tag on the line under a paragraph is inline HTML of that paragraph (`B. </domain>`). + let mut kept = b.text.trim_end(); + while let Some((head, last)) = kept.rsplit_once(char::is_whitespace) { + if !is_tag(last) { + break; + } + kept = head.trim_end(); + } + if kept.split('\n').all(|l| l.trim().is_empty() || is_tag(l)) { + return None; + } + let len = kept.len(); + b.text.truncate(len); + b.lines.truncate(len); + lines + .get(b.lines[0]) + .is_none_or(|l| !is_footer(l) && !is_bold_only(l)) + .then_some(b) + }) + .collect(); + Text { + fenced: sections::fenced(text), + lines, + blocks, + } + } + + /// The trimmed text of each bullet of `body`, with its 0-based line. + pub fn bullets(&self, body: &Range<usize>) -> Vec<(usize, &str)> { + bullets_in(&self.blocks, &self.lines, body) + .into_iter() + .map(|b| (b.lines[0], b.text.trim())) + .collect() + } + + /// The raw lines outside a fence, with their 0-based numbers. + pub fn raw(&self) -> impl Iterator<Item = (usize, &&'t str)> { + self.lines + .iter() + .enumerate() + .filter(|(n, _)| !self.fenced[*n]) + } +} + +/// Reads the context `text`, served at `path` (`rel` under `.planning/`): `phases/<NN-slug>/<NN>-CONTEXT.md`. +pub fn read( + path: &str, + rel: &str, + text: &str, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let Some(f) = phase_file(path, rel, CX, cx, report) else { + return; + }; + let t = Text::new(text); + let mut fields: BTreeMap<String, Value> = BTreeMap::new(); + let mut rest = Rest::default(); + for (n, line) in t.raw() { + if let Some(v) = line.strip_prefix("**Gathered:**").map(str::trim) { + rest.take(n); + if is_date(v) { + fields.insert("gathered".to_string(), json!(v)); + } else { + report.push(f.unmapped( + n, + "Gathered", + "**Gathered:** is not a YYYY-MM-DD date: left out".to_string(), + )); + } + } else if line.starts_with("**Status:**") { + report.push(f.row("**Status:**", n, "Status")); + } else if is_footer(line) { + report.push(f.row("footer", n, "footer")); + } else if is_bold_only(line) { + report.push(f.row("**Downstream agents MUST read these", n, "<canonical_refs>")); + } + } + let mut title = None; + let mut parent = String::new(); + let mut covered = 0..0; + let mut decided = false; + let all = sections::sections(text); + for s in &all { + if covered.contains(&s.line) { + continue; + } + if s.level <= 2 { + parent = s.title.clone(); + } + let to = + |what: &str, report: &mut Report| report.push(mapped(&f.at(s.line), &s.title, what)); + // What the section holds itself: a sub-section is read under its own heading. + let mine = own(s, &all); + let list = |field: &str, fields: &mut BTreeMap<String, Value>, report: &mut Report| { + to(&format!("context.{field}"), report); + let items: Vec<&str> = t.bullets(&mine).into_iter().map(|(_, b)| b).collect(); + if !items.is_empty() { + fields.insert(field.to_string(), json!(items)); + } + }; + let prose_of = |field: &str, fields: &mut BTreeMap<String, Value>, report: &mut Report| { + to(&format!("context.{field}"), report); + if let Some(text) = prose(&t.blocks, &mine) { + fields.insert(field.to_string(), json!(text)); + } + }; + // A section read in part: its bullets are taken, and what else it holds is reported. + let in_part = match (s.level, parent.as_str(), s.title.as_str()) { + (1, ..) => title.is_none(), + (2, _, DECISIONS | INSIGHTS) => true, + (3, DECISIONS, _) => true, + (3, INSIGHTS, name) => { + matches!( + name, + "Reusable Assets" | "Established Patterns" | "Integration Points" + ) + } + _ => false, + }; + if in_part { + rest.section(mine.clone(), &s.title); + for b in bullets_in(&t.blocks, &t.lines, &mine) { + rest.take_block(b); + } + } + match (s.level, parent.as_str(), s.title.as_str()) { + (1, ..) if title.is_none() => title = Some(s.title.clone()), + (2, _, "Phase Boundary") => prose_of("boundary", &mut fields, report), + (2, _, "Specific Ideas") => prose_of("specifics", &mut fields, report), + (2, _, DECISIONS | INSIGHTS) => to("each area under it", report), + (2, _, "Canonical References") => { + to("context.canonical_refs", report); + covered = s.body.clone(); + let refs = canonical_refs(&t, s, &all); + if !refs.is_empty() { + fields.insert("canonical_refs".to_string(), json!(refs)); + } + } + (2, _, "Deferred Ideas") => { + to("each bullet a deferred_idea", report); + covered = s.body.clone(); + deferred(&f, &t, s, records, report); + } + (3, DECISIONS, title) if discretion(title) => list("discretion", &mut fields, report), + (3, DECISIONS, _) => { + to("each D-NN bullet a decision", report); + let area = Section { + body: mine.clone(), + ..s.clone() + }; + decisions(&f, &t, &area, &mut decided, records, report) + } + (3, INSIGHTS, "Reusable Assets") => list("reusable_assets", &mut fields, report), + (3, INSIGHTS, "Established Patterns") => list("patterns", &mut fields, report), + (3, INSIGHTS, "Integration Points") => list("integration_points", &mut fields, report), + _ => { + if s.level > 1 { + covered = s.body.clone(); + } + report.push(f.unmapped(s.line, &s.title, UNKNOWN.to_string())); + } + } + } + records.add( + f.within( + "context", + ("phase", &f.phase), + &f.stem, + title.as_deref().unwrap_or(&f.stem), + fields, + 0, + ), + report, + ); + rest.report(path, text, CX, report); +} + +/// Each `- **D-NN:** text` bullet of the area `s` as `decision D-NN` of the phase, origin `context`; any other bullet, +/// or an id that is no `D-NN`, is reported. The first decision of the file reports the filled origin. +fn decisions( + f: &PhaseFile<'_>, + t: &Text<'_>, + s: &Section, + decided: &mut bool, + records: &mut Records, + report: &mut Report, +) { + for (line, text) in t.bullets(&s.body) { + let Some((id, rest)) = text + .split_once(':') + .filter(|(id, _)| id.trim().starts_with("D-")) + else { + report.push(f.unmapped( + line, + &s.title, + "a decision bullet with no `**D-NN:**` id: not imported".to_string(), + )); + continue; + }; + let (id, rest) = (id.trim(), rest.trim()); + if !ids::decision(id) || rest.is_empty() { + report.push(f.unmapped( + line, + &s.title, + format!("`{id}` is no decision `D-NN` with a text: not imported"), + )); + continue; + } + if !std::mem::replace(decided, true) { + report.push(f.row("- **D-NN:**", line, &s.title)); + } + let fields = BTreeMap::from([ + ("area".to_string(), json!(s.title)), + ("text".to_string(), json!(rest)), + ("origin".to_string(), json!("context")), + ]); + records.add( + f.within("decision", ("phase", &f.phase), id, rest, fields, line), + report, + ); + } +} + +/// Each `## Deferred Ideas` bullet `- text — why` as `deferred_idea DI<n>` of the phase, origin `discussion`; a bullet +/// with no ` — ` is imported without a `why`, reported. +fn deferred( + f: &PhaseFile<'_>, + t: &Text<'_>, + s: &Section, + records: &mut Records, + report: &mut Report, +) { + for (n, (line, text)) in t.bullets(&s.body).into_iter().enumerate() { + if n == 0 { + report.push(f.row("<deferred>", line, &s.title)); + } + let mut fields = BTreeMap::from([("origin".to_string(), json!("discussion"))]); + let idea = match text.split_once(" — ") { + Some((idea, why)) if !why.trim().is_empty() => { + fields.insert("why".to_string(), json!(why.trim())); + idea.trim() + } + _ => { + report.push(f.unmapped( + line, + &s.title, + "a deferred idea with no ` — why`: imported without a why".to_string(), + )); + text + } + }; + fields.insert("text".to_string(), json!(idea)); + records.add( + f.within( + "deferred_idea", + ("phase", &f.phase), + &format!("DI{}", n + 1), + idea, + fields, + line, + ), + report, + ); + } +} + +/// The `<canonical_refs>` blocks of `s`: one `{topic, paths}` per bullet or paragraph, its code spans without a space +/// the `paths` and the rest its topic, after the `### <Topic>` heading over it (`all` are the file's sections). +fn canonical_refs(t: &Text<'_>, s: &Section, all: &[Section]) -> Vec<Value> { + let heading = |line: usize| { + all.iter() + .rfind(|h| h.level > s.level && s.body.contains(&h.line) && h.line < line) + .map(|h| h.title.as_str()) + }; + blocks_in(&t.blocks, &s.body) + .map(|b| { + let (rest, paths) = code_paths(b.text.trim()); + let topic = match (heading(b.lines[0]), rest.as_str()) { + (Some(h), "") => h.to_string(), + (Some(h), rest) => format!("{h}: {rest}"), + (None, rest) => rest.to_string(), + }; + let mut block = json!({ "paths": paths }); + if !topic.is_empty() { + block["topic"] = json!(topic); + } + block + }) + .collect() +} + +/// `text` without its code spans that hold no space, and those spans: an odd count of backticks keeps all as text. +fn code_paths(text: &str) -> (String, Vec<String>) { + if text.matches('`').count() % 2 == 1 { + return (text.to_string(), Vec::new()); + } + let (mut rest, mut paths) = (String::new(), Vec::new()); + for (i, part) in text.split('`').enumerate() { + if i % 2 == 0 { + rest.push_str(part); + } else if !part.is_empty() && !part.contains(char::is_whitespace) { + paths.push(part.to_string()); + } else { + rest.push_str(&format!("`{part}`")); + } + } + let rest = rest + .trim_matches(|c: char| c.is_whitespace() || matches!(c, '—' | '-' | ':' | ',' | ';')) + .to_string(); + (rest, paths) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_ref_keeps_its_paths_apart_from_its_topic() { + assert_eq!( + code_paths("`docs/a.md` — Feed rules"), + ("Feed rules".to_string(), vec!["docs/a.md".to_string()]) + ); + assert_eq!( + code_paths("No external specs — fully captured"), + ("No external specs — fully captured".to_string(), vec![]) + ); + assert_eq!( + code_paths("`a b` and `x"), + ("`a b` and `x".to_string(), vec![]) + ); + assert_eq!( + code_paths("`a b` uses `c.md`"), + ("`a b` uses".to_string(), vec!["c.md".to_string()]) + ); + } +} diff --git a/gsd/import/src/read/discussion.rs b/gsd/import/src/read/discussion.rs new file mode 100644 index 0000000000..0c2aa8084a --- /dev/null +++ b/gsd/import/src/read/discussion.rs @@ -0,0 +1,153 @@ +//! `NN-DISCUSSION-LOG.md` to a `discussion` (13-RESEARCH Part B, the DISCUSSION-LOG rows; the rows are +//! `table::sections::DISCUSSION_LOG`): the file stem is its id, and each `## <Area>` one of its `entries`, the area's +//! Option column its `options`, the row marked ✓ (else `**User's choice:**`) its `chosen`, `**Notes:**` its `notes`. +//! The header, the note under the title and the sections CONTEXT.md gives are reported. + +use std::collections::BTreeMap; + +use gsd_kit::markdown::{self, Table}; +use serde_json::{Value, json}; + +use super::context::{Text, discretion}; +use super::{Context, PhaseFile, is_footer, labelled, phase_file}; +use crate::records::Records; +use crate::report::Report; +use crate::sections::{self, Section}; + +/// The fate table's name of a discussion log. +pub const DL: &str = "NN-DISCUSSION-LOG.md"; + +const HEADER: &str = "**Date:**, **Phase:**, **Areas discussed:**"; +const UNKNOWN: &str = "a section no row of the NN-DISCUSSION-LOG.md table names: no field holds it"; + +/// Reads the discussion log `text`, served at `path` (`rel` under `.planning/`): `phases/<NN-slug>/<NN>-DISCUSSION-LOG.md`. +pub fn read( + path: &str, + rel: &str, + text: &str, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let Some(f) = phase_file(path, rel, DL, cx, report) else { + return; + }; + let t = Text::new(text); + for (n, line) in t.raw() { + if ["**Date:**", "**Phase:**", "**Areas discussed:**"] + .iter() + .any(|h| line.starts_with(h)) + { + let label = line.trim_start_matches('*').split(":**").next(); + report.push(f.row(HEADER, n, label.unwrap_or(line))); + } else if line.starts_with('>') { + report.push(f.row("> **Audit trail only.**", n, "note")); + } else if is_footer(line) { + report.push(f.row("footer", n, "footer")); + } + } + let tables = markdown::tables(text); + let mut title = None; + let mut entries = Vec::new(); + for s in sections::sections(text) { + match (s.level, s.title.as_str()) { + (1, _) if title.is_none() => title = Some(s.title.clone()), + (2, area) if discretion(area) => { + report.push(f.row("## Claude's Discretion", s.line, area)) + } + (2, "Deferred Ideas") => report.push(f.row("## Deferred Ideas", s.line, &s.title)), + (2, _) => { + report.push(match entries.is_empty() { + true => f.row("## Area", s.line, &s.title), + false => f.mapped(s.line, &s.title, "one of discussion.entries"), + }); + entries.push(entry(&f, &t, &s, &tables, report)); + } + _ => report.push(f.unmapped(s.line, &s.title, UNKNOWN.to_string())), + } + } + let mut fields = BTreeMap::new(); + if !entries.is_empty() { + fields.insert("entries".to_string(), json!(entries)); + } + records.add( + f.within( + "discussion", + ("phase", &f.phase), + &f.stem, + title.as_deref().unwrap_or(&f.stem), + fields, + 0, + ), + report, + ); +} + +/// The entry of the area `s`: its first table's options and ✓ row, its user's choice and its notes, mode `interactive`. +fn entry( + f: &PhaseFile<'_>, + t: &Text<'_>, + s: &Section, + tables: &[Table], + report: &mut Report, +) -> Value { + let mut entry = json!({ "area": s.title, "mode": "interactive" }); + let mut marked = Vec::new(); + if let Some(table) = tables.iter().find(|t| s.body.contains(&t.line)) { + let column = |name: &str| { + table + .header + .iter() + .position(|h| h.eq_ignore_ascii_case(name)) + }; + let option = column("Option").unwrap_or(0); + if let Some(c) = column("Description") { + report.push(f.row("| Description |", table.line, &table.header[c])); + } + let cell = |row: &[String], c: usize| row.get(c).map_or("", |c| c.trim()).to_string(); + let options: Vec<String> = table + .rows + .iter() + .map(|r| cell(r, option)) + .filter(|o| !o.is_empty()) + .collect(); + if let Some(selected) = column("Selected") { + marked = table + .rows + .iter() + .filter(|r| cell(r, selected).contains(['✓', '✔'])) + .map(|r| cell(r, option)) + .collect(); + } + if !options.is_empty() { + entry["options"] = json!(options); + } + if marked.len() > 1 { + report.push(f.unmapped( + table.line, + &s.title, + format!( + "{} options are marked ✓: the user's choice is taken instead", + marked.len() + ), + )); + } + } + let choice = labelled( + &t.lines, + &t.fenced, + &s.body, + &["**User's choice:**", "**User’s choice:**"], + ); + match (marked.as_slice(), choice) { + ([one], _) => entry["chosen"] = json!(one), + (_, Some((_, choice))) if !choice.is_empty() => entry["chosen"] = json!(choice), + _ => {} + } + if let Some((_, notes)) = + labelled(&t.lines, &t.fenced, &s.body, &["**Notes:**"]).filter(|(_, n)| !n.is_empty()) + { + entry["notes"] = json!(notes); + } + entry +} diff --git a/gsd/import/src/read/mod.rs b/gsd/import/src/read/mod.rs new file mode 100644 index 0000000000..da64f92892 --- /dev/null +++ b/gsd/import/src/read/mod.rs @@ -0,0 +1,672 @@ +//! The readers: each served `.planning/` file goes to the reader of its format, or to one report entry with the fate +//! the table gives it ([`crate::table`]). + +pub mod context; +pub mod discussion; +pub mod plan; +pub mod project; +pub mod quick; +pub mod requirements; +pub mod research; +pub mod roadmap; +pub mod security; +pub mod state; +pub mod summary; +pub mod tasks; +pub mod threats; +pub mod uat; +pub mod verification; + +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::Range; + +use gsd_kit::markdown::{self, InlineBlock}; +use serde_json::{Value, json}; + +use crate::ids; +use crate::paths; +use crate::preflight::Manifest; +use crate::records::{Record, Records, Source}; +use crate::report::{Entry, Outcome, Report}; +use crate::sections::Section; +use crate::settings; +use crate::table::{self, Fate, Home, TIER_2}; +use plan::{Doc, Scope}; + +/// One file the host served under `.planning/`: its project-relative path and what it read. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Served { + pub path: String, + pub text: Option<String>, + /// The host's reason it sent no text (`too_large`, `denied`, ..). + pub error: Option<String>, +} + +/// What a reader knows beyond its own file. +#[derive(Debug, Clone, Copy)] +pub struct Context<'a> { + pub manifest: &'a Manifest, + /// The roadmap's phases and plan titles (empty while `ROADMAP.md` itself is read). + pub roadmap: &'a roadmap::Roadmap, + /// Every served path, relative to `.planning/`. + pub served: &'a [&'a str], +} + +/// The path of `served` relative to `.planning/`. +fn relative(served: &Served) -> &str { + served + .path + .strip_prefix(".planning/") + .unwrap_or(&served.path) +} + +/// Whether `served` is read after every other file: a summary takes its plan's title, a research names its phase +/// context's decisions, a security audit sets its phase's plan threats. +fn is_late(served: &&Served) -> bool { + let rel = relative(served); + ["-SUMMARY.md", "-RESEARCH.md", "-SECURITY.md"] + .iter() + .any(|end| rel.ends_with(end)) +} + +/// Reads every served file: `REQUIREMENTS.md` first (a phase keeps only the requirements it defines), then +/// `ROADMAP.md` (later readers take its phases and plan titles), then the rest in the order served, the summaries, +/// researches and security audits last, then the Traceability check of `REQUIREMENTS.md` against the roadmap. The roadmap read is returned +/// for the readers after it. +pub fn all( + planning: &[Served], + manifest: &Manifest, + records: &mut Records, + report: &mut Report, +) -> roadmap::Roadmap { + let find = |name: &str| planning.iter().find(|s| relative(s) == name); + let (requirements, road) = (find("REQUIREMENTS.md"), find("ROADMAP.md")); + let served: Vec<&str> = planning.iter().map(relative).collect(); + let empty = roadmap::Roadmap::default(); + let early = Context { + manifest, + roadmap: &empty, + served: &served, + }; + if let Some(served) = requirements { + file(served, &early, records, report); + } + // The directories under `phases/`, from the files the host served in them (a `.gitkeep` keeps an empty one). + let mut dirs: Vec<&str> = planning + .iter() + .filter_map(|s| relative(s).strip_prefix("phases/")?.split_once('/')) + .map(|(dir, _)| dir) + .collect(); + dirs.dedup(); + let roadmap = match road { + Some(Served { + path, + text: Some(text), + .. + }) => roadmap::read(path, text, &dirs, records, report), + Some(served) => { + file(served, &early, records, report); + roadmap::Roadmap::default() + } + None => roadmap::Roadmap::default(), + }; + let cx = Context { + roadmap: &roadmap, + ..early + }; + let rest = || { + planning + .iter() + .filter(|s| !matches!(relative(s), "REQUIREMENTS.md" | "ROADMAP.md")) + }; + for served in rest().filter(|s| !is_late(s)).chain(rest().filter(is_late)) { + file(served, &cx, records, report); + } + if let ( + Some(Served { + path, + text: Some(text), + .. + }), + Some(_), + ) = (requirements, road) + { + roadmap::cross_check(path, text, &roadmap, report); + } + roadmap +} + +/// Reads `served` into `records`, or reports it whole with its fate. +pub fn file(served: &Served, cx: &Context<'_>, records: &mut Records, report: &mut Report) { + let manifest = cx.manifest; + let Some((name, fate)) = table::fate_of(relative(served)) else { + report.push(whole(served, Outcome::Unmapped, "unknown file".to_string())); + return; + }; + match (name, fate, &served.text) { + ("REQUIREMENTS.md", _, Some(text)) => { + requirements::read(&served.path, text, records, report) + } + ("PROJECT.md", _, Some(text)) => project::read(&served.path, text, records, report), + ("NN-MM-PLAN.md", _, Some(text)) => { + plan::read_phase(&served.path, relative(served), text, cx, records, report) + } + ("NN-MM-SUMMARY.md", _, Some(text)) => { + summary::read_phase(&served.path, relative(served), text, cx, records, report) + } + ("quick/*", _, Some(text)) => { + quick::read(&served.path, relative(served), text, cx, records, report) + } + ("NN-CONTEXT.md", _, Some(text)) => { + context::read(&served.path, relative(served), text, cx, records, report) + } + ("NN-DISCUSSION-LOG.md", _, Some(text)) => { + discussion::read(&served.path, relative(served), text, cx, records, report) + } + ("NN-RESEARCH.md", _, Some(text)) => { + research::read(&served.path, relative(served), text, cx, records, report) + } + ("NN-VERIFICATION.md", _, Some(text)) => { + verification::read(&served.path, relative(served), text, cx, records, report) + } + ("NN-UAT.md", _, Some(text)) => { + uat::read(&served.path, relative(served), text, cx, records, report) + } + ("STATE.md", _, Some(text)) => { + report.push(whole( + served, + table::outcome(fate), + table::reason(name, fate), + )); + state::read(&served.path, text, report); + } + ("config.json", Fate::Settings, Some(text)) => { + let (lines, entries) = settings::settings_lines(text, manifest); + let reason = format!("{} settings lines, printed below", lines.len()); + report.push(whole(served, Outcome::Setting, reason)); + for line in lines { + report.setting(line); + } + for entry in entries { + report.push(entry); + } + } + ("SECURITY.md", Fate::Maps, _) if !manifest.security => { + let fate = Fate::NeedsExtension("@gsd/security"); + report.push(whole( + served, + table::outcome(fate), + table::reason(name, fate), + )); + } + ("SECURITY.md", Fate::Maps, Some(text)) => { + security::read(&served.path, relative(served), text, cx, records, report) + } + // The extension is loaded, but this importer does not read its formats. + (_, Fate::NeedsExtension(extension), _) + if manifest.loaded.iter().any(|l| l == extension) => + { + let fate = Fate::Unmapped(TIER_2); + report.push(whole( + served, + table::outcome(fate), + table::reason(name, fate), + )); + } + _ => report.push(whole( + served, + table::outcome(fate), + table::reason(name, fate), + )), + } +} + +/// One entry about the whole of `served`, naming the host's read error, if any. +fn whole(served: &Served, outcome: Outcome, mut reason: String) -> Entry { + if let Some(error) = &served.error { + reason.push_str(&format!(" (not read: {error})")); + } + Entry::file(&served.path, outcome, reason) +} + +/// The entry of the table row `key` of the format `file`, at `source` in `section`: its first home that writes nothing, +/// as an outcome and its reason. A reader reports with it, so the reason is the table's, not the reader's. +pub fn row(file: &str, key: &str, source: &Source, section: &str) -> Entry { + let home = table::section(file, key).and_then(|row| { + row.homes + .iter() + .find(|h| !matches!(h, Home::To { .. })) + .copied() + }); + let (outcome, reason) = match home { + Some(Home::Computed { kind, field }) => ( + Outcome::Computed, + format!("{kind}.{field} is computed: never written"), + ), + Some(Home::Redundant(why)) => (Outcome::Redundant, why.to_string()), + Some(Home::Reported(why)) => (Outcome::Unmapped, why.to_string()), + Some(Home::Ignored(why)) => (Outcome::Ignored, why.to_string()), + Some(Home::Runtime(why)) => (Outcome::Runtime, why.to_string()), + Some(Home::Filled { why, .. }) => (Outcome::Filled, why.to_string()), + Some(Home::To { .. }) | None => ( + Outcome::Unmapped, + format!("no row of the {file} table reports {key}"), + ), + }; + Entry::at(source, section, outcome, reason) +} + +/// The entry of a heading whose section a reader maps (into `to`: `project.core_value`, `each row a decision`), so no +/// heading goes unreported (the census of `tests/census.rs`). +pub fn mapped(source: &Source, section: &str, to: &str) -> Entry { + Entry::at(source, section, Outcome::Mapped, format!("mapped: {to}")) +} + +/// `text` as an id: ASCII letters and digits lower-cased, every other run of characters one `-`, none at either end +/// (`Hotfix: titles survive a reload` is `hotfix-titles-survive-a-reload`). +pub fn slug(text: &str) -> String { + let mut out = String::new(); + for c in text.chars() { + if c.is_ascii_alphanumeric() { + out.push(c.to_ascii_lowercase()); + } else if !out.is_empty() && !out.ends_with('-') { + out.push('-'); + } + } + out.trim_end_matches('-').to_string() +} + +/// The lines the section `s` holds itself: its body up to its first sub-section (`all` are the file's sections, in line +/// order). A sub-section is read under its own heading, never into its parent's field. +pub fn own(s: &Section, all: &[Section]) -> Range<usize> { + let end = all + .iter() + .find(|h| h.line > s.line) + .map_or(s.body.end, |h| h.line.min(s.body.end)); + s.body.start..end +} + +/// What a reader leaves of the sections it maps (ADR 0391 D3: nothing is dropped silently). A section a reader maps in +/// part (key lines, a list, a table) is named with its own lines, and each line the reader takes into a field or a +/// record is taken; at the end, each run of lines of a leaf block in a named section that nothing took or reported is +/// reported once, at its first line, so a line no row reads is never lost without a word. +#[derive(Debug, Default)] +pub struct Rest { + open: Vec<(Range<usize>, String)>, + taken: BTreeSet<usize>, +} + +impl Rest { + /// The section `title`'s own 0-based `lines`, which the reader maps in part. + pub fn section(&mut self, lines: Range<usize>, title: &str) { + self.open.push((lines, title.to_string())); + } + + /// The 0-based `line`, taken into a field or a record. + pub fn take(&mut self, line: usize) { + self.taken.insert(line); + } + + /// Every line of the leaf block `b`, taken. + pub fn take_block(&mut self, b: &InlineBlock) { + self.taken.extend(b.lines.iter().copied()); + } + + /// The lines of `table`: its header, its delimiter row and its rows. + pub fn take_table(&mut self, table: &markdown::Table) { + self.taken + .extend(table.line..table.line + 2 + table.rows.len()); + } + + /// Reports what is left of the named sections of `text`, served at `path`; `format` names the table. + pub fn report(&self, path: &str, text: &str, format: &str, report: &mut Report) { + let lines: Vec<&str> = text.split('\n').collect(); + let reported = report.lines(path); + let mut left = Vec::new(); + for b in markdown::inline_blocks(text) { + let mut own = b.lines.clone(); + own.dedup(); + // Whether the line before, in this block, is in a run already reported. + let mut run = false; + for n in own { + let line = lines.get(n).copied().unwrap_or_default(); + let section = self.open.iter().find(|(r, _)| r.contains(&n)); + let free = section.is_some() + && !self.taken.contains(&n) + && !reported.contains(&(n + 1)) + && !line.trim().is_empty() + && !is_tag(line); + if let Some((_, title)) = section.filter(|_| free && !run) { + left.push(Entry::at( + &Source { + file: path.to_string(), + line: n + 1, + }, + title, + Outcome::Unmapped, + format!("text no row of the {format} table reads: no field holds it"), + )); + } + run = free; + } + } + for entry in left { + report.push(entry); + } + } +} + +/// The leaf blocks whose first line lies in `lines`. +pub fn blocks_in<'b>( + blocks: &'b [InlineBlock], + lines: &Range<usize>, +) -> impl Iterator<Item = &'b InlineBlock> { + blocks + .iter() + .filter(move |b| b.lines.first().is_some_and(|l| lines.contains(l))) +} + +/// The prose of `lines`: each leaf block's text, the blocks joined by a blank line; none when empty. +pub fn prose(blocks: &[InlineBlock], lines: &Range<usize>) -> Option<String> { + let text: Vec<&str> = blocks_in(blocks, lines).map(|b| b.text.trim()).collect(); + (!text.is_empty()).then(|| text.join("\n\n")) +} + +/// Whether the raw line `line` starts a list item (`- `, `* `, `+ `). +pub fn is_bullet(line: &str) -> bool { + let t = line.trim_start(); + t.starts_with("- ") || t.starts_with("* ") || t.starts_with("+ ") +} + +/// Whether the raw line `line` is a template footer line, wholly in emphasis (`*Phase: 02-persistence*`). +pub fn is_footer(line: &str) -> bool { + let t = line.trim(); + t.len() > 2 + && t.starts_with('*') + && t.ends_with('*') + && !t.starts_with("**") + && !t.starts_with("* ") +} + +/// Whether `line` is one XML section tag alone (`<decisions>`, `</domain>`), which only wraps the Markdown inside it. +pub fn is_tag(line: &str) -> bool { + let t = line.trim(); + let name = t + .strip_prefix("</") + .or_else(|| t.strip_prefix('<')) + .and_then(|t| t.strip_suffix('>')) + .map(|t| t.split(' ').next().unwrap_or(t)); + name.is_some_and(|n| { + n.starts_with(|c: char| c.is_ascii_alphabetic()) + && n.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') + }) +} + +/// Whether the raw line `line` is wholly bold: a template's instruction to agents +/// (`**Downstream agents MUST read these before planning or implementing.**`). +pub fn is_bold_only(line: &str) -> bool { + let t = line.trim(); + t.len() > 4 && t.starts_with("**") && t.ends_with("**") && !t[2..t.len() - 2].contains("**") +} + +/// The leaf blocks of `blocks` in `body` that a raw list marker starts (`lines` are the file's raw lines). +pub fn bullets_in<'b>( + blocks: &'b [InlineBlock], + lines: &[&str], + body: &Range<usize>, +) -> Vec<&'b InlineBlock> { + blocks_in(blocks, body) + .filter(|b| lines.get(b.lines[0]).is_some_and(|l| is_bullet(l))) + .collect() +} + +/// The text after the bold label `label` (`**What:**`) on the first raw line of `body` that starts with it, outside a +/// fence, trimmed, with its 0-based line. +pub fn labelled<'l>( + lines: &[&'l str], + fenced: &[bool], + body: &Range<usize>, + labels: &[&str], +) -> Option<(usize, &'l str)> { + body.clone().filter(|n| !fenced[*n]).find_map(|n| { + let line = lines.get(n)?.trim_start(); + labels + .iter() + .find_map(|l| line.strip_prefix(l)) + .map(|v| (n, v.trim())) + }) +} + +/// Whether `value` is a `YYYY-MM-DD` date of the calendar (`2026-13-45` is not): the host refuses a plan holding one +/// that is not. +pub fn is_date(value: &str) -> bool { + let b = value.as_bytes(); + let shaped = b.len() == 10 + && b.iter().enumerate().all(|(i, c)| match i { + 4 | 7 => *c == b'-', + _ => c.is_ascii_digit(), + }); + let n = |r: Range<usize>| value[r].parse::<u32>().unwrap_or(0); + shaped && { + let (year, month, day) = (n(0..4), n(5..7), n(8..10)); + let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let days = match month { + 2 if leap => 29, + 2 => 28, + 4 | 6 | 9 | 11 => 30, + 1..=12 => 31, + _ => 0, + }; + (1..=days).contains(&day) + } +} + +/// Whether `value` is a timestamp the gsd family's rule E107 accepts on an authored `ts` field: exactly +/// `gsd_kit::dsl::RFC3339_UTC` (`YYYY-MM-DDTHH:MM:SS`, an optional fraction, `Z`; an uppercase `T`, no offset), which +/// the unit test holds this equal to. The import never writes a value `check` turns into an Error. +pub fn is_timestamp(value: &str) -> bool { + let b = value.as_bytes(); + let digits = |r: Range<usize>| b[r].iter().all(u8::is_ascii_digit); + let two = |at: usize| (b[at] - b'0') * 10 + (b[at + 1] - b'0'); + let Some(rest) = value.strip_suffix('Z') else { + return false; + }; + let fraction = match rest.get(19..) { + Some("") => true, + Some(f) => f.len() > 1 && f.starts_with('.') && f[1..].bytes().all(|c| c.is_ascii_digit()), + None => false, + }; + fraction + && digits(0..4) + && b[4] == b'-' + && digits(5..7) + && b[7] == b'-' + && digits(8..10) + && b[10] == b'T' + && digits(11..13) + && b[13] == b':' + && digits(14..16) + && b[16] == b':' + && digits(17..19) + && (1..=12).contains(&two(5)) + && (1..=31).contains(&two(8)) + && two(11) <= 23 + && two(14) <= 59 + && two(17) <= 60 +} + +/// A file of one phase, `phases/<dir>/<NN><suffix>` (`02-CONTEXT.md`): where its records go. +#[derive(Debug, Clone)] +pub struct PhaseFile<'a> { + pub doc: Doc<'a>, + /// The phase number (`02`). + pub number: String, + /// The phase's graph path (`v1.0/02`). + pub phase: String, + /// The file stem, the record's own id (`02-CONTEXT`). + pub stem: String, +} + +impl PhaseFile<'_> { + /// The 0-based `line` of the file. + pub fn at(&self, line: usize) -> Source { + self.doc.at(line + 1) + } + + /// The table's entry for its key `key`, at the 0-based `line`, in `section`. + pub fn row(&self, key: &str, line: usize, section: &str) -> Entry { + self.doc.row(key, line + 1, section) + } + + /// An `unmapped` entry at the 0-based `line`. + pub fn unmapped(&self, line: usize, section: &str, why: String) -> Entry { + self.doc.unmapped(line + 1, section, why) + } + + /// The [`mapped`] entry of the heading at the 0-based `line`. + pub fn mapped(&self, line: usize, section: &str, to: &str) -> Entry { + mapped(&self.at(line), section, to) + } + + /// The `spec/gsd/` file of the phase. + pub fn file(&self) -> String { + paths::phase(&self.number) + } + + /// A record of the phase file, scoped by the entity `scope` through its field `field`: its id is `<scope>/<id>`. + pub fn within( + &self, + kind: &'static str, + (field, scope): (&str, &str), + id: &str, + title: &str, + mut fields: BTreeMap<String, Value>, + line: usize, + ) -> Record { + fields.insert(field.to_string(), json!(scope)); + Record { + kind, + id: format!("{scope}/{id}"), + title: title.to_string(), + file: self.file(), + fields, + refs: vec![scope.to_string()], + links: Vec::new(), + source: self.at(line), + } + } +} + +/// The phase file of the format `format` (`NN-CONTEXT.md`) served at `path` (`rel` under `.planning/`); none, reported, +/// when its name gives no phase number or the roadmap holds no such phase. +pub fn phase_file<'a>( + path: &'a str, + rel: &str, + format: &'static str, + cx: &Context<'_>, + report: &mut Report, +) -> Option<PhaseFile<'a>> { + let doc = Doc { + path, + format, + prefix: "", + }; + // `NN-CONTEXT.md` names its number; `SECURITY.md` is the kit's name of `NN-SECURITY.md`. + let suffix = format + .strip_prefix("NN") + .map_or_else(|| format!("-{format}"), str::to_string); + let Some((dir, number)) = plan::in_phase(rel, &suffix).filter(|(_, n)| ids::phase(n)) else { + report.push(doc.unmapped( + 1, + "file name", + "the file name gives no phase number `NN`: not imported".to_string(), + )); + return None; + }; + match plan::phase_scope(&doc, dir, number, cx, report)? { + Scope::Phase { number, path } => Some(PhaseFile { + doc, + stem: format!("{number}{}", suffix.trim_end_matches(".md")), + number, + phase: path, + }), + Scope::Quick => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dates_and_timestamps_are_the_calendars() { + for ok in ["2026-10-30", "2024-02-29", "2026-12-31"] { + assert!(is_date(ok), "{ok}"); + } + for bad in [ + "2026-13-45", + "2026-02-29", + "2026-04-31", + "2026-00-10", + "26-10-30", + "2026/10/30", + ] { + assert!(!is_date(bad), "{bad}"); + } + for ok in [ + "2026-03-03T10:30:00Z", + "2026-03-03T23:59:60.123Z", + "2026-02-31T00:00:00Z", + ] { + assert!(is_timestamp(ok), "{ok}"); + } + for bad in [ + "2026-03-03", + "yesterday", + "2026-03-03T24:00:00Z", + "2026-03-03T10:30Z", + "2026-03-03T10:30:00", + "2026-03-03T10:30:00.5+01:00", + "2026-03-03t23:59:60z", + "2026-03-03T10:30:00z", + "2026-03-03T10:30:00.Z", + ] { + assert!(!is_timestamp(bad), "{bad}"); + } + } + + /// `is_timestamp` is E107's `RFC3339_UTC`, value for value: the import writes no `ts` that `check` refuses. + #[test] + fn a_timestamp_is_what_e107_accepts() { + let e107 = regex::Regex::new(gsd_kit::dsl::RFC3339_UTC).expect("a pattern"); + let mut values = vec![ + String::new(), + "Z".to_string(), + "2026-10-28 09:30:00Z".to_string(), + "\u{662}\u{660}\u{662}\u{666}-10-28T09:30:00Z".to_string(), + "2026-10-28T09:30:00Zx".to_string(), + "2026-10-28T09:30:00.1234567Z".to_string(), + "2026-10-28T09:30:00+00:00".to_string(), + "2026-10-28T09:30:0éZ".to_string(), + ]; + for (month, day, hour, minute, second) in [ + ("00", "10", "09", "30", "00"), + ("13", "10", "09", "30", "00"), + ("12", "00", "09", "30", "00"), + ("12", "31", "09", "30", "00"), + ("12", "32", "09", "30", "00"), + ("02", "30", "20", "59", "60"), + ("02", "30", "24", "00", "00"), + ("02", "30", "23", "60", "00"), + ("02", "30", "23", "59", "61"), + ("1a", "30", "23", "59", "59"), + ] { + let at = format!("2026-{month}-{day}T{hour}:{minute}:{second}"); + values.extend([format!("{at}Z"), format!("{at}.5Z"), format!("{at}z")]); + } + for value in values { + assert_eq!(is_timestamp(&value), e107.is_match(&value), "{value:?}"); + } + } +} diff --git a/gsd/import/src/read/plan.rs b/gsd/import/src/read/plan.rs new file mode 100644 index 0000000000..c8627ef213 --- /dev/null +++ b/gsd/import/src/read/plan.rs @@ -0,0 +1,672 @@ +//! `NN-MM-PLAN.md` and a quick plan to a `plan` (13-RESEARCH Part B, the `NN-MM-PLAN.md` and `quick/` tables; the rows +//! are `table::sections::{PLAN, PLAN_SHARED, QUICK, QUICK_PLAN}`): the file name gives the id, the frontmatter and the +//! `<objective>`, `<context>`, `<verification>` and `<success_criteria>` elements the fields, and [`super::tasks`] the +//! tasks and must-haves, and [`super::threats`] its threat model. Every other key and element is reported with the table's reason. +//! +//! The file name wins over the frontmatter: a `phase:` or `plan:` (or a quick plan's `quick_id:`) that disagrees with it +//! is reported at its line, never used. Element bodies are cut by their literal closing tag ([`crate::xmltags`]) and +//! kept verbatim, trimmed at both ends. + +use std::collections::{BTreeMap, BTreeSet}; + +use gsd_kit::markdown; +use serde_json::{Value as Json, json}; + +use super::{Context, is_bullet, row, tasks, threats}; +use crate::frontmatter::{self, Entries, Located, Value}; +use crate::ids; +use crate::paths; +use crate::records::{Record, Records, Source}; +use crate::report::{Entry, Outcome, Report}; +use crate::sections; +use crate::xmltags::{self, Tagged}; + +/// The fate table's name of a phase plan. +pub const PL: &str = "NN-MM-PLAN.md"; + +/// A plan's `type:` values. +const PLAN_TYPES: &[&str] = &["execute", "tdd"]; + +/// The elements this reader reads or reports by name; any other element is reported as one no row names. +const ELEMENTS: &[&str] = &[ + "objective", + "execution_context", + "context", + "tasks", + "task", + "name", + "files", + "read_first", + "action", + "verify", + "automated", + "fails_when", + "done", + "acceptance_criteria", + "behavior", + "verification", + "success_criteria", + "output", + "threat_model", +]; + +/// The directory GSD keeps its own files in: a `<context>` path under it is GSD-internal. +const PLANNING: &str = ".planning/"; + +/// One served file of a plan's or a summary's format: where it is, and its rows in the fate table. +#[derive(Debug, Clone, Copy)] +pub struct Doc<'a> { + /// The served path (`.planning/phases/01-core/01-01-PLAN.md`). + pub path: &'a str, + /// The `FATES` name of its format (`NN-MM-PLAN.md`, `quick/*`). + pub format: &'static str, + /// What its keys start with in the table (`PLAN ` for a quick plan). + pub prefix: &'static str, +} + +impl Doc<'_> { + /// The 1-based `line` of the file. + pub fn at(&self, line: usize) -> Source { + Source { + file: self.path.to_string(), + line, + } + } + + /// The table's entry for its key `key`, at the 1-based `line`, in `section`. + pub fn row(&self, key: &str, line: usize, section: &str) -> Entry { + row( + self.format, + &format!("{}{key}", self.prefix), + &self.at(line), + section, + ) + } + + /// An `unmapped` entry at the 1-based `line`. + pub fn unmapped(&self, line: usize, section: &str, why: String) -> Entry { + Entry::at(&self.at(line), section, Outcome::Unmapped, why) + } +} + +/// Where a plan sits. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Scope { + /// Under the phase `number` (`01`), whose graph path is `path` (`v1.0/01`). + Phase { number: String, path: String }, + /// A quick plan: no phase, in the project's scope. + Quick, +} + +impl Scope { + /// The graph path of the plan `id`. + pub fn plan_path(&self, id: &str) -> String { + match self { + Scope::Phase { path, .. } => format!("{path}/{id}"), + Scope::Quick => id.to_string(), + } + } + + /// The `spec/gsd/` file of everything under the plan. + pub fn file(&self) -> String { + match self { + Scope::Phase { number, .. } => paths::phase(number), + Scope::Quick => paths::quick(), + } + } +} + +/// Reads the phase plan `text`, served at `path` (`rel` under `.planning/`): `phases/<NN-slug>/<NN-MM>-PLAN.md`. +pub fn read_phase( + path: &str, + rel: &str, + text: &str, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let doc = Doc { + path, + format: PL, + prefix: "", + }; + let Some((dir, id)) = in_phase(rel, "-PLAN.md").filter(|(_, id)| ids::plan(id)) else { + report.push(doc.unmapped( + 1, + "file name", + "the file name gives no plan id `NN-MM`: not imported".to_string(), + )); + return; + }; + if let Some(scope) = phase_scope(&doc, dir, id, cx, report) { + read(&doc, text, id, &scope, cx, records, report); + } +} + +/// The directory and the stem of `rel`, a file `phases/<dir>/<stem><suffix>`. +pub fn in_phase<'r>(rel: &'r str, suffix: &str) -> Option<(&'r str, &'r str)> { + let (dir, name) = rel.strip_prefix("phases/")?.split_once('/')?; + Some((dir, name.strip_suffix(suffix)?)) +} + +/// The phase of the plan `id` (`01-02`) in the directory `dir`: the file name's number wins over the directory's, and +/// a phase the roadmap does not hold imports nothing. +pub fn phase_scope( + doc: &Doc<'_>, + dir: &str, + id: &str, + cx: &Context<'_>, + report: &mut Report, +) -> Option<Scope> { + let number = id.rsplit_once('-').map_or(id, |(number, _)| number); + let named = ids::padded(dir.split_once('-').map_or(dir, |(n, _)| n)); + if named.as_deref() != Some(number) { + report.push(doc.unmapped( + 1, + "file name", + format!("the directory `{dir}` names another phase than the file name's {number}: the file name wins"), + )); + } + match cx.roadmap.phases.get(number) { + Some(path) => Some(Scope::Phase { + number: number.to_string(), + path: path.clone(), + }), + None => { + report.push(doc.unmapped( + 1, + "file name", + format!("phase {number} is no phase of ROADMAP.md: not imported"), + )); + None + } + } +} + +/// The frontmatter entries of `text` in the order written (none when it has no frontmatter, or one refused and +/// reported); and the index of the body's first line. +pub fn front(doc: &Doc<'_>, text: &str, report: &mut Report) -> (Entries, usize) { + let (front, start) = frontmatter::split(text); + match front.and_then(|f| f.map(|f| frontmatter::read(&f)).transpose()) { + Ok(front) => (front.map(|f| f.value).unwrap_or_default(), start), + Err(refused) => { + report.push(doc.unmapped( + refused.line, + "---", + format!("frontmatter not read: {}", refused.reason), + )); + (Vec::new(), start) + } + } +} + +/// A list of texts: a list's items, or one text; none for a map or a list holding one. +pub fn list(value: &Value) -> Option<Vec<String>> { + match value { + Value::Str(s) if s.trim().is_empty() => Some(Vec::new()), + Value::Str(s) => Some(vec![s.trim().to_string()]), + Value::List(items) => items + .iter() + .map(|i| i.value.as_str().map(|s| s.trim().to_string())) + .collect(), + Value::Map(_) => None, + } +} + +/// The `<name>` elements of `text`, whose first line is the file's 1-based line `base`, each at its line in the file; +/// each refusal (an unclosed element, broken attributes) is reported. +pub fn elements( + doc: &Doc<'_>, + text: &str, + base: usize, + name: &str, + report: &mut Report, +) -> Vec<Tagged> { + let (found, refused) = xmltags::tagged(text, name); + for r in refused { + report.push(doc.unmapped( + base + r.line - 1, + &format!("<{name}>"), + format!("{}: not read", r.reason), + )); + } + found + .into_iter() + .map(|t| Tagged { + line: base + t.line - 1, + ..t + }) + .collect() +} + +/// The items of an element's body: each bullet (its continuation lines joined by a line break) when it has bullets, +/// else each paragraph; every line trimmed. +pub fn items(body: &str) -> Vec<String> { + let bulleted = body.split('\n').any(is_bullet); + let mut out = Vec::new(); + let mut current: Option<String> = None; + for line in body.split('\n') { + let t = line.trim(); + if t.is_empty() { + if !bulleted { + out.extend(current.take()); + } + continue; + } + if bulleted && is_bullet(line) { + out.extend(current.take()); + current = Some(t[2..].trim().to_string()); + } else if let Some(item) = &mut current { + item.push('\n'); + item.push_str(t); + } else { + current = Some(t.to_string()); + } + } + out.extend(current); + out +} + +/// Reads the plan `text` with the id `id` (its file name's) under `scope`. +pub fn read( + doc: &Doc<'_>, + text: &str, + id: &str, + scope: &Scope, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let plan = scope.plan_path(id); + let file = scope.file(); + let mut fields: BTreeMap<String, Json> = BTreeMap::new(); + let mut refs: Vec<String> = Vec::new(); + let mut links = Vec::new(); + if let Scope::Phase { path, .. } = scope { + fields.insert("phase".to_string(), json!(path)); + refs.push(path.clone()); + } + let (front, start) = front(doc, text, report); + let mut must_haves = None; + for (key, v) in &front { + let built = (&mut fields, &mut links); + frontmatter_key(doc, (key, v), id, scope, cx, records, built, report); + if key == "must_haves" { + must_haves = Some(v); + } + } + let body = frontmatter::body(text, start); + let mut title = None; + for (n, o) in elements(doc, &body, 1, "objective", report) + .iter() + .enumerate() + { + if n > 0 { + report.push(doc.unmapped( + o.line, + "<objective>", + "a second <objective>: not read".to_string(), + )); + continue; + } + title = objective(doc, o, &mut fields, report); + } + for element in ["execution_context", "output"] { + for e in elements(doc, &body, 1, element, report) { + let key = format!("<{element}>"); + report.push(doc.row(&key, e.line, &key)); + } + } + let mut context_refs = Vec::new(); + for c in elements(doc, &body, 1, "context", report) { + context_refs.extend(context(doc, &c, report)); + } + if !context_refs.is_empty() { + fields.insert("context_refs".to_string(), json!(context_refs)); + } + for (element, field) in [ + ("verification", "verification"), + ("success_criteria", "success_criteria"), + ] { + let all: Vec<String> = elements(doc, &body, 1, element, report) + .iter() + .flat_map(|e| items(&e.body)) + .collect(); + if !all.is_empty() { + fields.insert(field.to_string(), json!(all)); + } + } + unknown_elements(doc, &body, report); + outside_elements(doc, &body, report); + let title = match (scope, cx.roadmap.plan_titles.get(id)) { + (Scope::Phase { .. }, Some(t)) => t.clone(), + (Scope::Phase { .. }, None) => { + let line = title.as_ref().map_or(1, |(_, line)| *line); + report.push(Entry::at( + &doc.at(line), + "<objective>", + Outcome::Filled, + format!("ROADMAP.md's Plans: names no title for {id}: the objective's first line is its title"), + )); + title.map_or_else(|| id.to_string(), |(t, _)| t) + } + (Scope::Quick, _) => title.map_or_else(|| id.to_string(), |(t, _)| t), + }; + records.add( + Record { + kind: "plan", + id: plan.clone(), + title, + file: file.clone(), + fields, + refs, + links, + source: doc.at(1), + }, + report, + ); + tasks::tasks(doc, &body, &plan, &file, records, report); + if let Some(v) = must_haves { + tasks::must_haves(doc, v, &plan, &file, records, report); + } + let security = cx.manifest.security; + threats::read(doc, &body, (&plan, &file), security, records, report); +} + +/// One frontmatter key of the plan `id`: a field, a cross-check, or a report entry with the table's reason. +#[allow( + clippy::too_many_arguments, + reason = "a key reads the plan's scope, the roadmap and the requirements read before it" +)] +fn frontmatter_key( + doc: &Doc<'_>, + (key, v): (&str, &Located<Value>), + id: &str, + scope: &Scope, + cx: &Context<'_>, + records: &Records, + (fields, links): ( + &mut BTreeMap<String, Json>, + &mut Vec<(&'static str, String)>, + ), + report: &mut Report, +) { + let line = v.line; + let text = v.value.as_str().map(str::trim); + let not_list = |report: &mut Report| { + report.push(doc.unmapped( + line, + key, + format!("`{key}` is not a list of text: not imported"), + )) + }; + match (key, scope) { + ("phase" | "plan", Scope::Phase { number, .. }) => { + report.push(names_file(doc, (key, v), id, number)) + } + ("quick_id", Scope::Quick) if text == Some(id) => {} + ("quick_id", Scope::Quick) => report.push(doc.unmapped( + line, + key, + format!( + "`quick_id: {}` disagrees with the file name {id}: the file name wins", + text.unwrap_or_default() + ), + )), + ("slug", Scope::Quick) => match text.filter(|t| !t.is_empty()) { + Some(slug) => { + fields.insert("slug".to_string(), json!(slug)); + } + None => report.push(doc.unmapped(line, key, "an empty slug: not imported".to_string())), + }, + ("type", _) => match text.filter(|t| PLAN_TYPES.contains(t)) { + Some(t) => { + fields.insert("type".to_string(), json!(t)); + } + None => report.push(doc.unmapped( + line, + key, + format!( + "`{}` is none of {}: not imported", + text.unwrap_or_default(), + PLAN_TYPES.join(", ") + ), + )), + }, + ("wave", Scope::Phase { .. }) => { + report.push(doc.row(key, line, key)); + if text == Some("0") { + fields.insert("wave0".to_string(), json!(true)); + } + } + ("files_modified", _) => match list(&v.value) { + Some(files) if !files.is_empty() => { + fields.insert(key.to_string(), json!(files)); + } + Some(_) => {} + None => not_list(report), + }, + ("depends_on", Scope::Phase { .. }) => { + match list(&v.value) { + Some(plans) => { + let mut kept = Vec::new(); + for p in plans { + let phase = p.rsplit_once('-').map(|(n, _)| n).filter(|_| ids::plan(&p)); + match phase.and_then(|n| cx.roadmap.phases.get(n)) { + Some(path) => kept.push(format!("{path}/{p}")), + None => report.push(doc.unmapped( + line, + key, + format!("depends_on names `{p}`, no plan of a ROADMAP.md phase: left out"), + )), + } + } + if !kept.is_empty() { + links.extend(kept.iter().map(|p| ("depends_on", p.clone()))); + fields.insert(key.to_string(), json!(kept)); + } + } + None => not_list(report), + } + } + ("requirements", Scope::Phase { .. }) => match list(&v.value) { + Some(ids) => { + let kept = defined(doc, &ids, line, key, records, report); + if !kept.is_empty() { + links.extend(kept.iter().map(|r| ("requirements", r.clone()))); + fields.insert(key.to_string(), json!(kept)); + } + } + None => not_list(report), + }, + // Read by `tasks::must_haves` once the plan's path is known. + ("must_haves", _) => {} + _ => report.push(doc.row(key, line, key)), + } +} + +/// A frontmatter `phase:` or `plan:` against the file name's plan `id` in the phase `number`: `redundant` when it agrees +/// (the `phase, plan` row), else the mismatch, at its line; the file name wins either way. +pub fn names_file( + doc: &Doc<'_>, + (key, v): (&str, &Located<Value>), + id: &str, + number: &str, +) -> Entry { + let (_, own) = id.rsplit_once('-').unwrap_or((id, id)); + let written = v.value.as_str().map_or("", str::trim); + let agrees = match key { + "phase" => { + ids::padded(written.split_once('-').map_or(written, |(n, _)| n)).as_deref() + == Some(number) + } + _ => format!("{written:0>2}") == own, + }; + if agrees { + doc.row("phase, plan", v.line, key) + } else { + doc.unmapped( + v.line, + key, + format!("`{key}: {written}` disagrees with the file name {id}: the file name wins"), + ) + } +} + +/// The requirement ids a list may keep: the ones REQUIREMENTS.md defined (read before every plan), each other one +/// reported and left out, as the roadmap leaves it out of a phase. +pub fn defined( + doc: &Doc<'_>, + ids: &[String], + line: usize, + key: &str, + records: &Records, + report: &mut Report, +) -> Vec<String> { + let mut kept = Vec::new(); + for id in ids { + if records.contains("requirement", id) { + kept.push(id.clone()); + } else { + report.push(doc.unmapped( + line, + key, + format!("`{key}` names {id}, which REQUIREMENTS.md does not define: left out"), + )); + } + } + kept +} + +/// The objective's fields: its first paragraph, `Purpose:` and `Output:`; the first line of that paragraph less its +/// final period (the title of a plan the roadmap names no title for) and that line's number. +fn objective( + doc: &Doc<'_>, + o: &Tagged, + fields: &mut BTreeMap<String, Json>, + report: &mut Report, +) -> Option<(String, usize)> { + let mut first: Vec<&str> = Vec::new(); + let (mut first_line, mut past_first, mut extra) = (o.line, false, false); + for (i, raw) in o.body.split('\n').enumerate() { + let t = raw.trim(); + let line = o.line + i; + if let Some(rest) = t.strip_prefix("Purpose:") { + fields.insert("purpose".to_string(), json!(rest.trim())); + } else if let Some(rest) = t.strip_prefix("Output:") { + fields.insert("output".to_string(), json!(rest.trim())); + } else if t.is_empty() { + past_first |= !first.is_empty(); + } else if !past_first { + if first.is_empty() { + first_line = line; + } + first.push(t); + } else if !extra { + extra = true; + report.push(doc.unmapped( + line, + "<objective>", + "the objective's text past its first paragraph: no field holds it".to_string(), + )); + } + } + let head = first.first()?; + fields.insert("objective".to_string(), json!(first.join("\n"))); + Some(( + head.strip_suffix('.').unwrap_or(head).trim().to_string(), + first_line, + )) +} + +/// The `@` paths of a `<context>` element: a path under `.planning/` is GSD's own and reported, the others kept. +fn context(doc: &Doc<'_>, c: &Tagged, report: &mut Report) -> Vec<String> { + let mut kept = Vec::new(); + for (i, raw) in c.body.split('\n').enumerate() { + let line = c.line + i; + let t = raw.trim(); + match t.strip_prefix('@').map(str::trim) { + _ if t.is_empty() => {} + Some(path) if path.starts_with(PLANNING) => { + report.push(doc.row("<context> @.planning/", line, "<context>")); + } + Some(path) if !path.is_empty() => kept.push(path.to_string()), + _ => report.push(doc.unmapped( + line, + "<context>", + "a <context> line that names no @path: no field holds it".to_string(), + )), + } + } + kept +} + +/// The element name a raw line opens with (`<task type="auto">` is `task`), if any. +fn element_name(raw: &str) -> Option<String> { + let rest = raw.trim_start().strip_prefix('<')?; + let name: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-')) + .collect(); + (!name.is_empty()).then_some(name) +} + +/// Reports each element outside a fence whose name this reader neither reads nor reports. +fn unknown_elements(doc: &Doc<'_>, body: &str, report: &mut Report) { + let fenced = sections::fenced(body); + for (n, raw) in body.split('\n').enumerate() { + let Some(name) = element_name(raw) else { + continue; + }; + if !fenced[n] && !ELEMENTS.contains(&name.as_str()) { + let key = format!("<{name}>"); + report.push(doc.row(&key, n + 1, &key)); + } + } +} + +/// Reports each Markdown block outside every element (a `## Notes` heading, the prose under it, a `# Plan 01-01` +/// title): a plan's fields are its frontmatter and its elements, so no field holds it. An unclosed element, refused at +/// its line, holds every line after it. +fn outside_elements(doc: &Doc<'_>, body: &str, report: &mut Report) { + let fenced = sections::fenced(body); + let mut inside = vec![false; fenced.len()]; + let names: BTreeSet<String> = body + .split('\n') + .enumerate() + .filter(|(n, _)| !fenced[*n]) + .filter_map(|(_, raw)| element_name(raw)) + .collect(); + for name in names { + let (found, refused) = xmltags::tagged(body, &name); + for e in found { + let first = e.line - 1; + let last = (first + e.body.matches('\n').count()).min(inside.len() - 1); + inside[first..=last].fill(true); + } + for r in refused + .iter() + .filter(|r| r.reason.contains("is not closed")) + { + inside[r.line - 1..].fill(true); + } + } + let headings: BTreeMap<usize, String> = markdown::headings(body) + .into_iter() + .map(|h| (h.line, h.text)) + .collect(); + for b in markdown::inline_blocks(body) { + let first = b.lines[0]; + if inside.get(first).copied().unwrap_or(true) { + continue; + } + let section = headings + .get(&first) + .map_or("outside every element", String::as_str); + report.push(doc.unmapped( + first + 1, + section, + "text outside every element of the plan: no field holds it".to_string(), + )); + } +} diff --git a/gsd/import/src/read/project.rs b/gsd/import/src/read/project.rs new file mode 100644 index 0000000000..86b324f767 --- /dev/null +++ b/gsd/import/src/read/project.rs @@ -0,0 +1,351 @@ +//! `PROJECT.md` to the `project` and its decisions (13-RESEARCH Part B, the `PROJECT.md` table; the rows are +//! `table::sections::PROJECT`): `# Name` gives the project's name and id, its prose sections their fields, `### Out of +//! Scope` and `## Constraints` their bullets as blocks, and each `## Key Decisions` row one `decision D-<NN>`. + +use std::collections::BTreeMap; +use std::ops::Range; + +use gsd_kit::markdown::{self, InlineBlock}; +use serde_json::{Value, json}; + +use super::{Rest, blocks_in, is_bullet, mapped, own, prose, row, slug}; +use crate::ids; +use crate::paths; +use crate::records::{Record, Records, Source}; +use crate::report::{Entry, Outcome, Report}; +use crate::sections::{self, Section}; + +const P: &str = "PROJECT.md"; + +/// A constraint's `kind` values (`@gsd/core`'s `project.constraints.kind`). +const CONSTRAINT_KINDS: &[&str] = &[ + "tech_stack", + "timeline", + "budget", + "dependencies", + "compatibility", + "performance", + "security", + "other", +]; + +/// What a section no row names becomes. +const UNKNOWN: &str = "a section no row of the PROJECT.md table names: no field holds it"; + +/// Reads `text`, served at `path`. +pub fn read(path: &str, text: &str, records: &mut Records, report: &mut Report) { + let lines: Vec<&str> = text.split('\n').map(|l| l.trim_end_matches('\r')).collect(); + let fenced = sections::fenced(text); + let blocks = markdown::inline_blocks(text); + let at = |line: usize| Source { + file: path.to_string(), + line: line + 1, + }; + let mut name: Option<(String, usize)> = None; + let mut fields: BTreeMap<String, Value> = BTreeMap::new(); + let mut decisions: Vec<String> = Vec::new(); + // A section reported whole covers its sub-sections. + let mut covered = 0..0; + let mut rest = Rest::default(); + let all = sections::sections(text); + for s in all.iter().cloned() { + if covered.contains(&s.line) { + continue; + } + // What the section holds itself: a sub-section is read under its own heading. + let mine = Section { + body: own(&s, &all), + ..s.clone() + }; + let to = |what: &str, report: &mut Report| report.push(mapped(&at(s.line), &s.title, what)); + let prose_of = |field: &str, fields: &mut BTreeMap<String, Value>, report: &mut Report| { + to(&format!("project.{field}"), report); + if let Some(text) = prose(&blocks, &mine.body) { + fields.insert(field.to_string(), json!(text)); + } + }; + match (s.level, s.title.as_str()) { + (1, title) if name.is_none() => { + // A tagline under the name is no field's. + rest.section(mine.body.clone(), title); + name = Some((title.to_string(), s.line)); + } + (2, "What This Is") => prose_of("what", &mut fields, report), + (2, "Core Value") => prose_of("core_value", &mut fields, report), + (2, "Context") => prose_of("context", &mut fields, report), + (2, "Requirements") => report.push(row(P, "## Requirements", &at(s.line), &s.title)), + (3, "Validated" | "Active") => { + let key = format!("### {}", s.title); + report.push(row(P, &key, &at(s.line), &s.title)); + for b in blocks_in(&blocks, &s.body).filter(|b| b.text.starts_with("(None yet")) { + report.push(row(P, "(None yet", &at(b.lines[0]), &s.title)); + } + } + (3, "Out of Scope") => { + to("project.out_of_scope", report); + rest.section(mine.body.clone(), &s.title); + for (b, _) in bullets(&blocks, &lines, &mine.body) { + rest.take_block(b); + } + let items = out_of_scope(&mine, &blocks, &lines, &at, report); + if !items.is_empty() { + fields.insert("out_of_scope".to_string(), json!(items)); + } + } + (2, "Constraints") => { + to("project.constraints", report); + rest.section(mine.body.clone(), &s.title); + for (b, _) in bullets(&blocks, &lines, &mine.body) { + rest.take_block(b); + } + let items = constraints(&mine, &blocks, &lines, &at, report); + if !items.is_empty() { + fields.insert("constraints".to_string(), json!(items)); + } + } + (2, "Key Decisions") => { + to("each row a decision", report); + rest.section(mine.body.clone(), &s.title); + for t in markdown::tables(text) + .iter() + .filter(|t| mine.body.contains(&t.line)) + { + rest.take_table(t); + } + decisions = key_decisions(text, &mine.body, &at, records, report); + } + (2, "Business Context" | "Current Milestone") => { + covered = s.body.clone(); + let key = format!("## {}", s.title); + report.push(row(P, &key, &at(s.line), &s.title)); + } + _ => { + // A second `# ...` is reported, never a cover over the sections after it. + if s.level > 1 { + covered = s.body.clone(); + } + report.push(Entry::at( + &at(s.line), + &s.title, + Outcome::Unmapped, + UNKNOWN.to_string(), + )); + } + } + } + for (n, line) in lines.iter().enumerate() { + if !fenced[n] && line.starts_with("*Last updated") { + report.push(row(P, "*Last updated:", &at(n), "*Last updated:")); + } + } + rest.report(path, text, P, report); + let Some((name, line)) = name else { + report.push(Entry::at( + &at(0), + "# Name", + Outcome::Unmapped, + "no `# Name` heading names the project: it is not imported".to_string(), + )); + return; + }; + let id = slug(&name); + if !ids::name(&id) { + report.push(Entry::at( + &at(line), + "# Name", + Outcome::Unmapped, + format!("the project's name `{name}` gives no id: it is not imported"), + )); + return; + } + fields.insert("name".to_string(), json!(name)); + if !decisions.is_empty() { + fields.insert("key_decisions".to_string(), json!(decisions)); + } + records.add( + Record { + kind: "project", + id, + title: name, + file: paths::project(), + fields, + refs: Vec::new(), + links: decisions + .into_iter() + .map(|d| ("key_decisions", d)) + .collect(), + source: at(line), + }, + report, + ); +} + +/// The bullets of `body`: each leaf block that a raw list marker starts, with whether its text opens with a bold label. +fn bullets<'b>( + blocks: &'b [InlineBlock], + lines: &[&str], + body: &Range<usize>, +) -> Vec<(&'b InlineBlock, bool)> { + blocks_in(blocks, body) + .filter_map(|b| { + let raw = lines.get(b.lines[0])?; + is_bullet(raw).then(|| (b, raw.trim_start()[2..].trim_start().starts_with("**"))) + }) + .collect() +} + +/// `### Out of Scope` bullets `- item — why` as `{item, why}` blocks; a bullet with no ` — ` is reported. +fn out_of_scope( + s: &Section, + blocks: &[InlineBlock], + lines: &[&str], + at: &dyn Fn(usize) -> Source, + report: &mut Report, +) -> Vec<Value> { + let mut items = Vec::new(); + for (b, _) in bullets(blocks, lines, &s.body) { + match b.text.split_once(" — ") { + Some((item, why)) if !item.trim().is_empty() && !why.trim().is_empty() => { + items.push(json!({"item": item.trim(), "why": why.trim()})); + } + _ => report.push(Entry::at( + &at(b.lines[0]), + &s.title, + Outcome::Unmapped, + "an Out of Scope item needs a reason (`- item — why`): not imported".to_string(), + )), + } + } + items +} + +/// `## Constraints` bullets `- **Label**: what — why` as `{kind, what, why}` blocks: the label lower-cased with `_` +/// for spaces is the kind; a label that names no kind, or none, is `other` with the label kept in `what`, reported. +fn constraints( + s: &Section, + blocks: &[InlineBlock], + lines: &[&str], + at: &dyn Fn(usize) -> Source, + report: &mut Report, +) -> Vec<Value> { + let mut items = Vec::new(); + for (b, bold) in bullets(blocks, lines, &s.body) { + let text = b.text.trim(); + let labelled = bold.then(|| text.split_once(':')).flatten(); + let (kind, rest) = match labelled { + Some((label, rest)) => (label.trim().to_lowercase().replace(' ', "_"), rest.trim()), + None => (String::new(), text), + }; + let (what, why) = match rest.split_once(" — ") { + Some((what, why)) => (what.trim(), Some(why.trim())), + None => (rest, None), + }; + let mut block = if CONSTRAINT_KINDS.contains(&kind.as_str()) { + json!({"kind": kind, "what": what}) + } else { + report.push(row(P, "## Constraints", &at(b.lines[0]), &s.title)); + let what = match labelled { + Some((label, _)) => format!("{}: {what}", label.trim()), + None => what.to_string(), + }; + json!({"kind": "other", "what": what}) + }; + if let Some(why) = why.filter(|w| !w.is_empty()) { + block["why"] = json!(why); + } + items.push(block); + } + items +} + +/// Each `## Key Decisions` row as `decision D-<NN>` (row order, from 01), origin `project`; their ids. +fn key_decisions( + text: &str, + body: &Range<usize>, + at: &dyn Fn(usize) -> Source, + records: &mut Records, + report: &mut Report, +) -> Vec<String> { + let mut ids = Vec::new(); + for table in markdown::tables(text) + .into_iter() + .filter(|t| body.contains(&t.line)) + { + let column = |name: &str, or: usize| { + table + .header + .iter() + .position(|h| h.eq_ignore_ascii_case(name)) + .unwrap_or(or) + }; + let (decision, rationale, outcome) = ( + column("Decision", 0), + column("Rationale", 1), + column("Outcome", 2), + ); + report.push(row(P, "## Key Decisions", &at(table.line), "Key Decisions")); + for (i, cells) in table.rows.iter().enumerate() { + // The header and the delimiter row come first. + let source = at(table.line + 2 + i); + let cell = |i: usize| cells.get(i).map(|c| c.trim()).unwrap_or_default(); + if cell(decision).is_empty() { + report.push(Entry::at( + &source, + "Key Decisions", + Outcome::Unmapped, + "a Key Decisions row with no decision: not imported".to_string(), + )); + continue; + } + let id = format!("D-{:02}", ids.len() + 1); + let mut fields = BTreeMap::from([ + ("text".to_string(), json!(cell(decision))), + ("origin".to_string(), json!("project")), + ]); + if !cell(rationale).is_empty() { + fields.insert("rationale".to_string(), json!(cell(rationale))); + } + match outcome_of(cell(outcome)) { + Some(word) => { + fields.insert("outcome".to_string(), json!(word)); + } + None if cell(outcome).is_empty() => {} + None => report.push(Entry::at( + &source, + "Key Decisions", + Outcome::Unmapped, + format!( + "decision {id}: the outcome `{}` is none of Good, Revisit, Pending: imported without one", + cell(outcome) + ), + )), + } + records.add( + Record { + kind: "decision", + id: id.clone(), + title: cell(decision).to_string(), + file: paths::project(), + fields, + refs: Vec::new(), + links: Vec::new(), + source, + }, + report, + ); + ids.push(id); + } + } + ids +} + +/// `— Pending`, `✓ Good`, `⚠️ Revisit` as `pending`, `good`, `revisit`. +fn outcome_of(cell: &str) -> Option<&'static str> { + let word = cell + .trim_start_matches(|c: char| !c.is_alphanumeric()) + .trim() + .to_lowercase(); + ["pending", "good", "revisit"] + .into_iter() + .find(|w| *w == word) +} diff --git a/gsd/import/src/read/quick.rs b/gsd/import/src/read/quick.rs new file mode 100644 index 0000000000..ba0756ce82 --- /dev/null +++ b/gsd/import/src/read/quick.rs @@ -0,0 +1,61 @@ +//! A `quick/<id>-<slug>/` directory (13-RESEARCH Part B, the `quick/` table; the rows are +//! `table::sections::{QUICK, QUICK_PLAN, QUICK_SUMMARY}`): `<id>-PLAN.md` is a plan with no phase, read by +//! [`super::plan`] with [`Scope::Quick`] (its id the file name's, which its `quick_id` repeats); `<id>-SUMMARY.md` its +//! summary, read by [`super::summary`]; a quick `CONTEXT.md` or `RESEARCH.md` is Tier 2 and reported whole. + +use super::plan::{self, Doc, Scope}; +use super::{Context, row, summary}; +use crate::ids; +use crate::records::{Records, Source}; +use crate::report::{Entry, Outcome, Report}; + +/// The fate table's name of a quick directory's files. +pub const QK: &str = "quick/*"; + +/// Reads the file `text` of a quick directory, served at `path` (`rel` under `.planning/`). +pub fn read( + path: &str, + rel: &str, + text: &str, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let (dir, name) = rel.rsplit_once('/').unwrap_or(("", rel)); + let doc = |prefix| Doc { + path, + format: QK, + prefix, + }; + let stem = |suffix: &str| name.strip_suffix(suffix).filter(|id| ids::quick(id)); + if let Some(id) = stem("-PLAN.md") { + plan::read(&doc("PLAN "), text, id, &Scope::Quick, cx, records, report); + } else if let Some(id) = stem("-SUMMARY.md") { + let doc = doc("SUMMARY "); + if summary::has_plan(cx, &format!("{dir}/{id}-PLAN.md"), &doc, report) { + summary::read(&doc, text, id, &Scope::Quick, cx, records, report); + } + } else if let Some(key) = ["CONTEXT", "RESEARCH"] + .into_iter() + .find(|k| name.ends_with(&format!("-{k}.md"))) + { + let mut entry = row( + QK, + key, + &Source { + file: path.to_string(), + line: 1, + }, + "", + ); + entry.line = None; + report.push(entry); + } else { + report.push(Entry::file( + path, + Outcome::Unmapped, + "a file of a quick directory that is no `<YYMMDD-id>-PLAN.md`, SUMMARY, CONTEXT or RESEARCH: no row names it" + .to_string(), + )); + } +} diff --git a/gsd/import/src/read/requirements.rs b/gsd/import/src/read/requirements.rs new file mode 100644 index 0000000000..061e40fd43 --- /dev/null +++ b/gsd/import/src/read/requirements.rs @@ -0,0 +1,327 @@ +//! `REQUIREMENTS.md` to `requirement` records (13-RESEARCH Part B, the `REQUIREMENTS.md` table): the `## v1`, `## v2` +//! and `## Out of Scope` sections give the tier, `### Category` the category, each `**ID**: text` bullet one +//! requirement, and each row of the Out of Scope table one `OOS-<NN>` requirement, whose id the import mints. + +use std::collections::BTreeMap; + +use gsd_kit::markdown; +use serde_json::{Value, json}; + +use super::{Rest, is_date, is_footer, mapped, own, row}; +use crate::paths; +use crate::records::{Record, Records, Source}; +use crate::report::{Entry, Outcome, Report}; +use crate::sections::{self, Section}; + +const OUT_OF_SCOPE: &str = "Out of Scope"; + +const RQ: &str = "REQUIREMENTS.md"; + +/// What a section no row names becomes. +const UNKNOWN: &str = "a section no row of the REQUIREMENTS.md table names: not imported"; + +/// Reads `text`, served at `path`. +pub fn read(path: &str, text: &str, records: &mut Records, report: &mut Report) { + let lines: Vec<&str> = text.split('\n').map(|l| l.trim_end_matches('\r')).collect(); + let fenced = sections::fenced(text); + // The family's one Markdown reader: a `#` line in a fence or a comment is no heading, `##\t` and setext are. + let all = sections::sections(text); + let headings: BTreeMap<usize, &Section> = all.iter().map(|s| (s.line, s)).collect(); + let mut rest = Rest::default(); + let at = |line: usize| Source { + file: path.to_string(), + line: line + 1, + }; + let defined = defined(&lines, &at, report); + let mut section = String::new(); + let mut tier: Option<&'static str> = None; + let mut category: Option<String> = None; + let mut checkboxes = false; + let mut i = 0; + while i < lines.len() { + let line = lines[i]; + let n = i; + i += 1; + if fenced[n] { + continue; + } + if let Some(s) = headings.get(&n) { + let title = s.title.trim(); + // What a mapped heading holds itself is read below, and what no line takes is reported. + if s.level == 1 || s.level == 3 || tier_of(title).is_some() { + rest.section(own(s, &all), title); + } + match s.level { + 1 => report.push(Entry::at( + &at(n), + title, + Outcome::Redundant, + "PROJECT.md's title names the project".to_string(), + )), + 2 => { + section = title.to_string(); + category = None; + tier = tier_of(§ion); + let entry = match tier { + _ if section == "Traceability" => Entry::at( + &at(n), + §ion, + Outcome::Redundant, + "ROADMAP.md's **Requirements** lines give each phase's requirements" + .to_string(), + ), + Some(tier) => mapped(&at(n), §ion, &format!("requirement.tier {tier}")), + None => Entry::at(&at(n), §ion, Outcome::Unmapped, UNKNOWN.to_string()), + }; + report.push(entry); + } + 3 => { + category = Some(title.to_string()); + report.push(mapped(&at(n), title, "requirement.category")); + } + _ => report.push(Entry::at( + &at(n), + title, + Outcome::Unmapped, + UNKNOWN.to_string(), + )), + } + continue; + } + if line.starts_with("**Defined:**") { + rest.take(n); + } else if let Some(key) = ["*Requirements defined:", "*Last updated:"] + .into_iter() + .find(|k| is_footer(line) && line.starts_with(k)) + { + report.push(row(RQ, key, &at(n), §ion)); + } else if line.starts_with("**Core Value:**") { + report.push(Entry::at( + &at(n), + "Core Value", + Outcome::Redundant, + "PROJECT.md's ## Core Value gives it".to_string(), + )); + } else if line.starts_with("**Coverage:**") { + report.push(Entry::at( + &at(n), + §ion, + Outcome::Redundant, + "the coverage counts follow from the roadmap's requirements".to_string(), + )); + } else if let Some(tier) = tier.filter(|t| *t != "out_of_scope") { + let Some(item) = bullet(line) else { + continue; + }; + rest.take(n); + // A bullet's text runs on over its indented lines. + let mut words = vec![item.text.to_string()]; + while i < lines.len() + && !fenced[i] + && lines[i].starts_with([' ', '\t']) + && !lines[i].trim().is_empty() + && bullet(lines[i]).is_none() + { + words.push(lines[i].trim().to_string()); + rest.take(i); + i += 1; + } + let text = words.join(" ").trim().to_string(); + if item.checkbox && !checkboxes { + checkboxes = true; + report.push(Entry::at( + &at(n), + §ion, + Outcome::Computed, + "a requirement's checkbox is requirement.status, computed from plans, summaries and verifications" + .to_string(), + )); + } + let Some(category) = &category else { + report.push(Entry::at( + &at(n), + §ion, + Outcome::Unmapped, + format!( + "requirement {} has no ### category above it: not imported", + item.id + ), + )); + continue; + }; + if text.is_empty() { + report.push(Entry::at( + &at(n), + category, + Outcome::Unmapped, + format!("requirement {} has no text: not imported", item.id), + )); + continue; + } + let mut fields = BTreeMap::from([ + ("text".to_string(), json!(text)), + ("category".to_string(), json!(category)), + ("tier".to_string(), json!(tier)), + ]); + add_defined(&mut fields, defined); + records.add( + Record { + kind: "requirement", + id: item.id.to_string(), + title: text, + file: paths::requirements(), + fields, + refs: Vec::new(), + links: Vec::new(), + source: at(n), + }, + report, + ); + } + } + out_of_scope(text, defined, &at, &mut rest, records, report); + rest.report(path, text, RQ, report); +} + +/// The `**Defined:**` date, if the file gives one; a value that is no date is reported. +fn defined<'a>( + lines: &[&'a str], + at: &dyn Fn(usize) -> Source, + report: &mut Report, +) -> Option<&'a str> { + let (n, value) = lines + .iter() + .enumerate() + .find_map(|(n, l)| Some((n, l.strip_prefix("**Defined:**")?.trim())))?; + if is_date(value) { + return Some(value); + } + report.push(Entry::at( + &at(n), + "Defined", + Outcome::Unmapped, + "**Defined:** is not a YYYY-MM-DD date: no requirement gets one".to_string(), + )); + None +} + +fn add_defined(fields: &mut BTreeMap<String, Value>, defined: Option<&str>) { + if let Some(date) = defined { + fields.insert("defined".to_string(), json!(date)); + } +} + +/// The tier a `## ` heading names. +fn tier_of(heading: &str) -> Option<&'static str> { + if heading.starts_with("v1") { + Some("v1") + } else if heading.starts_with("v2") { + Some("v2") + } else if heading == OUT_OF_SCOPE { + Some("out_of_scope") + } else { + None + } +} + +/// A requirement bullet: `- [x] **ID**: text`, `- **ID**: text` or `- **ID:** text`. +struct Bullet<'a> { + checkbox: bool, + id: &'a str, + text: &'a str, +} + +fn bullet(line: &str) -> Option<Bullet<'_>> { + let rest = line.trim_start(); + let rest = rest + .strip_prefix("- ") + .or_else(|| rest.strip_prefix("* "))?; + let (checkbox, rest) = match ["[x] ", "[X] ", "[ ] "] + .iter() + .find_map(|b| rest.strip_prefix(b)) + { + Some(rest) => (true, rest), + None => (false, rest), + }; + let (id, after) = rest.strip_prefix("**")?.split_once("**")?; + let (id, text) = match id.strip_suffix(':') { + Some(id) => (id, after), + None => (id, after.strip_prefix(':')?), + }; + Some(Bullet { + checkbox, + id: id.trim(), + text: text.trim(), + }) +} + +/// Each row of a table under `## Out of Scope`: a requirement `OOS-<NN>` in row order, its id `filled`. +fn out_of_scope( + text: &str, + defined: Option<&str>, + at: &dyn Fn(usize) -> Source, + rest: &mut Rest, + records: &mut Records, + report: &mut Report, +) { + let mut n = 0; + for table in markdown::tables(text) + .into_iter() + .filter(|t| t.heading == OUT_OF_SCOPE) + { + let column = |name: &str, or: usize| { + table + .header + .iter() + .position(|h| h.eq_ignore_ascii_case(name)) + .unwrap_or(or) + }; + let (feature, reason) = (column("Feature", 0), column("Reason", 1)); + // The header, the delimiter row and every row: each row is a requirement or reported. + rest.take_table(&table); + for (row_index, row) in table.rows.iter().enumerate() { + // The header and the delimiter row come first. + let source = at(table.line + 2 + row_index); + let cell = |i: usize| row.get(i).map(|c| c.trim()).unwrap_or_default(); + if cell(feature).is_empty() { + report.push(Entry::at( + &source, + OUT_OF_SCOPE, + Outcome::Unmapped, + "an Out of Scope row with no feature: not imported".to_string(), + )); + continue; + } + n += 1; + let id = format!("OOS-{n:02}"); + let mut fields = BTreeMap::from([ + ("text".to_string(), json!(cell(feature))), + ("category".to_string(), json!(OUT_OF_SCOPE)), + ("tier".to_string(), json!("out_of_scope")), + ]); + if !cell(reason).is_empty() { + fields.insert("reason".to_string(), json!(cell(reason))); + } + add_defined(&mut fields, defined); + report.push(Entry::at( + &source, + OUT_OF_SCOPE, + Outcome::Filled, + format!("requirement {id}: GSD gives an Out of Scope row no id, so the import numbers the rows"), + )); + records.add( + Record { + kind: "requirement", + id, + title: cell(feature).to_string(), + file: paths::requirements(), + fields, + refs: Vec::new(), + links: Vec::new(), + source, + }, + report, + ); + } + } +} diff --git a/gsd/import/src/read/research.rs b/gsd/import/src/read/research.rs new file mode 100644 index 0000000000..e5c79714b9 --- /dev/null +++ b/gsd/import/src/read/research.rs @@ -0,0 +1,705 @@ +//! `NN-RESEARCH.md` to a `research` and its items (13-RESEARCH Part B, the RESEARCH rows; the rows are +//! `table::sections::RESEARCH`): the file stem is its id; the primary recommendation a `finding F1`; the Standard +//! Stack rows `stack_choice SC<n>`; each `### Pattern N:` and Anti-Patterns bullet a `pattern P<n>`; the Don't +//! Hand-Roll rows `dont_hand_roll DH<n>`; each `### Pitfall N:` a `pitfall PF<n>`; each Open Questions item an +//! `open_question OQ<n>`; each Sources bullet a `source SRC<n>`, all scoped by the research. A decision the research +//! names (`user_constraints`, `resolved_by`) is one of the phase's CONTEXT.md, read before it; another is left out and +//! reported. The package-legitimacy table is reported and its `legitimacy` (a verdict) never written. + +use std::collections::BTreeMap; + +use gsd_kit::markdown::{self, Table}; +use serde_json::{Value, json}; + +use super::context::{Text, discretion}; +use super::{ + Context, PhaseFile, Rest, blocks_in, bullets_in, is_date, is_footer, labelled, own, phase_file, + prose, +}; +use crate::ids; +use crate::records::{Record, Records}; +use crate::report::Report; +use crate::sections::{self, Section}; + +/// The fate table's name of a phase research. +pub const RS: &str = "NN-RESEARCH.md"; + +const UNKNOWN: &str = "a section no row of the NN-RESEARCH.md table names: no field holds it"; +const CONFIDENCE: &[&str] = &["high", "medium", "low"]; +const RECOMMENDATION: &str = "Primary recommendation:"; + +const CONSTRAINTS: &str = "User Constraints"; +const STACK: &str = "Standard Stack"; +const PATTERNS: &str = "Architecture Patterns"; +const PITFALLS: &str = "Common Pitfalls"; +const SOURCES: &str = "Sources"; + +/// What one research file gives its items: its phase file, its path, its confidence, and each id prefix's last number. +struct Items<'f, 'a> { + f: &'f PhaseFile<'a>, + research: String, + confidence: Option<String>, + numbers: BTreeMap<&'static str, usize>, + /// What the research's sections leave: each item's lines are taken. + rest: Rest, +} + +impl Items<'_, '_> { + /// The record of the next item `kind <prefix><n>` of the research, in document order from 1. + fn next( + &mut self, + (kind, prefix): (&'static str, &'static str), + title: &str, + fields: BTreeMap<String, Value>, + line: usize, + ) -> Record { + let n = self.numbers.entry(prefix).or_default(); + *n += 1; + let id = format!("{prefix}{n}"); + self.f + .within(kind, ("research", &self.research), &id, title, fields, line) + } + + /// Adds the next item `kind <prefix><n>`. + fn add( + &mut self, + kind: (&'static str, &'static str), + title: &str, + fields: BTreeMap<String, Value>, + line: usize, + records: &mut Records, + report: &mut Report, + ) { + let record = self.next(kind, title, fields, line); + records.add(record, report); + } +} + +const FINDING: (&str, &str) = ("finding", "F"); +const STACK_CHOICE: (&str, &str) = ("stack_choice", "SC"); +const PATTERN: (&str, &str) = ("pattern", "P"); +const DONT: (&str, &str) = ("dont_hand_roll", "DH"); +const PITFALL: (&str, &str) = ("pitfall", "PF"); +const QUESTION: (&str, &str) = ("open_question", "OQ"); +const SOURCE: (&str, &str) = ("source", "SRC"); + +/// Reads the research `text`, served at `path` (`rel` under `.planning/`): `phases/<NN-slug>/<NN>-RESEARCH.md`. +pub fn read( + path: &str, + rel: &str, + text: &str, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let Some(f) = phase_file(path, rel, RS, cx, report) else { + return; + }; + let t = Text::new(text); + let all = sections::sections(text); + let tables = markdown::tables(text); + let mut fields: BTreeMap<String, Value> = BTreeMap::new(); + let mut links = Vec::new(); + let mut rest = Rest::default(); + // The header: the lines before the first `##`. + let first = all + .iter() + .find(|s| s.level == 2) + .map_or(t.lines.len(), |s| s.line); + for (n, line) in t.raw() { + let value = |label: &str| line.strip_prefix(label).map(str::trim); + let header = n < first + && ["**Researched:**", "**Domain:**", "**Confidence:**"] + .iter() + .any(|l| line.starts_with(l)); + if header { + rest.take(n); + } + if n < first + && let Some(v) = value("**Researched:**") + { + if is_date(v) { + fields.insert("researched".to_string(), json!(v)); + } else { + report.push(f.unmapped( + n, + "Researched", + "**Researched:** is not a YYYY-MM-DD date: left out".to_string(), + )); + } + } else if n < first + && let Some(v) = value("**Domain:**").filter(|v| !v.is_empty()) + { + fields.insert("domain".to_string(), json!(v)); + } else if n < first + && let Some(v) = value("**Confidence:**") + { + let word = v.to_lowercase(); + if CONFIDENCE.contains(&word.as_str()) { + fields.insert("confidence".to_string(), json!(word)); + } else { + report.push(f.unmapped( + n, + "Confidence", + format!("`{v}` is none of high, medium, low: left out"), + )); + } + } else if is_footer(line) { + report.push(f.row("footer", n, "footer")); + } + } + let mut items = Items { + f: &f, + research: format!("{}/{}", f.phase, f.stem), + confidence: fields + .get("confidence") + .and_then(Value::as_str) + .map(str::to_string), + numbers: BTreeMap::new(), + rest, + }; + let mut title = None; + let mut parent = String::new(); + let mut covered = 0..0; + for s in &all { + if covered.contains(&s.line) { + continue; + } + if s.level <= 2 { + parent = s.title.clone(); + } + let in_parent = |name: &str| parent.starts_with(name); + let (level, title_) = (s.level, s.title.as_str()); + let mine = own(s, &all); + if level == 1 { + if title.is_none() { + items.rest.section(mine, title_); + title = Some(s.title.clone()); + } else { + report.push(f.unmapped(s.line, title_, UNKNOWN.to_string())); + } + } else if level == 2 + && [CONSTRAINTS, STACK, PATTERNS, PITFALLS, SOURCES] + .iter() + .any(|c| title_.starts_with(c)) + { + items.rest.section(mine, title_); + report.push(f.mapped(s.line, title_, "each ### section under it")); + } else if level == 3 && in_parent(CONSTRAINTS) && title_ == "Locked Decisions" { + report.push(f.mapped(s.line, title_, "research.user_constraints")); + items.rest.section(mine.clone(), title_); + for b in bullets_in(&t.blocks, &t.lines, &mine) { + items.rest.take_block(b); + } + let named = locked(&f, &t, s, records, report); + if !named.is_empty() { + links.extend(named.iter().map(|d| ("user_constraints", d.clone()))); + fields.insert("user_constraints".to_string(), json!(named)); + } + } else if level == 3 && in_parent(CONSTRAINTS) && discretion(title_) { + report.push(f.row("<user_constraints> ### Claude's Discretion", s.line, title_)); + } else if level == 3 && in_parent(CONSTRAINTS) && title_.starts_with("Deferred Ideas") { + report.push(f.row("<user_constraints> ### Deferred Ideas", s.line, title_)); + } else if level == 2 && title_ == "Architectural Responsibility Map" { + report.push(f.mapped(s.line, title_, "research.responsibility_map")); + items.rest.section(mine, title_); + if let Some(table) = table_in(s, &tables) { + items.rest.take_table(table); + } + let map = responsibility_map(&f, s, &tables, report); + if !map.is_empty() { + fields.insert("responsibility_map".to_string(), json!(map)); + } + } else if level == 2 && title_ == "Summary" { + report.push(f.mapped(s.line, title_, "research.summary and its findings")); + // What the section holds itself: a sub-section is read under its own heading. + let mine = Section { + body: mine, + ..s.clone() + }; + summary(&mut items, &t, &mine, &mut fields, records, report); + } else if level == 3 + && in_parent(STACK) + && let Some(tier) = tier_of(title_) + { + report.push(f.mapped(s.line, title_, "each row a stack_choice")); + items.rest.section(mine, title_); + stack(&mut items, s, tier, &tables, records, report); + } else if level == 3 && in_parent(PATTERNS) && numbered(title_, "Pattern").is_some() { + report.push(f.mapped(s.line, title_, "a pattern")); + items.rest.section(mine, title_); + pattern(&mut items, &t, s, text, records, report); + } else if level == 3 && in_parent(PATTERNS) && title_ == "Anti-Patterns to Avoid" { + report.push(f.mapped(s.line, title_, "each bullet an anti-pattern")); + items.rest.section(mine, title_); + anti_patterns(&mut items, &t, s, records, report); + } else if level == 2 && matches!(title_, "Don't Hand-Roll" | "Don’t Hand-Roll") { + report.push(f.mapped(s.line, title_, "each row a dont_hand_roll")); + items.rest.section(mine, title_); + dont_hand_roll(&mut items, s, &tables, records, report); + } else if level == 3 + && in_parent(PITFALLS) + && let Some(name) = numbered(title_, "Pitfall") + { + report.push(f.mapped(s.line, title_, "a pitfall")); + items.rest.section(mine, title_); + pitfall(&mut items, &t, s, name, records, report); + } else if level == 2 && title_.starts_with("Open Questions") { + covered = s.body.clone(); + report.push(f.mapped(s.line, title_, "each question an open_question")); + questions(&mut items, &t, s, records, report); + } else if level == 3 + && in_parent(SOURCES) + && let Some(tier) = source_tier(title_) + { + report.push(f.mapped(s.line, title_, "each bullet a source")); + items.rest.section(mine, title_); + sources(&mut items, &t, s, tier, records, report); + } else if level == 2 && title_.starts_with("Package Legitimacy") { + covered = s.body.clone(); + report.push(f.row("package legitimacy", s.line, title_)); + } else { + covered = s.body.clone(); + report.push(f.unmapped(s.line, title_, UNKNOWN.to_string())); + } + } + let mut record = f.within( + "research", + ("phase", &f.phase), + &f.stem, + title.as_deref().unwrap_or(&f.stem), + fields, + 0, + ); + record.links = links; + records.add(record, report); + items.rest.report(path, text, RS, report); +} + +/// `Pattern 1: Write then rename` as `Write then rename` (for `word` `Pattern`). +fn numbered<'t>(title: &'t str, word: &str) -> Option<&'t str> { + let (n, name) = title.strip_prefix(word)?.trim_start().split_once(':')?; + (!n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) && !name.trim().is_empty()) + .then(|| name.trim()) +} + +/// A Standard Stack `###` heading's tier. +fn tier_of(title: &str) -> Option<&'static str> { + match title { + "Core" => Some("core"), + "Supporting" => Some("supporting"), + "Alternatives Considered" => Some("alternative"), + _ => None, + } +} + +/// A Sources `###` heading's tier (`Primary (HIGH confidence)`). +fn source_tier(title: &str) -> Option<&'static str> { + ["primary", "secondary", "tertiary"] + .into_iter() + .find(|t| title.to_lowercase().starts_with(t)) +} + +/// The phase decision of each `D-NN` a `### Locked Decisions` bullet starts with; any other is reported, left out. +fn locked( + f: &PhaseFile<'_>, + t: &Text<'_>, + s: &Section, + records: &Records, + report: &mut Report, +) -> Vec<String> { + let mut named = Vec::new(); + for (line, text) in t.bullets(&s.body) { + let id = text.split_once(':').map_or(text, |(id, _)| id).trim(); + match decision(f, id, records) { + Some(path) => named.push(path), + None => report.push(f.unmapped( + line, + &s.title, + format!("`{id}` names no decision of the phase's CONTEXT.md: left out"), + )), + } + } + named +} + +/// The path of the phase's decision `id`, when its CONTEXT.md gave it. +fn decision(f: &PhaseFile<'_>, id: &str, records: &Records) -> Option<String> { + let path = format!("{}/{id}", f.phase); + (ids::decision(id) && records.contains("decision", &path)).then_some(path) +} + +/// The first table of `s`, if any. +fn table_in<'t>(s: &Section, tables: &'t [Table]) -> Option<&'t Table> { + tables.iter().find(|t| s.body.contains(&t.line)) +} + +/// The index of the first of `names` among `table`'s columns, ignoring case and apostrophe style. +fn column(table: &Table, names: &[&str]) -> Option<usize> { + let fold = |s: &str| s.to_lowercase().replace('’', "'"); + table + .header + .iter() + .position(|h| names.iter().any(|n| fold(h) == fold(n))) +} + +/// The trimmed cell `c` of `row`, none when empty. +fn cell(row: &[String], c: Option<usize>) -> Option<&str> { + c.and_then(|c| row.get(c)) + .map(|v| v.trim()) + .filter(|v| !v.is_empty()) +} + +/// Reports, with the row `key`, each column of `table` no member reads (any index not in `read`). +fn other_columns( + f: &PhaseFile<'_>, + table: &Table, + read: &[Option<usize>], + key: &str, + report: &mut Report, +) { + for (i, header) in table.header.iter().enumerate() { + if !read.contains(&Some(i)) { + report.push(f.row(key, table.line, header)); + } + } +} + +/// The `{capability, tier}` rows of the responsibility map's table. +fn responsibility_map( + f: &PhaseFile<'_>, + s: &Section, + tables: &[Table], + report: &mut Report, +) -> Vec<Value> { + let Some(table) = table_in(s, tables) else { + return Vec::new(); + }; + let (capability, tier) = ( + column(table, &["Capability"]), + column(table, &["Primary Tier", "Tier"]), + ); + other_columns( + f, + table, + &[capability, tier], + "| Secondary Tier | Rationale |", + report, + ); + table + .rows + .iter() + .filter_map(|row| { + let mut block = json!({ "capability": cell(row, capability)? }); + if let Some(tier) = cell(row, tier) { + block["tier"] = json!(tier); + } + Some(block) + }) + .collect() +} + +/// `## Summary`: its paragraphs the research's `summary`, its `**Primary recommendation:**` the finding `F1`. +fn summary( + items: &mut Items<'_, '_>, + t: &Text<'_>, + s: &Section, + fields: &mut BTreeMap<String, Value>, + records: &mut Records, + report: &mut Report, +) { + for b in blocks_in(&t.blocks, &s.body) { + items.rest.take_block(b); + } + let (recommended, rest): (Vec<_>, Vec<_>) = blocks_in(&t.blocks, &s.body) + .partition(|b| b.text.trim_start().starts_with(RECOMMENDATION)); + let paragraphs: Vec<_> = rest.into_iter().cloned().collect(); + if let Some(text) = prose(¶graphs, &s.body) { + fields.insert("summary".to_string(), json!(text)); + } + for b in recommended { + let text = b.text.trim_start()[RECOMMENDATION.len()..].trim(); + let mut finding = BTreeMap::from([("text".to_string(), json!(text))]); + if let Some(confidence) = &items.confidence { + finding.insert("confidence".to_string(), json!(confidence)); + } + items.add(FINDING, text, finding, b.lines[0], records, report); + } +} + +/// One `stack_choice SC<n>` per row of the Standard Stack table of `s`, its tier the heading's. +fn stack( + items: &mut Items<'_, '_>, + s: &Section, + tier: &str, + tables: &[Table], + records: &mut Records, + report: &mut Report, +) { + let Some(table) = table_in(s, tables) else { + return; + }; + items.rest.take_table(table); + let name = column(table, &["Library", "Could Use"]); + let version = column(table, &["Version"]); + let purpose = column(table, &["Purpose", "Tradeoff"]); + other_columns( + items.f, + table, + &[name, version, purpose], + "| Why Standard |", + report, + ); + for (i, row) in table.rows.iter().enumerate() { + let line = table.line + 2 + i; + let Some(n) = cell(row, name) else { + report.push(items.f.unmapped( + line, + &s.title, + "a stack row with no name: not imported".to_string(), + )); + continue; + }; + let mut fields = BTreeMap::from([ + ("name".to_string(), json!(n)), + ("tier".to_string(), json!(tier)), + ]); + for (field, c) in [("version", version), ("purpose", purpose)] { + if let Some(v) = cell(row, c) { + fields.insert(field.to_string(), json!(v)); + } + } + items.add(STACK_CHOICE, n, fields, line, records, report); + } +} + +/// `### Pattern N: Name` as `pattern P<n>`: its `**What:**`, `**When to use:**` and `**Example:**` (its text, else the +/// fence under it). +fn pattern( + items: &mut Items<'_, '_>, + t: &Text<'_>, + s: &Section, + text: &str, + records: &mut Records, + report: &mut Report, +) { + let name = numbered(&s.title, "Pattern").unwrap_or(&s.title); + let mut fields = BTreeMap::from([("name".to_string(), json!(name))]); + let label = |labels: &[&str]| labelled(&t.lines, &t.fenced, &s.body, labels); + for (field, labels) in [("what", "**What:**"), ("when", "**When to use:**")] { + if let Some((line, v)) = label(&[labels]).filter(|(_, v)| !v.is_empty()) { + items.rest.take(line); + fields.insert(field.to_string(), json!(v)); + } + } + if let Some((line, v)) = label(&["**Example:**"]) { + items.rest.take(line); + let fence = markdown::fences(text) + .into_iter() + .find(|f| f.open > line && s.body.contains(&f.open)); + let example = match (v, fence) { + ("", Some(fence)) => fence.text.trim_end().to_string(), + (v, _) => v.to_string(), + }; + if !example.is_empty() { + fields.insert("example".to_string(), json!(example)); + } + } + items.add(PATTERN, name, fields, s.line, records, report); +} + +/// Each `- **Name:** text` bullet of Anti-Patterns to Avoid as `pattern P<n>` with `anti` true. +fn anti_patterns( + items: &mut Items<'_, '_>, + t: &Text<'_>, + s: &Section, + records: &mut Records, + report: &mut Report, +) { + for b in bullets_in(&t.blocks, &t.lines, &s.body) { + items.rest.take_block(b); + } + for (line, text) in t.bullets(&s.body) { + let Some((name, what)) = text + .split_once(':') + .filter(|(n, w)| !n.trim().is_empty() && !w.trim().is_empty()) + else { + report.push(items.f.unmapped( + line, + &s.title, + "an anti-pattern needs `**Name:** text`: not imported".to_string(), + )); + continue; + }; + let name = name.trim(); + let fields = BTreeMap::from([ + ("name".to_string(), json!(name)), + ("what".to_string(), json!(what.trim())), + ("anti".to_string(), json!(true)), + ]); + items.add(PATTERN, name, fields, line, records, report); + } +} + +/// One `dont_hand_roll DH<n>` per row of the table of `s`; its Don't Build column is reported. +fn dont_hand_roll( + items: &mut Items<'_, '_>, + s: &Section, + tables: &[Table], + records: &mut Records, + report: &mut Report, +) { + let Some(table) = table_in(s, tables) else { + return; + }; + items.rest.take_table(table); + let problem = column(table, &["Problem"]); + let instead = column(table, &["Use Instead"]); + let why = column(table, &["Why"]); + other_columns( + items.f, + table, + &[problem, instead, why], + "| Don't Build |", + report, + ); + for (i, row) in table.rows.iter().enumerate() { + let mut fields = BTreeMap::new(); + for (field, c) in [("problem", problem), ("instead", instead), ("why", why)] { + if let Some(v) = cell(row, c) { + fields.insert(field.to_string(), json!(v)); + } + } + let title = cell(row, problem).unwrap_or_default(); + items.add(DONT, title, fields, table.line + 2 + i, records, report); + } +} + +/// `### Pitfall N: Name` as `pitfall PF<n>` with its four bold lines. +fn pitfall( + items: &mut Items<'_, '_>, + t: &Text<'_>, + s: &Section, + name: &str, + records: &mut Records, + report: &mut Report, +) { + let mut fields = BTreeMap::from([("name".to_string(), json!(name))]); + for (field, label) in [ + ("goes_wrong", "**What goes wrong:**"), + ("why", "**Why it happens:**"), + ("avoid", "**How to avoid:**"), + ("warning_signs", "**Warning signs:**"), + ] { + if let Some((line, v)) = + labelled(&t.lines, &t.fenced, &s.body, &[label]).filter(|(_, v)| !v.is_empty()) + { + items.rest.take(line); + fields.insert(field.to_string(), json!(v)); + } + } + items.add(PITFALL, name, fields, s.line, records, report); +} + +/// Each numbered item of Open Questions as `open_question OQ<n>`: `**Question** — RESOLVED: …` and its bullets +/// `What we know:`, `What's unclear:`, `Recommendation:`; `resolved_by` the first `D-NN` after `RESOLVED`. +fn questions( + items: &mut Items<'_, '_>, + t: &Text<'_>, + s: &Section, + records: &mut Records, + report: &mut Report, +) { + let mut asked: Vec<(usize, BTreeMap<String, Value>, Option<String>)> = Vec::new(); + for b in blocks_in(&t.blocks, &s.body) { + let line = b.lines[0]; + let text = b.text.trim(); + if ordered(t.lines.get(line).copied().unwrap_or_default()) { + let (question, rest) = text.split_once(" — ").unwrap_or((text, "")); + let resolved = rest.split_once("RESOLVED").map(|(_, r)| r); + let mut fields = BTreeMap::from([("question".to_string(), json!(question.trim()))]); + let mut refs = None; + if let Some(resolved) = resolved { + let named = resolved + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-')) + .find(|w| ids::decision(w)); + match named.map(|id| (id, decision(items.f, id, records))) { + Some((_, Some(path))) => { + fields.insert("resolved_by".to_string(), json!(path)); + refs = Some(path); + } + Some((id, None)) => report.push(items.f.unmapped( + line, + &s.title, + format!("resolved_by `{id}` names no decision of the phase's CONTEXT.md: left out"), + )), + None => {} + } + } + asked.push((line, fields, refs)); + } else if let Some((_, fields, _)) = asked.last_mut() { + let value = |labels: &[&str]| { + labels + .iter() + .find_map(|l| text.strip_prefix(l)) + .map(str::trim) + }; + let found = [ + ("known", value(&["What we know:"])), + ("unclear", value(&["What's unclear:", "What’s unclear:"])), + ("recommendation", value(&["Recommendation:"])), + ]; + match found.into_iter().find_map(|(k, v)| Some((k, v?))) { + Some((field, v)) if !v.is_empty() => { + fields.insert(field.to_string(), json!(v)); + } + _ => report.push(items.f.unmapped(line, &s.title, UNKNOWN_LINE.to_string())), + } + } else { + report.push(items.f.unmapped(line, &s.title, UNKNOWN_LINE.to_string())); + } + } + for (line, fields, resolved) in asked { + let title = fields["question"].as_str().unwrap_or_default().to_string(); + let mut record = items.next(QUESTION, &title, fields, line); + record.links.extend(resolved.map(|d| ("resolved_by", d))); + records.add(record, report); + } +} + +const UNKNOWN_LINE: &str = "no member of an open question holds it"; + +/// Whether the raw line `line` starts an ordered list item (`1. `). +fn ordered(line: &str) -> bool { + let t = line.trim_start(); + let digits = t.bytes().take_while(u8::is_ascii_digit).count(); + digits > 0 && t[digits..].starts_with(". ") +} + +/// Each bullet `- url - note` of a Sources section as `source SRC<n>` of `tier`. +fn sources( + items: &mut Items<'_, '_>, + t: &Text<'_>, + s: &Section, + tier: &str, + records: &mut Records, + report: &mut Report, +) { + for b in bullets_in(&t.blocks, &t.lines, &s.body) { + items.rest.take_block(b); + } + for (line, text) in t.bullets(&s.body) { + let (url, checked) = match text.split_once(" - ") { + Some((url, checked)) => (url.trim(), Some(checked.trim())), + None => (text, None), + }; + let mut fields = BTreeMap::from([ + ("url".to_string(), json!(url)), + ("tier".to_string(), json!(tier)), + ]); + if let Some(checked) = checked.filter(|c| !c.is_empty()) { + fields.insert("checked".to_string(), json!(checked)); + } + items.add(SOURCE, url, fields, line, records, report); + } +} diff --git a/gsd/import/src/read/roadmap.rs b/gsd/import/src/read/roadmap.rs new file mode 100644 index 0000000000..626a870e9b --- /dev/null +++ b/gsd/import/src/read/roadmap.rs @@ -0,0 +1,639 @@ +//! `ROADMAP.md` to milestones and phases (13-RESEARCH Part B, the `ROADMAP.md` table; the rows are +//! `table::sections::ROADMAP`), in both of GSD's forms: +//! +//! - **Flat** (GSD's initial roadmap): no `## Milestones` section, so one milestone `v1.0` holds every phase, its id +//! reported `filled` and its title authored after the import (ADR 0391 D4). +//! - **Milestone-grouped** (after v1.0 ships): a `## Milestones` bullet per version (`- ✅ **v1.0 MVP** - ...`); a +//! phase belongs to the milestone whose `<details><summary>` block or `### <emoji> vX.Y Name` heading holds it, and +//! `**Milestone Goal:**` gives that milestone's goal. +//! +//! A phase heading (`### Phase 02.1: Name (INSERTED)`, `#### Phase 5: Name`) gives the phase, its id the number with the +//! integer part on two digits; its `**Goal**`, `**Depends on**`, `**Requirements**` and `**Success Criteria**` lines its +//! fields. A `Plans:` bullet gives a plan's title to the plan reader. Every other section is reported. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{Value, json}; + +use super::{Rest, is_bullet, own, row, slug}; +use crate::ids::{self, padded}; +use crate::paths; +use crate::records::{Record, Records, Source}; +use crate::report::{Entry, Outcome, Report}; +use crate::sections::{self, Section}; + +const RM: &str = "ROADMAP.md"; + +/// The flat roadmap's one milestone. +const FLAT: &str = "v1.0"; + +/// What a section no row names becomes. +const UNKNOWN: &str = "a section no row of the ROADMAP.md table names: no field holds it"; + +/// What later readers take from the roadmap. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Roadmap { + /// Each phase's number (`01`, `02.1`) and its graph path (`v1.0/01`). + pub phases: BTreeMap<String, String>, + /// Each `Plans:` bullet's plan id (`01-01`) and its title, backticks cut. + pub plan_titles: BTreeMap<String, String>, + /// Each requirement a phase's `**Requirements**` names, and that phase's number. + pub requirements: BTreeMap<String, String>, +} + +/// One phase as its heading and lines give it, before its references are resolved. +struct Draft { + number: String, + milestone: String, + title: String, + /// The heading as written: the section of the phase's report entries. + heading: String, + line: usize, + fields: BTreeMap<String, Value>, + depends: Option<(String, usize)>, + requirements: Option<(String, usize)>, +} + +/// The classes reported once per file, not at each line. +#[derive(Default)] +struct Once(BTreeSet<&'static str>); + +impl Once { + fn push(&mut self, key: &'static str, source: &Source, section: &str, report: &mut Report) { + if self.0.insert(key) { + report.push(row(RM, key, source, section)); + } + } +} + +/// Reads `text`, served at `path`; `dirs` are the names of the directories under `.planning/phases/`, which give the +/// phases' slugs. The requirement records must be read first: a phase keeps only the requirements they hold. +pub fn read( + path: &str, + text: &str, + dirs: &[&str], + records: &mut Records, + report: &mut Report, +) -> Roadmap { + let lines: Vec<&str> = text.split('\n').map(|l| l.trim_end_matches('\r')).collect(); + let fenced = sections::fenced(text); + let all = sections::sections(text); + let at = |line: usize| Source { + file: path.to_string(), + line: line + 1, + }; + let mut once = Once::default(); + let mut rest = Rest::default(); + let mut roadmap = Roadmap::default(); + let grouped = all.iter().find(|s| s.level == 2 && s.title == "Milestones"); + let mut current: Option<String> = None; + let mut milestone_goal: BTreeMap<String, (String, usize)> = BTreeMap::new(); + let mut found = match grouped { + Some(s) => { + rest.section(own(s, &all), &s.title); + let found = milestones(s, &lines, &fenced, &at, &mut once, report); + for m in &found { + rest.take(m.source.line - 1); + } + found + } + None => { + let line = all.iter().find(|s| s.level == 1).map_or(0, |s| s.line); + report.push(row(RM, "(no milestone)", &at(line), "(no milestone)")); + report.authored_after_import(format!("milestone {FLAT}: its title")); + current = Some(FLAT.to_string()); + vec![milestone(FLAT, FLAT, at(line))] + } + }; + let headings: BTreeMap<usize, &Section> = all.iter().map(|s| (s.line, s)).collect(); + let mut drafts: Vec<Draft> = Vec::new(); + let mut covered = 0..0; + for (n, raw) in lines.iter().enumerate() { + // A phase heading is read wherever it stands: a section reported whole never swallows the phases. + let phase_heading = headings + .get(&n) + .is_some_and(|s| s.level >= 3 && s.title.starts_with("Phase")); + if fenced[n] || (covered.contains(&n) && !phase_heading) { + continue; + } + if phase_heading { + covered = 0..0; + } + if let Some(s) = headings.get(&n) { + let title = s.title.as_str(); + match (s.level, title) { + // Any title (`# Roadmap: X`, `# Project Roadmap`): its spelling is not load-bearing. + (1, _) => { + rest.section(own(s, &all), title); + report.push(row(RM, "# Roadmap:", &at(n), title)); + } + (2, "Overview") => report.push(row(RM, "## Overview", &at(n), title)), + (2, "Phases") => report.push(row(RM, "## Phases", &at(n), title)), + (2, "Phase Details") => report.push(row(RM, "## Phase Details", &at(n), title)), + (2, "Progress") => { + covered = s.body.clone(); + report.push(row(RM, "## Progress", &at(n), title)); + } + (2, "Milestones") if grouped.is_some() => {} + (3.., _) if title.starts_with("Phase") => { + // The phase's own lines: a sub-section is read under its own heading. + let mine = Section { + body: own(s, &all), + ..(*s).clone() + }; + let mut cx = Lines { + lines: &lines, + fenced: &fenced, + at: &at, + once: &mut once, + rest: &mut rest, + }; + let draft = phase(&mine, &mut cx, &mut roadmap, report); + match (draft, ¤t) { + (Some(draft), Some(milestone)) => drafts.push(Draft { + milestone: milestone.clone(), + ..draft + }), + (Some(_), None) => report.push(Entry::at( + &at(n), + title, + Outcome::Unmapped, + "a phase outside any milestone's heading or <details> block: not imported".to_string(), + )), + (None, _) => {} + } + } + (3.., _) if grouped.is_some() && version(title).is_some() => { + rest.section(own(s, &all), title); + current = opens(title, &at(n), title, report); + if current.is_some() { + once.push("milestone status", &at(n), title, report); + } + } + _ => { + covered = s.body.clone(); + report.push(Entry::at( + &at(n), + title, + Outcome::Unmapped, + UNKNOWN.to_string(), + )); + } + } + continue; + } + let line = raw.trim(); + if grouped.is_some() && line.contains("<summary>") { + rest.take(n); + if version(line).is_some() { + current = opens(line, &at(n), "<details>", report); + if current.is_some() { + once.push("milestone status", &at(n), "<details>", report); + } + } + } else if let Some(("Milestone Goal", goal)) = key_line(line) { + rest.take(n); + match ¤t { + Some(m) if !goal.is_empty() => { + milestone_goal.insert(m.clone(), (goal.to_string(), n)); + } + _ => report.push(Entry::at( + &at(n), + "**Milestone Goal:**", + Outcome::Unmapped, + "a milestone goal outside a milestone, or empty: not imported".to_string(), + )), + } + } else if let Some(("Phase Numbering", _)) = key_line(line) { + report.push(row(RM, "Phase Numbering", &at(n), "Phase Numbering")); + } + } + for (id, (goal, n)) in milestone_goal { + match found.iter_mut().find(|m| m.id == id) { + Some(m) => { + m.fields.insert("goal".to_string(), json!(goal)); + } + None => report.push(Entry::at( + &at(n), + "**Milestone Goal:**", + Outcome::Unmapped, + format!("milestone {id} is in no ## Milestones bullet: its goal is not imported"), + )), + } + } + for m in found { + records.add(m, report); + } + // Every phase's path is known: resolve the references. + for d in &drafts { + roadmap + .phases + .entry(d.number.clone()) + .or_insert(format!("{}/{}", d.milestone, d.number)); + } + for mut d in drafts { + // The phase directory `NN-slug` gives the slug, else the title does (13-RESEARCH Pitfall 9). + let dir = dirs.iter().find_map(|dir| { + let (number, slug) = dir.split_once('-')?; + (padded(number).as_deref() == Some(d.number.as_str())).then_some(slug) + }); + let slug = dir.map_or_else(|| slug(&d.title), str::to_string); + if !slug.is_empty() { + d.fields.insert("slug".to_string(), json!(slug)); + } + let mut links = Vec::new(); + if let Some((value, n)) = &d.depends { + let deps = depends(value, *n, &roadmap, &at, &d.heading, report); + links.extend(deps.iter().map(|id| ("depends_on", id.clone()))); + if !deps.is_empty() { + // The field holds paths, not the line's words: the line says where they come from. + report.push(row(RM, "**Depends on**", &at(*n), &d.heading)); + d.fields.insert("depends_on".to_string(), json!(deps)); + } + } + if let Some((value, n)) = &d.requirements { + let mut kept = Vec::new(); + for id in requirement_ids(value) { + if id == "TBD" { + report.push(row(RM, "TBD", &at(*n), &d.heading)); + } else if records.contains("requirement", id) { + roadmap + .requirements + .insert(id.to_string(), d.number.clone()); + kept.push(id.to_string()); + } else { + report.push(Entry::at( + &at(*n), + &d.heading, + Outcome::Unmapped, + format!("**Requirements** names {id}, which REQUIREMENTS.md does not define: left out of the phase"), + )); + } + } + links.extend(kept.iter().map(|id| ("requirements", id.clone()))); + if !kept.is_empty() { + d.fields.insert("requirements".to_string(), json!(kept)); + } + } + d.fields.insert("milestone".to_string(), json!(d.milestone)); + records.add( + Record { + kind: "phase", + id: format!("{}/{}", d.milestone, d.number), + title: d.title, + file: paths::milestone(&d.milestone), + fields: d.fields, + refs: vec![d.milestone.clone()], + links, + source: at(d.line), + }, + report, + ); + } + rest.report(path, text, RM, report); + roadmap +} + +/// The roadmap's lines as a phase reads them, and what it reports once and leaves. +struct Lines<'a, 'l> { + lines: &'a [&'l str], + fenced: &'a [bool], + at: &'a dyn Fn(usize) -> Source, + once: &'a mut Once, + rest: &'a mut Rest, +} + +/// A milestone record, its goal added later. +fn milestone(id: &str, title: &str, source: Source) -> Record { + Record { + kind: "milestone", + id: id.to_string(), + title: title.to_string(), + file: paths::milestone(id), + fields: BTreeMap::new(), + refs: Vec::new(), + links: Vec::new(), + source, + } +} + +/// The `## Milestones` bullets: one milestone per version, its title the bold text. +fn milestones( + s: &Section, + lines: &[&str], + fenced: &[bool], + at: &dyn Fn(usize) -> Source, + once: &mut Once, + report: &mut Report, +) -> Vec<Record> { + let mut out = Vec::new(); + for n in s.body.clone() { + let Some(line) = lines.get(n).filter(|l| !fenced[n] && is_bullet(l)) else { + continue; + }; + let Some(v) = version(line).filter(|v| ids::milestone(v)) else { + report.push(Entry::at( + &at(n), + "Milestones", + Outcome::Unmapped, + "a milestone bullet names no version vX.Y: not imported".to_string(), + )); + continue; + }; + let title = line + .split_once("**") + .and_then(|(_, rest)| rest.split_once("**")) + .map_or(v, |(bold, _)| bold.trim()); + once.push("milestone status", &at(n), "Milestones", report); + out.push(milestone(v, title, at(n))); + } + out +} + +/// The milestone a version heading or `<summary>` line `text` opens: its version, when a milestone takes it as an id +/// (as a `## Milestones` bullet's is checked); else reported, and the phases under it stand in no milestone. +fn opens(text: &str, source: &Source, section: &str, report: &mut Report) -> Option<String> { + let v = version(text)?; + if ids::milestone(v) { + return Some(v.to_string()); + } + report.push(Entry::at( + source, + section, + Outcome::Unmapped, + format!("`{v}` names no version vX.Y: the phases under it are not imported"), + )); + None +} + +/// The first word of `text` that is a version `v<digit>...` (`v1.0`), without trailing punctuation. +fn version(text: &str) -> Option<&str> { + text.split(|c: char| c.is_whitespace() || matches!(c, '*' | '(' | ')' | '>' | '<')) + .map(|w| w.trim_end_matches([':', ',', '.', ';'])) + .find(|w| { + w.strip_prefix('v') + .is_some_and(|r| r.starts_with(|c: char| c.is_ascii_digit())) + }) +} + +/// `**Key**: value`, `**Key:** value` or `**Key** (note): value`, as the key and the value, trimmed. +fn key_line(line: &str) -> Option<(&str, &str)> { + let rest = line.trim_start().strip_prefix("**")?; + let (key, after) = rest.split_once("**")?; + match key.strip_suffix(':') { + Some(key) => Some((key.trim(), after.trim())), + None => after.split_once(':').map(|(_, v)| (key.trim(), v.trim())), + } +} + +/// The phase of the heading `s` (its own lines), read from its lines, with no milestone yet; none, reported, when the +/// heading is in neither form. Each line it takes is taken from `cx.rest`; a line it does not read is left there. +fn phase( + s: &Section, + cx: &mut Lines<'_, '_>, + roadmap: &mut Roadmap, + report: &mut Report, +) -> Option<Draft> { + let (lines, at) = (cx.lines, cx.at); + let refuse = |why: String, report: &mut Report| { + report.push(Entry::at( + &at(s.line), + &s.title, + Outcome::Unmapped, + format!("{why}: not imported"), + )); + }; + let Some((number, name)) = s + .title + .strip_prefix("Phase") + .and_then(|r| r.split_once(':')) + else { + refuse( + "a phase heading in neither form `Phase N: Name`".to_string(), + report, + ); + return None; + }; + let number = number.trim(); + if number.is_empty() { + refuse("a phase heading with no number".to_string(), report); + return None; + } + let Some(id) = padded(number) else { + refuse(format!("`{number}` is not a phase number"), report); + return None; + }; + cx.rest.section(s.body.clone(), &s.title); + let mut title = name.trim(); + if let Some(cut) = title.strip_suffix("(INSERTED)") { + title = cut.trim_end(); + cx.once.push("(INSERTED)", &at(s.line), &s.title, report); + } + let mut d = Draft { + number: id, + milestone: String::new(), + title: title.to_string(), + heading: s.title.clone(), + line: s.line, + fields: BTreeMap::new(), + depends: None, + requirements: None, + }; + let mut n = s.body.start; + while n < s.body.end { + let line = lines[n]; + let here = n; + n += 1; + if cx.fenced[here] { + continue; + } + if line.trim() == "Plans:" { + cx.rest.take(here); + while n < s.body.end && (is_bullet(lines[n]) || lines[n].trim().is_empty()) { + cx.rest.take(n); + plan_title(lines[n], n, at, &s.title, roadmap, report); + n += 1; + } + continue; + } + let Some((key, value)) = key_line(line) else { + continue; + }; + cx.rest.take(here); + match key { + "Goal" if !value.is_empty() => { + d.fields.insert("goal".to_string(), json!(value)); + } + "Depends on" => d.depends = Some((value.to_string(), here)), + "Requirements" => d.requirements = Some((value.to_string(), here)), + "Success Criteria" => { + // The list may stand a blank line below its key. + let first = (n..s.body.end) + .find(|&m| !lines[m].trim().is_empty()) + .unwrap_or(s.body.end); + let mut criteria = Vec::new(); + let mut m = first; + while let Some(item) = (m < s.body.end).then(|| numbered(lines[m])).flatten() { + criteria.push(item.to_string()); + cx.rest.take(m); + m += 1; + } + if !criteria.is_empty() { + n = m; + d.fields + .insert("success_criteria".to_string(), json!(criteria)); + } + } + "Plans" => report.push(row( + RM, + "**Plans**: N/M plans complete", + &at(here), + &s.title, + )), + "Mode" => report.push(row(RM, "**Mode**", &at(here), &s.title)), + _ => report.push(Entry::at( + &at(here), + &s.title, + Outcome::Unmapped, + format!("a phase line **{key}** no row names: no field holds it"), + )), + } + } + Some(d) +} + +/// A numbered list item's text (` 1. A user can add a task`), verbatim. +fn numbered(line: &str) -> Option<&str> { + let t = line.trim_start(); + let digits = t.bytes().take_while(u8::is_ascii_digit).count(); + let rest = t[digits..].strip_prefix(". ")?; + (digits > 0 && !rest.trim().is_empty()).then(|| rest.trim()) +} + +/// A `Plans:` bullet `- [x] 01-01: Title`: the plan's title for the plan reader; `TBD (run ...)` is ignored. +fn plan_title( + line: &str, + n: usize, + at: &dyn Fn(usize) -> Source, + section: &str, + roadmap: &mut Roadmap, + report: &mut Report, +) { + if !is_bullet(line) { + return; + } + let item = line.trim_start()[2..].trim_start(); + let item = ["[x] ", "[X] ", "[ ] "] + .iter() + .find_map(|b| item.strip_prefix(b)) + .unwrap_or(item); + if item.starts_with("TBD") { + report.push(row(RM, "TBD (run /gsd-plan-phase", &at(n), section)); + return; + } + match item.split_once(": ") { + Some((id, title)) if ids::plan(id.trim()) => { + roadmap.plan_titles.insert( + id.trim().to_string(), + title.replace('`', "").trim().to_string(), + ); + } + _ => report.push(Entry::at( + &at(n), + section, + Outcome::Unmapped, + "a Plans: bullet names no plan `NN-MM: Title`: no title taken".to_string(), + )), + } +} + +/// The graph paths of the phases `**Depends on**` names (`Phase 2`, `Phase 1, Phase 2`); `Nothing (first phase)` is +/// ignored, and a phase the roadmap does not hold is reported. +fn depends( + value: &str, + n: usize, + roadmap: &Roadmap, + at: &dyn Fn(usize) -> Source, + section: &str, + report: &mut Report, +) -> Vec<String> { + if value.starts_with("Nothing") || value.is_empty() { + report.push(row(RM, "Nothing (first phase)", &at(n), section)); + return Vec::new(); + } + let mut out = Vec::new(); + for part in value.split(',').map(str::trim).filter(|p| !p.is_empty()) { + let word = part.strip_prefix("Phase").unwrap_or(part).trim(); + let number: String = word + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '.') + .collect(); + match padded(number.trim_end_matches('.')).and_then(|p| roadmap.phases.get(&p)) { + Some(path) => out.push(path.clone()), + None => report.push(Entry::at( + &at(n), + section, + Outcome::Unmapped, + format!( + "**Depends on** names `{part}`, which is no phase of the roadmap: left out" + ), + )), + } + } + out +} + +/// The ids of a `**Requirements**` value: `[A-01, B-02]` or `A-01, B-02`. +fn requirement_ids(value: &str) -> impl Iterator<Item = &str> { + value + .trim() + .trim_start_matches('[') + .trim_end_matches(']') + .split(',') + .map(str::trim) + .filter(|id| !id.is_empty()) +} + +/// Reports each row of REQUIREMENTS.md's Traceability table (served at `path`) that disagrees with the roadmap's +/// `**Requirements**` lines: the roadmap wins (13-RESEARCH Pitfall 8). +pub fn cross_check(path: &str, text: &str, roadmap: &Roadmap, report: &mut Report) { + for table in gsd_kit::markdown::tables(text) + .into_iter() + .filter(|t| t.heading == "Traceability") + { + let column = |name: &str, or: usize| { + table + .header + .iter() + .position(|h| h.eq_ignore_ascii_case(name)) + .unwrap_or(or) + }; + let (requirement, phase) = (column("Requirement", 0), column("Phase", 1)); + for (i, cells) in table.rows.iter().enumerate() { + let cell = |i: usize| cells.get(i).map(|c| c.trim()).unwrap_or_default(); + let named = cell(phase) + .strip_prefix("Phase") + .unwrap_or(cell(phase)) + .trim(); + let roadmap_phase = roadmap.requirements.get(cell(requirement)); + let why = match (padded(named), roadmap_phase) { + (Some(p), Some(r)) if p == *r => continue, + (_, Some(r)) => format!( + "Traceability puts {} in `{}`, the roadmap's **Requirements** in phase {r}: the roadmap wins", + cell(requirement), + cell(phase) + ), + (_, None) => format!( + "Traceability puts {} in `{}`, and no phase's **Requirements** names it: the roadmap wins", + cell(requirement), + cell(phase) + ), + }; + let source = Source { + file: path.to_string(), + line: table.line + 3 + i, + }; + report.push(Entry::at(&source, "Traceability", Outcome::Redundant, why)); + } + } +} diff --git a/gsd/import/src/read/security.rs b/gsd/import/src/read/security.rs new file mode 100644 index 0000000000..8dffaa102b --- /dev/null +++ b/gsd/import/src/read/security.rs @@ -0,0 +1,463 @@ +//! `NN-SECURITY.md` to `@gsd/security`'s kinds, when the project loads it (ADR 0391 D7, D11; 13-RESEARCH Part B, the +//! `SECURITY.md` table; the rows are `table::sections::SECURITY`): the file stem is a `security_audit` of its phase, with +//! the harness `asvs_level` and `created` a person recorded. Its other tables record the auditor's results on the +//! phase's plans, read before it ([`super::all`] reads it last): +//! +//! - a Threat Register row sets the harness `status` of the one plan threat with the same Threat ID **and** the same +//! component; no match, or two, sets nothing and is reported (a duplicate id across plans is by design); +//! - a Trust Boundaries row sets `data_crossing` on the one plan boundary whose `Boundary` text is equal; +//! - an Accepted Risks Log row is an `accepted_risk AR<n>` naming its unique threat; +//! - a `## Security Audit <date>` block is an `audit_run AU<n>`, its `at` filled `<date>T00:00:00Z` and reported. +//! +//! Nothing SECURITY.md does not record is written: a plan threat with no row keeps no status. + +use std::collections::BTreeMap; + +use gsd_kit::markdown::{self, Table}; +use serde_json::{Value as Json, json}; + +use super::plan::front; +use super::{Context, PhaseFile, is_date, is_footer, is_timestamp, phase_file}; +use crate::frontmatter; +use crate::ids; +use crate::records::Records; +use crate::report::{Entry, Outcome, Report}; +use crate::sections::{self, Section}; + +/// The fate table's name of a security audit. +pub const SC: &str = "SECURITY.md"; + +const THREAT_STATUS: &[&str] = &["open", "closed"]; +const UNKNOWN: &str = "a section no row of the SECURITY.md table names: not imported"; +const RUN: &str = "Security Audit "; + +/// Reads the security audit `text`, served at `path` (`rel` under `.planning/`): `phases/<NN-slug>/<NN>-SECURITY.md`. +pub fn read( + path: &str, + rel: &str, + text: &str, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let Some(f) = phase_file(path, rel, SC, cx, report) else { + return; + }; + let audit = format!("{}/{}", f.phase, f.stem); + let mut fields = BTreeMap::new(); + let (front, start) = front(&f.doc, text, report); + for (key, v) in &front { + let line = v.line; + let text = v.value.as_str().map(str::trim).unwrap_or_default(); + match key.as_str() { + "phase" => { + let named = ids::padded(text.split_once('-').map_or(text, |(n, _)| n)); + if named.as_deref() == Some(f.number.as_str()) { + report.push(f.doc.row("phase, slug", line, key)); + } else { + report.push(f.doc.unmapped( + line, + key, + format!("`phase: {text}` names another phase than the file name's {}: the file name wins", f.number), + )); + } + } + "slug" => report.push(f.doc.row("phase, slug", line, key)), + "status" | "threats_open" => report.push(f.doc.row(key, line, key)), + "asvs_level" => match text.parse::<u8>().ok().filter(|l| (1..=3).contains(l)) { + Some(level) => { + fields.insert("asvs_level".to_string(), json!(level)); + } + None => report.push(f.doc.unmapped( + line, + key, + format!("`asvs_level: {text}` is no level 1 to 3: left out"), + )), + }, + "created" if is_timestamp(text) => { + fields.insert("created".to_string(), json!(text)); + } + "created" if is_date(text) => { + fields.insert("created".to_string(), json!(format!("{text}T00:00:00Z"))); + report.push(f.doc.row("created", line, key)); + } + "created" => report.push(f.doc.unmapped( + line, + key, + format!("`created: {text}` is no date or RFC 3339 timestamp: left out"), + )), + _ => report.push(f.doc.unmapped( + line, + key, + format!("a key `{key}` no row of the SECURITY.md table names: not imported"), + )), + } + } + let body = frontmatter::body(text, start); + let lines: Vec<&str> = body.split('\n').collect(); + let fenced = sections::fenced(&body); + for (n, line) in lines.iter().enumerate() { + if fenced[n] { + continue; + } + if is_footer(line) { + report.push(f.row("status legend", n, "legend")); + } else if line.starts_with('>') { + report.push(f.row("> Per-phase security contract", n, "note")); + } else if line.trim_start().starts_with("**Approval:**") { + report.push(f.row("**Approval:**", n, "Sign-Off")); + } + } + let tables = markdown::tables(&body); + let mut title = None; + let mut at = 0; + let mut run = 0; + for s in sections::sections(&body) { + let table = tables.iter().find(|t| s.body.contains(&t.line)); + let mapped = |what: &str, report: &mut Report| { + report.push(Entry::at( + &f.at(s.line), + &s.title, + Outcome::Mapped, + what.to_string(), + )); + }; + match (s.level, s.title.as_str()) { + (1, _) if title.is_none() => { + title = Some(s.title.clone()); + at = s.line; + } + (2, "Trust Boundaries") => { + mapped( + "each row sets data_crossing on the plan boundary it names", + report, + ); + if let Some(t) = table { + boundaries(&f, &s, t, records, report); + } + } + (2, "Threat Register") => { + mapped( + "each row sets status on the plan threat with its Threat ID and component", + report, + ); + if let Some(t) = table { + register(&f, &s, t, records, report); + } + } + (2, "Accepted Risks Log") => { + mapped("each row is an accepted_risk", report); + if let Some(t) = table { + for (i, cells) in t.rows.iter().enumerate() { + let row = Row::new(t, cells, t.line + 2 + i); + accepted(&f, &s, &audit, &row, records, report); + } + } + } + (2, "Security Audit Trail") => { + report.push(f.row("## Security Audit Trail", s.line, &s.title)) + } + (2, title) if title.starts_with(RUN) => { + run += 1; + audit_run(&f, &s, &audit, run, table, records, report); + } + (2, "Sign-Off") => report.push(f.row("## Sign-Off", s.line, &s.title)), + _ => report.push(f.unmapped(s.line, &s.title, UNKNOWN.to_string())), + } + } + records.add( + f.within( + "security_audit", + ("phase", &f.phase), + &f.stem, + title.as_deref().unwrap_or(&f.stem), + fields, + at, + ), + report, + ); +} + +/// One body row of a table: its cells by column name, and its 0-based line. +struct Row<'t> { + cells: BTreeMap<&'t str, &'t str>, + line: usize, +} + +impl<'t> Row<'t> { + fn new(table: &'t Table, cells: &'t [String], line: usize) -> Self { + let cells = table + .header + .iter() + .zip(cells) + .map(|(h, c)| (h.trim(), c.trim())) + .filter(|(_, c)| !c.is_empty()) + .collect(); + Row { cells, line } + } + + fn get(&self, column: &str) -> Option<&'t str> { + self.cells.get(column).copied() + } +} + +/// The ids of the `kind` records of the phase of `f` whose fields `matches`. +fn of_phase( + f: &PhaseFile<'_>, + records: &Records, + kind: &str, + matches: impl Fn(&str, &Json) -> bool, +) -> Vec<String> { + let prefix = format!("{}/", f.phase); + records + .iter() + .filter(|r| r.kind == kind && r.id.starts_with(&prefix)) + .filter(|r| matches(r.id.rsplit('/').next().unwrap_or(&r.id), &json!(r.fields))) + .map(|r| r.id.clone()) + .collect() +} + +/// `found`'s one id, or the reason none is taken (none, or more than one). +fn unique(found: Vec<String>, what: &str) -> Result<String, String> { + match found.as_slice() { + [one] => Ok(one.clone()), + [] => Err(format!("no plan of the phase holds {what}")), + many => Err(format!( + "{} plans' entities match {what} ({})", + many.len(), + many.join(", ") + )), + } +} + +/// Each Trust Boundaries row: `data_crossing` on the plan boundary whose `Boundary` text is equal. +fn boundaries( + f: &PhaseFile<'_>, + s: &Section, + table: &Table, + records: &mut Records, + report: &mut Report, +) { + for (i, cells) in table.rows.iter().enumerate() { + let row = Row::new(table, cells, table.line + 2 + i); + let boundary = row.get("Boundary").unwrap_or_default(); + let Some(crossing) = row.get("Data Crossing") else { + report.push(f.unmapped( + row.line, + &s.title, + "no Data Crossing: nothing to set".to_string(), + )); + continue; + }; + let found = of_phase(f, records, "trust_boundary", |_, fields| { + fields["boundary"] == boundary + }); + match unique(found, &format!("the boundary `{boundary}`")) { + Ok(id) => { + if let Some(r) = records.get_mut("trust_boundary", &id) { + r.fields + .insert("data_crossing".to_string(), json!(crossing)); + } + report.push(Entry::at( + &f.at(row.line), + &s.title, + Outcome::Mapped, + format!("trust_boundary {id}: data_crossing"), + )); + } + Err(why) => report.push(f.unmapped(row.line, &s.title, format!("{why}: nothing set"))), + } + } +} + +/// Each Threat Register row: the harness `status` of the one plan threat with its Threat ID and component. +fn register( + f: &PhaseFile<'_>, + s: &Section, + table: &Table, + records: &mut Records, + report: &mut Report, +) { + for (i, cells) in table.rows.iter().enumerate() { + let row = Row::new(table, cells, table.line + 2 + i); + let (id, component) = ( + row.get("Threat ID").unwrap_or_default(), + row.get("Component").unwrap_or_default(), + ); + let found = of_phase(f, records, "threat", |local, fields| { + local == id && fields["component"] == component + }); + let threat = match unique( + found, + &format!("the threat `{id}` of the component `{component}`"), + ) { + Ok(threat) => threat, + Err(why) => { + report.push(f.unmapped(row.line, &s.title, format!("{why}: no status set"))); + continue; + } + }; + let status = row.get("Status").map(str::to_ascii_lowercase); + let Some(status) = status.filter(|st| THREAT_STATUS.contains(&st.as_str())) else { + report.push(f.unmapped( + row.line, + &s.title, + format!( + "the Status of {threat} is none of {}: no status set", + THREAT_STATUS.join(", ") + ), + )); + continue; + }; + let Some(record) = records.get_mut("threat", &threat) else { + continue; + }; + record.fields.insert("status".to_string(), json!(status)); + let planned = record.fields.get("mitigation").and_then(Json::as_str); + if let Some(mitigation) = row.get("Mitigation").filter(|m| Some(*m) != planned) { + report.push(f.unmapped( + row.line, + &s.title, + format!( + "the Mitigation `{mitigation}` differs from the plan's `{}`: the plan's is kept", + planned.unwrap_or_default() + ), + )); + } + report.push(Entry::at( + &f.at(row.line), + &s.title, + Outcome::Mapped, + format!("threat {threat}: status {status}"), + )); + } +} + +/// The Accepted Risks Log row `row` as `accepted_risk AR<n>` of the audit `audit`; its `at` the harness date a person +/// recorded. +fn accepted( + f: &PhaseFile<'_>, + s: &Section, + audit: &str, + row: &Row<'_>, + records: &mut Records, + report: &mut Report, +) { + let said = row.get("Risk ID").unwrap_or_default(); + let id = said.replace('-', ""); + if !ids::minted("AR", &id) { + report.push(f.unmapped( + row.line, + &s.title, + format!("the Risk ID `{said}` is no `AR-<n>`: not imported"), + )); + return; + } + let reference = row.get("Threat Ref").unwrap_or_default(); + let threat = match unique( + of_phase(f, records, "threat", |local, _| local == reference), + &format!("the threat `{reference}`"), + ) { + Ok(threat) => threat, + Err(why) => { + report.push(f.unmapped(row.line, &s.title, format!("{why}: not imported"))); + return; + } + }; + let mut fields = BTreeMap::new(); + fields.insert("threat".to_string(), json!(threat)); + for (column, field) in [("Rationale", "rationale"), ("Accepted By", "accepted_by")] { + if let Some(v) = row.get(column) { + fields.insert(field.to_string(), json!(v)); + } + } + match row.get("Date") { + Some(date) if is_date(date) => { + fields.insert("at".to_string(), json!(date)); + } + Some(date) => report.push(f.unmapped( + row.line, + &s.title, + format!("the Date `{date}` is no YYYY-MM-DD date: `at` left out"), + )), + None => {} + } + let mut record = f.within( + "accepted_risk", + ("audit", audit), + &id, + said, + fields, + row.line, + ); + record.refs.push(threat); + records.add(record, report); +} + +/// The `## Security Audit <date>` block `s` as `audit_run AU<n>`: `at` filled from the heading's date, the `Metric | +/// Count` table its counts. +fn audit_run( + f: &PhaseFile<'_>, + s: &Section, + audit: &str, + n: usize, + table: Option<&Table>, + records: &mut Records, + report: &mut Report, +) { + let mut fields = BTreeMap::new(); + let date = s.title.trim_start_matches(RUN).trim(); + if is_date(date) { + fields.insert("at".to_string(), json!(format!("{date}T00:00:00Z"))); + report.push(f.row("## Security Audit <date>", s.line, &s.title)); + } else { + report.push(f.unmapped( + s.line, + &s.title, + format!("the heading's `{date}` is no YYYY-MM-DD date: `at` left out"), + )); + } + let rows = table.into_iter().flat_map(|t| { + t.rows + .iter() + .enumerate() + .map(move |(i, cells)| Row::new(t, cells, t.line + 2 + i)) + }); + for row in rows { + let metric = row.get("Metric").unwrap_or_default(); + let field = match metric.to_ascii_lowercase().as_str() { + "threats found" | "threats total" | "total" => "total", + "closed" => "closed", + "open" => "open", + _ => { + report.push(f.unmapped( + row.line, + &s.title, + format!("the metric `{metric}` is no field of an audit run: not imported"), + )); + continue; + } + }; + match row.get("Count").and_then(|c| c.parse::<u64>().ok()) { + Some(count) => { + fields.insert(field.to_string(), json!(count)); + // The row's words name a field, they are not its value: the entry says which. + report.push(f.mapped(row.line, &s.title, &format!("audit_run.{field}"))); + } + None => report.push(f.unmapped( + row.line, + &s.title, + format!("the Count of `{metric}` is no whole number: left out"), + )), + } + } + let record = f.within( + "audit_run", + ("audit", audit), + &format!("AU{n}"), + &s.title, + fields, + s.line, + ); + records.add(record, report); +} diff --git a/gsd/import/src/read/state.rs b/gsd/import/src/read/state.rs new file mode 100644 index 0000000000..55a1ef61c9 --- /dev/null +++ b/gsd/import/src/read/state.rs @@ -0,0 +1,70 @@ +//! `STATE.md` maps nothing (13-RESEARCH Part B, the `STATE.md` fate; the rows are `table::sections::STATE`): the graph +//! computes its frontmatter and position, its session continuity is a session's, and each blocker is a Tier 2 entity. +//! Every section is reported with its outcome, so nothing of it is dropped silently. + +use gsd_kit::markdown; + +use super::{blocks_in, row}; +use crate::frontmatter; +use crate::records::Source; +use crate::report::{Entry, Outcome, Report}; +use crate::sections; + +const ST: &str = "STATE.md"; + +/// What a section no row names becomes. +const DERIVED: &str = + "no field holds it: STATE.md is derived from the project's other files and the graph"; + +/// Reports `text`, served at `path`, section by section. +pub fn read(path: &str, text: &str, report: &mut Report) { + let at = |line: usize| Source { + file: path.to_string(), + line, + }; + let (front, start) = frontmatter::split(text); + match front.and_then(|f| f.map(|f| frontmatter::read(&f)).transpose()) { + Ok(Some(_)) => report.push(row(ST, "---", &at(1), "---")), + Ok(None) => {} + Err(refused) => report.push(Entry::at( + &at(refused.line), + "---", + Outcome::Unmapped, + format!("frontmatter not read: {}", refused.reason), + )), + } + let body = frontmatter::body(text, start); + let blocks = markdown::inline_blocks(&body); + let all = sections::sections(&body); + for (i, s) in all.iter().enumerate() { + let here = at(s.line + 1); + match s.title.as_str() { + "Current Position" | "Session Continuity" if s.level == 2 => { + report.push(row(ST, &format!("## {}", s.title), &here, &s.title)); + } + "Blockers/Concerns" if s.level == 3 => { + // The section's own lines, up to the next heading: a sub-section reports itself. + let own = s.body.start..all.get(i + 1).map_or(s.body.end, |n| n.line); + let mut any = false; + for b in blocks_in(&blocks, &own) { + any = true; + let key = if b.text.trim() == "None yet." { + "None yet." + } else { + "### Blockers/Concerns" + }; + report.push(row(ST, key, &at(b.lines[0] + 1), &s.title)); + } + if !any { + report.push(row(ST, "None yet.", &here, &s.title)); + } + } + _ => report.push(Entry::at( + &here, + &s.title, + Outcome::Unmapped, + DERIVED.to_string(), + )), + } + } +} diff --git a/gsd/import/src/read/summary.rs b/gsd/import/src/read/summary.rs new file mode 100644 index 0000000000..c824386739 --- /dev/null +++ b/gsd/import/src/read/summary.rs @@ -0,0 +1,572 @@ +//! `NN-MM-SUMMARY.md` and a quick summary to a `summary` and its `deliverable`s (13-RESEARCH Part B, the +//! `NN-MM-SUMMARY.md` and `quick/` tables; the rows are `table::sections::{SUMMARY, SUMMARY_SHARED, QUICK, +//! QUICK_SUMMARY}`): the file stem gives the id, scoped by its plan; the frontmatter and the bold one-liner the fields; +//! each `coverage` item one `deliverable` (its checks' `status` is computed, never written). `started` and `completed` +//! are harness timestamps and never written (ADR 0391 D7). A summary whose plan file was not served is not imported. + +use std::collections::BTreeMap; + +use serde_json::{Map, Value as Json, json}; + +use super::Context; +use super::plan::{self, Doc, Scope, defined, list}; +use crate::frontmatter::{self, Located, Value}; +use crate::ids; +use crate::records::{Record, Records}; +use crate::report::{Entry, Outcome, Report}; +use crate::sections; + +/// The fate table's name of a phase summary. +pub const SM: &str = "NN-MM-SUMMARY.md"; + +/// A summary's `status:` values. +const STATUS: &[&str] = &["complete", "halted"]; + +/// A deliverable check's `kind` values. +const CHECK_KINDS: &[&str] = &[ + "unit", + "integration", + "e2e", + "automated_ui", + "manual_procedural", + "other", +]; + +/// Reads the phase summary `text`, served at `path` (`rel` under `.planning/`): `phases/<NN-slug>/<NN-MM>-SUMMARY.md`. +pub fn read_phase( + path: &str, + rel: &str, + text: &str, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let doc = Doc { + path, + format: SM, + prefix: "", + }; + let Some((dir, id)) = plan::in_phase(rel, "-SUMMARY.md").filter(|(_, id)| ids::plan(id)) else { + report.push(doc.unmapped( + 1, + "file name", + "the file name gives no plan id `NN-MM`: not imported".to_string(), + )); + return; + }; + if !has_plan(cx, &format!("phases/{dir}/{id}-PLAN.md"), &doc, report) { + return; + } + if let Some(scope) = plan::phase_scope(&doc, dir, id, cx, report) { + read(&doc, text, id, &scope, cx, records, report); + } +} + +/// Whether the plan file `rel` was served; reports the summary when it was not. +pub fn has_plan(cx: &Context<'_>, rel: &str, doc: &Doc<'_>, report: &mut Report) -> bool { + let found = cx.served.contains(&rel); + if !found { + report.push(doc.unmapped( + 1, + "file name", + format!("no plan for this summary (.planning/{rel} was not served): not imported"), + )); + } + found +} + +/// Reads the summary `text` of the plan `plan_id` under `scope`. +pub fn read( + doc: &Doc<'_>, + text: &str, + plan_id: &str, + scope: &Scope, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let plan = scope.plan_path(plan_id); + let id = format!("{plan}/{plan_id}-SUMMARY"); + let file = scope.file(); + let mut fields: BTreeMap<String, Json> = BTreeMap::new(); + fields.insert("plan".to_string(), json!(plan)); + let mut links = Vec::new(); + let (front, start) = plan::front(doc, text, report); + let mut coverage = None; + for (key, v) in &front { + let line = v.line; + let text = v.value.as_str().map(str::trim).filter(|t| !t.is_empty()); + match (key.as_str(), scope) { + ("phase" | "plan", Scope::Phase { number, .. }) => { + report.push(plan::names_file(doc, (key, v), plan_id, number)) + } + ("quick_id" | "slug", Scope::Quick) => { + report.push(doc.row("quick_id, slug", line, key)) + } + ("status", _) => { + match text + .map(str::to_ascii_lowercase) + .filter(|s| STATUS.contains(&s.as_str())) + { + Some(status) => { + fields.insert("status".to_string(), json!(status)); + } + None => report.push(doc.unmapped( + line, + key, + "a status none of complete, halted: not imported".to_string(), + )), + } + } + ("subsystem", _) => { + if let Some(t) = text { + fields.insert("subsystem".to_string(), json!(t)); + } + } + ("tags" | "provides" | "affects", _) => texts(doc, (key, v), key, &mut fields, report), + ("tech-stack", _) => tech_stack(doc, v, &mut fields, report), + ("requirements-completed", _) => match list(&v.value) { + Some(ids) => { + let kept = defined(doc, &ids, line, key, records, report); + links.extend(kept.iter().map(|r| ("requirements_completed", r.clone()))); + fields.insert("requirements_completed".to_string(), json!(kept)); + } + None => report.push(doc.unmapped( + line, + key, + format!("`{key}` is not a list of text: not imported"), + )), + }, + ("requires", _) => { + let blocks = requires(doc, v, cx, &mut links, report); + if !blocks.is_empty() { + fields.insert("requires".to_string(), json!(blocks)); + } + } + ("coverage", _) => coverage = Some(v), + _ => report.push(doc.row(key, line, key)), + } + } + if *scope == Scope::Quick { + for (field, value, key) in [ + ("subsystem", json!("quick"), "subsystem"), + ( + "requirements_completed", + json!([]), + "requirements-completed", + ), + ] { + if !fields.contains_key(field) { + fields.insert(field.to_string(), value); + report.push(doc.row(key, 1, key)); + } + } + } + let body = frontmatter::body(text, start); + body_sections(doc, &body, cx, &mut fields, report); + let title = records + .get("plan", &plan) + .map_or_else(|| plan_id.to_string(), |p| p.title.clone()); + records.add( + Record { + kind: "summary", + id: id.clone(), + title: format!("{title}: summary"), + file: file.clone(), + fields, + refs: vec![plan.clone()], + links, + source: doc.at(1), + }, + report, + ); + if let Some(v) = coverage { + deliverables(doc, v, (&id, &file), records, report); + } +} + +/// `tech-stack:`: `added` and `patterns`, each a list. +fn tech_stack( + doc: &Doc<'_>, + v: &Located<Value>, + fields: &mut BTreeMap<String, Json>, + report: &mut Report, +) { + let Value::Map(members) = &v.value else { + report.push(doc.unmapped( + v.line, + "tech-stack", + "tech-stack is not a map: not imported".to_string(), + )); + return; + }; + for (member, value) in members { + let key = format!("tech-stack.{member}"); + let field = match member.as_str() { + "added" => "tech_added", + "patterns" => "tech_patterns", + _ => { + report.push(doc.row(&key, value.line, &key)); + continue; + } + }; + texts(doc, (&key, value), field, fields, report); + } +} + +/// The list `v` of the key `key` into `field`, when it holds an item; reported when it is no list of text. +fn texts( + doc: &Doc<'_>, + (key, v): (&str, &Located<Value>), + field: &str, + fields: &mut BTreeMap<String, Json>, + report: &mut Report, +) { + match list(&v.value) { + Some(items) if !items.is_empty() => { + fields.insert(field.to_string(), json!(items)); + } + Some(_) => {} + None => report.push(doc.unmapped( + v.line, + key, + format!("`{key}` is not a list of text: not imported"), + )), + } +} + +/// `requires:` in its block form (`- phase: 01-core` with `provides:`), each block's phase as its path; the flow list of +/// plan ids names no `provides` and is reported. +fn requires( + doc: &Doc<'_>, + v: &Located<Value>, + cx: &Context<'_>, + links: &mut Vec<(&'static str, String)>, + report: &mut Report, +) -> Vec<Json> { + let items = match &v.value { + Value::List(items) => items, + Value::Str(s) if s.trim().is_empty() => return Vec::new(), + _ => { + report.push(doc.unmapped( + v.line, + "requires", + "requires is not a list: not imported".to_string(), + )); + return Vec::new(); + } + }; + let mut out = Vec::new(); + for item in items { + let Value::Map(members) = &item.value else { + report.push(doc.row("requires: [plan ids]", item.line, "requires")); + continue; + }; + for (member, value) in members { + if !matches!(member.as_str(), "phase" | "provides") { + report.push(doc.unmapped( + value.line, + "requires", + format!( + "a requires member `{member}` no row of the table names: no field holds it" + ), + )); + } + } + let get = |k: &str| { + item.value + .get(k) + .and_then(|v| v.value.as_str()) + .map(str::trim) + }; + let phase = get("phase").and_then(|p| ids::padded(p.split_once('-').map_or(p, |(n, _)| n))); + match ( + phase.and_then(|p| cx.roadmap.phases.get(&p)), + get("provides"), + ) { + (Some(path), Some(provides)) if !provides.is_empty() => { + links.push(("requires", path.clone())); + out.push(json!({"phase": path, "provides": provides})); + } + _ => report.push( + doc.unmapped( + item.line, + "requires", + "a requires block without a ROADMAP.md phase or a provides: not imported" + .to_string(), + ), + ), + } + } + out +} + +/// The body's sections: the H1 and its bold one-liner, the table's sections, `## Threat Flags` with `@gsd/security`. +fn body_sections( + doc: &Doc<'_>, + body: &str, + cx: &Context<'_>, + fields: &mut BTreeMap<String, Json>, + report: &mut Report, +) { + let lines: Vec<&str> = body.split('\n').collect(); + let fenced = sections::fenced(body); + let mut h1 = false; + // Whether a `##` section, reported with its sub-sections, holds the lines here. + let mut under = false; + let all = sections::sections(body); + for s in all.iter().cloned() { + let line = s.line + 1; + if s.level <= 2 { + under = s.level == 2; + } + match (s.level, s.title.as_str()) { + (1, _) if !h1 => { + h1 = true; + report.push(doc.row("# title", line, &s.title)); + let first = s + .body + .clone() + .find(|&n| !fenced[n] && !lines[n].trim().is_empty()); + let bold = first + .and_then(|n| lines[n].trim().strip_prefix("**")?.strip_suffix("**")) + .map(str::trim) + .filter(|l| !l.is_empty()); + // The title's own text past its one-liner (a paragraph, a list) is no field's. + let mine = super::own(&s, &all); + for b in gsd_kit::markdown::inline_blocks(body) { + let left = b.lines.iter().copied().find(|&n| { + mine.contains(&n) && !(bold.is_some() && Some(n) == first) + }); + if let Some(at) = left { + report.push(doc.unmapped( + at + 1, + &s.title, + "text under the title other than its bold one-liner: no field holds it".to_string(), + )); + } + } + match bold { + Some(one_liner) => { + fields.insert("one_liner".to_string(), json!(one_liner)); + } + None => report.push(doc.unmapped(line, &s.title, "no bold one-liner under the title: not imported".to_string())), + } + } + (2, "Threat Flags") if cx.manifest.security => { + report.push(super::mapped(&doc.at(line), &s.title, "summary.threat_flags")); + let flags: Vec<String> = gsd_kit::markdown::tables(body) + .into_iter() + .filter(|t| t.heading == "Threat Flags") + .flat_map(|t| t.rows) + .map(|cells| cells.iter().map(|c| c.trim()).collect::<Vec<_>>().join(" | ")) + .collect(); + if !flags.is_empty() { + fields.insert("threat_flags".to_string(), json!(flags)); + } + } + (2, "Threat Flags") => report.push(Entry::at( + &doc.at(line), + &s.title, + Outcome::NeedsExtension, + "summary.threat_flags follows @gsd/security's threat model, which the project does not load".to_string(), + )), + (2, title @ ("Task Commits" | "Performance" | "Accomplishments" | "Issues Encountered" + | "Next Phase Readiness" | "Deviations from Plan")) => { + report.push(doc.row(&format!("## {title}"), line, title)); + } + // A sub-section of a `##` section is its section's; one under the title alone is no row's. + (3.., _) if under => {} + (_, title) => report.push(doc.unmapped( + line, + title, + format!("a section no row of the {} table names: no field holds it", doc.format), + )), + } + } +} + +/// Each `coverage` item of `v` as a `deliverable` of the summary `summary`, written to `file`. +fn deliverables( + doc: &Doc<'_>, + v: &Located<Value>, + (summary, file): (&str, &str), + records: &mut Records, + report: &mut Report, +) { + let Value::List(items) = &v.value else { + report.push(doc.unmapped( + v.line, + "coverage", + "coverage is not a list: not imported".to_string(), + )); + return; + }; + for item in items { + let Value::Map(members) = &item.value else { + report.push(doc.unmapped( + item.line, + "coverage", + "a coverage item that is not a map: not imported".to_string(), + )); + continue; + }; + let mut fields: BTreeMap<String, Json> = BTreeMap::new(); + fields.insert("summary".to_string(), json!(summary)); + let mut links = Vec::new(); + let mut id = None; + for (key, value) in members { + let text = value + .value + .as_str() + .map(str::trim) + .filter(|t| !t.is_empty()); + let bad = |why: &str| { + doc.unmapped( + value.line, + "coverage", + format!("`{key}` {why}: not imported"), + ) + }; + match key.as_str() { + "id" => match text.filter(|t| ids::name(t)) { + Some(t) => id = Some(t.to_string()), + None => report.push(bad("is not an id a deliverable takes")), + }, + "description" | "rationale" => match text { + Some(t) => { + fields.insert(key.clone(), json!(t)); + } + None => report.push(bad("is not one text")), + }, + "requirement" if matches!(value.value, Value::List(_) | Value::Map(_)) => { + report.push(bad("is not one requirement id")) + } + "requirement" => { + let kept = defined( + doc, + &text.map(str::to_string).into_iter().collect::<Vec<_>>(), + value.line, + key, + records, + report, + ); + if let Some(r) = kept.into_iter().next() { + links.push(("requirement", r.clone())); + fields.insert(key.clone(), json!(r)); + } + } + "human_judgment" => match text { + Some("true") => { + fields.insert(key.clone(), json!(true)); + } + Some("false") => { + fields.insert(key.clone(), json!(false)); + } + _ => report.push(bad("is neither true nor false")), + }, + "verification" => { + let checks = checks(doc, value, report); + if !checks.is_empty() { + fields.insert("checks".to_string(), json!(checks)); + } + } + _ => report.push(doc.unmapped( + value.line, + "coverage", + format!("a member `{key}` no row of the table names: no field holds it"), + )), + } + } + let Some(id) = id else { + report.push(doc.unmapped( + item.line, + "coverage", + "a coverage item with no id: not imported".to_string(), + )); + continue; + }; + let title = fields + .get("description") + .and_then(Json::as_str) + .map_or_else(|| id.clone(), str::to_string); + records.add( + Record { + kind: "deliverable", + id: format!("{summary}/{id}"), + title, + file: file.to_string(), + fields, + refs: vec![summary.to_string()], + links, + source: doc.at(item.line), + }, + report, + ); + } +} + +/// A coverage item's `verification` list as `checks` blocks `{kind, ref}`; each `status` is reported computed, and any +/// other member, a check that is no map and a value that is no list are reported. +fn checks(doc: &Doc<'_>, v: &Located<Value>, report: &mut Report) -> Vec<Json> { + let items = match &v.value { + Value::List(items) => items.as_slice(), + Value::Str(s) if s.trim().is_empty() => &[], + _ => { + report.push(doc.unmapped( + v.line, + "coverage", + "`verification` is not a list: not imported".to_string(), + )); + &[] + } + }; + let mut out = Vec::new(); + for item in items { + let Value::Map(members) = &item.value else { + report.push(doc.unmapped( + item.line, + "coverage", + "a check that is not a map: not imported".to_string(), + )); + continue; + }; + let get = |k: &str| item.value.get(k); + for (member, value) in members { + match member.as_str() { + "kind" | "ref" => {} + "status" => { + report.push(doc.row("coverage verification status", value.line, "coverage")) + } + _ => report.push(doc.unmapped( + value.line, + "coverage", + format!( + "a check member `{member}` no row of the table names: no field holds it" + ), + )), + } + } + let text = |k: &str| get(k).and_then(|v| v.value.as_str()).map(str::trim); + match ( + text("kind").filter(|k| CHECK_KINDS.contains(k)), + text("ref").filter(|r| !r.is_empty()), + ) { + (Some(kind), Some(reference)) => { + let mut block = Map::new(); + block.insert("kind".to_string(), json!(kind)); + block.insert("ref".to_string(), json!(reference)); + out.push(Json::Object(block)); + } + _ => report.push(doc.unmapped( + item.line, + "coverage", + format!( + "a check without a kind of {} or a ref: not imported", + CHECK_KINDS.join(", ") + ), + )), + } + } + out +} diff --git a/gsd/import/src/read/tasks.rs b/gsd/import/src/read/tasks.rs new file mode 100644 index 0000000000..90cf7fc987 --- /dev/null +++ b/gsd/import/src/read/tasks.rs @@ -0,0 +1,374 @@ +//! A plan's `<task>` elements and its frontmatter `must_haves` (13-RESEARCH Part B, the `NN-MM-PLAN.md` table; the rows +//! are `table::sections::PLAN_SHARED` and `QUICK_PLAN`): each `auto`, `tdd` or `tracer` task is `task T<n>`, each truth +//! `truth TR<n>`, each artifact `artifact AR<n>`, each key link `key_link KL<n>`, numbered in document order and scoped +//! by the plan. A `checkpoint:*` task and a `<behavior>` block are reported with the table's reasons. + +use std::collections::BTreeMap; + +use serde_json::{Map, Value as Json, json}; + +use super::plan::{Doc, elements, items, list}; +use crate::frontmatter::{Located, Value}; +use crate::records::{Record, Records}; +use crate::report::Report; + +/// The task types a `task` takes; a `checkpoint:*` task is a `checkpoint` (Tier 2). +const TASK_TYPES: &[&str] = &["auto", "tdd", "tracer"]; + +/// The table's key of a mapped task. +const TASK: &str = "<task type=\"auto|tdd|tracer\">"; + +/// One entity scoped by the plan `plan`, written to `file`. +pub fn scoped( + doc: &Doc<'_>, + kind: &'static str, + id: String, + title: String, + (plan, file): (&str, &str), + mut fields: BTreeMap<String, Json>, + line: usize, +) -> Record { + fields.insert("plan".to_string(), json!(plan)); + Record { + kind, + id: format!("{plan}/{id}"), + title, + file: file.to_string(), + fields, + refs: vec![plan.to_string()], + links: Vec::new(), + source: doc.at(line), + } +} + +/// Reads the `<task>` elements of `body` into tasks of the plan `plan`, written to `file`. +pub fn tasks( + doc: &Doc<'_>, + body: &str, + plan: &str, + file: &str, + records: &mut Records, + report: &mut Report, +) { + let mut n = 0; + for t in elements(doc, body, 1, "task", report) { + let kind = t + .attrs + .iter() + .find(|(k, _)| k == "type") + .map_or("", |(_, v)| v.as_str()); + if kind.starts_with("checkpoint:") { + let key = "<task type=\"checkpoint:*\">"; + report.push(doc.row(key, t.line, key)); + continue; + } + if !TASK_TYPES.contains(&kind) { + report.push(doc.unmapped( + t.line, + "<task>", + format!("a task of type `{kind}`, none of auto, tdd, tracer or checkpoint:*: not imported"), + )); + continue; + } + n += 1; + let mut fields = BTreeMap::new(); + fields.insert("type".to_string(), json!(kind)); + let child = |name: &str, report: &mut Report| { + elements(doc, &t.body, t.line, name, report) + .into_iter() + .next() + }; + let title = child("name", report).map_or_else( + || format!("T{n}"), + |c| task_title(c.body.trim()).to_string(), + ); + if let Some(c) = child("files", report) { + let files: Vec<&str> = c + .body + .split(',') + .map(str::trim) + .filter(|f| !f.is_empty()) + .collect(); + if !files.is_empty() { + fields.insert("files".to_string(), json!(files)); + } + } + if let Some(c) = child("read_first", report) { + // A `- path (why)` line: the path is its first word. + let paths: Vec<&str> = c + .body + .split('\n') + .filter_map(|l| l.trim().strip_prefix("- ")) + .filter_map(|l| l.split_whitespace().next()) + .map(|p| p.trim_matches('`')) + .filter(|p| !p.is_empty()) + .collect(); + if !paths.is_empty() { + fields.insert("read_first".to_string(), json!(paths)); + } + } + for (name, field) in [("action", "action"), ("done", "done")] { + if let Some(c) = child(name, report).filter(|c| !c.body.trim().is_empty()) { + fields.insert(field.to_string(), json!(c.body.trim())); + } + } + if let Some(c) = child("verify", report) { + verify(doc, &c.body, c.line, &mut fields, report); + } + if let Some(c) = child("acceptance_criteria", report) { + let all = items(&c.body); + if !all.is_empty() { + fields.insert("acceptance".to_string(), json!(all)); + } + } + if let Some(c) = child("behavior", report) { + report.push(doc.row("<behavior>", c.line, TASK)); + } + let record = scoped( + doc, + "task", + format!("T{n}"), + title, + (plan, file), + fields, + t.line, + ); + records.add(record, report); + } +} + +/// A `<name>`'s title: the text after `Task <N>: `, or all of it. +fn task_title(name: &str) -> &str { + name.strip_prefix("Task ") + .and_then(|rest| rest.split_once(": ")) + .filter(|(n, _)| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) + .map_or(name, |(_, title)| title.trim()) +} + +/// A `<verify>` body: its `<automated>` commands, each with the `<fails_when>` of the same rank, as `verify` blocks; +/// a body with none as `verify_text`. +fn verify( + doc: &Doc<'_>, + body: &str, + line: usize, + fields: &mut BTreeMap<String, Json>, + report: &mut Report, +) { + let automated = elements(doc, body, line, "automated", report); + if automated.is_empty() { + if !body.trim().is_empty() { + fields.insert("verify_text".to_string(), json!(body.trim())); + } + return; + } + let fails = elements(doc, body, line, "fails_when", report); + let blocks: Vec<Json> = automated + .iter() + .enumerate() + .map(|(i, a)| { + let mut block = Map::new(); + block.insert("automated".to_string(), json!(a.body.trim())); + if let Some(f) = fails.get(i) { + block.insert("fails_when".to_string(), json!(f.body.trim())); + } + Json::Object(block) + }) + .collect(); + fields.insert("verify".to_string(), json!(blocks)); +} + +/// Reads the frontmatter `must_haves` map `v` into the truths, artifacts and key links of the plan `plan`. +pub fn must_haves( + doc: &Doc<'_>, + v: &Located<Value>, + plan: &str, + file: &str, + records: &mut Records, + report: &mut Report, +) { + let Value::Map(entries) = &v.value else { + report.push(doc.unmapped( + v.line, + "must_haves", + "must_haves is not a map: not imported".to_string(), + )); + return; + }; + for (key, value) in entries { + let section = format!("must_haves.{key}"); + let read = match key.as_str() { + "truths" => truth, + "artifacts" => artifact, + "key_links" => key_link, + _ => { + report.push(doc.row(§ion, value.line, §ion)); + continue; + } + }; + let items: &[Located<Value>] = match &value.value { + Value::List(items) => items, + Value::Str(s) if s.trim().is_empty() => &[], + _ => { + report.push(doc.unmapped( + value.line, + §ion, + format!("{section} is not a list: not imported"), + )); + continue; + } + }; + for (i, item) in items.iter().enumerate() { + let record = read(doc, item, i + 1, (plan, file), report); + if let Some(record) = record { + records.add(record, report); + } + } + } +} + +/// A truth: one text. +fn truth( + doc: &Doc<'_>, + item: &Located<Value>, + n: usize, + owner: (&str, &str), + report: &mut Report, +) -> Option<Record> { + let Some(text) = item.value.as_str().map(str::trim).filter(|t| !t.is_empty()) else { + report.push(doc.unmapped( + item.line, + "must_haves.truths", + "a truth that is not one text: not imported".to_string(), + )); + return None; + }; + let fields = BTreeMap::from([("text".to_string(), json!(text))]); + Some(scoped( + doc, + "truth", + format!("TR{n}"), + text.to_string(), + owner, + fields, + item.line, + )) +} + +/// The members of a must-have map `item` that the kind `kind` takes, each through `read`; any other member reported. +fn members( + doc: &Doc<'_>, + item: &Located<Value>, + section: &str, + read: impl Fn(&str, &Value) -> Option<Option<Json>>, + report: &mut Report, +) -> Option<BTreeMap<String, Json>> { + let Value::Map(entries) = &item.value else { + report.push(doc.unmapped( + item.line, + section, + "an item that is not a map: not imported".to_string(), + )); + return None; + }; + let mut fields = BTreeMap::new(); + for (key, value) in entries { + match read(key, &value.value) { + Some(Some(json)) => { + fields.insert(key.clone(), json); + } + Some(None) => report.push(doc.unmapped( + value.line, + section, + format!("`{key}` is not a value its field takes: not imported"), + )), + None => report.push(doc.unmapped( + value.line, + section, + format!("a member `{key}` no row of the table names: no field holds it"), + )), + } + } + Some(fields) +} + +/// A text member's value; none when it is not one text. +fn text(value: &Value) -> Option<Json> { + value + .as_str() + .map(str::trim) + .filter(|t| !t.is_empty()) + .map(|t| json!(t)) +} + +/// An artifact: `path`, `provides`, `contains`, `min_lines` (a whole number), `exports` (a list). +fn artifact( + doc: &Doc<'_>, + item: &Located<Value>, + n: usize, + owner: (&str, &str), + report: &mut Report, +) -> Option<Record> { + let section = "must_haves.artifacts"; + let fields = members( + doc, + item, + section, + |key, value| match key { + "path" | "provides" | "contains" => Some(text(value)), + "min_lines" => Some( + value + .as_str() + .and_then(|v| v.trim().parse::<u64>().ok()) + .map(|n| json!(n)), + ), + "exports" => Some(list(value).map(|l| json!(l))), + _ => None, + }, + report, + )?; + let title = ["provides", "path"] + .iter() + .find_map(|k| fields.get(*k).and_then(Json::as_str)) + .map_or_else(|| format!("AR{n}"), str::to_string); + Some(scoped( + doc, + "artifact", + format!("AR{n}"), + title, + owner, + fields, + item.line, + )) +} + +/// A key link: `from`, `to`, `via`, `pattern`; its title `<from> -> <to>`. +fn key_link( + doc: &Doc<'_>, + item: &Located<Value>, + n: usize, + owner: (&str, &str), + report: &mut Report, +) -> Option<Record> { + let section = "must_haves.key_links"; + let fields = members( + doc, + item, + section, + |key, value| match key { + "from" | "to" | "via" | "pattern" => Some(text(value)), + _ => None, + }, + report, + )?; + let end = |k: &str| fields.get(k).and_then(Json::as_str).unwrap_or("?"); + let title = format!("{} -> {}", end("from"), end("to")); + Some(scoped( + doc, + "key_link", + format!("KL{n}"), + title, + owner, + fields, + item.line, + )) +} diff --git a/gsd/import/src/read/threats.rs b/gsd/import/src/read/threats.rs new file mode 100644 index 0000000000..db5541ba4e --- /dev/null +++ b/gsd/import/src/read/threats.rs @@ -0,0 +1,207 @@ +//! A plan's `<threat_model>` to `@gsd/security`'s kinds (ADR 0391 D11; 13-RESEARCH Part B, the `SECURITY.md` and +//! `<threat_model>` table; the rows are `<threat_model> ## Trust Boundaries` and `## STRIDE Threat Register` of +//! `table::sections::PLAN`): each Trust Boundaries row a `trust_boundary TB<n>`, each register row a `threat` named by +//! its Threat ID, both scoped by the plan. Without `@gsd/security` loaded, each element is one needs-extension entry +//! and no record. A threat's `status` is the auditor's (`SECURITY.md`, 13-08): never written here. + +use std::collections::BTreeMap; + +use serde_json::{Value as Json, json}; + +use super::plan::{Doc, elements}; +use super::tasks::scoped; +use crate::ids; +use crate::records::Records; +use crate::report::{Entry, Outcome, Report}; + +/// `@gsd/security`'s `threat.category` values, in STRIDE order: a letter is the first of its word. +const CATEGORY: &[&str] = &[ + "spoofing", + "tampering", + "repudiation", + "information_disclosure", + "denial_of_service", + "elevation_of_privilege", +]; +const SEVERITY: &[&str] = &["critical", "high", "medium", "low"]; +const DISPOSITION: &[&str] = &["mitigate", "accept", "transfer"]; + +const BOUNDARIES: &str = "Trust Boundaries"; +const REGISTER: &str = "STRIDE Threat Register"; + +/// Reads the `<threat_model>` elements of the plan body `body` into trust boundaries and threats of the plan `plan`, +/// written to `file`, when `security`; else reports each element. +pub fn read( + doc: &Doc<'_>, + body: &str, + (plan, file): (&str, &str), + security: bool, + records: &mut Records, + report: &mut Report, +) { + let mut boundary = 0; + for element in elements(doc, body, 1, "threat_model", report) { + if !security { + report.push(Entry::at( + &doc.at(element.line), + "<threat_model>", + Outcome::NeedsExtension, + "trust_boundary and threat are kinds of @gsd/security, which the project does not load".to_string(), + )); + continue; + } + for h in gsd_kit::markdown::headings(&element.body) { + let section = format!("<threat_model> ## {}", h.text); + let source = doc.at(element.line + h.line); + report.push(match h.text.as_str() { + BOUNDARIES => super::mapped(&source, §ion, "each row a trust_boundary"), + REGISTER => super::mapped(&source, §ion, "each row a threat"), + _ => doc.unmapped( + element.line + h.line, + §ion, + "a section no row of the plan's table names: not imported".to_string(), + ), + }); + } + for table in gsd_kit::markdown::tables(&element.body) { + // The body starts on the opening tag's line; a table's line is 0-based, its rows two lines below it. + let at = element.line + table.line; + let section = format!("<threat_model> ## {}", table.heading); + let kind = match table.heading.as_str() { + BOUNDARIES => "trust_boundary", + REGISTER => "threat", + _ => { + report.push(doc.unmapped( + at, + §ion, + "a table no row of the plan's table names: not imported".to_string(), + )); + continue; + } + }; + let columns = columns(doc, &table.header, kind, at, §ion, report); + for (i, cells) in table.rows.iter().enumerate() { + let line = at + 2 + i; + let cell = |name: &str| { + columns + .get(name) + .and_then(|&c| cells.get(c)) + .map(|c| c.trim()) + .filter(|c| !c.is_empty()) + }; + let built = if kind == "trust_boundary" { + boundary += 1; + Ok((format!("TB{boundary}"), trust_boundary(&cell))) + } else { + threat(&cell) + }; + let (id, (title, fields)) = match built { + Ok(built) => built, + Err(why) => { + report.push(doc.unmapped(line, §ion, format!("{why}: not imported"))); + continue; + } + }; + let title = title.unwrap_or_else(|| id.clone()); + let record = scoped(doc, kind, id, title, (plan, file), fields, line); + records.add(record, report); + } + } + } +} + +/// The columns of a table's `header` this reader takes, by name; each other column is reported once. +fn columns( + doc: &Doc<'_>, + header: &[String], + kind: &str, + at: usize, + section: &str, + report: &mut Report, +) -> BTreeMap<String, usize> { + let known: &[&str] = match kind { + "trust_boundary" => &["Boundary", "Description"], + _ => &[ + "Threat ID", + "Category", + "Component", + "Severity", + "Disposition", + "Mitigation Plan", + "Mitigation", + ], + }; + let mut out = BTreeMap::new(); + for (i, name) in header.iter().map(|h| h.trim()).enumerate() { + if known.contains(&name) { + out.insert(name.to_string(), i); + } else { + report.push(doc.unmapped( + at, + section, + format!("a column `{name}` no row of the table names: not imported"), + )); + } + } + out +} + +type Fields = (Option<String>, BTreeMap<String, Json>); + +/// A Trust Boundaries row: its title (the boundary) and fields. A missing cell is a missing field, which the emit +/// reports. +fn trust_boundary<'c>(cell: &impl Fn(&str) -> Option<&'c str>) -> Fields { + let mut fields = BTreeMap::new(); + for (column, field) in [("Boundary", "boundary"), ("Description", "description")] { + if let Some(v) = cell(column) { + fields.insert(field.to_string(), json!(v)); + } + } + (cell("Boundary").map(str::to_string), fields) +} + +/// A register row: its Threat ID, title (the component) and fields; or why it is refused (an id the grammar refuses, +/// a value no enum of `threat` holds). +fn threat<'c>(cell: &impl Fn(&str) -> Option<&'c str>) -> Result<(String, Fields), String> { + let id = cell("Threat ID").unwrap_or_default(); + if !ids::name(id) { + return Err(format!("the Threat ID `{id}` is no id a threat takes")); + } + let mut fields = BTreeMap::new(); + if let Some(v) = cell("Category") { + let word = v.to_ascii_lowercase().replace([' ', '-'], "_"); + let found = CATEGORY + .iter() + .find(|c| **c == word || (word.len() == 1 && c.starts_with(&word))) + .ok_or_else(|| { + format!( + "the Category `{v}` is no STRIDE letter or word ({})", + CATEGORY.join(", ") + ) + })?; + fields.insert("category".to_string(), json!(found)); + } + for (column, field, values) in [ + ("Severity", "severity", SEVERITY), + ("Disposition", "disposition", DISPOSITION), + ] { + if let Some(v) = cell(column) { + let word = v.to_ascii_lowercase(); + if !values.contains(&word.as_str()) { + return Err(format!( + "the {column} `{v}` is none of {}", + values.join(", ") + )); + } + fields.insert(field.to_string(), json!(word)); + } + } + if let Some(v) = cell("Component") { + fields.insert("component".to_string(), json!(v)); + } + if let Some(v) = cell("Mitigation Plan").or_else(|| cell("Mitigation")) { + fields.insert("mitigation".to_string(), json!(v)); + } + let title = cell("Component").map(str::to_string); + Ok((id.to_string(), (title, fields))) +} diff --git a/gsd/import/src/read/uat.rs b/gsd/import/src/read/uat.rs new file mode 100644 index 0000000000..81bc02fb86 --- /dev/null +++ b/gsd/import/src/read/uat.rs @@ -0,0 +1,453 @@ +//! `NN-UAT.md` to a `uat_session`, its `uat_test`s and their `uat_gap`s (13-RESEARCH Part B, the UAT table; the rows +//! are `table::sections::UAT`). The file stem is the session's id; each `### N. Title` under `## Tests` is a test `U<N>` +//! scoped by the session, its `key: value` lines read by the frontmatter reader (so `expected: |` is a block scalar); +//! each `- truth:` item of `## Gaps` a gap `G<n>` scoped by the test it names. A test's `result` is a harness value a +//! person recorded: written as a declared peer of `@gsd/core` (ADR 0391 D7). Statuses and totals are computed. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{Value as Json, json}; + +use super::plan::{front, list}; +use super::{Context, PhaseFile, is_timestamp, phase_file}; +use crate::frontmatter::{self, Entries, Front, Located, Value}; +use crate::ids; +use crate::records::Records; +use crate::report::{Entry, Outcome, Report}; +use crate::sections::{self, Section}; + +/// The fate table's name of a UAT session. +pub const UA: &str = "NN-UAT.md"; + +/// `uat_test.result`'s values. +const RESULT: &[&str] = &["pending", "pass", "issue", "skipped", "blocked"]; +const SEVERITY: &[&str] = &["blocker", "major", "minor", "cosmetic"]; +const BLOCKED_BY: &[&str] = &[ + "server", + "physical_device", + "release_build", + "third_party", + "prior_phase", +]; + +const UNKNOWN: &str = "a section no row of the NN-UAT.md table names: not imported"; +const TEST: &str = "### N. Title"; + +/// Reads the UAT session `text`, served at `path` (`rel` under `.planning/`): `phases/<NN-slug>/<NN>-UAT.md`. +pub fn read( + path: &str, + rel: &str, + text: &str, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let Some(f) = phase_file(path, rel, UA, cx, report) else { + return; + }; + let session = format!("{}/{}", f.phase, f.stem); + let mut fields = BTreeMap::new(); + let mut sources = Vec::new(); + let (front, start) = front(&f.doc, text, report); + for (key, v) in &front { + let line = v.line; + let text = v.value.as_str().map(str::trim).filter(|t| !t.is_empty()); + match key.as_str() { + "phase" | "status" | "updated" => report.push(f.doc.row(key, line, key)), + "started" => match text { + Some(t) if is_timestamp(t) => { + fields.insert("started".to_string(), json!(t)); + } + _ => report.push(f.doc.unmapped( + line, + key, + "`started` is not an RFC 3339 timestamp: left out".to_string(), + )), + }, + "source" => { + for (item, at) in items(v) { + match summary(&item, cx) { + Some(path) => sources.push(path), + None => report.push(f.doc.unmapped( + at, + key, + format!( + "`{item}` names no NN-MM-SUMMARY.md of a roadmap phase: left out" + ), + )), + } + } + } + _ => report.push(f.doc.unmapped( + line, + key, + format!("a key `{key}` no row of the NN-UAT.md table names: not imported"), + )), + } + } + // Written as read, empty or not: a session none of whose summaries is imported is dropped by emit + // (`kinds::NON_EMPTY`), whether the summary was never named or dropped later. + fields.insert("source".to_string(), json!(sources)); + let body = frontmatter::body(text, start); + let lines: Vec<&str> = body.split('\n').map(|l| l.trim_end_matches('\r')).collect(); + let all = sections::sections(&body); + let mut tests = BTreeSet::new(); + let mut parent = String::new(); + let mut gaps = Vec::new(); + for s in &all { + if s.level <= 2 { + parent = s.title.clone(); + } + match (s.level, parent.as_str(), s.title.as_str()) { + (2, _, "Tests") => report.push(f.row("## Tests", s.line, &s.title)), + (3, "Tests", _) => { + if let Some(n) = test(&f, &session, s, &lines, records, report) { + tests.insert(n); + } + } + (2, _, "Current Test" | "Summary" | "Deferred Follow-Ups") => { + report.push(f.row(&format!("## {}", s.title), s.line, &s.title)) + } + (2, _, "Gaps") => gaps.push(s), + _ => report.push(f.unmapped(s.line, &s.title, UNKNOWN.to_string())), + } + } + // The gaps last: each names a test of the file. + let mut gap = 0; + for s in gaps { + report.push(Entry::at( + &f.at(s.line), + &s.title, + Outcome::Mapped, + "each item is a uat_gap".to_string(), + )); + for (at, item) in gap_items(&lines, s) { + gap += 1; + read_gap(&f, &session, gap, (at, &item), &tests, records, report); + } + } + let mut record = f.within( + "uat_session", + ("phase", &f.phase), + &f.stem, + &f.stem, + fields, + 0, + ); + record + .links + .extend(sources.into_iter().map(|s| ("source", s))); + records.add(record, report); +} + +/// The texts of a list (or one text) with each item's 1-based line. +fn items(v: &Located<Value>) -> Vec<(String, usize)> { + match &v.value { + Value::List(items) => items + .iter() + .filter_map(|i| Some((i.value.as_str()?.trim().to_string(), i.line))) + .collect(), + _ => list(&v.value) + .unwrap_or_default() + .into_iter() + .map(|t| (t, v.line)) + .collect(), + } +} + +/// The graph path of the summary `item` names (`01-01-SUMMARY.md` is `v1.0/01/01-01/01-01-SUMMARY`), when its plan's +/// phase is the roadmap's. +fn summary(item: &str, cx: &Context<'_>) -> Option<String> { + let name = item.rsplit('/').next().unwrap_or(item); + let plan = name.strip_suffix("-SUMMARY.md")?; + let number = plan.rsplit_once('-')?.0; + let phase = cx.roadmap.phases.get(number).filter(|_| ids::plan(plan))?; + Some(format!("{phase}/{plan}/{plan}-SUMMARY")) +} + +/// The entries the frontmatter reader reads from `lines`, the first at the 0-based `first`; its refusal reported. +fn block( + f: &PhaseFile<'_>, + lines: Vec<&str>, + first: usize, + report: &mut Report, +) -> Option<Entries> { + match frontmatter::read(&Front { + lines, + line: first + 1, + }) { + Ok(map) => Some(map.value), + Err(refused) => { + report.push(f.doc.unmapped( + refused.line, + "## Tests", + format!("not read: {}", refused.reason), + )); + None + } + } +} + +/// `value` when it is one of `values`, else reported at its line and none. +fn word( + f: &PhaseFile<'_>, + key: &str, + v: &Located<Value>, + values: &[&str], + report: &mut Report, +) -> Option<Json> { + let text = v.value.as_str().map(str::trim).unwrap_or_default(); + if values.contains(&text) { + return Some(json!(text)); + } + report.push(f.doc.unmapped( + v.line, + key, + format!("`{key}: {text}` is none of {}: left out", values.join(", ")), + )); + None +} + +/// The test `### N. Title` of `s`: `U<N>` with its key lines; its number, when its heading gives one. +fn test( + f: &PhaseFile<'_>, + session: &str, + s: &Section, + lines: &[&str], + records: &mut Records, + report: &mut Report, +) -> Option<u64> { + let parsed = s.title.split_once(". ").and_then(|(n, title)| { + let n = n.trim().parse::<u64>().ok().filter(|n| *n > 0)?; + Some((n, title.trim())) + }); + let Some((n, title)) = parsed else { + report.push(f.unmapped( + s.line, + &s.title, + "a test heading is `### N. Title`: not imported".to_string(), + )); + return None; + }; + let mut fields = BTreeMap::new(); + let body: Vec<&str> = lines[s.body.clone()].to_vec(); + if let Some(keys) = block(f, body, s.body.start, report) { + for (key, v) in &keys { + let text = v.value.as_str().map(str::trim).filter(|t| !t.is_empty()); + let value = match key.as_str() { + "expected" | "reported" | "reason" => text.map(|t| json!(t)), + "result" => word(f, key, v, RESULT, report), + "severity" => word(f, key, v, SEVERITY, report), + "blocked_by" => word(f, key, v, BLOCKED_BY, report), + _ => { + report.push(f.doc.unmapped( + v.line, + key, + format!("a key `{key}` no row of the {TEST} table names: not imported"), + )); + None + } + }; + if let Some(value) = value { + fields.insert(key.clone(), value); + } + } + } + let record = f.within( + "uat_test", + ("session", session), + &format!("U{n}"), + title, + fields, + s.line, + ); + records.add(record, report); + Some(n) +} + +/// Each `- ` item of the gaps section `s`: its 0-based line and its lines, the marker and the item's indent removed. +fn gap_items<'l>(lines: &[&'l str], s: &Section) -> Vec<(usize, Vec<&'l str>)> { + let mut out: Vec<(usize, Vec<&str>)> = Vec::new(); + for n in s.body.clone() { + let line = lines[n]; + if let Some(first) = line.strip_prefix("- ") { + out.push((n, vec![first])); + } else if let Some((_, item)) = out.last_mut() { + item.push(line.strip_prefix(" ").unwrap_or(line)); + } + } + out +} + +/// The items of a gap's list `key` (`missing`, `artifacts`), each read by `read`, which reports an item it does not +/// take; a value that is neither a list nor empty is reported. +fn gap_list( + f: &PhaseFile<'_>, + (key, v): (&str, &Located<Value>), + report: &mut Report, + read: impl Fn(&Located<Value>, &mut Report) -> Option<Json>, +) -> Vec<Json> { + match &v.value { + Value::List(items) => items.iter().filter_map(|item| read(item, report)).collect(), + Value::Str(s) if s.trim().is_empty() => Vec::new(), + _ => { + report.push(f.doc.unmapped( + v.line, + key, + format!("`{key}` is not a list: not imported"), + )); + Vec::new() + } + } +} + +/// One `artifacts` item: a path (`- src/a.js`), or GSD's diagnosed form `- path: ..` with `issue: ..` +/// (gsd-core templates/UAT.md); any other member, or an item holding neither, is reported. +fn artifact(f: &PhaseFile<'_>, item: &Located<Value>, report: &mut Report) -> Option<Json> { + let members = match &item.value { + Value::Str(path) if path.trim().is_empty() => return None, + Value::Str(path) => return Some(json!({ "path": path.trim() })), + Value::Map(members) => members, + Value::List(_) => { + report.push(f.doc.unmapped( + item.line, + "artifacts", + "an artifact that is a list: not imported".to_string(), + )); + return None; + } + }; + let mut block = serde_json::Map::new(); + for (member, v) in members { + match (member.as_str(), v.value.as_str().map(str::trim)) { + ("path" | "issue", Some(t)) if !t.is_empty() => { + block.insert(member.clone(), json!(t)); + } + ("path" | "issue", Some(_)) => {} + ("path" | "issue", None) => report.push(f.doc.unmapped( + v.line, + "artifacts", + format!("an artifact's `{member}` is not one text: not imported"), + )), + _ => report.push(f.doc.unmapped( + v.line, + "artifacts", + format!( + "an artifact member `{member}` no row of the ## Gaps table names: not imported" + ), + )), + } + } + if block.is_empty() { + report.push(f.doc.unmapped( + item.line, + "artifacts", + "an artifact with neither a path nor an issue: not imported".to_string(), + )); + return None; + } + Some(Json::Object(block)) +} + +/// The gap `G<n>` read from `item`, at the 0-based `at`: scoped by the test its `test:` names, which must be a test of +/// the file (`tests`); else reported and dropped. +fn read_gap( + f: &PhaseFile<'_>, + session: &str, + n: usize, + (at, item): (usize, &[&str]), + tests: &BTreeSet<u64>, + records: &mut Records, + report: &mut Report, +) { + let Some(keys) = block(f, item.to_vec(), at, report) else { + return; + }; + let mut fields = BTreeMap::new(); + let mut test = None; + for (key, v) in &keys { + let text = v.value.as_str().map(str::trim).filter(|t| !t.is_empty()); + let not_text = matches!(v.value, Value::List(_) | Value::Map(_)); + match key.as_str() { + "truth" | "reason" | "root_cause" | "severity" if not_text => { + report.push(f.doc.unmapped( + v.line, + key, + format!("`{key}` is not one text: not imported"), + )) + } + "truth" | "reason" | "root_cause" => { + if let Some(t) = text { + fields.insert(key.clone(), json!(t)); + } + } + "severity" => { + if let Some(w) = text.and_then(|_| word(f, key, v, SEVERITY, report)) { + fields.insert(key.clone(), w); + } + } + "missing" => { + let items = gap_list(f, (key, v), report, |item, report| match &item.value { + Value::Str(t) => (!t.trim().is_empty()).then(|| json!(t.trim())), + _ => { + report.push(f.doc.unmapped( + item.line, + key, + "a `missing` item that is not one text: not imported".to_string(), + )); + None + } + }); + if !items.is_empty() { + fields.insert(key.clone(), json!(items)); + } + } + "artifacts" => { + let items = gap_list(f, (key, v), report, |item, report| { + artifact(f, item, report) + }); + if !items.is_empty() { + fields.insert(key.clone(), json!(items)); + } + } + "status" => report.push(f.doc.row("## Gaps status", v.line, key)), + "debug_session" if text.is_some() => { + report.push(f.doc.row("## Gaps debug_session", v.line, key)) + } + "debug_session" => {} + "test" => test = Some((text.unwrap_or_default().to_string(), v.line)), + _ => report.push(f.doc.unmapped( + v.line, + key, + format!("a key `{key}` no row of the ## Gaps table names: not imported"), + )), + } + } + let named = test + .as_ref() + .and_then(|(t, _)| t.parse::<u64>().ok()) + .filter(|t| tests.contains(t)); + let Some(t) = named else { + let (said, line) = test.unwrap_or_default(); + report.push(f.doc.unmapped( + if line == 0 { at + 1 } else { line }, + "## Gaps", + format!("the gap names no test of this file (`test: {said}`): not imported"), + )); + return; + }; + let title = fields + .get("truth") + .and_then(Json::as_str) + .map_or_else(|| format!("G{n}"), str::to_string); + let test_path = format!("{session}/U{t}"); + let record = f.within( + "uat_gap", + ("test", &test_path), + &format!("G{n}"), + &title, + fields, + at, + ); + records.add(record, report); +} diff --git a/gsd/import/src/read/verification.rs b/gsd/import/src/read/verification.rs new file mode 100644 index 0000000000..ebec3af52d --- /dev/null +++ b/gsd/import/src/read/verification.rs @@ -0,0 +1,131 @@ +//! `NN-VERIFICATION.md` to a `verification` (13-RESEARCH Part B, the VERIFICATION table; the rows are +//! `table::sections::VERIFICATION`): the file stem is its id and its phase its only field. Everything else the file +//! records is the verifier's: the frontmatter's status, score and coverage are computed, and the Observable Truths, +//! Required Artifacts and Key Link tables are verdicts, never imported (ADR 0391 D5): the report lists them owed +//! instead ([`crate::owed`]). An `override` is a person's value, written in an editor. + +use std::collections::BTreeMap; + +use super::plan::front; +use super::{Context, is_footer, phase_file}; +use crate::records::Records; +use crate::report::Report; +use crate::sections; + +/// The fate table's name of a verification report. +pub const VF: &str = "NN-VERIFICATION.md"; + +const UNKNOWN: &str = "a section no row of the NN-VERIFICATION.md table names: not imported"; + +/// The frontmatter keys the table names, each reported with its row. +const KEYS: &[&str] = &[ + "phase", + "status", + "score", + "verified", + "covered_files", + "covered_digest", + "re_verification", + "anti_patterns", + "scan_partial", + "behavior_unverified", +]; + +/// The header lines over the first section, and the row each reports with. +const HEADER: &[(&str, &str)] = &[ + ("**Phase Goal:**", "**Phase Goal:**"), + ("**Verified:**", "verified"), + ("**Status:**", "status"), + ("**Score:**", "score"), +]; + +/// Reads the verification report `text`, served at `path` (`rel` under `.planning/`): +/// `phases/<NN-slug>/<NN>-VERIFICATION.md`. +pub fn read( + path: &str, + rel: &str, + text: &str, + cx: &Context<'_>, + records: &mut Records, + report: &mut Report, +) { + let Some(f) = phase_file(path, rel, VF, cx, report) else { + return; + }; + let (front, start) = front(&f.doc, text, report); + for (key, v) in &front { + let line = v.line; + match key.as_str() { + k if KEYS.contains(&k) => report.push(f.doc.row(k, line, k)), + "override" | "overrides" => report.push(f.doc.row("override", line, key)), + _ => report.push(f.doc.unmapped( + line, + key, + format!("a key `{key}` no row of the NN-VERIFICATION.md table names: not imported"), + )), + } + } + let body = crate::frontmatter::body(text, start); + let lines: Vec<&str> = body.split('\n').collect(); + let all = sections::sections(&body); + let first = all + .iter() + .find(|s| s.level >= 2) + .map_or(lines.len(), |s| s.line); + let fenced = sections::fenced(&body); + for (n, line) in lines.iter().enumerate() { + if fenced[n] { + continue; + } + let t = line.trim_start(); + if let Some((_, key)) = HEADER.iter().find(|(label, _)| t.starts_with(label)) { + if n < first { + report.push(f.row(key, n, key)); + } + } else if is_footer(line) { + report.push(f.row("footer", n, "footer")); + } + } + let mut title = None; + let mut at = 0; + for s in &all { + let gaps_none = || { + lines[s.body.clone()] + .iter() + .any(|l| l.contains("No gaps found")) + }; + match (s.level, s.title.as_str()) { + (1, _) if title.is_none() => { + title = Some(s.title.clone()); + at = s.line; + } + (2, "Goal Achievement") => report.push(f.row("## Goal Achievement", s.line, &s.title)), + ( + 3, + "Observable Truths" + | "Required Artifacts" + | "Key Link Verification" + | "Requirements Coverage", + ) => report.push(f.row(&format!("### {}", s.title), s.line, &s.title)), + (2, "Gaps Summary" | "Gaps") if gaps_none() => { + report.push(f.row("No gaps found", s.line, &s.title)) + } + (2, "Gaps Summary" | "Gaps") => report.push(f.row("## Gaps Summary", s.line, &s.title)), + (2, "Human Verification Required") => { + report.push(f.row("## Human Verification Required", s.line, &s.title)) + } + _ => report.push(f.unmapped(s.line, &s.title, UNKNOWN.to_string())), + } + } + records.add( + f.within( + "verification", + ("phase", &f.phase), + &f.stem, + title.as_deref().unwrap_or(&f.stem), + BTreeMap::new(), + at, + ), + report, + ); +} diff --git a/gsd/import/src/records.rs b/gsd/import/src/records.rs new file mode 100644 index 0000000000..37ebb92a48 --- /dev/null +++ b/gsd/import/src/records.rs @@ -0,0 +1,232 @@ +//! What the readers find: one [`Record`] per entity to create, each with the `.planning` line it comes from. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; + +use serde_json::Value; + +use crate::report::{Entry, Outcome, Report}; + +/// Where a record or an entry comes from: a served `.planning/` path and its 1-based line. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct Source { + pub file: String, + pub line: usize, +} + +impl fmt::Display for Source { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}:{}", self.file, self.line) + } +} + +/// One entity the plan creates. +#[derive(Debug, Clone, PartialEq)] +pub struct Record { + pub kind: &'static str, + /// The id path the host's create takes (`TASK-01`). + pub id: String, + pub title: String, + /// The `spec/gsd/` file it is written to. + pub file: String, + pub fields: BTreeMap<String, Value>, + /// The ids its scope and required reference fields name (its phase, its plan): each must be created by the plan or + /// be in the graph, else the record is not imported ("parent not imported"). + pub refs: Vec<String>, + /// `(field, id)` for each id an optional reference field or a reference list names (a phase's `requirements`, a + /// plan's `depends_on`): an id that is not imported is left out of `field`, reported, and the record is kept. + pub links: Vec<(&'static str, String)>, + pub source: Source, +} + +/// Every record, keyed by kind then id, so the plan's order does not depend on the order files are read in. +#[derive(Debug, Default)] +pub struct Records { + kept: BTreeMap<(&'static str, String), Record>, + /// `(served file, id)` of each record not added because another file gave its id first, and of each record of + /// that file dropped under it: a record of the same file naming one of them is its child, never the first's. + dropped: BTreeSet<(String, String)>, +} + +impl Records { + /// Adds `record`. A second record of the same kind and id is not added, and `report` names both lines; when the + /// first came from another file, the second's children in its file (read before or after it) are not added either, + /// each reported "parent not imported", so no child of one file is grafted onto another file's record. + pub fn add(&mut self, record: Record, report: &mut Report) { + let file = &record.source.file; + if let Some(parent) = record + .refs + .iter() + .find(|r| self.dropped.contains(&(file.clone(), (*r).clone()))) + { + report.push(orphan(&record, parent)); + self.dropped.insert((file.clone(), record.id)); + return; + } + let key = (record.kind, record.id.clone()); + let Some(first) = self.kept.get(&key) else { + self.kept.insert(key, record); + return; + }; + report.push(Entry::at( + &record.source, + record.kind, + Outcome::Unmapped, + format!( + "{} {} is given twice (first at {}): not imported", + record.kind, record.id, first.source + ), + )); + if first.source.file != *file { + self.drop_children(file.clone(), record.id, report); + } + } + + /// Drops, reported, every record of `file` naming `id` and, in turn, every record of `file` naming one dropped. + fn drop_children(&mut self, file: String, id: String, report: &mut Report) { + let mut parents = vec![id]; + while let Some(parent) = parents.pop() { + let children: Vec<_> = self + .kept + .iter() + .filter(|(_, r)| r.source.file == file && r.refs.contains(&parent)) + .map(|(key, _)| key.clone()) + .collect(); + for key in children { + if let Some(child) = self.kept.remove(&key) { + report.push(orphan(&child, &parent)); + parents.push(child.id); + } + } + self.dropped.insert((file.clone(), parent)); + } + } + + /// Whether a record `kind id` was added. + pub fn contains(&self, kind: &'static str, id: &str) -> bool { + self.kept.contains_key(&(kind, id.to_string())) + } + + /// The record `kind id`, if one was added. + pub fn get(&self, kind: &'static str, id: &str) -> Option<&Record> { + self.kept.get(&(kind, id.to_string())) + } + + /// The record `kind id`, to enrich (a SECURITY.md row sets its plan threat's status). + pub fn get_mut(&mut self, kind: &'static str, id: &str) -> Option<&mut Record> { + self.kept.get_mut(&(kind, id.to_string())) + } + + /// The records in kind then id order. + pub fn iter(&self) -> impl Iterator<Item = &Record> { + self.kept.values() + } + + pub fn len(&self) -> usize { + self.kept.len() + } + + pub fn is_empty(&self) -> bool { + self.kept.is_empty() + } +} + +/// The entry of `record`, not added because its file's `parent` was not. +fn orphan(record: &Record, parent: &str) -> Entry { + Entry::at( + &record.source, + record.kind, + Outcome::Unmapped, + format!( + "{} {}: parent not imported ({parent}, given twice): not imported", + record.kind, record.id + ), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record(kind: &'static str, id: &str, refs: &[&str], (file, line): (&str, usize)) -> Record { + Record { + kind, + id: id.to_string(), + title: id.to_string(), + file: "spec/gsd/x.spec".to_string(), + fields: BTreeMap::new(), + refs: refs.iter().map(|r| r.to_string()).collect(), + links: Vec::new(), + source: Source { + file: file.to_string(), + line, + }, + } + } + + fn ids(records: &Records) -> Vec<(&str, &str)> { + records + .iter() + .map(|r| (r.id.as_str(), r.source.file.as_str())) + .collect() + } + + fn says(report: &Report, file: &str, line: usize) -> String { + report + .entries() + .into_iter() + .filter(|e| e.file == file && e.line == Some(line)) + .map(|e| e.reason.clone()) + .collect() + } + + #[test] + fn a_duplicate_plans_children_are_its_own_never_the_firsts() { + let (a, b) = ("a/01-01-PLAN.md", "b/01-01-PLAN.md"); + let mut records = Records::default(); + let mut report = Report::default(); + records.add(record("plan", "P", &[], (a, 1)), &mut report); + records.add(record("task", "P/T1", &["P"], (a, 2)), &mut report); + // The second file's plan, then its tasks (one id the first has, one it lacks) and a truth under a task. + records.add(record("plan", "P", &[], (b, 1)), &mut report); + records.add(record("task", "P/T1", &["P"], (b, 2)), &mut report); + records.add(record("task", "P/T5", &["P"], (b, 3)), &mut report); + records.add(record("truth", "P/T5/X", &["P/T5"], (b, 4)), &mut report); + assert_eq!(ids(&records), [("P", a), ("P/T1", a)]); + assert!(says(&report, b, 1).contains("plan P is given twice (first at a/01-01-PLAN.md:1)")); + for line in [2, 3] { + let said = says(&report, b, line); + assert!( + said.contains("parent not imported (P, given twice)"), + "{line}: {said}" + ); + } + assert!(says(&report, b, 4).contains("parent not imported (P/T5, given twice)")); + } + + #[test] + fn children_read_before_a_duplicate_are_dropped_with_it() { + let (a, b) = ("a/01-RESEARCH.md", "b/01-RESEARCH.md"); + let mut records = Records::default(); + let mut report = Report::default(); + records.add(record("research", "R", &[], (a, 1)), &mut report); + // A research's items are read before the research itself. + records.add(record("finding", "R/F1", &["R"], (b, 2)), &mut report); + records.add(record("source", "R/S1/X", &["R/F1"], (b, 3)), &mut report); + records.add(record("research", "R", &[], (b, 1)), &mut report); + assert_eq!(ids(&records), [("R", a)]); + assert!(says(&report, b, 2).contains("parent not imported (R, given twice)")); + assert!(says(&report, b, 3).contains("parent not imported (R/F1, given twice)")); + } + + #[test] + fn a_duplicate_in_the_first_records_own_file_drops_only_itself() { + let f = "ROADMAP.md"; + let mut records = Records::default(); + let mut report = Report::default(); + records.add(record("milestone", "v1", &[], (f, 1)), &mut report); + records.add(record("milestone", "v1", &[], (f, 2)), &mut report); + records.add(record("phase", "v1/01", &["v1"], (f, 3)), &mut report); + assert_eq!(ids(&records), [("v1", f), ("v1/01", f)]); + } +} diff --git a/gsd/import/src/report.rs b/gsd/import/src/report.rs new file mode 100644 index 0000000000..92396264f2 --- /dev/null +++ b/gsd/import/src/report.rs @@ -0,0 +1,330 @@ +//! The import's report (ADR 0391 D8): one entry per file, section or row, with its outcome and the reason, then the +//! settings lines, the owed verdicts, what is authored after the import and the minted ids. Sorted, with no clock and +//! no absolute path, so one input gives the same bytes whatever the order it was read in. Every echoed string is +//! escaped once, here, as it is rendered; the plan's field values keep the source text verbatim. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; + +use crate::owed::{self, Owed}; +use crate::records::Source; + +/// What became of a file, a section or a row: the ten classes of ADR 0391 D3. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Outcome { + /// Written to an entity's field. + Mapped, + /// A field `@gsd/core` computes: never written. + Computed, + /// Another file already gives it. + Redundant, + /// gsd-tools' runtime state, which the graph computes. + Runtime, + /// Nothing to import. + Ignored, + /// No kind holds it; the reason says why. + Unmapped, + /// Its kinds are an extension's the project does not load. + NeedsExtension, + /// A setting: the report prints the line that sets it. + Setting, + /// No `.planning` source: the user writes it after the import. + AuthoredAfterImport, + /// No `.planning` source, so the import filled it (a minted id). + Filled, +} + +impl Outcome { + pub fn as_str(self) -> &'static str { + match self { + Outcome::Mapped => "mapped", + Outcome::Computed => "computed", + Outcome::Redundant => "redundant", + Outcome::Runtime => "runtime", + Outcome::Ignored => "ignored", + Outcome::Unmapped => "unmapped", + Outcome::NeedsExtension => "needs-extension", + Outcome::Setting => "setting", + Outcome::AuthoredAfterImport => "authored-after-import", + Outcome::Filled => "filled", + } + } +} + +/// The most characters of one echoed value the report shows. +pub const SHOWN_MAX: usize = 200; + +/// Whether `c` is a character no `.spec` file holds: a C0 control (tab and line feed too), DEL, a C1 control, the line +/// and paragraph separators, or a Unicode bidi control, which a terminal acts on or reorders. Exactly the parser's +/// `is_unprintable`, so a record holding one is dropped (`emit::unwritable`) as the host would refuse its file. +pub fn hidden(c: char) -> bool { + c.is_control() + || matches!( + c, + '\u{061C}' + | '\u{200E}' + | '\u{200F}' + | '\u{2028}' + | '\u{2029}' + | '\u{202A}'..='\u{202E}' + | '\u{2066}'..='\u{2069}' + ) +} + +/// Whether `c` is written `\u{..}` when echoed (ADR 0391 D8): a [`hidden`] character or any other Unicode format +/// control (General Category Cf): the soft hyphen, the zero-width characters, the word joiner and invisible +/// operators, U+FEFF, the interlinear annotation marks, the tag characters (U+E0001, U+E0020-U+E007F) and the rest. +/// A `.spec` file may hold these, so they are escaped, never dropped: text can carry no invisible content into the +/// report, which an agent may read. +pub fn invisible(c: char) -> bool { + hidden(c) + || matches!( + c, + '\u{00AD}' + | '\u{0600}'..='\u{0605}' + | '\u{06DD}' + | '\u{070F}' + | '\u{0890}'..='\u{0891}' + | '\u{08E2}' + | '\u{180E}' + | '\u{200B}'..='\u{200D}' + | '\u{2060}'..='\u{2064}' + | '\u{206A}'..='\u{206F}' + | '\u{FEFF}' + | '\u{FFF9}'..='\u{FFFB}' + | '\u{110BD}' + | '\u{110CD}' + | '\u{13430}'..='\u{1343F}' + | '\u{1BCA0}'..='\u{1BCA3}' + | '\u{1D173}'..='\u{1D17A}' + | '\u{E0001}' + | '\u{E0020}'..='\u{E007F}' + ) +} + +/// `text` with every [`invisible`] character written `\u{<hex>}`; any other text unchanged. +pub fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + if invisible(c) { + out.push_str(&format!("\\u{{{:x}}}", c as u32)); + } else { + out.push(c); + } + } + out +} + +/// `text` escaped and capped at [`SHOWN_MAX`] characters, a trailing `…` marking the cut. +pub fn shown(text: &str) -> String { + match text.char_indices().nth(SHOWN_MAX) { + Some((at, _)) => format!("{}…", escape(&text[..at])), + None => escape(text), + } +} + +/// One line of the report. Fields in sort order: file, line (none, the whole file, first), section, outcome, reason. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct Entry { + pub file: String, + /// 1-based; none when the entry is about the whole file. + pub line: Option<usize>, + pub section: String, + pub outcome: Outcome, + pub reason: String, +} + +impl Entry { + /// An entry about the line `source`, in `section`. + pub fn at(source: &Source, section: &str, outcome: Outcome, reason: String) -> Self { + Entry { + file: source.file.clone(), + line: Some(source.line), + section: section.to_string(), + outcome, + reason, + } + } + + /// An entry about the whole file `file`. + pub fn file(file: &str, outcome: Outcome, reason: String) -> Self { + Entry { + file: file.to_string(), + line: None, + section: String::new(), + outcome, + reason, + } + } + + /// `file:line` or `file`, shown. + pub fn location(&self) -> String { + match self.line { + Some(line) => format!("{}:{line}", shown(&self.file)), + None => shown(&self.file), + } + } +} + +/// An id the import gave an entity whose source names it otherwise (or not at all). +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct Minted { + pub kind: String, + /// What the source calls it (a row, a file name). + pub old: String, + pub new: String, +} + +/// Everything one import reports. +#[derive(Debug, Default)] +pub struct Report { + entries: Vec<Entry>, + /// `specforge settings set` lines (ADR 0391 D6), each already quoted for a shell. + settings: Vec<String>, + /// The verdicts the imported entities owe, each listed with the commands that record it (D5). + owed: Vec<Owed>, + /// The fields no `.planning` source gives, which the user writes after the import. + authored_after_import: Vec<String>, + ids: Vec<Minted>, +} + +impl Report { + pub fn push(&mut self, entry: Entry) { + self.entries.push(entry); + } + + pub fn setting(&mut self, line: String) { + self.settings.push(line); + } + + pub fn owed(&mut self, owed: Owed) { + self.owed.push(owed); + } + + pub fn authored_after_import(&mut self, note: String) { + self.authored_after_import.push(note); + } + + pub fn minted(&mut self, minted: Minted) { + self.ids.push(minted); + } + + /// The number of report lines the cap `MAX_ENTRIES` counts: the entries, the settings lines, the + /// authored-after-import notes and the minted ids. The owed verdicts are not counted: they follow the created + /// entities, which `MAX_OPS` bounds. + pub fn len(&self) -> usize { + self.entries.len() + self.settings.len() + self.authored_after_import.len() + self.ids.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// The 1-based lines of `file` that an entry is about. + pub fn lines(&self, file: &str) -> std::collections::BTreeSet<usize> { + self.entries + .iter() + .filter(|e| e.file == file) + .filter_map(|e| e.line) + .collect() + } + + /// The entries, sorted by file, line, section, outcome and reason. + pub fn entries(&self) -> Vec<&Entry> { + sorted(&self.entries) + } + + /// `{"format": 1, "entries", "settings", "owed", "authored_after_import", "ids", "counts"}`, every echoed string + /// shown or escaped. + pub fn payload(&self, counts: &BTreeMap<&'static str, usize>) -> Value { + let entries: Vec<Value> = self + .entries() + .into_iter() + .map(|e| { + json!({ + "file": shown(&e.file), + "line": e.line, + "section": shown(&e.section), + "outcome": e.outcome.as_str(), + "reason": shown(&e.reason), + }) + }) + .collect(); + let ids: Vec<Value> = sorted(&self.ids) + .into_iter() + .map(|m| json!({"kind": m.kind, "old": shown(&m.old), "new": escape(&m.new)})) + .collect(); + json!({ + "format": 1, + "entries": entries, + "settings": rendered(&self.settings), + "owed": sorted(&self.owed).into_iter().map(Owed::json).collect::<Vec<Value>>(), + "authored_after_import": rendered(&self.authored_after_import), + "ids": ids, + "counts": counts, + }) + } + + /// One line per entry (`<file>:<line> <section> <outcome> <reason>`, `-` for no section), then the settings + /// lines, the owed verdicts and what is authored after the import, each under its heading, then the count line. + pub fn text(&self, counts: &BTreeMap<&'static str, usize>) -> String { + let mut out = String::new(); + for e in self.entries() { + let section = match e.section.as_str() { + "" => "-".to_string(), + section => shown(section), + }; + out.push_str(&format!( + "{} {section} {} {}\n", + e.location(), + e.outcome.as_str(), + shown(&e.reason) + )); + } + let mut owed: Vec<Owed> = self.owed.clone(); + owed.sort(); + // The owed lines keep their order: each phase's command, then its queries, then the count. + let owed: Vec<String> = owed::lines(&owed).iter().map(|l| escape(l)).collect(); + for (heading, lines) in [ + ( + "settings: run each line to keep the setting", + rendered(&self.settings), + ), + ("owed: record each verdict anew", owed), + ( + "authored after import: no .planning source gives these", + rendered(&self.authored_after_import), + ), + ] { + if !lines.is_empty() { + out.push_str(&format!("\n{heading}\n")); + for line in lines { + out.push_str(&format!(" {line}\n")); + } + } + } + let total: usize = counts.values().sum(); + let kinds: Vec<String> = counts.iter().map(|(k, n)| format!("{k} {n}")).collect(); + out.push_str(&format!( + "import: {total} entities ({}), {} report entries\n", + kinds.join(", "), + self.entries.len() + )); + out + } +} + +fn sorted<T: Ord>(items: &[T]) -> Vec<&T> { + let mut out: Vec<&T> = items.iter().collect(); + out.sort(); + out +} + +/// `lines` sorted, each escaped (a settings or owed line is never capped: it is meant to be run). +fn rendered(lines: &[String]) -> Vec<String> { + sorted(lines).into_iter().map(|l| escape(l)).collect() +} + +#[cfg(test)] +mod tests; diff --git a/gsd/import/src/report/tests.rs b/gsd/import/src/report/tests.rs new file mode 100644 index 0000000000..b15657b2cc --- /dev/null +++ b/gsd/import/src/report/tests.rs @@ -0,0 +1,184 @@ +use std::collections::BTreeMap; + +use super::*; + +#[test] +fn escape_writes_controls_as_code_points() { + assert_eq!(escape("\u{1b}[31mred"), "\\u{1b}[31mred"); + assert_eq!(escape("a\u{202e}b"), "a\\u{202e}b"); + assert_eq!(escape("one\ntwo\tthree"), "one\\u{a}two\\u{9}three"); + assert_eq!(escape("nul\0"), "nul\\u{0}"); + assert_eq!(escape("del\u{7f} c1\u{85}"), "del\\u{7f} c1\\u{85}"); + for c in [ + '\u{061c}', '\u{200e}', '\u{200f}', '\u{202a}', '\u{202d}', '\u{2066}', '\u{2069}', + ] { + assert_eq!(escape(&c.to_string()), format!("\\u{{{:x}}}", c as u32)); + } +} + +#[test] +fn escape_writes_format_controls_but_drops_only_what_the_parser_refuses() { + for c in [ + '\u{00ad}', + '\u{180e}', + '\u{200b}', + '\u{200c}', + '\u{200d}', + '\u{2060}', + '\u{2064}', + '\u{feff}', + '\u{fff9}', + '\u{fffb}', + '\u{e0001}', + '\u{e0041}', + '\u{e007f}', + ] { + assert_eq!( + escape(&format!("a{c}b")), + format!("a\\u{{{:x}}}b", c as u32) + ); + // A `.spec` file may hold it: the record holding it is written, only its echo is escaped. + assert!(!hidden(c), "{:x}", c as u32); + } + // The tag block's unassigned neighbours and ordinary joiners' lookalikes stay text. + for c in ['\u{e0000}', '\u{e0080}', '\u{2010}'] { + assert_eq!(escape(&c.to_string()), c.to_string()); + } +} + +#[test] +fn escape_leaves_other_text_unchanged() { + let text = "Tâche — « déjà » 日本語 `code` \\u{1b} 'quoted' $(id)"; + assert_eq!(escape(text), text); +} + +#[test] +fn escape_shown_caps_a_value_at_200_characters() { + let long = "é".repeat(10_000); + let out = shown(&long); + assert_eq!(out.chars().count(), SHOWN_MAX + 1); + assert!(out.ends_with('…')); + assert_eq!(shown(&"x".repeat(SHOWN_MAX)), "x".repeat(SHOWN_MAX)); + // The cut comes before the escape, so no escape is split. + let hostile = "\u{1b}".repeat(300); + assert_eq!(shown(&hostile), format!("{}…", "\\u{1b}".repeat(SHOWN_MAX))); +} + +fn hostile() -> Vec<Entry> { + let at = |line| Source { + file: ".planning/PROJECT.md".to_string(), + line, + }; + vec![ + Entry::at( + &at(3), + "## What This Is", + Outcome::Unmapped, + "title \u{1b}[31mred\u{1b}[0m\nforged: mapped".to_string(), + ), + Entry::at( + &at(3), + "## Core", + Outcome::Redundant, + "bidi \u{202e}txt.exe".to_string(), + ), + Entry::at(&at(9), "", Outcome::Filled, "nul \0 here".to_string()), + Entry::file(".planning/state.json", Outcome::Runtime, "x".repeat(10_000)), + Entry::file( + ".planning/notes\n.txt", + Outcome::Unmapped, + "unknown file".to_string(), + ), + ] +} + +fn filled(entries: Vec<Entry>) -> Report { + let mut report = Report::default(); + for entry in entries { + report.push(entry); + } + report.setting("specforge settings set @gsd/core mode 'yolo'".to_string()); + report.setting("specforge settings set @gsd/core granularity 'fine'".to_string()); + report.owed(Owed { + phase: Some("01".to_string()), + code: owed::E501, + entity: "v1.0/01/01-01/TR1".to_string(), + }); + report.authored_after_import("milestone v1.0: its title".to_string()); + report.minted(Minted { + kind: "requirement".to_string(), + old: "Out of Scope row 1".to_string(), + new: "OOS-01".to_string(), + }); + report +} + +#[test] +fn report_is_stable() { + let counts = BTreeMap::from([("requirement", 1)]); + let mut reversed = hostile(); + reversed.reverse(); + let (a, b) = (filled(hostile()), filled(reversed)); + assert_eq!(a.text(&counts), b.text(&counts)); + assert_eq!( + serde_json::to_string(&a.payload(&counts)).expect("JSON"), + serde_json::to_string(&b.payload(&counts)).expect("JSON") + ); +} + +#[test] +fn report_text_is_one_escaped_line_per_entry() { + let report = filled(hostile()); + let text = report.text(&BTreeMap::new()); + let lines: Vec<&str> = text.lines().collect(); + // Five entries, then the headed sections, then the count line: no echoed string breaks a line. + assert_eq!( + &lines[..5], + [ + ".planning/PROJECT.md:3 ## Core redundant bidi \\u{202e}txt.exe", + ".planning/PROJECT.md:3 ## What This Is unmapped title \\u{1b}[31mred\\u{1b}[0m\\u{a}forged: mapped", + ".planning/PROJECT.md:9 - filled nul \\u{0} here", + ".planning/notes\\u{a}.txt - unmapped unknown file", + &format!( + ".planning/state.json - runtime {}…", + "x".repeat(SHOWN_MAX) + ), + ] + ); + assert!(text.contains("\nsettings: run each line to keep the setting\n specforge settings set @gsd/core granularity 'fine'\n specforge settings set @gsd/core mode 'yolo'\n")); + assert!(text.contains("\nowed: record each verdict anew\n /gsd-verify-work 01\n specforge query 'v1.0/01/01-01/TR1' --inputs gsd/E501 --format json\n 1 verdicts owed: `specforge check` exits 1 until these verdicts are recorded\n")); + assert!(text.ends_with("import: 0 entities (), 5 report entries\n")); + assert!(!text.chars().any(|c| hidden(c) && c != '\n')); +} + +#[test] +fn report_payload_has_every_section() { + let payload = filled(hostile()).payload(&BTreeMap::from([("requirement", 1)])); + let mut keys: Vec<&String> = payload.as_object().expect("an object").keys().collect(); + keys.sort(); + assert_eq!( + keys, + [ + "authored_after_import", + "counts", + "entries", + "format", + "ids", + "owed", + "settings" + ] + ); + assert_eq!(payload["format"], 1); + assert_eq!( + payload["ids"], + json!([{"kind": "requirement", "old": "Out of Scope row 1", "new": "OOS-01"}]) + ); + assert_eq!( + payload["owed"], + json!([{"code": "gsd/E501", "entity": "v1.0/01/01-01/TR1", "phase": "01"}]) + ); + let first = &payload["entries"][0]; + assert_eq!(first["reason"], "bidi \\u{202e}txt.exe"); + assert_eq!(first["line"], 3); + assert_eq!(payload["entries"][3]["line"], Value::Null); +} diff --git a/gsd/import/src/sections.rs b/gsd/import/src/sections.rs new file mode 100644 index 0000000000..72fef8c775 --- /dev/null +++ b/gsd/import/src/sections.rs @@ -0,0 +1,98 @@ +//! A Markdown file's sections, from the gsd family's one Markdown reader (`gsd_kit::markdown::headings`, ADR 0332 D7): +//! a `#` line inside a fence or an HTML comment never starts a section, and a heading under an XML section tag does. +//! +//! Lines are 0-based, as `gsd_kit::markdown` gives them; a reader adds 1 for a report entry. Give a file with a +//! frontmatter as `frontmatter::body`, so its `---` lines read as nothing. + +use std::ops::Range; + +use gsd_kit::markdown; + +/// One heading and the lines it holds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Section { + pub level: u8, + /// The heading's text, its code spans in backticks. + pub title: String, + /// The heading's line. + pub line: usize, + /// The lines after the heading, up to the next heading of the same or a higher level (sub-sections included). + pub body: Range<usize>, +} + +/// Every section of `text`, in line order. +pub fn sections(text: &str) -> Vec<Section> { + let headings = markdown::headings(text); + let total = text.split('\n').count(); + let mut out: Vec<Section> = headings + .iter() + .map(|h| Section { + level: h.level, + title: h.text.clone(), + line: h.line, + body: h.line + 1..total, + }) + .collect(); + // One pass: each heading closes the open sections of its level or deeper. + let mut open: Vec<usize> = Vec::new(); + for i in 0..out.len() { + while let Some(&j) = open.last() { + if out[j].level < out[i].level { + break; + } + out[j].body.end = out[i].line; + open.pop(); + } + open.push(i); + } + out +} + +/// Whether each line of `text` is part of a fenced code block (its marks included). +pub fn fenced(text: &str) -> Vec<bool> { + let mut fenced = vec![false; text.split('\n').count()]; + for fence in markdown::fences(text) { + let end = (fence.code.end + 1).min(fenced.len()); + fenced[fence.open.min(end)..end].fill(true); + } + fenced +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_section_runs_to_the_next_heading_of_its_level_or_higher() { + let text = "# A\nx\n## B\ny\n### C\nz\n## D\n```\n# no\n```\n"; + let all = sections(text); + let found: Vec<(u8, &str, usize, Range<usize>)> = all + .iter() + .map(|s| (s.level, s.title.as_str(), s.line, s.body.clone())) + .collect(); + assert_eq!( + found, + [ + (1, "A", 0, 1..11), + (2, "B", 2, 3..6), + (3, "C", 4, 5..6), + (2, "D", 6, 7..11) + ] + ); + assert_eq!( + fenced(text), + [ + false, false, false, false, false, false, false, true, true, true, false + ] + ); + } + + #[test] + fn a_frontmatter_given_as_its_body_starts_no_section() { + let text = "---\na: 1\n---\n# Title\n"; + let (_, start) = crate::frontmatter::split(text); + let found = sections(&crate::frontmatter::body(text, start)); + assert_eq!(found.len(), 1); + assert_eq!((found[0].title.as_str(), found[0].line), ("Title", 3)); + } +} diff --git a/gsd/import/src/settings.rs b/gsd/import/src/settings.rs new file mode 100644 index 0000000000..fa5a4ab0c0 --- /dev/null +++ b/gsd/import/src/settings.rs @@ -0,0 +1,406 @@ +//! `config.json` to `specforge settings set` lines (ADR 0391 D6). The plan never writes `specforge.json`: the report +//! prints one line per mappable key, under the extension that owns it (`gsd/core/spec/settings.md`'s family table), +//! each value POSIX single-quoted because the line is meant to be pasted into a shell and the input is untrusted. A value +//! holding a control character is reported, never printed; a search provider's API key is reported by the name of the +//! environment variable that holds it, never printed. + +use std::collections::BTreeMap; + +use serde_json::{Map, Value}; + +use crate::preflight::Manifest; +use crate::report::{Entry, Outcome, invisible}; + +/// The file the lines come from. +pub const CONFIG: &str = ".planning/config.json"; + +/// The owner of each key family: `gsd/core/spec/settings.md`'s table, token for token (a test holds them equal). A +/// token `a.b` names that key, `a.*` every key under `a.`, `a_*` every key starting `a_`; the longest token that +/// names a key wins, so `workflow.security_enforcement` is `@gsd/security`'s and not `workflow.*`'s. +pub const OWNERS: &[(&str, &[&str])] = &[ + ( + "@gsd/core", + &[ + "mode", + "granularity", + "granularities.*", + "model_profile", + "model_profile_overrides.*", + "model_policy.*", + "models.*", + "dynamic_routing.*", + "runtime", + "phase_id_convention", + "project_code", + "phase_naming", + "response_language", + "context_window", + "context", + "workflow.*", + "executor.*", + "planner.*", + "parallelization.*", + "gates.*", + "git.*", + "worktree.*", + "ship.*", + "review.*", + "agent_skills", + "agent_tools.*", + "hooks.*", + "statusline.*", + "refactor.*", + "model_overrides.*", + "resolve_model_ids", + "effort.*", + "fast_mode.*", + "manager.*", + "plan_review.*", + "audit.*", + "features.*", + "learnings.*", + "claude_orchestration.*", + "external_job.*", + "agent_skills_security.*", + "planning.chunked_parallel", + "parallelization", + // The key `parallelization` is the shorthand for. + "parallelization.enabled", + // The search availability flags `brave_search` … `jina`: all seven are in SECRETS. + "brave_search", + "jina", + ], + ), + ( + "@gsd/security", + &[ + "workflow.security_enforcement", + "workflow.security_asvs_level", + "workflow.security_block_on", + "security.*", + ], + ), + ( + "@gsd/ui", + &[ + "workflow.ui_phase", + "workflow.ui_safety_gate", + "workflow.ui_review", + "workflow.live_dom_uat", + "workflow.ui_interaction_capture", + ], + ), + ( + "@gsd/ai", + &[ + "workflow.ai_integration_phase", + "workflow.api_coverage_gate", + ], + ), + ( + "@gsd/ops", + &[ + "workflow.code_review", + "workflow.code_review_*", + "code_quality.*", + "mempalace.*", + "profile-pipeline.*", + ], + ), + ( + "@gsd/codebase", + &[ + "workflow.drift_threshold", + "workflow.drift_action", + "workflow.plan_drift_precheck", + "intel.*", + ], + ), +]; + +/// The search availability flags (`@gsd/core` bools) and the environment variable that holds each one's API key. +pub const SECRETS: &[(&str, &str)] = &[ + ("brave_search", "BRAVE_API_KEY"), + ("firecrawl", "FIRECRAWL_API_KEY"), + ("exa_search", "EXA_API_KEY"), + ("tavily_search", "TAVILY_API_KEY"), + ("ref_search", "REF_API_KEY"), + ("perplexity", "PERPLEXITY_API_KEY"), + ("jina", "JINA_API_KEY"), +]; + +const NO_PLANNING: &str = "there is no .planning/: spec/gsd/ is source and is committed like code"; +const HOST_FILES: &str = "host files are rendered by `specforge install`, which owns their paths"; + +/// settings.md's "Not applicable" keys (tokens as in [`OWNERS`]), each with its reason. +pub const NOT_APPLICABLE: &[(&str, &str)] = &[ + ("planning.commit_docs", NO_PLANNING), + ("commit_docs", NO_PLANNING), + ("phase_commit_docs.*", NO_PLANNING), + ("planning.search_gitignored", NO_PLANNING), + ("planning.pr_strict", NO_PLANNING), + ("search_gitignored", NO_PLANNING), + ( + "planning.sub_repos", + "a sub-repository is another SpecForge project", + ), + ( + "git.repo_tagging", + "a sub-repository is another SpecForge project", + ), + ("claude_md_path", HOST_FILES), + ("claude_md_assembly.*", HOST_FILES), + ( + "workflow.auto_prune_state", + "STATE.md is derived, nothing to prune", + ), + ( + "capabilities.*", + "an extension is enabled by specforge.json's extensions, and installing one is SpecForge's", + ), + ( + "graphify.*", + "graphify is absorbed: SpecForge is the graph, compiled on every change", + ), +]; + +/// The block settings (`{model, reasoning_effort}`) and how many key segments follow their prefix. +const BLOCKS: &[(&str, usize)] = &[ + ("model_profile_overrides", 2), + ("model_policy.runtime_tiers", 2), +]; + +/// `text` as one POSIX shell word: single-quoted, each `'` written `'\''`. +pub fn shell_quote(text: &str) -> String { + format!("'{}'", text.replace('\'', "'\\''")) +} + +/// The settings lines of `config.json`'s `text`, in key order, and an entry for every key that has none. +pub fn settings_lines(text: &str, manifest: &Manifest) -> (Vec<String>, Vec<Entry>) { + let mut out = Lines::default(); + match serde_json::from_str::<Value>(text) { + Ok(Value::Object(map)) => out.object("", &map), + Ok(_) => out.file(Outcome::Unmapped, "not a JSON object".to_string()), + Err(e) => out.file(Outcome::Unmapped, format!("not JSON: {e}")), + } + let mut lines = Vec::new(); + for (key, value) in std::mem::take(&mut out.values) { + out.line(&key, &value, manifest, &mut lines); + } + out.entries.push(entry( + "worktree.baseRef", + Outcome::Unmapped, + "GSD keeps it in .claude/settings.local.json, outside .planning/: not read".to_string(), + )); + (lines, out.entries) +} + +/// The flattened keys and what is reported on the way. +#[derive(Default)] +struct Lines { + values: BTreeMap<String, Value>, + entries: Vec<Entry>, +} + +impl Lines { + fn file(&mut self, outcome: Outcome, reason: String) { + self.entries.push(Entry::file(CONFIG, outcome, reason)); + } + + /// Flattens `map` under `prefix` to dotted keys, down to a block setting's depth. + fn object(&mut self, prefix: &str, map: &Map<String, Value>) { + if map.is_empty() && !prefix.is_empty() { + self.entries.push(entry( + prefix, + Outcome::Ignored, + "an empty object sets nothing".to_string(), + )); + } + for (name, value) in map { + // `agent_tools.*`'s key `*` is every agent: the family's key is a segment, so `all` (settings.md). + let name = if prefix == "agent_tools" && name == "*" { + "all" + } else { + name + }; + let key = match prefix { + "" => name.to_string(), + _ => format!("{prefix}.{name}"), + }; + // Whatever sits under a search flag is its API key: kept whole at the flag, never a printable child. + let key = SECRETS + .iter() + .find(|(flag, _)| names(flag, &key)) + .map_or(key, |(flag, _)| flag.to_string()); + match value { + Value::Object(inner) + if secret(&key).is_none() && block_depth(&key).is_none_or(|left| left > 0) => + { + self.object(&key, inner) + } + _ => { + // `*` and `all`, or `git.x` and `git: {x}`, flatten to one key: the later read is kept, reported. + if self.values.insert(key.clone(), value.clone()).is_some() { + self.entries.push(entry( + &key, + Outcome::Unmapped, + format!("{key} is given twice in config.json: the last is kept"), + )); + } + } + } + } + } + + /// The line of `key`, or the entry saying why it has none. + fn line(&mut self, key: &str, value: &Value, manifest: &Manifest, lines: &mut Vec<String>) { + let mut report = |outcome, reason: String| self.entries.push(entry(key, outcome, reason)); + if !key.split('.').all(is_segment) { + return report(Outcome::Unmapped, "not a setting name".to_string()); + } + if value.is_null() { + return report(Outcome::Ignored, "null: unset".to_string()); + } + if let Some((_, why)) = NOT_APPLICABLE.iter().find(|(token, _)| names(token, key)) { + return report(Outcome::Unmapped, why.to_string()); + } + let Some(extension) = owner(key) else { + return report(Outcome::Unmapped, "not a gsd-core 1.19 setting".to_string()); + }; + if extension != "@gsd/core" && !manifest.loaded.iter().any(|l| l == extension) { + return report( + Outcome::NeedsExtension, + format!("{extension}'s setting, and the project does not load {extension}"), + ); + } + if has_invisible(value) { + return report( + Outcome::Unmapped, + format!("control character in the value of {key}"), + ); + } + let words = match (key, value) { + // A flag is a bool (null is unset above): any other shape is the API key itself. + (_, Value::String(_) | Value::Number(_) | Value::Array(_) | Value::Object(_)) + if secret(key).is_some() => + { + let variable = secret(key).unwrap_or_default(); + report( + Outcome::Setting, + format!( + "a non-bool value is an API key, not printed: export {variable} to give it" + ), + ); + "true".to_string() + } + ("resolve_model_ids", value) => match value { + Value::Bool(false) => "aliases".to_string(), + Value::Bool(true) => "ids".to_string(), + Value::String(s) if s == "omit" => "omit".to_string(), + _ => { + return report( + Outcome::Unmapped, + "resolve_model_ids takes false, true or \"omit\"".to_string(), + ); + } + }, + (_, Value::String(model)) if block_depth(key) == Some(0) => { + json_words(&serde_json::json!({ "model": model })) + } + (_, Value::Object(_)) => json_words(value), + (_, Value::String(s)) => shell_quote(s), + (_, Value::Bool(_) | Value::Number(_)) => value.to_string(), + (_, Value::Array(items)) if !items.is_empty() && items.iter().all(Value::is_string) => { + let words: Vec<String> = items + .iter() + .filter_map(Value::as_str) + .map(shell_quote) + .collect(); + words.join(" ") + } + (_, Value::Array(_) | Value::Null) => json_words(value), + }; + lines.push(format!("specforge settings set {extension} {key} {words}")); + } +} + +/// An entry about the key `key` of `config.json`. +fn entry(key: &str, outcome: Outcome, reason: String) -> Entry { + Entry { + file: CONFIG.to_string(), + line: None, + section: key.to_string(), + outcome, + reason, + } +} + +/// `--value-json '<compact JSON>'`. +fn json_words(value: &Value) -> String { + format!("--value-json {}", shell_quote(&value.to_string())) +} + +/// A setting key's segment: `[A-Za-z0-9_-]+`. +fn is_segment(segment: &str) -> bool { + !segment.is_empty() + && segment + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') +} + +/// Whether the token `token` names the key `key`: `a.*` / `a_*` a key past the prefix, `a` the key `a` and every key +/// under `a.` (settings.md's `agent_skills` is the family `agent_skills.*`). +fn names(token: &str, key: &str) -> bool { + match token.strip_suffix('*') { + Some(prefix) => key.starts_with(prefix) && key.len() > prefix.len(), + None => key + .strip_prefix(token) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('.')), + } +} + +/// The extension that owns `key`: the owner of the longest token naming it. +fn owner(key: &str) -> Option<&'static str> { + if secret(key).is_some() { + return Some("@gsd/core"); + } + OWNERS + .iter() + .flat_map(|(extension, tokens)| tokens.iter().map(move |token| (*extension, *token))) + .filter(|(_, token)| names(token, key)) + .max_by_key(|(_, token)| token.len()) + .map(|(extension, _)| extension) +} + +/// The environment variable of a search flag. +fn secret(key: &str) -> Option<&'static str> { + SECRETS + .iter() + .find(|(flag, _)| *flag == key) + .map(|(_, variable)| *variable) +} + +/// How many segments a key under a block setting's prefix lacks to be the block (`Some(0)`: it is one); none for a +/// key under no block prefix. +fn block_depth(key: &str) -> Option<usize> { + BLOCKS.iter().find_map(|(prefix, segments)| { + let rest = key.strip_prefix(prefix)?.strip_prefix('.')?; + Some(segments.saturating_sub(rest.split('.').count())) + }) +} + +/// Whether any string of `value` (or any object key) holds a character the report would escape ([`invisible`]), so a +/// printed settings line never holds an invisible character. +fn has_invisible(value: &Value) -> bool { + match value { + Value::String(s) => s.chars().any(invisible), + Value::Array(items) => items.iter().any(has_invisible), + Value::Object(map) => map + .iter() + .any(|(k, v)| k.chars().any(invisible) || has_invisible(v)), + _ => false, + } +} + +#[cfg(test)] +mod tests; diff --git a/gsd/import/src/settings/tests.rs b/gsd/import/src/settings/tests.rs new file mode 100644 index 0000000000..eb0058395c --- /dev/null +++ b/gsd/import/src/settings/tests.rs @@ -0,0 +1,351 @@ +use serde_json::json; + +use super::*; + +fn manifest(loaded: &[&str]) -> Manifest { + Manifest { + security: loaded.contains(&"@gsd/security"), + loaded: loaded.iter().map(|s| s.to_string()).collect(), + } +} + +/// The lines and `(key, outcome, reason)` of each entry of `config`. +fn run(config: Value, loaded: &[&str]) -> (Vec<String>, Vec<(String, Outcome, String)>) { + let (lines, entries) = settings_lines(&config.to_string(), &manifest(loaded)); + let entries = entries + .into_iter() + .filter(|e| e.section != "worktree.baseRef") + .map(|e| (e.section, e.outcome, e.reason)) + .collect(); + (lines, entries) +} + +#[test] +fn settings_lines_quote_each_value_for_a_shell() { + assert_eq!(shell_quote("plain"), "'plain'"); + assert_eq!(shell_quote("'; rm -rf ~ #"), "''\\''; rm -rf ~ #'"); + assert_eq!(shell_quote("$(id)"), "'$(id)'"); + let (lines, entries) = run( + json!({ + "mode": "'; rm -rf ~ #", + "phase_naming": "$(id)", + "parallelization": false, + "workflow": {"node_repair_budget": 2, "research": true}, + "agent_skills": {"gsd-executor": ["a b", "it's"]}, + "ship": {"pr_body_sections": []}, + }), + &[], + ); + assert_eq!( + lines, + [ + "specforge settings set @gsd/core agent_skills.gsd-executor 'a b' 'it'\\''s'", + "specforge settings set @gsd/core mode ''\\''; rm -rf ~ #'", + "specforge settings set @gsd/core parallelization false", + "specforge settings set @gsd/core phase_naming '$(id)'", + "specforge settings set @gsd/core ship.pr_body_sections --value-json '[]'", + "specforge settings set @gsd/core workflow.node_repair_budget 2", + "specforge settings set @gsd/core workflow.research true", + ] + ); + assert!(entries.is_empty(), "{entries:?}"); +} + +#[test] +fn settings_lines_refuse_a_control_character() { + let (lines, entries) = run( + json!({"mode": "yolo\nrm -rf ~", "granularity": "fine\u{7}", "models": {"plan": ["a\u{202e}"]}}), + &[], + ); + assert!(lines.is_empty(), "{lines:?}"); + let reasons: Vec<&str> = entries.iter().map(|(_, _, r)| r.as_str()).collect(); + assert_eq!( + reasons, + [ + "control character in the value of granularity", + "control character in the value of mode", + "control character in the value of models.plan", + ] + ); + assert!(entries.iter().all(|(_, o, _)| *o == Outcome::Unmapped)); +} + +#[test] +fn settings_lines_refuse_an_invisible_format_character() { + for value in ["yo\u{200B}lo", "\u{FEFF}yolo", "yolo\u{E0041}"] { + let (lines, entries) = run(json!({ "mode": value }), &[]); + assert!(lines.is_empty(), "{value:?}: {lines:?}"); + assert_eq!( + entries + .iter() + .map(|(_, _, r)| r.as_str()) + .collect::<Vec<_>>(), + ["control character in the value of mode"], + "{value:?}" + ); + } +} + +#[test] +fn settings_keys_that_flatten_to_one_are_reported() { + let (lines, entries) = run( + json!({"agent_tools": {"*": ["Read"], "all": ["Bash"]}, "git": {"x": 1}, "git.x": 2}), + &[], + ); + let twice: Vec<&str> = entries + .iter() + .filter(|(_, _, r)| r.contains("given twice")) + .map(|(k, o, _)| { + assert_eq!(*o, Outcome::Unmapped); + k.as_str() + }) + .collect(); + assert_eq!(twice, ["agent_tools.all", "git.x"], "{entries:#?}"); + // One line per key: the last read. + assert!( + lines + .iter() + .filter(|l| l.contains(" agent_tools.all ")) + .count() + <= 1, + "{lines:?}" + ); +} + +#[test] +fn settings_lines_never_print_a_secret() { + let (lines, entries) = run( + json!({"brave_search": "sk-SECRET-1", "jina": "jina-SECRET-2", "exa_search": false}), + &[], + ); + assert_eq!( + lines, + [ + "specforge settings set @gsd/core brave_search true", + "specforge settings set @gsd/core exa_search false", + "specforge settings set @gsd/core jina true", + ] + ); + assert_eq!(entries.len(), 2); + assert!(entries[0].2.contains("BRAVE_API_KEY"), "{entries:?}"); + assert!(entries[1].2.contains("JINA_API_KEY"), "{entries:?}"); + let all = format!("{lines:?}{entries:?}"); + assert!(!all.contains("SECRET"), "{all}"); +} + +#[test] +fn settings_lines_never_print_a_secret_of_any_shape() { + let (lines, entries) = run( + json!({ + "brave_search": {"api_key": "sk-SECRET-OBJECT"}, + "exa_search": {"a": {"b": {"key": "sk-SECRET-NESTED"}}}, + "jina": ["sk-SECRET-ARRAY"], + "perplexity": 4_242_424_242_u64, + "tavily_search.api_key": "sk-SECRET-CHILD", + "ref_search": {"*": "sk-SECRET-STAR"}, + "firecrawl": null, + }), + &[], + ); + // One line per flag, none per child key. + assert_eq!( + lines, + [ + "specforge settings set @gsd/core brave_search true", + "specforge settings set @gsd/core exa_search true", + "specforge settings set @gsd/core jina true", + "specforge settings set @gsd/core perplexity true", + "specforge settings set @gsd/core ref_search true", + "specforge settings set @gsd/core tavily_search true", + ] + ); + let reasons: Vec<(&str, &str)> = entries + .iter() + .map(|(k, _, r)| (k.as_str(), r.as_str())) + .collect(); + for (flag, variable) in [ + ("brave_search", "BRAVE_API_KEY"), + ("exa_search", "EXA_API_KEY"), + ("jina", "JINA_API_KEY"), + ("perplexity", "PERPLEXITY_API_KEY"), + ("ref_search", "REF_API_KEY"), + ("tavily_search", "TAVILY_API_KEY"), + ] { + assert!( + reasons + .iter() + .any(|(k, r)| *k == flag && r.contains(variable) && r.contains("not printed")), + "{flag}: {entries:?}" + ); + } + let all = format!("{lines:?}{entries:?}"); + assert!(!all.contains("SECRET") && !all.contains("4242"), "{all}"); +} + +#[test] +fn settings_lines_report_what_has_no_line() { + let (lines, entries) = run( + json!({ + "project_code": null, + "commit_docs": true, + "search_gitignored": false, + "claude_md_path": "./.claude/CLAUDE.md", + "workflow": {"auto_prune_state": false}, + "git": {"repo_tagging": true}, + "made_up": 1, + "a;rm": {"b": 1}, + }), + &[], + ); + assert!(lines.is_empty(), "{lines:?}"); + let got: Vec<(&str, Outcome)> = entries.iter().map(|(k, o, _)| (k.as_str(), *o)).collect(); + assert_eq!( + got, + [ + ("a;rm.b", Outcome::Unmapped), + ("claude_md_path", Outcome::Unmapped), + ("commit_docs", Outcome::Unmapped), + ("git.repo_tagging", Outcome::Unmapped), + ("made_up", Outcome::Unmapped), + ("project_code", Outcome::Ignored), + ("search_gitignored", Outcome::Unmapped), + ("workflow.auto_prune_state", Outcome::Unmapped), + ] + ); + let reason = |key: &str| { + entries + .iter() + .find(|(k, ..)| k == key) + .map(|(.., r)| r.as_str()) + .expect("an entry") + }; + assert_eq!(reason("commit_docs"), NO_PLANNING); + assert_eq!(reason("claude_md_path"), HOST_FILES); + assert_eq!( + reason("workflow.auto_prune_state"), + "STATE.md is derived, nothing to prune" + ); + assert_eq!(reason("made_up"), "not a gsd-core 1.19 setting"); + assert_eq!(reason("a;rm.b"), "not a setting name"); +} + +#[test] +fn settings_lines_map_gsds_loose_shapes() { + let (lines, entries) = run( + json!({ + "resolve_model_ids": "omit", + "agent_tools": {"*": ["Read"], "gsd-planner": ["Bash"]}, + "model_profile_overrides": { + "claude": {"opus": "claude-opus-4", "haiku": {"model": "h", "reasoning_effort": "low"}} + }, + }), + &[], + ); + assert_eq!( + lines, + [ + "specforge settings set @gsd/core agent_tools.all 'Read'", + "specforge settings set @gsd/core agent_tools.gsd-planner 'Bash'", + "specforge settings set @gsd/core model_profile_overrides.claude.haiku --value-json '{\"model\":\"h\",\"reasoning_effort\":\"low\"}'", + "specforge settings set @gsd/core model_profile_overrides.claude.opus --value-json '{\"model\":\"claude-opus-4\"}'", + "specforge settings set @gsd/core resolve_model_ids omit", + ] + ); + assert!(entries.is_empty(), "{entries:?}"); + for (value, word) in [(false, "aliases"), (true, "ids")] { + let (lines, _) = run(json!({ "resolve_model_ids": value }), &[]); + assert_eq!( + lines, + [format!( + "specforge settings set @gsd/core resolve_model_ids {word}" + )] + ); + } +} + +#[test] +fn settings_lines_need_the_owning_extension() { + let config = json!({ + "workflow": { + "security_asvs_level": 1, + "ui_phase": true, + "ai_integration_phase": true, + "code_review_depth": "standard", + "drift_action": "warn", + }, + "security": {"injection_blocking": false}, + }); + let (lines, entries) = run(config.clone(), &[]); + assert!(lines.is_empty(), "{lines:?}"); + assert_eq!(entries.len(), 6); + assert!( + entries + .iter() + .all(|(_, o, _)| *o == Outcome::NeedsExtension) + ); + let (lines, entries) = run(config, &["@gsd/core", "@gsd/security", "@gsd/ops"]); + assert_eq!( + lines, + [ + "specforge settings set @gsd/security security.injection_blocking false", + "specforge settings set @gsd/ops workflow.code_review_depth 'standard'", + "specforge settings set @gsd/security workflow.security_asvs_level 1", + ] + ); + let left: Vec<&str> = entries.iter().map(|(k, ..)| k.as_str()).collect(); + assert_eq!( + left, + [ + "workflow.ai_integration_phase", + "workflow.drift_action", + "workflow.ui_phase" + ] + ); +} + +#[test] +fn settings_lines_report_a_file_that_is_no_object() { + let (lines, entries) = settings_lines("[1]", &manifest(&[])); + assert!(lines.is_empty()); + assert_eq!(entries[0].reason, "not a JSON object"); + let (_, entries) = settings_lines("{", &manifest(&[])); + assert!(entries[0].reason.starts_with("not JSON")); + // worktree.baseRef is reported once, whatever the file holds. + assert_eq!(entries[1].section, "worktree.baseRef"); +} + +/// `OWNERS` is settings.md's owner table, token for token. +#[test] +fn settings_owners_are_the_specs_table() { + let text = std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../core/spec/settings.md" + )) + .expect("settings.md"); + let table = gsd_kit::markdown::tables(&text) + .into_iter() + .find(|t| t.header.first().is_some_and(|h| h == "Owner")) + .expect("the owner table"); + let spans = |cell: &str| -> Vec<String> { + cell.split('`') + .skip(1) + .step_by(2) + .map(str::to_string) + .collect() + }; + let read: Vec<(String, Vec<String>)> = table + .rows + .iter() + .map(|row| (spans(&row[0]).concat(), spans(&row[1]))) + .collect(); + let ours: Vec<(String, Vec<String>)> = OWNERS + .iter() + .map(|(owner, tokens)| { + ( + owner.to_string(), + tokens.iter().map(|t| t.to_string()).collect(), + ) + }) + .collect(); + assert_eq!(ours, read); +} diff --git a/gsd/import/src/table.rs b/gsd/import/src/table.rs new file mode 100644 index 0000000000..1805a95d62 --- /dev/null +++ b/gsd/import/src/table.rs @@ -0,0 +1,334 @@ +//! The fate table (ADR 0391 D3, ADR 0372's pattern applied to files): one [`Fate`] for every name of +//! `gsd_kit::files::PLANNING_FILES` ([`FATES`]) and for the three names it lacks ([`EXTRAS`]), and one [`Row`] for every +//! known section, key and table row of the Tier 1 formats ([`SECTIONS`]). A reader implements rows of this table; it +//! does not invent them. The tests count it: a name or a section with no row, or with two, fails. + +mod sections; + +use std::collections::BTreeSet; + +use gsd_kit::files::{PLANNING_FILES, planning_names}; + +use crate::report::Outcome; + +/// What becomes of a whole file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Fate { + /// Tier 1: a reader maps its sections, row by row ([`SECTIONS`]). + Maps, + /// `config.json`: the report prints the `specforge settings set` lines (ADR 0391 D6). + Settings, + /// Session or runtime state, which the graph computes; the reason says whose. + Runtime(&'static str), + /// Nothing to import; the reason says why. + Ignored(&'static str), + /// No reader. [`KIT`] is the kit's own "none: ..." text, read from the kit so the two cannot disagree; any other + /// reason follows the kit's kinds ([`reason`]). + Unmapped(&'static str), + /// Its kinds are this extension's. + NeedsExtension(&'static str), + /// Another file gives the same entities; the reason names it. + Redundant(&'static str), +} + +/// The reason of a name whose kit row reads "none: ...": the kit's text, verbatim. +pub const KIT: &str = ""; + +/// The reason of a Tier 2 name: its kinds exist, the importer does not read the format yet. +pub const TIER_2: &str = "this importer reads the Tier 1 formats of ADR 0391 D3"; + +/// gsd-tools' session state, over once the project is imported. +const SESSION: &str = "a session's state, over once the project is imported"; + +/// One fate per `PLANNING_FILES` name, in the kit's order. +pub const FATES: &[(&str, Fate)] = &[ + ("PROJECT.md", Fate::Maps), + ("SKELETON.md", Fate::Unmapped(TIER_2)), + ("REQUIREMENTS.md", Fate::Maps), + ("ROADMAP.md", Fate::Maps), + ("MILESTONES.md", Fate::Unmapped(TIER_2)), + ( + "milestones/*", + Fate::Redundant( + "an archive copy of a closed milestone's files, which have no counterpart: the live files give its entities", + ), + ), + ( + "STATE.md", + Fate::Runtime( + "derived: the graph computes its progress and position, and its session continuity is a session's", + ), + ), + ("RETROSPECTIVE.md", Fate::Unmapped(TIER_2)), + ("LEARNINGS.md", Fate::Unmapped(TIER_2)), + ("METHODOLOGY.md", Fate::Unmapped(TIER_2)), + ("NN-CONTEXT.md", Fate::Maps), + ("NN-DISCUSSION-LOG.md", Fate::Maps), + ("NN-DISCUSS-CHECKPOINT.json", Fate::Unmapped(TIER_2)), + ("NN-SPEC.md", Fate::Unmapped(TIER_2)), + ("NN-RESEARCH.md", Fate::Maps), + ("research/*.md", Fate::Unmapped(TIER_2)), + ("NN-MM-PLAN.md", Fate::Maps), + ("NN-REVIEWS.md", Fate::Unmapped(TIER_2)), + ("NN-MM-SUMMARY.md", Fate::Maps), + (".continue-here.md", Fate::Unmapped(TIER_2)), + ("NN-VERIFICATION.md", Fate::Maps), + ("NN-UAT.md", Fate::Maps), + ("NN-VALIDATION.md", Fate::Unmapped(TIER_2)), + ("v<version>-MILESTONE-AUDIT.md", Fate::Unmapped(TIER_2)), + ("WINDOWS.md", Fate::Unmapped(TIER_2)), + ("NN-REFACTOR.md", Fate::Unmapped(TIER_2)), + ("quick/*", Fate::Maps), + ("workstreams/*", Fate::Unmapped(TIER_2)), + // Mapped only when the project loads `@gsd/security`, decided at read time (ADR 0391 D11). + ("SECURITY.md", Fate::Maps), + ("AI-SPEC.md", Fate::NeedsExtension("@gsd/ai")), + ("NN-EVAL-REVIEW.md", Fate::NeedsExtension("@gsd/ai")), + ("NN-UI-SPEC.md", Fate::NeedsExtension("@gsd/ui")), + ("NN-UI-REVIEW.md", Fate::NeedsExtension("@gsd/ui")), + ("codebase/*", Fate::NeedsExtension("@gsd/codebase")), + ("intel/*", Fate::NeedsExtension("@gsd/codebase")), + ("NN-PATTERNS.md", Fate::NeedsExtension("@gsd/codebase")), + ("debug/*", Fate::NeedsExtension("@gsd/ops")), + ("NN-REVIEW.md", Fate::NeedsExtension("@gsd/ops")), + ("todos/*", Fate::NeedsExtension("@gsd/ops")), + ("seeds/*", Fate::NeedsExtension("@gsd/ops")), + ("threads/*", Fate::NeedsExtension("@gsd/ops")), + ("BACKLOG.md", Fate::NeedsExtension("@gsd/ops")), + ("USER-PROFILE.md", Fate::NeedsExtension("@gsd/ops")), + ("reports/*.md", Fate::Unmapped(KIT)), + ("onboarding/SUMMARY.md", Fate::Unmapped(KIT)), + ("INGEST-CONFLICTS.md", Fate::Unmapped(KIT)), + ("estimation-calibration.json", Fate::Unmapped(KIT)), + ("WORKSPACE.md", Fate::Unmapped(KIT)), + ("MILESTONE_SUMMARY-v*.md", Fate::Unmapped(KIT)), + ("SESSION_REPORT*.md", Fate::Unmapped(KIT)), + ("*-session-report.md", Fate::Unmapped(KIT)), + ("*continue-here*.md", Fate::Unmapped(TIER_2)), + ("HANDOFF.json", Fate::Unmapped(TIER_2)), + ("*HANDOFF*.md", Fate::Unmapped(TIER_2)), + ("agent-history.json", Fate::Runtime(SESSION)), + ("current-agent-id.txt", Fate::Runtime(SESSION)), + ("USER-SETUP.md", Fate::Unmapped(TIER_2)), + ("deferred-items.md", Fate::Unmapped(TIER_2)), + ( + "DECISIONS-INDEX.md", + Fate::Redundant( + "a query of the decisions, not data: the decisions are read where they are made", + ), + ), + ("active-workstream", Fate::Runtime(SESSION)), + (".gsd-ws-arg", Fate::Runtime(SESSION)), + (".gsd-outgoing-milestone", Fate::Runtime(SESSION)), + (".gsd-allow-shrink", Fate::Unmapped(KIT)), + ("SEED-*.md", Fate::NeedsExtension("@gsd/ops")), + ("quick-batches/*", Fate::Unmapped(TIER_2)), + ("ui-reviews/*", Fate::NeedsExtension("@gsd/ui")), + ("MEMORY.md", Fate::Unmapped(KIT)), + ("memory/*", Fate::Unmapped(KIT)), + ("async-jobs/*", Fate::Unmapped(KIT)), + ("deliberations/*", Fate::Unmapped(KIT)), + ("graphs/*", Fate::Unmapped(KIT)), + ("logs/*", Fate::Unmapped(KIT)), + ("sketches/*", Fate::Unmapped(KIT)), + ("spikes/*", Fate::Unmapped(KIT)), + ("tmp/*", Fate::Unmapped(KIT)), +]; + +/// The names `PLANNING_FILES` lacks that a `.planning/` folder holds, matched by a path's last segment. +pub const EXTRAS: &[(&str, Fate)] = &[ + ("config.json", Fate::Settings), + ( + "state.json", + Fate::Runtime("gsd-tools' derived state (`state json`): STATE.md and the graph compute it"), + ), + ( + ".gitkeep", + Fate::Ignored("an empty directory's placeholder"), + ), +]; + +/// The name of the `FATES` or `EXTRAS` row the path `rel` (relative to `.planning/`) matches, and its fate: a kit hit +/// spanning the whole path, else an extra (`.gitkeep` in any directory, the others at the folder's root); none for an +/// unknown file. +pub fn fate_of(rel: &str) -> Option<(&'static str, Fate)> { + let row = planning_names(rel) + .into_iter() + .find(|(range, _)| *range == (0..rel.len())) + .map(|(_, row)| row); + let last = rel.rsplit('/').next().unwrap_or(rel); + match row { + Some(row) => FATES.iter().find(|(name, _)| *name == row), + None => EXTRAS + .iter() + .find(|(name, _)| *name == rel || (*name == ".gitkeep" && *name == last)), + } + .copied() +} + +/// Whether the file `rel` (under `.planning/`) maps to entities in a project that loads `@gsd/security` when +/// `security`: a read error on one refuses the import (D9). Without it a `SECURITY.md` maps to nothing, only reported +/// `needs-extension`. +pub fn maps(rel: &str, security: bool) -> bool { + match fate_of(rel) { + Some(("SECURITY.md", Fate::Maps)) => security, + Some((_, fate)) => fate == Fate::Maps, + None => false, + } +} + +/// The kit's kinds column for the `PLANNING_FILES` row `name` (empty for an extra). +pub fn kit_kinds(name: &str) -> &'static str { + PLANNING_FILES + .iter() + .find(|(row, _)| *row == name) + .map_or("", |(_, kinds)| *kinds) +} + +/// The report's outcome for a whole file of fate `fate` that no reader read. +pub fn outcome(fate: Fate) -> Outcome { + match fate { + // A Tier 1 file with no reader yet: what its kinds are, unread. + Fate::Maps | Fate::Unmapped(_) => Outcome::Unmapped, + Fate::Settings => Outcome::Setting, + Fate::Runtime(_) => Outcome::Runtime, + Fate::Ignored(_) => Outcome::Ignored, + Fate::NeedsExtension(_) => Outcome::NeedsExtension, + Fate::Redundant(_) => Outcome::Redundant, + } +} + +/// The report's reason for a whole file of the row `name` and fate `fate`. +pub fn reason(name: &str, fate: Fate) -> String { + let kinds = kit_kinds(name); + match fate { + Fate::Maps => kinds.to_string(), + Fate::Settings => "settings: the report prints the line that sets each".to_string(), + Fate::Unmapped(KIT) => kinds.to_string(), + Fate::Unmapped(why) => format!("kinds {kinds} exist; {why}"), + Fate::NeedsExtension(extension) => { + format!("kinds {kinds} are {extension}'s, which the project does not load") + } + Fate::Runtime(why) | Fate::Ignored(why) | Fate::Redundant(why) => why.to_string(), + } +} + +/// Where one source value goes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Home { + /// Written to the field `field` of a `kind` entity through `how` (a `block.member` field names a member; [`ID`] + /// and [`TITLE`] write no field). + To { + kind: &'static str, + field: &'static str, + how: How, + }, + /// A field the kind computes: never written. + Computed { + kind: &'static str, + field: &'static str, + }, + /// Another file gives it; the reason names it. + Redundant(&'static str), + /// No field holds it, or it is a Tier 2 section: reported with the reason. + Reported(&'static str), + /// An empty placeholder or nothing to import. + Ignored(&'static str), + /// A session's or gsd-tools' runtime state; the reason says whose. + Runtime(&'static str), + /// A field with no `.planning` source, written with `value`, reported `filled` with `why`. + Filled { + kind: &'static str, + field: &'static str, + value: &'static str, + why: &'static str, + }, +} + +/// How a source value becomes a field's value. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum How { + /// The text as written (trimmed): a string, a date, a timestamp, a number. + Text, + /// Each item of a list or of the bullets, verbatim. + List, + /// Each row or bullet as a block of named members. + Blocks, + /// A word read as one of the field's enum values (or a bool). + Word, + /// The id of the entity the source names (a phase, a plan, a requirement), as its path. + Ref, + /// The entity's id or title: it writes no field. + Id, +} + +/// The field of an [`How::Id`] home that gives the entity's id. +pub const ID: &str = "(id)"; +/// The field of a home that gives the entity's title. +pub const TITLE: &str = "(title)"; + +/// The reason of a Tier 2 section inside a Tier 1 file (ADR 0391 D3). +pub const LATER: &str = + "a Tier 2 section: its kind exists, and this phase reports it instead of mapping it"; + +/// One known section, key or table row of a Tier 1 format, and its homes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Row { + /// The `FATES` name of the format (`NN-MM-PLAN.md`). + pub file: &'static str, + /// The section, key or row as the document writes it (`## Core Value`, `depends_on`, `<objective>`). + pub key: &'static str, + pub homes: &'static [Home], +} + +/// Every Tier 1 format's rows, one `const` per format (a plan's and a summary's shared rows apart, as a quick plan and +/// a quick summary have them too). +pub const SECTIONS: &[&[Row]] = &[ + sections::PROJECT, + sections::REQUIREMENTS, + sections::ROADMAP, + sections::STATE, + sections::PLAN, + sections::PLAN_SHARED, + sections::SUMMARY, + sections::SUMMARY_SHARED, + sections::CONTEXT, + sections::DISCUSSION_LOG, + sections::RESEARCH, + sections::VERIFICATION, + sections::UAT, + sections::QUICK, + sections::QUICK_PLAN, + sections::QUICK_SUMMARY, + sections::SECURITY, +]; + +/// Every row of [`SECTIONS`]. +pub fn rows() -> impl Iterator<Item = &'static Row> { + SECTIONS.iter().flat_map(|rows| rows.iter()) +} + +/// Every `(kind, field)` a row writes ([`Home::To`], [`Home::Filled`]): a `block.member` home writes its block, and the +/// id and title write no field. A record writing outside it is dropped (`emit`): the table is what is checked against +/// the writers (`tests/measure.rs`). +pub fn written() -> BTreeSet<(&'static str, &'static str)> { + rows() + .flat_map(|row| row.homes) + .filter_map(|home| match *home { + Home::To { kind, field, .. } | Home::Filled { kind, field, .. } + if field != ID && field != TITLE => + { + Some((kind, field.split('.').next().unwrap_or(field))) + } + _ => None, + }) + .collect() +} + +/// The row of the format `file` for the section or key `key`. +pub fn section(file: &str, key: &str) -> Option<&'static Row> { + rows().find(|row| row.file == file && row.key == key) +} + +#[cfg(test)] +mod tests; diff --git a/gsd/import/src/table/sections.rs b/gsd/import/src/table/sections.rs new file mode 100644 index 0000000000..4f240bcf64 --- /dev/null +++ b/gsd/import/src/table/sections.rs @@ -0,0 +1,747 @@ +//! The rows of each Tier 1 format (13-RESEARCH Part B, "Tier 1 section and key tables"), one `const` per format. A key +//! is the section, key or row as the document writes it; a quick plan's and summary's keys start `PLAN ` / `SUMMARY `. + +use super::How::{Blocks, Id, List, Ref, Text, Word}; +use super::{Home, How, ID, LATER, Row, TITLE}; + +const fn row(file: &'static str, key: &'static str, homes: &'static [Home]) -> Row { + Row { file, key, homes } +} + +const fn to(kind: &'static str, field: &'static str, how: How) -> Home { + Home::To { kind, field, how } +} + +const fn computed(kind: &'static str, field: &'static str) -> Home { + Home::Computed { kind, field } +} + +/// The entity's id. +const fn id(kind: &'static str) -> Home { + to(kind, ID, Id) +} + +/// The entity's title. +const fn title(kind: &'static str) -> Home { + to(kind, TITLE, Id) +} + +const fn filled( + kind: &'static str, + field: &'static str, + value: &'static str, + why: &'static str, +) -> Home { + Home::Filled { + kind, + field, + value, + why, + } +} + +const fn reported(why: &'static str) -> Home { + Home::Reported(why) +} + +const fn redundant(why: &'static str) -> Home { + Home::Redundant(why) +} + +const PROSE: &str = "prose: no field holds it"; +const EMPTY: &str = "an empty placeholder"; +const VERDICT: &str = "the verifier's per-item results are verdicts, never imported (ADR 0391 D5): the plans give the entities"; +const CONTEXT_MD: &str = "the phase's CONTEXT.md gives it"; +const INSTRUCTION: &str = "the template's instruction to agents"; +const HARNESS_TS: &str = "a harness timestamp the import does not write (ADR 0391 D7)"; +const FILE_NAME: &str = "the file name gives the phase"; + +const P: &str = "PROJECT.md"; +#[rustfmt::skip] +pub const PROJECT: &[Row] = &[ + row(P, "# Name", &[id("project"), title("project"), to("project", "name", Text)]), + row(P, "## What This Is", &[to("project", "what", Text)]), + row(P, "## Core Value", &[to("project", "core_value", Text)]), + row(P, "## Requirements", &[redundant("REQUIREMENTS.md gives the requirements; its ### Validated and ### Active lists are computed from them")]), + row(P, "## Business Context", &[reported(LATER)]), + row(P, "## Current Milestone", &[reported(LATER)]), + row(P, "### Validated", &[computed("project", "validated")]), + row(P, "### Active", &[computed("project", "active")]), + row(P, "(None yet", &[Home::Ignored(EMPTY)]), + row(P, "### Out of Scope", &[to("project", "out_of_scope.item", Blocks), to("project", "out_of_scope.why", Blocks)]), + row(P, "## Context", &[to("project", "context", Text)]), + row(P, "## Constraints", &[ + to("project", "constraints.kind", Word), + to("project", "constraints.what", Blocks), + to("project", "constraints.why", Blocks), + filled("project", "constraints.kind", "other", "a label that names no kind keeps its words in `what`"), + ]), + row(P, "## Key Decisions", &[ + id("decision"), + to("decision", "text", Text), + to("decision", "rationale", Text), + to("decision", "outcome", Word), + filled("decision", "origin", "project", "a Key Decisions row is a project decision"), + to("project", "key_decisions", Ref), + ]), + row(P, "*Last updated:", &[computed("project", "updated")]), +]; + +const RQ: &str = "REQUIREMENTS.md"; +#[rustfmt::skip] +pub const REQUIREMENTS: &[Row] = &[ + row(RQ, "**Defined:**", &[to("requirement", "defined", Text)]), + row(RQ, "**Core Value:**", &[redundant("PROJECT.md's ## Core Value gives it")]), + row(RQ, "## v1 Requirements", &[to("requirement", "tier", Word)]), + row(RQ, "## v2 Requirements", &[to("requirement", "tier", Word)]), + row(RQ, "## Out of Scope", &[to("requirement", "tier", Word)]), + row(RQ, "### Category", &[to("requirement", "category", Text)]), + row(RQ, "- **ID**: text", &[id("requirement"), title("requirement"), to("requirement", "text", Text)]), + row(RQ, "- [x]", &[computed("requirement", "status")]), + row(RQ, "| Feature | Reason |", &[ + filled("requirement", ID, "OOS-<NN>", "GSD gives an Out of Scope row no id, so the import numbers the rows"), + title("requirement"), + to("requirement", "text", Text), + to("requirement", "reason", Text), + filled("requirement", "category", "Out of Scope", "the row's section"), + ]), + row(RQ, "## Traceability", &[redundant("ROADMAP.md's **Requirements** lines give each phase's requirements")]), + row(RQ, "**Coverage:**", &[redundant("the coverage counts follow from the roadmap's requirements")]), + row(RQ, "*Requirements defined:", &[reported(PROSE)]), + row(RQ, "*Last updated:", &[reported("the graph keeps no edit date of a file")]), +]; + +const RM: &str = "ROADMAP.md"; +#[rustfmt::skip] +pub const ROADMAP: &[Row] = &[ + row(RM, "(no milestone)", &[filled( + "milestone", + ID, + "v1.0", + "the roadmap names no milestone: GSD's initial roadmap is v1.0; its title is authored after import", + )]), + row(RM, "# Roadmap:", &[redundant("PROJECT.md's # Name names the project")]), + row(RM, "## Milestones", &[id("milestone"), title("milestone")]), + row(RM, "milestone status", &[computed("milestone", "state")]), + row(RM, "**Milestone Goal:**", &[to("milestone", "goal", Text)]), + row(RM, "## Phase Details", &[Home::Ignored("a heading over the phases, each mapped under its own heading")]), + row(RM, "<details>", &[to("phase", "milestone", Ref)]), + row(RM, "## Overview", &[reported(PROSE)]), + row(RM, "## Phases", &[computed("phase", "status")]), + row(RM, "**Plans**: N/M plans complete", &[computed("phase", "plans_complete")]), + row(RM, "## Progress", &[computed("phase", "completed")]), + row(RM, "Phase Numbering", &[reported(PROSE)]), + row(RM, "### Phase N: Name", &[id("phase"), title("phase"), to("phase", "slug", Text)]), + row(RM, "(INSERTED)", &[computed("phase", "inserted")]), + row(RM, "**Goal**", &[to("phase", "goal", Text)]), + row(RM, "**Depends on**", &[to("phase", "depends_on", Ref)]), + row(RM, "Nothing (first phase)", &[Home::Ignored(EMPTY)]), + row(RM, "**Requirements**", &[to("phase", "requirements", Ref)]), + row(RM, "TBD", &[Home::Ignored(EMPTY)]), + row(RM, "**Success Criteria**", &[to("phase", "success_criteria", List)]), + row(RM, "**Mode**", &[reported(LATER)]), + row(RM, "Plans:", &[title("plan")]), + row(RM, "TBD (run /gsd-plan-phase", &[Home::Ignored(EMPTY)]), +]; + +const ST: &str = "STATE.md"; +/// STATE.md maps nothing (13-RESEARCH Part B): a section no row names is unmapped, "derived". +#[rustfmt::skip] +pub const STATE: &[Row] = &[ + row(ST, "---", &[computed("milestone", "progress")]), + row(ST, "## Current Position", &[computed("phase", "status")]), + row(ST, "## Session Continuity", &[Home::Runtime("a session's state: a pause needs the host's clock and who paused, and the session is over once the project is imported")]), + row(ST, "### Blockers/Concerns", &[reported(LATER)]), + row(ST, "None yet.", &[Home::Ignored(EMPTY)]), +]; + +/// A phase plan's and a quick plan's keys, tags and tasks: only where the id comes from differs. +macro_rules! plan_rows { + ($file:expr, $prefix:literal) => { + &[ + row($file, concat!($prefix, "type"), &[to("plan", "type", Word)]), + row( + $file, + concat!($prefix, "autonomous"), + &[computed("plan", "autonomous")], + ), + row( + $file, + concat!($prefix, "files_modified"), + &[to("plan", "files_modified", List)], + ), + row( + $file, + concat!($prefix, "must_haves.truths"), + &[ + id("truth"), + title("truth"), + to("truth", "plan", Ref), + to("truth", "text", Text), + ], + ), + row( + $file, + concat!($prefix, "must_haves.artifacts"), + &[ + id("artifact"), + title("artifact"), + to("artifact", "plan", Ref), + to("artifact", "path", Text), + to("artifact", "provides", Text), + to("artifact", "contains", Text), + to("artifact", "min_lines", Text), + to("artifact", "exports", List), + ], + ), + row( + $file, + concat!($prefix, "must_haves.key_links"), + &[ + id("key_link"), + title("key_link"), + to("key_link", "plan", Ref), + to("key_link", "from", Text), + to("key_link", "to", Text), + to("key_link", "via", Text), + to("key_link", "pattern", Text), + ], + ), + row( + $file, + concat!($prefix, "must_haves.prohibitions"), + &[reported(LATER)], + ), + row($file, concat!($prefix, "files_deleted"), &[reported(LATER)]), + row( + $file, + concat!($prefix, "coupling_justified"), + &[reported(LATER)], + ), + row($file, concat!($prefix, "gap_closure"), &[reported(LATER)]), + row($file, concat!($prefix, "agent_hint"), &[reported(LATER)]), + row($file, concat!($prefix, "estimate"), &[reported(LATER)]), + row($file, concat!($prefix, "user_setup"), &[reported(LATER)]), + row( + $file, + concat!($prefix, "<objective>"), + &[to("plan", "objective", Text)], + ), + row( + $file, + concat!($prefix, "Purpose:"), + &[to("plan", "purpose", Text)], + ), + row( + $file, + concat!($prefix, "Output:"), + &[to("plan", "output", Text)], + ), + row( + $file, + concat!($prefix, "<execution_context>"), + &[reported( + "@-references to GSD's own files: `specforge gsd reference` serves them", + )], + ), + row( + $file, + concat!($prefix, "<context>"), + &[to("plan", "context_refs", List)], + ), + row( + $file, + concat!($prefix, "<context> @.planning/"), + &[reported("GSD-internal: the spec replaces it")], + ), + row( + $file, + concat!($prefix, "<task type=\"auto|tdd|tracer\">"), + &[ + id("task"), + title("task"), + to("task", "plan", Ref), + to("task", "type", Word), + to("task", "files", List), + to("task", "read_first", List), + to("task", "action", Text), + to("task", "verify", Blocks), + to("task", "verify_text", Text), + to("task", "acceptance", List), + to("task", "done", Text), + ], + ), + row( + $file, + concat!($prefix, "<task type=\"checkpoint:*\">"), + &[reported(LATER)], + ), + row( + $file, + concat!($prefix, "<behavior>"), + &[reported( + "a TDD task's expected behaviours: no field holds them, its truths and tests do", + )], + ), + row( + $file, + concat!($prefix, "<verification>"), + &[to("plan", "verification", List)], + ), + row( + $file, + concat!($prefix, "<success_criteria>"), + &[to("plan", "success_criteria", List)], + ), + row( + $file, + concat!($prefix, "<output>"), + &[reported("an instruction to the executor")], + ), + row( + $file, + concat!($prefix, "<threat_model> ## Trust Boundaries"), + &[ + id("trust_boundary"), + to("trust_boundary", "plan", Ref), + to("trust_boundary", "boundary", Text), + to("trust_boundary", "description", Text), + ], + ), + row( + $file, + concat!($prefix, "<threat_model> ## STRIDE Threat Register"), + &[ + id("threat"), + to("threat", "plan", Ref), + to("threat", "category", Word), + to("threat", "component", Text), + to("threat", "severity", Word), + to("threat", "disposition", Word), + to("threat", "mitigation", Text), + ], + ), + ] + }; +} + +/// A phase summary's and a quick summary's keys and sections. +macro_rules! summary_rows { + ($file:expr, $prefix:literal) => { + &[ + row( + $file, + concat!($prefix, "file stem"), + &[id("summary"), to("summary", "plan", Ref)], + ), + row( + $file, + concat!($prefix, "status"), + &[to("summary", "status", Word)], + ), + row( + $file, + concat!($prefix, "one-liner"), + &[to("summary", "one_liner", Text)], + ), + row( + $file, + concat!($prefix, "# title"), + &[redundant("the plan's title names the summary")], + ), + row( + $file, + concat!($prefix, "tags"), + &[to("summary", "tags", List)], + ), + row( + $file, + concat!($prefix, "provides"), + &[to("summary", "provides", List)], + ), + row( + $file, + concat!($prefix, "affects"), + &[to("summary", "affects", List)], + ), + row( + $file, + concat!($prefix, "tech-stack.added"), + &[to("summary", "tech_added", List)], + ), + row( + $file, + concat!($prefix, "tech-stack.patterns"), + &[to("summary", "tech_patterns", List)], + ), + row( + $file, + concat!($prefix, "coverage"), + &[ + id("deliverable"), + to("deliverable", "summary", Ref), + to("deliverable", "description", Text), + to("deliverable", "requirement", Ref), + to("deliverable", "human_judgment", Word), + to("deliverable", "rationale", Text), + to("deliverable", "checks.kind", Blocks), + to("deliverable", "checks.ref", Blocks), + ], + ), + row( + $file, + concat!($prefix, "coverage verification status"), + &[computed("deliverable", "checks.status")], + ), + row( + $file, + concat!($prefix, "requires"), + &[to("summary", "requires", Blocks)], + ), + row( + $file, + concat!($prefix, "requires: [plan ids]"), + &[reported( + "a list of plan ids names no `provides`, which a requires block needs", + )], + ), + row($file, concat!($prefix, "key-decisions"), &[reported(LATER)]), + row( + $file, + concat!($prefix, "key-files"), + &[ + computed("summary", "files_created"), + computed("summary", "files_modified"), + ], + ), + row( + $file, + concat!($prefix, "duration"), + &[computed("summary", "duration")], + ), + row($file, concat!($prefix, "started"), &[reported(HARNESS_TS)]), + row( + $file, + concat!($prefix, "completed"), + &[reported(HARNESS_TS)], + ), + row( + $file, + concat!($prefix, "## Task Commits"), + &[reported( + "git history is the collector's: gsd-git writes commit entities", + )], + ), + row( + $file, + concat!($prefix, "## Performance"), + &[reported(PROSE)], + ), + row( + $file, + concat!($prefix, "## Accomplishments"), + &[reported(PROSE)], + ), + row( + $file, + concat!($prefix, "## Issues Encountered"), + &[reported(PROSE)], + ), + row( + $file, + concat!($prefix, "## Next Phase Readiness"), + &[reported(LATER)], + ), + row( + $file, + concat!($prefix, "## Deviations from Plan"), + &[reported(LATER)], + ), + row( + $file, + concat!($prefix, "## Threat Flags"), + &[to("summary", "threat_flags", List)], + ), + ] + }; +} + +const PL: &str = "NN-MM-PLAN.md"; +#[rustfmt::skip] +pub const PLAN: &[Row] = &[ + row(PL, "file name", &[id("plan"), to("plan", "phase", Ref)]), + row(PL, "phase, plan", &[redundant("the file name gives them; a mismatch is reported")]), + row(PL, "wave", &[computed("plan", "wave"), to("plan", "wave0", Word)]), + row(PL, "depends_on", &[to("plan", "depends_on", Ref)]), + row(PL, "requirements", &[to("plan", "requirements", Ref)]), +]; +pub const PLAN_SHARED: &[Row] = plan_rows!(PL, ""); + +const SM: &str = "NN-MM-SUMMARY.md"; +#[rustfmt::skip] +pub const SUMMARY: &[Row] = &[ + row(SM, "phase, plan", &[redundant("the file name gives them; a mismatch is reported")]), + row(SM, "subsystem", &[to("summary", "subsystem", Text)]), + row(SM, "requirements-completed", &[to("summary", "requirements_completed", Ref)]), +]; +pub const SUMMARY_SHARED: &[Row] = summary_rows!(SM, ""); + +const CX: &str = "NN-CONTEXT.md"; +#[rustfmt::skip] +pub const CONTEXT: &[Row] = &[ + row(CX, "file stem", &[id("context"), to("context", "phase", Ref)]), + row(CX, "# Phase N: Name - Context", &[title("context")]), + row(CX, "**Gathered:**", &[to("context", "gathered", Text)]), + row(CX, "**Status:**", &[computed("context", "status")]), + row(CX, "## Phase Boundary", &[to("context", "boundary", Text)]), + row(CX, "- **D-NN:**", &[ + id("decision"), + to("decision", "phase", Ref), + to("decision", "area", Text), + to("decision", "text", Text), + filled("decision", "origin", "context", "a decision of a phase's CONTEXT.md"), + ]), + row(CX, "### Claude's Discretion", &[to("context", "discretion", List)]), + row(CX, "<specifics>", &[to("context", "specifics", Text)]), + row(CX, "<canonical_refs>", &[to("context", "canonical_refs", Blocks)]), + row(CX, "**Downstream agents MUST read these", &[Home::Ignored(INSTRUCTION)]), + row(CX, "### Reusable Assets", &[to("context", "reusable_assets", List)]), + row(CX, "### Established Patterns", &[to("context", "patterns", List)]), + row(CX, "### Integration Points", &[to("context", "integration_points", List)]), + row(CX, "<deferred>", &[ + id("deferred_idea"), + to("deferred_idea", "phase", Ref), + to("deferred_idea", "text", Text), + to("deferred_idea", "why", Text), + filled("deferred_idea", "origin", "discussion", "an idea deferred in a phase's discussion"), + ]), + row(CX, "footer", &[reported(PROSE)]), +]; + +const DL: &str = "NN-DISCUSSION-LOG.md"; +#[rustfmt::skip] +pub const DISCUSSION_LOG: &[Row] = &[ + row(DL, "file stem", &[id("discussion"), to("discussion", "phase", Ref)]), + row(DL, "# Phase N: Name - Discussion Log", &[title("discussion")]), + row(DL, "> **Audit trail only.**", &[Home::Ignored(INSTRUCTION)]), + row(DL, "**Date:**, **Phase:**, **Areas discussed:**", &[redundant("the directory and CONTEXT.md give them")]), + row(DL, "## Area", &[ + to("discussion", "entries.area", Blocks), + to("discussion", "entries.options", Blocks), + to("discussion", "entries.chosen", Blocks), + to("discussion", "entries.notes", Blocks), + filled("discussion", "entries.mode", "interactive", "the only shape a discussion log has"), + ]), + row(DL, "| Description |", &[reported("no member of a discussion entry holds it")]), + row(DL, "## Claude's Discretion", &[redundant(CONTEXT_MD)]), + row(DL, "## Deferred Ideas", &[redundant(CONTEXT_MD)]), + row(DL, "footer", &[reported(PROSE)]), +]; + +const RS: &str = "NN-RESEARCH.md"; +#[rustfmt::skip] +pub const RESEARCH: &[Row] = &[ + row(RS, "file stem", &[id("research"), to("research", "phase", Ref)]), + row(RS, "# Phase N: Name - Research", &[title("research")]), + row(RS, "**Researched:**", &[to("research", "researched", Text)]), + row(RS, "**Domain:**", &[to("research", "domain", Text)]), + row(RS, "**Confidence:**", &[to("research", "confidence", Word)]), + row(RS, "### Locked Decisions", &[to("research", "user_constraints", Ref)]), + row(RS, "<user_constraints> ### Claude's Discretion", &[redundant(CONTEXT_MD)]), + row(RS, "<user_constraints> ### Deferred Ideas", &[redundant(CONTEXT_MD)]), + row(RS, "<architectural_responsibility_map>", &[to("research", "responsibility_map", Blocks)]), + row(RS, "| Secondary Tier | Rationale |", &[reported("no member of a responsibility map holds it")]), + row(RS, "## Summary", &[to("research", "summary", Text)]), + row(RS, "**Primary recommendation:**", &[ + id("finding"), to("finding", "research", Ref), to("finding", "text", Text), to("finding", "confidence", Word), + ]), + row(RS, "## Standard Stack", &[ + id("stack_choice"), + title("stack_choice"), + to("stack_choice", "research", Ref), + to("stack_choice", "name", Text), + to("stack_choice", "version", Text), + to("stack_choice", "purpose", Text), + to("stack_choice", "tier", Word), + ]), + row(RS, "| Why Standard |", &[reported("no field of a stack choice holds it")]), + row(RS, "### Pattern N: Name", &[ + id("pattern"), + to("pattern", "research", Ref), + to("pattern", "name", Text), + to("pattern", "what", Text), + to("pattern", "when", Text), + to("pattern", "example", Text), + ]), + row(RS, "### Anti-Patterns to Avoid", &[ + id("pattern"), + to("pattern", "research", Ref), + to("pattern", "name", Text), + to("pattern", "what", Text), + to("pattern", "anti", Word), + ]), + row(RS, "## Don't Hand-Roll", &[ + id("dont_hand_roll"), + to("dont_hand_roll", "research", Ref), + to("dont_hand_roll", "problem", Text), + to("dont_hand_roll", "instead", Text), + to("dont_hand_roll", "why", Text), + ]), + row(RS, "| Don't Build |", &[reported("no field of a don't-hand-roll holds it")]), + row(RS, "## Common Pitfalls", &[ + id("pitfall"), + to("pitfall", "research", Ref), + to("pitfall", "name", Text), + to("pitfall", "goes_wrong", Text), + to("pitfall", "why", Text), + to("pitfall", "avoid", Text), + to("pitfall", "warning_signs", Text), + ]), + row(RS, "## Open Questions", &[ + id("open_question"), + to("open_question", "research", Ref), + to("open_question", "question", Text), + to("open_question", "known", Text), + to("open_question", "unclear", Text), + to("open_question", "recommendation", Text), + to("open_question", "resolved_by", Ref), + ]), + row(RS, "## Sources", &[ + id("source"), + to("source", "research", Ref), + to("source", "url", Text), + to("source", "tier", Word), + to("source", "checked", Text), + ]), + row(RS, "package legitimacy", &[reported(LATER)]), + row(RS, "footer", &[reported(PROSE)]), +]; + +const VF: &str = "NN-VERIFICATION.md"; +#[rustfmt::skip] +pub const VERIFICATION: &[Row] = &[ + row(VF, "file stem", &[id("verification"), to("verification", "phase", Ref)]), + row(VF, "phase", &[redundant(FILE_NAME)]), + row(VF, "**Phase Goal:**", &[redundant("ROADMAP.md gives the phase goal")]), + row(VF, "## Goal Achievement", &[Home::Ignored("a heading over the verifier's tables, each reported under its own")]), + row(VF, "footer", &[reported(PROSE)]), + row(VF, "status", &[computed("verification", "status")]), + row(VF, "score", &[computed("verification", "score")]), + row(VF, "verified", &[computed("verification", "verified")]), + row(VF, "covered_files", &[computed("verification", "covered_files")]), + row(VF, "covered_digest", &[computed("verification", "covered_digest")]), + row(VF, "re_verification", &[computed("verification", "re_verification")]), + row(VF, "anti_patterns", &[computed("verification", "anti_patterns")]), + row(VF, "scan_partial", &[computed("verification", "scan_partial")]), + row(VF, "behavior_unverified", &[reported("no field of a verification holds it")]), + row(VF, "### Observable Truths", &[reported(VERDICT)]), + row(VF, "### Required Artifacts", &[reported(VERDICT)]), + row(VF, "### Key Link Verification", &[reported(VERDICT)]), + row(VF, "### Requirements Coverage", &[redundant("the summaries' requirements-completed give it")]), + row(VF, "## Gaps Summary", &[reported(LATER)]), + row(VF, "No gaps found", &[Home::Ignored(EMPTY)]), + row(VF, "## Human Verification Required", &[reported(LATER)]), + row(VF, "override", &[reported( + "a person's value: the host refuses an agent's write of a human field; write it in your editor", + )]), +]; + +const UA: &str = "NN-UAT.md"; +#[rustfmt::skip] +pub const UAT: &[Row] = &[ + row(UA, "file stem", &[id("uat_session"), to("uat_session", "phase", Ref)]), + row(UA, "phase", &[redundant(FILE_NAME)]), + row(UA, "## Tests", &[Home::Ignored("a heading over the tests, each mapped under its own")]), + row(UA, "source", &[to("uat_session", "source", List)]), + row(UA, "started", &[to("uat_session", "started", Text)]), + row(UA, "status", &[computed("uat_session", "status")]), + row(UA, "updated", &[reported("the session's last edit: no field holds it")]), + row(UA, "## Current Test", &[reported("the session's position, a runtime state")]), + row(UA, "## Summary", &[computed("uat_session", "totals")]), + row(UA, "### N. Title", &[ + id("uat_test"), + title("uat_test"), + to("uat_test", "session", Ref), + to("uat_test", "expected", Text), + to("uat_test", "result", Word), + to("uat_test", "reported", Text), + to("uat_test", "severity", Word), + to("uat_test", "reason", Text), + to("uat_test", "blocked_by", Text), + ]), + row(UA, "## Gaps", &[ + id("uat_gap"), + to("uat_gap", "test", Ref), + to("uat_gap", "truth", Text), + to("uat_gap", "reason", Text), + to("uat_gap", "severity", Word), + to("uat_gap", "root_cause", Text), + to("uat_gap", "artifacts.path", Blocks), + to("uat_gap", "artifacts.issue", Blocks), + to("uat_gap", "missing", List), + ]), + row(UA, "## Gaps status", &[computed("uat_gap", "status")]), + row(UA, "## Gaps debug_session", &[reported("a gap's debug session is @gsd/ops's `uat_gap.debug`")]), + row(UA, "## Deferred Follow-Ups", &[reported("uat_session.follow_ups is the harness field set_uat_result writes")]), +]; + +const QK: &str = "quick/*"; +#[rustfmt::skip] +pub const QUICK: &[Row] = &[ + row(QK, "PLAN quick_id", &[id("plan")]), + row(QK, "PLAN slug", &[to("plan", "slug", Text)]), + row(QK, "PLAN title", &[title("plan")]), + row(QK, "SUMMARY quick_id, slug", &[redundant("the quick plan gives them")]), + row(QK, "SUMMARY subsystem", &[filled("summary", "subsystem", "quick", "a quick summary has no subsystem")]), + row(QK, "SUMMARY requirements-completed", &[filled( + "summary", + "requirements_completed", + "[]", + "a quick summary lists no requirements", + )]), + row(QK, "CONTEXT", &[reported(LATER)]), + row(QK, "RESEARCH", &[reported(LATER)]), +]; +pub const QUICK_PLAN: &[Row] = plan_rows!(QK, "PLAN "); +pub const QUICK_SUMMARY: &[Row] = summary_rows!(QK, "SUMMARY "); + +const SC: &str = "SECURITY.md"; +#[rustfmt::skip] +pub const SECURITY: &[Row] = &[ + row(SC, "phase, slug", &[ + id("security_audit"), + to("security_audit", "phase", Ref), + redundant("the file name gives the phase and the directory its slug; a mismatch is reported"), + ]), + row(SC, "asvs_level", &[to("security_audit", "asvs_level", Text)]), + row(SC, "created", &[ + to("security_audit", "created", Text), + filled("security_audit", "created", "<date>T00:00:00Z", "the frontmatter gives a date only; the field is a timestamp"), + ]), + row(SC, "> Per-phase security contract", &[Home::Ignored(INSTRUCTION)]), + row(SC, "## Security Audit Trail", &[Home::Ignored("a heading over the audit runs, each mapped under its own")]), + row(SC, "status", &[computed("security_audit", "status")]), + row(SC, "threats_open", &[computed("security_audit", "threats_open")]), + row(SC, "## Trust Boundaries", &[to("trust_boundary", "data_crossing", Text)]), + row(SC, "## Threat Register", &[to("threat", "status", Word)]), + row(SC, "## Threat Register Mitigation", &[redundant("the plan's Mitigation Plan gives it; a difference is reported")]), + row(SC, "## Accepted Risks Log", &[ + id("accepted_risk"), + to("accepted_risk", "audit", Ref), + to("accepted_risk", "threat", Ref), + to("accepted_risk", "rationale", Text), + to("accepted_risk", "accepted_by", Text), + to("accepted_risk", "at", Text), + ]), + row(SC, "## Security Audit <date>", &[ + id("audit_run"), + to("audit_run", "audit", Ref), + filled("audit_run", "at", "<date>T00:00:00Z", "the heading gives a date only; the field is a timestamp"), + to("audit_run", "total", Text), + to("audit_run", "closed", Text), + to("audit_run", "open", Text), + ]), + row(SC, "## Sign-Off", &[reported(PROSE)]), + row(SC, "**Approval:**", &[reported(PROSE)]), + row(SC, "status legend", &[reported(PROSE)]), +]; diff --git a/gsd/import/src/table/tests.rs b/gsd/import/src/table/tests.rs new file mode 100644 index 0000000000..30d0b1b039 --- /dev/null +++ b/gsd/import/src/table/tests.rs @@ -0,0 +1,119 @@ +use std::collections::BTreeSet; + +use gsd_kit::files::PLANNING_FILES; + +use super::*; + +#[test] +fn fates_cover_planning_files() { + let mut fated: Vec<&str> = FATES.iter().chain(EXTRAS).map(|(name, _)| *name).collect(); + let mut known: Vec<&str> = PLANNING_FILES.iter().map(|(name, _)| *name).collect(); + known.extend(["config.json", "state.json", ".gitkeep"]); + // In the kit's order, each once. + assert_eq!(fated, known); + fated.sort_unstable(); + fated.dedup(); + known.sort_unstable(); + known.dedup(); + assert_eq!( + fated.len(), + FATES.len() + EXTRAS.len(), + "a name given twice" + ); + assert_eq!(fated, known); +} + +#[test] +fn the_kits_reasons_are_reused() { + let mut none = 0; + for (name, kinds) in PLANNING_FILES { + let (_, fate) = FATES.iter().find(|(n, _)| n == name).expect("a fate"); + if kinds.starts_with("none:") { + none += 1; + assert_eq!(*fate, Fate::Unmapped(KIT), "{name}"); + assert_eq!(reason(name, *fate), *kinds, "{name}"); + } else { + assert_ne!( + *fate, + Fate::Unmapped(KIT), + "{name}: the kit gives kinds, not a reason" + ); + } + } + assert!(none > 0); + // A Tier 2 name says which kinds exist. + assert_eq!( + reason("SKELETON.md", Fate::Unmapped(TIER_2)), + format!("kinds {} exist; {TIER_2}", kit_kinds("SKELETON.md")) + ); +} + +#[test] +fn a_section_has_one_home() { + let mut seen = BTreeSet::new(); + for row in rows() { + assert!( + seen.insert((row.file, row.key)), + "{} {} has two rows", + row.file, + row.key + ); + assert!( + !row.homes.is_empty(), + "{} {} has no home", + row.file, + row.key + ); + // STATE.md maps nothing, but its reader reports it section by section. + assert!( + FATES.iter().any(|(name, fate)| *name == row.file + && (*fate == Fate::Maps + || (*name == "STATE.md" && matches!(fate, Fate::Runtime(_))))), + "{}: rows of a file no reader reads", + row.file + ); + assert_eq!(section(row.file, row.key), Some(row)); + } + // Every Tier 1 file has rows. + for (name, fate) in FATES { + if *fate == Fate::Maps { + assert!(rows().any(|row| row.file == *name), "{name} has no rows"); + } + } +} + +#[test] +fn fate_of_classifies_a_path_under_planning() { + assert_eq!( + fate_of("phases/01-core/01-01-PLAN.md"), + Some(("NN-MM-PLAN.md", Fate::Maps)) + ); + assert_eq!( + fate_of("quick/261105-tcl-x/261105-tcl-PLAN.md"), + Some(("quick/*", Fate::Maps)) + ); + assert!(matches!( + fate_of("state.json"), + Some(("state.json", Fate::Runtime(_))) + )); + assert!(matches!( + fate_of("phases/03-listing/.gitkeep"), + Some((".gitkeep", Fate::Ignored(_))) + )); + assert_eq!( + fate_of("config.json"), + Some(("config.json", Fate::Settings)) + ); + assert_eq!( + fate_of("phases/01-core/01-SECURITY.md"), + Some(("SECURITY.md", Fate::Maps)) + ); + assert_eq!(fate_of("notes.txt"), None); + // GSD keeps config.json and state.json at the folder's root only. + assert_eq!(fate_of("phases/01-core/config.json"), None); + assert!(maps("REQUIREMENTS.md", false)); + assert!(!maps("STATE.md", true)); + // A SECURITY.md maps only when the project loads @gsd/security. + assert!(maps("phases/01-core/01-SECURITY.md", true)); + assert!(!maps("phases/01-core/01-SECURITY.md", false)); +} diff --git a/gsd/import/src/xmltags.rs b/gsd/import/src/xmltags.rs new file mode 100644 index 0000000000..aad8aa8828 --- /dev/null +++ b/gsd/import/src/xmltags.rs @@ -0,0 +1,219 @@ +//! The XML-ish elements of a GSD file (`<objective>`, `<task type="auto">`, `<action>`), cut by their literal closing +//! tag (13-RESEARCH Pitfall 2): a body holds `<`, quotes and code that no XML reader would take, so the body is the text +//! up to the first `</name>` after the opening tag. No XML crate (ADR 0391 Rejected). A tag on a line of a fenced code +//! block is not a tag. +//! +//! Lines are 1-based, as a report entry gives them. + +use gsd_kit::markdown; + +use crate::frontmatter::Refused; + +/// One element: its attributes as written (`type="auto"`), its body verbatim, and the 1-based line of its opening tag. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Tagged { + pub attrs: Vec<(String, String)>, + pub body: String, + pub line: usize, +} + +/// Every `<name ...>` element of `text` outside a fence, in order, and what was refused: an opening tag whose attributes +/// are not `key="value"`, and an unclosed element, which ends the reading (all that follows it would be its body). +pub fn tagged(text: &str, name: &str) -> (Vec<Tagged>, Vec<Refused>) { + let starts: Vec<usize> = std::iter::once(0) + .chain(text.match_indices('\n').map(|(i, _)| i + 1)) + .collect(); + let line = |offset: usize| starts.partition_point(|&s| s <= offset); + let mut fenced = vec![false; starts.len()]; + for fence in markdown::fences(text) { + let end = (fence.code.end + 1).min(fenced.len()); + fenced[fence.open.min(end)..end].fill(true); + } + let (open, close) = (format!("<{name}"), format!("</{name}>")); + let (mut found, mut refused) = (Vec::new(), Vec::new()); + let mut from = 0; + while let Some(at) = text[from..].find(&open).map(|i| from + i) { + let after = at + open.len(); + from = after; + let no = line(at); + if fenced[no - 1] || !text[after..].starts_with([' ', '\t', '\n', '>', '/']) { + continue; + } + let Some(gt) = tag_end(&text[after..]) else { + refused.push(Refused { + line: no, + reason: format!("<{name}> has no `>` ending its opening tag"), + }); + break; + }; + let inside = &text[after..after + gt]; + from = after + gt + 1; + let (inside, empty) = match inside.trim_end().strip_suffix('/') { + Some(inside) => (inside, true), + None => (inside, false), + }; + let Some(attrs) = attributes(inside) else { + refused.push(Refused { + line: no, + reason: format!("<{name}>'s attributes are not key=\"value\""), + }); + continue; + }; + if empty { + found.push(Tagged { + attrs, + body: String::new(), + line: no, + }); + continue; + } + match text[from..].find(&close) { + Some(end) => { + found.push(Tagged { + attrs, + body: text[from..from + end].to_string(), + line: no, + }); + from += end + close.len(); + } + None => { + refused.push(Refused { + line: no, + reason: format!("<{name}> is not closed by {close}"), + }); + break; + } + } + } + (found, refused) +} + +/// The offset of the `>` ending an opening tag, outside a quoted attribute value. +fn tag_end(text: &str) -> Option<usize> { + let mut quoted = false; + for (i, c) in text.char_indices() { + match c { + '"' => quoted = !quoted, + '>' if !quoted => return Some(i), + _ => {} + } + } + None +} + +/// `key="value"` pairs separated by white space; none when the text is anything else. +fn attributes(mut text: &str) -> Option<Vec<(String, String)>> { + let mut attrs = Vec::new(); + loop { + text = text.trim_start(); + if text.is_empty() { + return Some(attrs); + } + let (key, rest) = text.split_once("=\"")?; + if key.is_empty() + || !key + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-' || b == b':') + { + return None; + } + let (value, rest) = rest.split_once('"')?; + attrs.push((key.to_string(), value.to_string())); + text = rest; + if !(text.is_empty() || text.starts_with([' ', '\t', '\n'])) { + return None; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_body_keeps_its_angle_brackets_and_quotes() { + let text = std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../parity/fixtures/taskboard/.planning/phases/01-core/01-02-PLAN.md" + )) + .expect("the fixture"); + let (actions, refused) = tagged(&text, "action"); + assert!(refused.is_empty(), "{refused:?}"); + assert_eq!(actions.len(), 2); + assert!( + actions[0] + .body + .contains("throw `no task <id>` when it is missing"), + "{}", + actions[0].body + ); + assert!( + actions[1] + .body + .contains("`add <title>` prints `added <id>: <title>`") + ); + let (verify, _) = tagged(&text, "verify"); + assert_eq!(verify[1].body, "node src/cli.js add \"Write the roadmap\""); + let (tasks, _) = tagged(&text, "task"); + assert_eq!(tasks.len(), 2); + assert_eq!(tasks[0].attrs, [("type".to_string(), "auto".to_string())]); + assert_eq!(actions[0].line, tasks[0].line + 3); + } + + #[test] + fn an_opening_tag_may_carry_attributes_and_a_longer_name_is_not_it() { + let text = "<tasks>\n<task type=\"checkpoint:human-verify\" gate=\"blocking\">\n<name>x</name>\n</task>\n</tasks>\n"; + let (tasks, refused) = tagged(text, "task"); + assert!(refused.is_empty()); + assert_eq!(tasks.len(), 1); + assert_eq!( + tasks[0].attrs, + [ + ("type".to_string(), "checkpoint:human-verify".to_string()), + ("gate".to_string(), "blocking".to_string()) + ] + ); + assert_eq!( + (tasks[0].line, tasks[0].body.as_str()), + (2, "\n<name>x</name>\n") + ); + } + + #[test] + fn an_unclosed_tag_is_one_refusal_and_no_body() { + let text = "<objective>\nok\n</objective>\n\n<action>\nnever closed <action> again\n"; + let (found, _) = tagged(text, "objective"); + assert_eq!(found.len(), 1); + let (actions, refused) = tagged(text, "action"); + assert!(actions.is_empty()); + assert_eq!(refused.len(), 1, "{refused:?}"); + assert_eq!(refused[0].line, 5); + } + + #[test] + fn a_tag_in_a_fence_is_not_a_tag() { + let text = "Example:\n\n```xml\n<action>not this</action>\n```\n\n<action>this</action>\n"; + let (actions, refused) = tagged(text, "action"); + assert!(refused.is_empty()); + assert_eq!(actions.len(), 1); + assert_eq!((actions[0].body.as_str(), actions[0].line), ("this", 7)); + } + + #[test] + fn a_body_ends_at_the_first_literal_closing_tag() { + let (found, refused) = tagged( + "<verify>a</verify> b </verify>\n<verify>c</verify>", + "verify", + ); + assert!(refused.is_empty()); + let bodies: Vec<&str> = found.iter().map(|t| t.body.as_str()).collect(); + assert_eq!(bodies, ["a", "c"]); + } + + #[test] + fn malformed_attributes_are_refused_at_their_line() { + let (found, refused) = tagged("\n<task type=auto>x</task>\n", "task"); + assert!(found.is_empty()); + assert_eq!(refused[0].line, 2); + } +} diff --git a/gsd/import/tests/census.rs b/gsd/import/tests/census.rs new file mode 100644 index 0000000000..089993ffa8 --- /dev/null +++ b/gsd/import/tests/census.rs @@ -0,0 +1,495 @@ +//! The measure of ADR 0391 D3 and D8: nothing a `.planning/` folder holds is dropped silently, and one folder gives the +//! same plan and report whatever the order its files are served in. + +mod common; + +use std::collections::BTreeSet; + +use serde_json::Value; +use specforge_extension_sdk::prelude::*; + +use common::{fact, feed, fixture, fixture_manifest, import, manifest, payload, planning_facts}; +use gsd_import::command::imported; +use gsd_import::frontmatter; +use gsd_import::preflight; +use gsd_import::read::Served; +use gsd_import::table::{self, EXTRAS, FATES, Fate}; + +/// A path under `.planning/` for the `FATES` name `name`: each placeholder filled (`NN`, `MM` → `01`, `<version>` → +/// `1.0`, `*` → `x`), a phase file in phase 01's directory. +fn path_for(name: &str) -> String { + let concrete = name + .replace("NN-", "01-") + .replace("MM-", "01-") + .replace("<version>", "1.0") + .replace('*', "x"); + if name.starts_with("NN") { + format!("phases/01-core/{concrete}") + } else { + concrete + } +} + +/// The served facts of `.planning/` in the census tree: the taskboard's folder, the ledger's quick plan and the vault's +/// security audit (the Tier 1 files, with sources the readers map), then one placeholder for every other `FATES` name, +/// and a file no row names. +fn census_tree() -> Vec<Value> { + let mut facts = planning_facts(&fixture("taskboard")); + let extra = |name: &str, rel: &str| -> Vec<Value> { + planning_facts(&fixture(name)) + .into_iter() + .filter(|f| f["path"].as_str().is_some_and(|p| p.starts_with(rel))) + .collect() + }; + facts.extend(extra("ledger", ".planning/quick/")); + facts.extend(extra("vault", ".planning/phases/01-core/01-SECURITY.md")); + let named = |facts: &[Value], name: &str| { + facts.iter().any(|f| { + let rel = f["path"] + .as_str() + .unwrap_or_default() + .trim_start_matches(".planning/"); + table::fate_of(rel).is_some_and(|(row, _)| row == name) + }) + }; + for (name, _) in FATES.iter().chain(EXTRAS) { + if !named(&facts, name) { + let path = path_for(name); + assert_eq!( + table::fate_of(&path).map(|(row, _)| row), + Some(*name), + "the placeholder {path} must take the row {name}" + ); + facts.push(fact(&format!(".planning/{path}"), "placeholder\n")); + } + } + facts.push(fact(".planning/notes.txt", "a note\n")); + facts +} + +/// Whether `entry` is the one `emit` writes for a record it creates (`<kind> <id>` in the section `<kind>`). +fn is_record(entry: &Value) -> bool { + let (section, reason) = (entry["section"].as_str(), entry["reason"].as_str()); + entry["outcome"] == "mapped" + && section + .zip(reason) + .is_some_and(|(s, r)| r.starts_with(&format!("{s} "))) +} + +/// The file level of D3: each served file of the census tree is a record's source or has one whole-file entry. +#[test] +fn every_served_file_has_a_record_or_one_file_entry() { + let facts = census_tree(); + let out = import( + &CommandGraph::default(), + &feed( + facts.clone(), + false, + Some(&manifest(&["@gsd/core", "@gsd/security"])), + ), + ); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let report = payload(&out); + let entries = report["entries"].as_array().expect("entries"); + // Every name of the table is in the tree. + let served: Vec<&str> = facts.iter().filter_map(|f| f["path"].as_str()).collect(); + for (name, _) in FATES.iter().chain(EXTRAS) { + assert!( + served + .iter() + .any(|p| table::fate_of(p.trim_start_matches(".planning/")) + .is_some_and(|(row, _)| row == *name)), + "{name}" + ); + } + let mut silent = Vec::new(); + for path in &served { + let of: Vec<&Value> = entries.iter().filter(|e| e["file"] == *path).collect(); + let records = of.iter().filter(|e| is_record(e)).count(); + let whole = of + .iter() + .filter(|e| e["line"].is_null() && e["section"] == "") + .count(); + if records == 0 && whole != 1 { + silent.push(format!("{path}: {records} records, {whole} file entries")); + } + } + assert!(silent.is_empty(), "{silent:#?}"); +} + +/// The words of `text`: its runs of letters and digits, lower-cased, each followed by one space. +fn words(text: &str) -> String { + let mut out = String::from(" "); + for word in text + .split(|c: char| !c.is_alphanumeric()) + .filter(|w| !w.is_empty()) + { + out.push_str(&word.to_lowercase()); + out.push(' '); + } + out +} + +/// Every text the plan of `out` writes, as [`words`]: each create's title and each string of its fields at any depth, +/// and each list or block whole, its texts in order (a `<files>` line is a list, a constraint bullet a block). +fn written(out: &CommandOutput) -> Vec<String> { + fn strings(value: &Value, into: &mut Vec<String>) -> String { + let parts: Vec<String> = match value { + Value::String(s) => vec![words(s)], + Value::Array(items) => items.iter().map(|v| strings(v, into)).collect(), + Value::Object(map) => map.values().map(|v| strings(v, into)).collect(), + _ => Vec::new(), + }; + let parts: Vec<&str> = parts + .iter() + .map(|p| p.trim()) + .filter(|p| !p.is_empty()) + .collect(); + let joined = format!(" {} ", parts.join(" ")); + into.push(joined.clone()); + joined + } + let mut out_texts = Vec::new(); + for c in common::creates(out) { + out_texts.push(words(&c.title)); + strings(&c.fields, &mut out_texts); + } + out_texts +} + +/// Each line of the served Tier 1 file `path` that nothing accounts for (ADR 0391 D3, D8): a line outside the +/// frontmatter (whose keys `read::row` holds) and every fence, holding a letter or a digit, that is not an XML tag alone. +/// A line is accounted for when: +/// +/// - an entry is at it, or at the first line of the leaf block holding it (a reader reports a paragraph once); +/// - its text is written: its words (XML tags and a list marker cut), or the words after its label (`**Goal**:`, +/// `- [x] 01-01:`), run inside a text of the plan; a table row cell by cell, a cell's column reported at the header +/// line counting for the cell; +/// - it is structure: a label with no word after it (`Plans:`, `**Success Criteria** (what must be TRUE):`, `missing: +/// []`), whose text is the lines under it or nothing, or a table's header row, whose columns go with the cells; +/// - it lies in a section (level 2 or deeper) or an element whose entry is not `mapped`, up to the next heading that has +/// an entry of its own: the section is reported whole. A level-1 heading never covers what follows it. +fn unaccounted(path: &str, text: &str, entries: &[Value], written: &[String]) -> Vec<String> { + let tag = regex::Regex::new(r#"^</?[A-Za-z][\w-]*(\s[^<>]*)?/?>$"#).expect("a pattern"); + let tags = regex::Regex::new(r#"^\s*<[A-Za-z][\w-]*(\s[^<>]*)?>|</[A-Za-z][\w-]*>\s*$"#) + .expect("a pattern"); + let marker = regex::Regex::new(r#"^\s*([-*+]|\d+[.)])\s+(\[[ xX]\]\s+)?"#).expect("a pattern"); + let held = |text: &str| { + let w = words(text); + !w.trim().is_empty() && written.iter().any(|t| t.contains(w.as_str())) + }; + let (_, start) = frontmatter::split(text); + let body = frontmatter::body(text, start); + let lines: Vec<&str> = body.split('\n').map(|l| l.trim_end_matches('\r')).collect(); + let fenced = gsd_import::sections::fenced(&body); + let of: Vec<&Value> = entries.iter().filter(|e| e["file"] == path).collect(); + let at = |n: usize| -> Vec<&&Value> { + of.iter() + .filter(|e| e["line"].as_u64() == Some(n as u64 + 1)) + .collect() + }; + // The first line of the leaf block holding each line. + let mut first: Vec<usize> = (0..lines.len()).collect(); + for b in gsd_kit::markdown::inline_blocks(&body) { + for &l in &b.lines { + if l < first.len() { + first[l] = first[l].min(b.lines[0]); + } + } + } + let headings: BTreeSet<usize> = gsd_kit::markdown::headings(&body) + .iter() + .filter(|h| h.level > 1) + .map(|h| h.line) + .collect(); + let h1: BTreeSet<usize> = gsd_kit::markdown::headings(&body) + .iter() + .filter(|h| h.level == 1) + .map(|h| h.line) + .collect(); + // Each table line: its header (no cells) or a row's cells. + let tables = gsd_kit::markdown::tables(&body); + let mut rows: std::collections::BTreeMap< + usize, + (&gsd_kit::markdown::Table, Option<&Vec<String>>), + > = std::collections::BTreeMap::new(); + for t in &tables { + rows.insert(t.line, (t, None)); + for (i, cells) in t.rows.iter().enumerate() { + rows.insert(t.line + 2 + i, (t, Some(cells))); + } + } + let mut covered = false; + // The element a non-mapped entry covers, until its closing tag. + let mut element: Option<String> = None; + let mut silent = Vec::new(); + for (n, raw) in lines.iter().enumerate() { + let line = raw.trim(); + let here = at(n); + let reported_whole = !here.is_empty() && here.iter().all(|e| e["outcome"] != "mapped"); + if h1.contains(&n) { + covered = false; + } else if headings.contains(&n) && !here.is_empty() { + covered = reported_whole; + } + if element.is_none() && reported_whole && !headings.contains(&n) { + let name: String = line + .strip_prefix('<') + .unwrap_or_default() + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-')) + .collect(); + if !name.is_empty() && !line.contains(&format!("</{name}>")) { + element = Some(name); + } + } + let inside = element.is_some(); + if let Some(name) = &element + && line.contains(&format!("</{name}>")) + { + element = None; + } + if fenced.get(n).copied().unwrap_or(false) + || words(line).trim().is_empty() + || tag.is_match(line) + || covered + || inside + || !here.is_empty() + || !at(first[n]).is_empty() + { + continue; + } + let accounted = match rows.get(&n) { + Some((t, None)) => t.header.iter().all(|h| !h.is_empty()), + Some((t, Some(cells))) => cells.iter().enumerate().all(|(i, cell)| { + words(cell).trim().is_empty() + || held(cell) + || t.header.get(i).is_some_and(|h| { + at(t.line) + .iter() + .any(|e| e["section"].as_str() == Some(h.as_str())) + }) + }), + None => { + let plain = tags.replace_all(line, ""); + let plain = marker.replace(&plain, ""); + let label = plain.split_once(':'); + let after_label = label.map_or("", |(_, rest)| rest); + // A label whose value holds no word (`missing: []`, `Plans:`) carries nothing to lose. + let empty = label.is_some() && words(after_label).trim().is_empty(); + empty || held(&plain) || held(after_label) + } + }; + if !accounted { + silent.push(format!("{path}:{} {line}", n + 1)); + } + } + silent +} + +/// The silent lines of each Tier 1 file of `facts`, imported with the manifest `manifest`. +fn silent_lines(facts: &[Value], manifest: &str) -> Vec<String> { + let out = import( + &CommandGraph::default(), + &feed(facts.to_vec(), false, Some(manifest)), + ); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let report = payload(&out); + let entries = report["entries"].as_array().expect("entries"); + let texts = written(&out); + let mut silent = Vec::new(); + for f in facts { + let path = f["path"].as_str().unwrap_or_default(); + let rel = path.trim_start_matches(".planning/"); + if matches!(table::fate_of(rel), Some((_, Fate::Maps))) { + let text = f["text"].as_str().unwrap_or_default(); + silent.extend(unaccounted(path, text, entries, &texts)); + } + } + silent +} + +/// The line level of D3 on the fixtures: every line of every Tier 1 file is accounted for. +#[test] +fn every_line_of_a_fixture_is_accounted_for() { + let mut silent = Vec::new(); + for (name, security) in [("taskboard", false), ("ledger", false), ("vault", true)] { + silent.extend(silent_lines( + &planning_facts(&fixture(name)), + &fixture_manifest(name, security), + )); + } + assert!(silent.is_empty(), "lines nothing accounts for: {silent:#?}"); +} + +/// A `.planning/` folder holding, in each Tier 1 format, a construct a reader once skipped with no entry: a title that is +/// not `# Roadmap:`, a phase's prose line, a requirement bullet with no id, a sub-section under a prose section, a plan's +/// heading and prose outside its elements, a `###` under a summary's title, a diagnosed gap's map-form `artifacts`, the +/// intro of a context's decisions and a research's `**Installation:**` line. +fn hostile_tree() -> Vec<Value> { + let files = [ + ( + "ROADMAP.md", + "# Project Roadmap\n\n### Phase 1: One\n\nSome prose about the phase.\n**Goal**: g\n\ + **Success Criteria**:\n\n 1. c\n\n### Phase 2: Two\n**Goal**: h\n**Success Criteria**:\n 1. d\n", + ), + ( + "REQUIREMENTS.md", + "# Requirements: X\n\n## v1 Requirements\n\n### Core\n\n- **CORE-01**: one\n- Users can share a board\n", + ), + ( + "PROJECT.md", + "# Hostile\n\n## What This Is\n\nA thing.\n\n### Details\n\nMore detail.\n\n## Core Value\n\nIt works.\n\n\ + ## Context\n\nNone.\n\n## Constraints\n\n- **Budget**: none — free\n", + ), + ( + "phases/01-one/01-01-PLAN.md", + "---\ntype: execute\nfiles_modified: [a.js]\n---\n\n# Plan 01-01\n\nIntro prose.\n\n<objective>\nDo it.\n\ + </objective>\n\n<tasks>\n<task type=\"auto\">\n <name>Task 1: T</name>\n <action>a</action>\n <done>d</done>\n\ + </task>\n</tasks>\n\n## Notes\n\nSome notes.\n", + ), + ( + "phases/01-one/01-01-SUMMARY.md", + "---\nphase: 01-one\nplan: 01\nsubsystem: core\nstatus: complete\nrequirements-completed: []\ncoverage:\n\ + \x20 - id: D1\n description: \"x\"\n verification: none\n---\n\n# Plan 01 Summary\n\n**It works.**\n\n\ + ### Stray\n\nstray words\n", + ), + ( + "phases/01-one/01-UAT.md", + "---\nstatus: complete\nphase: 01-one\nsource: [01-01-SUMMARY.md]\nstarted: 2026-03-03T10:30:00Z\n\ + updated: 2026-03-03T10:40:00Z\n---\n\n## Tests\n\n### 1. Works\nexpected: it works\nresult: issue\n\ + reported: \"broken\"\nseverity: minor\n\n## Gaps\n\n- truth: \"It works\"\n status: failed\n\ + \x20 reason: \"User reported: broken\"\n severity: minor\n test: 1\n root_cause: \"the cause\"\n\ + \x20 artifacts:\n - path: \"src/a.js\"\n issue: \"the bug\"\n missing: []\n", + ), + ( + "phases/01-one/01-CONTEXT.md", + "# Phase 1: One - Context\n\n**Gathered:** 2026-03-04\n\n<domain>\n## Phase Boundary\n\nB.\n\n</domain>\n\n\ + <decisions>\n## Implementation Decisions\n\nIntro prose here.\n\n### Area\n- **D-01:** one\n</decisions>\n", + ), + ( + "phases/01-one/01-RESEARCH.md", + "# Phase 1: One - Research\n\n**Researched:** 2026-03-04\n**Confidence:** HIGH\n\n## Summary\n\nS.\n\n\ + ## Standard Stack\n\n**Installation:** run npm\n\n### Core\n\n| Library | Version | Purpose |\n|---|---|---|\n\ + | a | 1 | b |\n", + ), + ]; + files + .into_iter() + .map(|(rel, text)| fact(&format!(".planning/{rel}"), text)) + .collect() +} + +/// The line level of D3 on hostile input: every line of each Tier 1 file of [`hostile_tree`] is accounted for, and +/// each file is read, not refused whole. +#[test] +fn every_line_of_a_hostile_folder_is_accounted_for() { + let facts = hostile_tree(); + let manifest = manifest(&["@gsd/core"]); + let out = import( + &CommandGraph::default(), + &feed(facts.clone(), false, Some(&manifest)), + ); + let silent = silent_lines(&facts, &manifest); + assert!(silent.is_empty(), "lines nothing accounts for: {silent:#?}"); + let all = common::creates(&out); + for (kind, path) in [ + ("phase", "01"), + ("requirement", "CORE-01"), + ("project", "hostile"), + ("task", "v1.0/01/01-01/T1"), + ("summary", "v1.0/01/01-01/01-01-SUMMARY"), + ("uat_gap", "v1.0/01/01-UAT/U1/G1"), + ("decision", "v1.0/01/D-01"), + ("stack_choice", "v1.0/01/01-RESEARCH/SC1"), + ] { + common::find(&all, kind, path); + } +} + +/// The fixture `name`'s import through [`imported`], its served files in `order`. +fn imported_in(name: &str, security: bool, reversed: bool) -> (String, String, String) { + let mut served: Vec<Served> = planning_facts(&fixture(name)) + .into_iter() + .map(|f| Served { + path: f["path"].as_str().unwrap_or_default().to_string(), + text: f["text"].as_str().map(str::to_string), + error: None, + }) + .collect(); + if reversed { + served.reverse(); + } + let manifest = preflight::manifest(&[Served { + path: "specforge.json".to_string(), + text: Some(fixture_manifest(name, security)), + error: None, + }]) + .expect("a manifest"); + let plan = PlanBuilder::new(Default::default(), Default::default()); + let out = imported(served, &manifest, &CommandGraph::default(), plan).expect("imported"); + ( + serde_json::to_string(&out.plan.finish()).expect("JSON"), + serde_json::to_string(&out.payload).expect("JSON"), + out.text, + ) +} + +#[test] +fn vault_owed_names_each_judged_entity() { + let report = payload(&common::import_with("vault", true)); + let owed: Vec<String> = report["owed"] + .as_array() + .expect("owed") + .iter() + .map(|o| { + format!( + "{} {} {}", + o["phase"].as_str().unwrap_or("-"), + o["code"].as_str().unwrap_or_default(), + o["entity"].as_str().unwrap_or_default() + ) + }) + .collect(); + // The closed threats, the audit, the must-haves of the two complete plans, and the plan checks of 02-01, which has + // no summary and so is open. + assert_eq!( + owed, + [ + "01 gsd.security/W302 v1.0/01/01-01/T-01-01", + "01 gsd.security/W302 v1.0/01/01-02/T-01-03", + "01 gsd.security/W303 v1.0/01/01-SECURITY", + "01 gsd/E501 v1.0/01/01-01/AR1", + "01 gsd/E501 v1.0/01/01-01/KL1", + "01 gsd/E501 v1.0/01/01-01/TR1", + "01 gsd/E501 v1.0/01/01-02/AR1", + "01 gsd/E501 v1.0/01/01-02/KL1", + "01 gsd/E501 v1.0/01/01-02/TR1", + "02 gsd/W311 v1.0/02/02-01", + "02 gsd/W313 v1.0/02/02-01", + "02 gsd/W315 v1.0/02/02-01", + "02 gsd/W316 v1.0/02/02-01", + ] + ); + let (_, _, text) = imported_in("vault", true, false); + assert!(text.contains("\n /gsd-secure-phase 01\n specforge query 'v1.0/01/01-01/T-01-01' --inputs gsd.security/W302 --format json\n"), "{text}"); + assert!(text.contains("\n /gsd-verify-work 01\n"), "{text}"); + assert!( + text.contains( + "\n 13 verdicts owed: `specforge check` exits 1 until these verdicts are recorded\n" + ), + "{text}" + ); +} + +#[test] +fn an_import_is_deterministic() { + for (name, security) in [("taskboard", false), ("ledger", false), ("vault", true)] { + let (plan, json, text) = imported_in(name, security, false); + let (plan2, json2, text2) = imported_in(name, security, true); + assert!(plan == plan2, "{name}: the plans differ"); + assert!(json == json2, "{name}: the JSON reports differ"); + assert_eq!(text, text2, "{name}: the text reports differ"); + assert!(plan.len() > 1000 && text.contains("import: "), "{name}"); + } +} diff --git a/gsd/import/tests/cli/compare.rs b/gsd/import/tests/cli/compare.rs new file mode 100644 index 0000000000..9c3ad22746 --- /dev/null +++ b/gsd/import/tests/cli/compare.rs @@ -0,0 +1,471 @@ +//! The comparator of an imported project with its hand-written twin (ADR 0391 D13): both as the graph export gives their +//! nodes, keyed by (kind, id path), each value folded the way the twins shorten what `.planning/` says, and what no +//! import can write left out: the computed and context fields (core's from its kinds golden, +//! `gsd/core/tests/golden/kinds.json`; `@gsd/security`'s from `gsd_security::kinds::computed()`), every verdict, and +//! every `context_pack`. What still differs is either listed, with its reason and the import's value, or a failure; a +//! listed difference that no longer occurs, or whose import value is not the listed one, is a failure too. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{Map, Value}; + +/// One entity of either side: its kind and its graph id path. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct Key { + pub kind: String, + pub id: String, +} + +/// The `field` of a [`Difference`] when the entity is in the import and not in the twin. +pub const IMPORT_ONLY: &str = "(import only)"; +/// The `field` of a [`Difference`] when the entity is in the twin and not in the import. +pub const TWIN_ONLY: &str = "(twin only)"; + +/// The kinds whose title a `.planning/` line names, so the import's can equal the twin's. Every other kind's title is +/// display the twin authored (13-RESEARCH, "Twin fields with NO .planning source"). +const TITLED: [&str; 6] = [ + "phase", + "plan", + "task", + "uat_test", + "deliverable", + "artifact", +]; + +/// The imported key `(kind, import id)` that stands for the twin's `twin id` on a fixture: the twin invents an id where +/// `.planning/` has none (an out-of-scope row is `OOS-<NN>` in the import, ADR 0391 D4). +pub const ID_PAIRS: [(&str, &str, &str, &str); 2] = [ + ("taskboard", "requirement", "OOS-01", "SHARE-01"), + ("ledger", "requirement", "OOS-01", "CURR-01"), +]; + +/// What a listed difference's import value is, folded as [`differences`] folds it: a listed field is checked on both +/// sides, never exempt from a value check. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Expect { + /// Exactly this JSON value. + Is(&'static str), + /// No value: the field is absent or empty in the import. + Absent, +} + +impl Expect { + /// Whether the folded import value `import` is this one. + pub fn admits(self, import: &Value) -> bool { + match self { + Expect::Is(json) => { + serde_json::from_str::<Value>(json).is_ok_and(|expected| expected == *import) + } + Expect::Absent => import.is_null(), + } + } +} + +/// One way the two sides differ: on the entity (twin's key once paired) and the field (`title`, a field name, +/// [`IMPORT_ONLY`] or [`TWIN_ONLY`]), with each side's folded value (`null` when absent or empty). +#[derive(Debug, Clone, PartialEq)] +pub struct Difference { + pub kind: String, + pub id: String, + pub field: String, + pub twin: Value, + pub import: Value, +} + +/// What [`compare`] leaves out: `kind.field` and `kind.field.member` of every computed, context or verdict writer. +pub struct Excluded(BTreeSet<String>); + +impl Excluded { + /// Core's from the kinds golden and `@gsd/security`'s computed fields. + pub fn gsd() -> Self { + let golden: Value = serde_json::from_str( + &std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../core/tests/golden/kinds.json" + )) + .expect("the kinds golden"), + ) + .expect("the golden is JSON"); + let mut out = Self::of(&golden["entities"]); + out.0.extend(gsd_security::kinds::computed()); + out + } + + /// The excluded fields and members of a `describe entities` answer. + pub fn of(entities: &Value) -> Self { + let excluded = |f: &Value| { + matches!( + f["writer"].as_str(), + Some("computed" | "context" | "verdict") + ) + }; + let mut out = BTreeSet::new(); + for kind in entities["items"].as_array().into_iter().flatten() { + let name = kind["name"].as_str().unwrap_or_default(); + for field in kind["fields"].as_array().into_iter().flatten() { + let field_name = field["name"].as_str().unwrap_or_default(); + if excluded(field) { + out.insert(format!("{name}.{field_name}")); + } + for member in field["members"].as_array().into_iter().flatten() { + if excluded(member) { + let member_name = member["name"].as_str().unwrap_or_default(); + out.insert(format!("{name}.{field_name}.{member_name}")); + } + } + } + } + Excluded(out) + } + + fn field(&self, kind: &str, field: &str) -> bool { + field == "context_pack" || self.0.contains(&format!("{kind}.{field}")) + } + + fn member(&self, kind: &str, field: &str, member: &str) -> bool { + self.0.contains(&format!("{kind}.{field}.{member}")) + } +} + +/// `s` as the twins shorten it: every backtick removed, trimmed, one trailing `.` dropped, the first character +/// lowercased. +pub fn fold(s: &str) -> String { + let unticked: String = s.chars().filter(|c| *c != '`').collect(); + let trimmed = unticked.trim(); + let trimmed = trimmed.strip_suffix('.').unwrap_or(trimmed); + let mut chars = trimmed.chars(); + match chars.next() { + Some(first) => first.to_lowercase().chain(chars).collect(), + None => String::new(), + } +} + +/// `value` folded throughout, the excluded members of `kind.field` dropped, and an empty string, list or block, or +/// `null`, as `null`. +fn folded(value: &Value, kind: &str, field: &str, excluded: &Excluded) -> Value { + let out = match value { + Value::String(s) => Value::String(fold(s)), + Value::Array(items) => Value::Array( + items + .iter() + .map(|item| folded(item, kind, field, excluded)) + .filter(|item| !item.is_null()) + .collect(), + ), + Value::Object(members) => Value::Object( + members + .iter() + .filter(|(member, _)| !excluded.member(kind, field, member)) + .map(|(member, v)| (member.clone(), folded(v, kind, field, excluded))) + .filter(|(_, v)| !v.is_null()) + .collect::<Map<String, Value>>(), + ), + other => other.clone(), + }; + let empty = match &out { + Value::String(s) => s.is_empty(), + Value::Array(items) => items.is_empty(), + Value::Object(members) => members.is_empty(), + Value::Null => true, + _ => false, + }; + if empty { Value::Null } else { out } +} + +/// A side's nodes by key, each with its comparable values: `title` for a [`TITLED`] kind, then every field not +/// excluded, folded. `pairs` maps an imported (kind, id) to the twin's id. +fn sided( + nodes: &[Value], + pairs: &[(&str, &str, &str)], + excluded: &Excluded, +) -> BTreeMap<Key, BTreeMap<String, Value>> { + let mut out = BTreeMap::new(); + for node in nodes { + let kind = node["kind"].as_str().unwrap_or_default().to_string(); + let id = node["id"].as_str().unwrap_or_default(); + let id = pairs + .iter() + .find(|(k, from, _)| *k == kind && *from == id) + .map_or(id, |(_, _, to)| to) + .to_string(); + let mut values = BTreeMap::new(); + if TITLED.contains(&kind.as_str()) { + values.insert( + "title".to_string(), + folded(&node["title"], &kind, "title", excluded), + ); + } + for (field, value) in node["fields"].as_object().into_iter().flatten() { + if !excluded.field(&kind, field) { + values.insert(field.clone(), folded(value, &kind, field, excluded)); + } + } + out.insert(Key { kind, id }, values); + } + out +} + +/// Every difference of `import` from `twin` (graph nodes), the imported keys `pairs` names (kind, import id, twin id) +/// mapped first. +pub fn differences( + import: &[Value], + twin: &[Value], + pairs: &[(&str, &str, &str)], + excluded: &Excluded, +) -> Vec<Difference> { + let import = sided(import, pairs, excluded); + let twin = sided(twin, &[], excluded); + let mut out = Vec::new(); + let keys: BTreeSet<&Key> = import.keys().chain(twin.keys()).collect(); + for key in keys { + let one = |field: &str, twin: Value, import: Value| Difference { + kind: key.kind.clone(), + id: key.id.clone(), + field: field.to_string(), + twin, + import, + }; + match (twin.get(key), import.get(key)) { + (None, Some(_)) => out.push(one(IMPORT_ONLY, Value::Null, Value::Bool(true))), + (Some(_), None) => out.push(one(TWIN_ONLY, Value::Bool(true), Value::Null)), + (Some(t), Some(i)) => { + let fields: BTreeSet<&String> = t.keys().chain(i.keys()).collect(); + for field in fields { + let tv = t.get(field).cloned().unwrap_or(Value::Null); + let iv = i.get(field).cloned().unwrap_or(Value::Null); + if tv != iv { + out.push(one(field, tv, iv)); + } + } + } + (None, None) => {} + } + } + out +} + +/// What [`compare`] found wrong: the differences no row lists, the rows listing a difference that no longer occurs, and +/// the listed differences whose import value is not the row's. All empty is a pass. +#[derive(Debug, Default, PartialEq)] +pub struct Compared { + pub unlisted: Vec<Difference>, + pub gone: Vec<(String, String, String)>, + pub wrong: Vec<Difference>, +} + +/// `import` against `twin` (graph nodes), with `pairs` (kind, import id, twin id) and `listed`, the (kind, id, field) +/// of each known difference and its import value. +pub fn compare( + import: &[Value], + twin: &[Value], + pairs: &[(&str, &str, &str)], + listed: &[(&str, &str, &str, Expect)], + excluded: &Excluded, +) -> Compared { + let found = differences(import, twin, pairs, excluded); + let row = |d: &Difference| { + listed + .iter() + .find(|(k, id, f, _)| d.kind == *k && d.id == *id && d.field == *f) + }; + let unlisted = found.iter().filter(|d| row(d).is_none()).cloned().collect(); + let wrong = found + .iter() + .filter(|d| row(d).is_some_and(|(.., expect)| !expect.admits(&d.import))) + .cloned() + .collect(); + let gone = listed + .iter() + .filter(|(k, id, f, _)| { + !found + .iter() + .any(|d| d.kind == *k && d.id == *id && d.field == *f) + }) + .map(|(k, id, f, _)| (k.to_string(), id.to_string(), f.to_string())) + .collect(); + Compared { + unlisted, + gone, + wrong, + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + fn node(kind: &str, id: &str, title: &str, fields: Value) -> Value { + json!({"kind": kind, "id": id, "title": title, "fields": fields}) + } + + fn excluded() -> Excluded { + Excluded::of(&json!({"items": [{"name": "plan", "fields": [ + {"name": "status", "writer": "computed"}, + {"name": "context_refs"}, + {"name": "tasks", "members": [{"name": "done", "writer": "computed"}, {"name": "name"}]}, + ]}]})) + } + + #[test] + fn fold_shortens_as_the_twins_do() { + assert_eq!(fold(" `Complete` tasks."), "complete tasks"); + assert_eq!(fold("Ends.."), "ends."); + assert_eq!(fold("``"), ""); + } + + #[test] + fn a_folded_match_is_no_difference() { + let import = [node( + "plan", + "v1.0/01/01-01", + "01-01: `list` tasks.", + json!({"goal": "Lists `tasks`.", "context_refs": [], "status": "complete", + "tasks": [{"name": "A", "done": true}]}), + )]; + let twin = [node( + "plan", + "v1.0/01/01-01", + "01-01: list tasks", + json!({"goal": "lists tasks", "tasks": [{"name": "a"}]}), + )]; + assert_eq!(differences(&import, &twin, &[], &excluded()), []); + } + + #[test] + fn a_real_mismatch_is_a_difference() { + let import = [node("plan", "P", "P", json!({"goal": "one"}))]; + let twin = [node("plan", "P", "P", json!({"goal": "two"}))]; + let found = differences(&import, &twin, &[], &excluded()); + assert_eq!( + found, + [Difference { + kind: "plan".into(), + id: "P".into(), + field: "goal".into(), + twin: json!("two"), + import: json!("one"), + }] + ); + } + + #[test] + fn a_title_is_compared_only_for_a_titled_kind() { + let import = [ + node("plan", "P", "One", json!({})), + node("research", "R", "One", json!({})), + ]; + let twin = [ + node("plan", "P", "Two", json!({})), + node("research", "R", "Two", json!({})), + ]; + let found = differences(&import, &twin, &[], &excluded()); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!( + (found[0].kind.as_str(), found[0].field.as_str()), + ("plan", "title") + ); + } + + #[test] + fn a_pair_maps_the_imported_key_to_the_twins() { + let import = [node("requirement", "OOS-01", "x", json!({"tier": "out"}))]; + let twin = [node("requirement", "SHARE-01", "y", json!({"tier": "out"}))]; + let pairs = [("requirement", "OOS-01", "SHARE-01")]; + assert_eq!(differences(&import, &twin, &pairs, &excluded()), []); + assert_eq!(differences(&import, &twin, &[], &excluded()).len(), 2); + } + + /// A pair stands only for an id the import mints (ADR 0391 D4): an out-of-scope requirement, once per fixture. + #[test] + fn id_pairs_name_only_minted_out_of_scope_ids() { + for (fixture, kind, from, to) in ID_PAIRS { + assert_eq!(kind, "requirement", "{fixture}"); + assert!( + from.starts_with("OOS-") && !to.starts_with("OOS-"), + "{fixture}" + ); + } + let fixtures: BTreeSet<&str> = ID_PAIRS.iter().map(|(f, ..)| *f).collect(); + assert_eq!(fixtures.len(), ID_PAIRS.len()); + } + + #[test] + fn an_entity_on_one_side_is_a_difference() { + let import = [node("plan", "A", "A", json!({}))]; + let twin = [node("plan", "B", "B", json!({}))]; + let found: Vec<(String, String)> = differences(&import, &twin, &[], &excluded()) + .into_iter() + .map(|d| (d.id, d.field)) + .collect(); + assert_eq!( + found, + [ + ("A".to_string(), IMPORT_ONLY.to_string()), + ("B".to_string(), TWIN_ONLY.to_string()) + ] + ); + } + + #[test] + fn a_listed_difference_that_is_gone_fails() { + let same = [node("plan", "P", "P", json!({"goal": "g"}))]; + let listed = [("plan", "P", "goal", Expect::Is(r#""g""#))]; + let compared = compare(&same, &same, &[], &listed, &excluded()); + assert_eq!(compared.unlisted, []); + assert_eq!(compared.gone, [("plan".into(), "P".into(), "goal".into())]); + } + + #[test] + fn an_unlisted_difference_fails_and_a_listed_one_passes() { + let import = [node("plan", "P", "P", json!({"goal": "one"}))]; + let twin = [node("plan", "P", "P", json!({"goal": "two"}))]; + let unlisted = compare(&import, &twin, &[], &[], &excluded()); + assert_eq!(unlisted.unlisted.len(), 1); + let row = [("plan", "P", "goal", Expect::Is(r#""one""#))]; + let listed = compare(&import, &twin, &[], &row, &excluded()); + assert_eq!(listed, Compared::default()); + } + + /// A listed field is no exemption: an import value other than the row's fails, the twin's differing or not. + #[test] + fn a_listed_difference_with_another_import_value_fails() { + let import = [node("plan", "P", "P", json!({"goal": "", "name": "one"}))]; + let twin = [node( + "plan", + "P", + "P", + json!({"goal": "two", "name": "two"}), + )]; + let rows = [ + ("plan", "P", "goal", Expect::Is(r#""one""#)), + ("plan", "P", "name", Expect::Absent), + ]; + let compared = compare(&import, &twin, &[], &rows, &excluded()); + let wrong: Vec<(&str, &Value)> = compared + .wrong + .iter() + .map(|d| (d.field.as_str(), &d.import)) + .collect(); + assert_eq!(wrong, [("goal", &Value::Null), ("name", &json!("one"))]); + let rows = [ + ("plan", "P", "goal", Expect::Absent), + ("plan", "P", "name", Expect::Is(r#""one""#)), + ]; + assert_eq!( + compare(&import, &twin, &[], &rows, &excluded()), + Compared::default() + ); + } + + #[test] + fn the_gsd_exclusions_hold_the_computed_and_context_fields() { + let excluded = Excluded::gsd(); + assert!(excluded.field("plan", "context_pack")); + let security = gsd_security::kinds::computed(); + assert!(!security.is_empty()); + assert!(security.iter().all(|f| excluded.0.contains(f))); + assert!(excluded.0.len() > 80, "{}", excluded.0.len()); + } +} diff --git a/gsd/import/tests/cli/hostile.rs b/gsd/import/tests/cli/hostile.rs new file mode 100644 index 0000000000..0b364e1557 --- /dev/null +++ b/gsd/import/tests/cli/hostile.rs @@ -0,0 +1,300 @@ +//! Hostile `.planning/` folders through the binary (ADR 0391 D6, D8, D9, D10, D11): what reaches the terminal is +//! escaped, a settings line is shell-quoted, a secret is never printed, an unknown file is named and not echoed, and +//! every refusal (a link out of the project, another spec root, a cap, a path that no longer exists) writes nothing. + +use gsd_import::limits::MAX_OPS; +use serde_json::json; + +use crate::harness::{Project, Run, taskboard, vault}; +use crate::{imported, tree}; + +const CONFIG: &str = ".planning/config.json"; + +/// `specforge gsd import` on `p`, asserted refused (exit 1) saying each of `says`, with nothing written. +fn refused(p: &Project, says: &[&str]) -> Run { + let before = tree(p); + let run = p.run(&["gsd", "import"]); + assert_eq!(run.code, 1, "{}", run.all()); + for words in says { + assert!(run.all().contains(words), "{words:?} not in {}", run.all()); + } + assert!(tree(p) == before, "a refused import wrote: {}", run.all()); + run +} + +/// `specforge gsd import` on `p`, asserted to exit 0. +fn import(p: &Project, args: &[&str]) -> Run { + let mut all = vec!["gsd", "import"]; + all.extend_from_slice(args); + let run = p.run(&all); + assert_eq!(run.code, 0, "{}", run.all()); + run +} + +#[test] +fn terminal_controls_are_escaped() { + let p = imported(taskboard()); + p.edit( + ".planning/ROADMAP.md", + "### Phase 1: Core\n", + "### Phase 1: Core\u{1b}[31m red\u{202e}evil\rinjected\n", + ); + let run = import(&p, &[]); + let all = run.all(); + for raw in ['\u{1b}', '\u{202e}', '\r'] { + assert!( + !all.contains(raw), + "a raw {raw:?} reached the terminal: {all:?}" + ); + } + assert!( + run.stdout.contains("Core\\u{1b}[31m red\\u{202e}evil"), + "the title is shown escaped: {}", + run.stdout + ); + assert!( + !all.lines().any(|line| line.starts_with("injected")), + "the title made a line of its own: {all}" + ); + // A .spec file holds no control character: the phase is reported, not written, and the host refuses nothing. + assert!( + run.stdout + .contains("phase v1.0/01: its title holds a control or bidirectional character"), + "{}", + run.stdout + ); +} + +#[test] +fn settings_lines_are_quoted() { + let p = imported(taskboard()); + p.edit( + CONFIG, + "\"model_profile\": \"balanced\"", + "\"model_profile\": \"x'; rm -rf ~ #\"", + ); + p.edit( + CONFIG, + "\"granularity\": \"coarse\"", + "\"granularity\": \"$(id)\"", + ); + p.edit(CONFIG, "\"mode\": \"yolo\"", "\"mode\": \"yo\\u0007lo\""); + let run = import(&p, &["--dry-run"]); + for line in [ + "specforge settings set @gsd/core model_profile 'x'\\''; rm -rf ~ #'", + "specforge settings set @gsd/core granularity '$(id)'", + ] { + assert!( + run.stdout.lines().any(|l| l.trim() == line), + "no `{line}`: {}", + run.stdout + ); + } + assert!( + !run.stdout.contains("settings set @gsd/core mode "), + "a value with a bell is printed: {}", + run.stdout + ); + assert!( + run.stdout + .contains("control character in the value of mode"), + "{}", + run.stdout + ); + assert!(!run.all().contains('\u{7}')); +} + +#[test] +fn a_secret_is_never_printed() { + let p = imported(taskboard()); + p.edit( + CONFIG, + "\"brave_search\": false", + "\"brave_search\": \"sk-test-123\"", + ); + // An object (and a key under the flag) and a one-string array are the API key too (U1, T-13-14). + p.edit( + CONFIG, + "\"exa_search\": false", + "\"exa_search\": {\"api_key\": \"sk-NESTED-LEAK\", \"deep\": {\"key\": \"sk-DEEP-LEAK\"}}", + ); + p.edit(CONFIG, "\"jina\": false", "\"jina\": [\"sk-ARRAY-LEAK\"]"); + let text = import(&p, &["--dry-run"]); + let json = import(&p, &["--dry-run", "--format", "json"]); + for run in [&text, &json] { + for leak in [ + "sk-test-123", + "sk-NESTED-LEAK", + "sk-DEEP-LEAK", + "sk-ARRAY-LEAK", + ] { + assert!( + !run.all().contains(leak), + "the secret {leak} is printed: {}", + run.all() + ); + } + for variable in ["BRAVE_API_KEY", "EXA_API_KEY", "JINA_API_KEY"] { + assert!(run.stdout.contains(variable), "{variable}: {}", run.stdout); + } + assert!(!run.stdout.contains("exa_search.api_key"), "{}", run.stdout); + } + for line in [ + "specforge settings set @gsd/core exa_search true", + "specforge settings set @gsd/core jina true", + ] { + assert!(text.stdout.contains(line), "{line}: {}", text.stdout); + } + let answer: serde_json::Value = serde_json::from_str(&json.stdout).expect("JSON"); + let entry = answer["output"]["entries"] + .as_array() + .expect("entries") + .iter() + .find(|e| e["section"] == "brave_search") + .unwrap_or_else(|| panic!("no brave_search entry: {answer}")); + assert_eq!(entry["outcome"], "setting"); + assert!( + entry["reason"] + .as_str() + .expect("a reason") + .contains("BRAVE_API_KEY") + ); +} + +#[test] +fn an_unknown_file_is_reported() { + let p = imported(taskboard()); + p.write(".planning/notes.txt", "NOTE-BODY-XYZ\n"); + let run = import(&p, &["--dry-run"]); + let named: Vec<&str> = run + .stdout + .lines() + .filter(|l| l.contains("notes.txt")) + .collect(); + assert_eq!(named.len(), 1, "{}", run.stdout); + assert!(named[0].contains("unmapped"), "{}", named[0]); + assert!(!run.all().contains("NOTE-BODY-XYZ"), "{}", run.all()); +} + +#[cfg(unix)] +#[test] +fn a_symlink_out_of_the_project_is_not_read() { + let p = imported(taskboard()); + let outside = tempfile::tempdir().expect("a temp dir"); + let target = outside.path().join("01-UAT.md"); + std::fs::write(&target, "OUTSIDE-BODY\n").expect("write the outside file"); + let uat = p.root().join(".planning/phases/01-core/01-UAT.md"); + std::fs::remove_file(&uat).expect("remove the UAT file"); + std::os::unix::fs::symlink(&target, &uat).expect("link out of the project"); + let run = refused( + &p, + &[".planning/phases/01-core/01-UAT.md", "outside_project"], + ); + assert!(!run.all().contains("OUTSIDE-BODY")); +} + +#[test] +fn another_spec_root_is_refused() { + let p = imported(taskboard()); + p.settings_in("specs", json!({})); + refused(&p, &["'specs'"]); +} + +#[test] +fn vault_without_security_reports_needs_extension() { + let p = imported(vault()); + let run = import(&p, &[]); + let needs = |file: &str, section: &str| { + run.stdout + .lines() + .any(|l| l.starts_with(file) && l.contains(&format!(" {section} needs-extension "))) + }; + assert!( + needs(".planning/phases/01-core/01-SECURITY.md", "-"), + "{}", + run.stdout + ); + for plan in ["01-01", "01-02"] { + assert!( + needs( + &format!(".planning/phases/01-core/{plan}-PLAN.md:"), + "<threat_model>" + ), + "{plan}: {}", + run.stdout + ); + } + let count = run + .stdout + .lines() + .find(|l| l.starts_with("import: ")) + .expect("the count line"); + for kind in [ + "threat", + "trust_boundary", + "security_audit", + "accepted_risk", + "audit_run", + ] { + assert!(!count.contains(kind), "{kind}: {count}"); + } +} + +#[test] +fn a_duplicate_plan_is_reported() { + let p = imported(taskboard()); + let plan = p.read(".planning/phases/01-core/01-01-PLAN.md"); + p.write(".planning/phases/01-copy/01-01-PLAN.md", &plan); + let run = import(&p, &[]); + // The served files are read in path order: `01-copy` before `01-core`. + assert!( + run.stdout.contains( + "plan v1.0/01/01-01 is given twice (first at .planning/phases/01-copy/01-01-PLAN.md:1): not imported" + ), + "{}", + run.stdout + ); + assert_eq!(p.nodes_of("plan").len(), 3); +} + +#[test] +fn a_plan_past_its_cap_is_refused() { + let p = imported(taskboard()); + let mut text = "# Requirements\n\n## v1 Requirements\n\n### Core\n".to_string(); + for n in 1..=MAX_OPS + 1 { + text.push_str(&format!("- [ ] **A-{n:04}**: x\n")); + } + p.write(".planning/REQUIREMENTS.md", &text); + refused(&p, &[&format!("truncated at {MAX_OPS}")]); +} + +#[test] +fn a_stale_path_is_refused_by_the_host() { + let p = imported(taskboard()); + p.edit( + ".planning/phases/01-core/01-01-PLAN.md", + "files_modified: [package.json, src/tasks.js, test/tasks.test.js]", + "files_modified: [package.json, src/gone.js, test/tasks.test.js]", + ); + refused(&p, &["E080", "src/gone.js"]); +} + +/// The vault's `.planning/` claims threat ID T-01-02 in plans 01-01 and 01-02 (the `gsd.security/E101` duplicate its +/// twin keeps by design). An import is judged for host errors only (ADR 0392), so both claims land and `check` +/// reports the two E101. +#[test] +fn the_vault_imports_in_time() { + let p = imported(vault()).with_extension("@gsd/security", "GSD_SECURITY_WASM"); + let start = std::time::Instant::now(); + let run = p.run(&["gsd", "import"]); + let elapsed = start.elapsed(); + eprintln!("the vault with @gsd/security imported in {elapsed:?}"); + assert_eq!(run.code, 0, "{}", run.all()); + assert!(elapsed < std::time::Duration::from_secs(30), "{elapsed:?}"); + let e101 = p + .codes() + .into_iter() + .filter(|code| code == "gsd.security/E101") + .count(); + assert_eq!(e101, 2); +} diff --git a/gsd/import/tests/cli/import.rs b/gsd/import/tests/cli/import.rs new file mode 100644 index 0000000000..d868bbe167 --- /dev/null +++ b/gsd/import/tests/cli/import.rs @@ -0,0 +1,164 @@ +//! `specforge gsd import` on the taskboard fixture through the binary (ADR 0391 D2, D5, D8, D10): what it writes, +//! the host's `--dry-run` and `--format json`, the refused second import, and the same bytes from the same folder. + +use std::collections::BTreeMap; + +use crate::harness::{Project, taskboard}; +use crate::{imported, tree}; + +/// The project paths whose bytes differ between `before` and `after`, or that only one of them holds. +fn changed(before: &BTreeMap<String, Vec<u8>>, after: &BTreeMap<String, Vec<u8>>) -> Vec<String> { + let mut paths: Vec<String> = before + .keys() + .chain(after.keys()) + .filter(|path| before.get(*path) != after.get(*path)) + .cloned() + .collect(); + paths.sort(); + paths.dedup(); + paths +} + +/// A path the import may write: under `spec/gsd/`, or the host's harness ledger with the `.gitattributes` line that +/// merges it. +fn importable(path: &str) -> bool { + path.starts_with("spec/gsd/") || matches!(path, "specforge-harness" | ".gitattributes") +} + +/// `spec/gsd/**` of `project`, path by path. +fn spec_gsd(project: &Project) -> BTreeMap<String, Vec<u8>> { + tree(project) + .into_iter() + .filter(|(path, _)| path.starts_with("spec/gsd/")) + .collect() +} + +#[test] +fn import_writes_spec_gsd_and_the_report() { + let p = imported(taskboard()); + let before = tree(&p); + let run = p.run(&["gsd", "import"]); + assert_eq!(run.code, 0, "import: {}", run.all()); + let written = changed(&before, &tree(&p)); + assert!( + written.iter().any(|path| path.starts_with("spec/gsd/")), + "nothing under spec/gsd/: {written:?}" + ); + assert!( + written.iter().all(|path| importable(path)), + "a write outside spec/gsd/ and the ledger: {written:?}" + ); + let ledger = p.read("specforge-harness"); + let results: Vec<&str> = ledger + .lines() + .filter(|line| line.split(' ').nth(1) == Some("result")) + .collect(); + assert_eq!(results.len(), 3, "the three uat_test results: {ledger}"); + assert!( + ledger + .lines() + .skip(1) + .all(|line| line.contains("/01-UAT/U")), + "only the UAT results are harness values: {ledger}" + ); + assert!( + run.stdout.contains(".planning/STATE.md"), + "no entry for STATE.md: {}", + run.stdout + ); + assert!( + run.stdout.lines().any(|l| l.starts_with("import: ")), + "no count line: {}", + run.stdout + ); + let spec_files = written + .iter() + .filter(|p| p.starts_with("spec/gsd/")) + .count(); + let diffed = run + .stdout + .lines() + .filter(|l| l.starts_with("--- spec/gsd/")) + .count(); + assert_eq!( + diffed, spec_files, + "one diff per written file: {}", + run.stdout + ); + assert_eq!(p.nodes_of("requirement").len(), 8); +} + +#[test] +fn a_dry_run_writes_nothing() { + let p = imported(taskboard()); + let before = tree(&p); + let run = p.run(&["gsd", "import", "--dry-run"]); + assert_eq!(run.code, 0, "dry run: {}", run.all()); + assert!( + run.stdout.lines().any(|l| l.starts_with("import: ")), + "no report: {}", + run.stdout + ); + assert_eq!(changed(&before, &tree(&p)), Vec::<String>::new()); +} + +#[test] +fn json_carries_the_report() { + let p = imported(taskboard()); + let run = p.run(&["gsd", "import", "--format", "json"]); + assert_eq!(run.code, 0, "json: {}", run.all()); + let answer: serde_json::Value = serde_json::from_str(&run.stdout) + .unwrap_or_else(|e| panic!("the answer is JSON ({e}): {}", run.all())); + assert_eq!(answer["output"]["format"], 1, "{answer}"); + assert!( + answer["output"]["entries"] + .as_array() + .is_some_and(|entries| !entries.is_empty()), + "no entries: {answer}" + ); + let files = answer["files_written"].as_array().expect("files_written"); + assert!(!files.is_empty(), "{answer}"); + for file in files { + let path = file.as_str().expect("a path"); + assert!(importable(path), "{path} is written: {answer}"); + } +} + +#[test] +fn a_second_import_is_refused() { + let p = imported(taskboard()); + let first = p.run(&["gsd", "import"]); + assert_eq!(first.code, 0, "first import: {}", first.all()); + let before = tree(&p); + let second = p.run(&["gsd", "import"]); + assert_eq!(second.code, 1, "second import: {}", second.all()); + let all = second.all(); + let named = all + .split("such as ") + .nth(1) + .unwrap_or_else(|| panic!("no entity named: {all}")); + let words: Vec<&str> = named.split_whitespace().collect(); + assert!( + words.len() >= 4 && words[2] == "in" && words[3].starts_with("spec/gsd/"), + "kind, path and file: {all}" + ); + assert_eq!(changed(&before, &tree(&p)), Vec::<String>::new()); +} + +#[test] +fn two_imports_write_the_same_bytes() { + let (a, b) = (imported(taskboard()), imported(taskboard())); + let (run_a, run_b) = (a.run(&["gsd", "import"]), b.run(&["gsd", "import"])); + assert_eq!(run_a.code, 0, "{}", run_a.all()); + assert_eq!(run_b.code, 0, "{}", run_b.all()); + assert_eq!(run_a.stdout, run_b.stdout); + let (spec_a, spec_b) = (spec_gsd(&a), spec_gsd(&b)); + assert!(!spec_a.is_empty()); + assert_eq!( + spec_a.keys().collect::<Vec<_>>(), + spec_b.keys().collect::<Vec<_>>() + ); + for (path, bytes) in &spec_a { + assert!(spec_b[path] == *bytes, "{path} differs"); + } +} diff --git a/gsd/import/tests/cli/main.rs b/gsd/import/tests/cli/main.rs new file mode 100644 index 0000000000..364555df8b --- /dev/null +++ b/gsd/import/tests/cli/main.rs @@ -0,0 +1,57 @@ +//! Black-box tests: the `specforge` binary running `specforge gsd import` on the parity fixtures, before their twin +//! exists (ADR 0391). The harness is core's. + +#[allow( + dead_code, + unused_imports, + reason = "core's harness serves every extension; each test crate uses part of it and of its re-exports" +)] +#[path = "../../../core/tests/cli/harness.rs"] +mod harness; + +mod compare; +mod hostile; +mod import; +mod parity_import; + +use std::collections::BTreeMap; +use std::path::Path; + +use harness::Project; + +/// The judged rules the harness knows: `@gsd/core`'s (`harness::Book`). +pub static BOOKS: &[harness::Book] = &[harness::Book::CORE]; + +/// Every file of `project`, by its `/`-separated path from the root, with its bytes: what a test compares before and +/// after a run. The host's own `.specforge/` (its write lock and caches) is left out. +pub fn tree(project: &Project) -> BTreeMap<String, Vec<u8>> { + fn walk(root: &Path, dir: &Path, into: &mut BTreeMap<String, Vec<u8>>) { + for entry in std::fs::read_dir(dir).expect("a project directory") { + let path = entry.expect("a directory entry").path(); + if path == root.join(".specforge") { + continue; + } else if path.is_dir() { + walk(root, &path, into); + } else { + let relative = path.strip_prefix(root).expect("under the root"); + let name: Vec<String> = relative + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect(); + into.insert( + name.join("/"), + std::fs::read(&path).unwrap_or_else(|e| format!("unread: {e}").into_bytes()), + ); + } + } + } + let mut files = BTreeMap::new(); + walk(project.root(), project.root(), &mut files); + files +} + +/// `project` as a GSD project before its import, loading `@gsd/import` by name: the vendored builtin the binary +/// embeds (ADR 0391 D12). Every test builds its project here. +pub fn imported(project: Project) -> Project { + project.without_spec().with_builtins(&["@gsd/import"]) +} diff --git a/gsd/import/tests/cli/parity_import.rs b/gsd/import/tests/cli/parity_import.rs new file mode 100644 index 0000000000..9de0641e82 --- /dev/null +++ b/gsd/import/tests/cli/parity_import.rs @@ -0,0 +1,694 @@ +//! IMP-02, the measure of ADR 0391 D13: each of taskboard, ledger and vault, imported from its `.planning/` alone by the +//! guest as built, against its hand-written twin. The entity sets are compared by [`crate::compare`], every remaining +//! difference listed with its reason in [`DIFFERENCES`] and held both ways. Run with `GSD_IMPORT_DIFF=1` (and +//! `--no-capture`) to print every difference instead of failing. + +use serde_json::{Value, json}; + +use crate::compare::Expect::{Absent, Is}; +use crate::compare::{self, Excluded, Expect, ID_PAIRS}; +use crate::harness::{Project, judged, ledger, taskboard, unjudged, vault}; +use crate::imported; + +/// The profiles every pin holds under: `PROFILES` of `gsd/core/tests/cli/interface_gate.rs`. +const PROFILES: [&str; 3] = ["gsd-compat", "gsd-strict", "gsd-plus"]; + +/// What the imported vault carries under every profile, sorted: the twin's `VAULT_CARRIES` +/// (`gsd/core/tests/cli/rules_silent.rs`) with two `gsd.security/W302` instead of five, because the twin's closed +/// `01-01/T-01-02` and both `T-01-SC` threats have no status in `.planning/` and the import invents none (ADR 0391 +/// D13). The two `gsd.security/E101` (threat `T-01-02` claimed in plans 01-01 and 01-02) land, an import being judged +/// for host errors only (ADR 0392). +pub const IMPORTED_VAULT_CARRIES: [&str; 7] = [ + "W019", + "gsd.security/E101", + "gsd.security/E101", + "gsd.security/W302", + "gsd.security/W302", + "gsd.security/W303", + "gsd/W103", +]; + +/// The security workflow's verdicts the imported vault owes, `(code, entity)`, which `@gsd/security`'s book judges and +/// core's harness `BOOKS` does not hold: W302 on each threat `01-SECURITY.md` closes (`T-01-01` of plan 01-01 and +/// `T-01-03` of plan 01-02), W303 on the audit. +pub const VAULT_SECURITY_OWED: [(&str, &str); 3] = [ + ("gsd.security/W302", "v1.0/01/01-01/T-01-01"), + ("gsd.security/W302", "v1.0/01/01-02/T-01-03"), + ("gsd.security/W303", "v1.0/01/01-SECURITY"), +]; + +/// `(fixture, kind, id, field, import, reason)`: each difference of an imported fixture from its twin that is not a +/// guest defect, what the import's value is (folded as [`compare::differences`] folds it), and where it comes from. +/// `field` is a field name, `title`, [`compare::IMPORT_ONLY`] or [`compare::TWIN_ONLY`]. A listed field is checked on +/// both sides: the twin's value differs, and the import's is the one the reason describes. +pub const DIFFERENCES: &[(&str, &str, &str, &str, Expect, &str)] = &[ + // taskboard + ( + "taskboard", + "deliverable", + "v1.0/01/01-01/01-01-SUMMARY/D1", + "title", + Is(r#""a task is added with the next integer id and keeps its title""#), + "twin shortens: its title cuts the coverage description `01-01-SUMMARY.md:27` (spec/plans.spec:264), which the import keeps whole", + ), + ( + "taskboard", + "deliverable", + "v1.0/01/01-02/01-02-SUMMARY/D1", + "title", + Is(r#""a task is completed by its id, and an unknown id is refused by name""#), + "twin shortens: its title cuts the coverage description `01-02-SUMMARY.md:30`, which the import keeps whole", + ), + ( + "taskboard", + "discussion", + "v1.0/02/02-DISCUSSION-LOG", + "entries", + Is( + r#"[{"area":"storage format","chosen":"one JSON file","mode":"interactive","notes":"the project ships as one script with no dependencies, so SQLite is out","options":["one JSON file","sQLite"]},{"area":"titles","chosen":"stored as typed","mode":"interactive","notes":"a title is the user's own words","options":["stored as typed","trimmed"]}]"#, + ), + "twin gap (RESEARCH D9): the twin drops each entry's `**Notes:**` line (`02-DISCUSSION-LOG.md:20,32`), which the import maps to `notes`", + ), + ( + "taskboard", + "finding", + "v1.0/02/02-RESEARCH/F1", + "sources", + Absent, + "no source (RESEARCH D7): the recommendation line `02-RESEARCH.md:85` names no source; the twin invents `[SRC1]`", + ), + ( + "taskboard", + "finding", + "v1.0/02/02-RESEARCH/F1", + "topic", + Absent, + "no source (RESEARCH D7): the recommendation line `02-RESEARCH.md:85` names no topic; the twin invents `stack`", + ), + ( + "taskboard", + "plan", + "v1.0/01/01-01", + "context_refs", + Absent, + "twin's own paths (RESEARCH D5): the twin names its spec files; the source's `.planning/*` refs name files the import does not write", + ), + ( + "taskboard", + "plan", + "v1.0/01/01-02", + "context_refs", + Absent, + "twin's own paths (RESEARCH D5): the twin names its spec files; the source's `.planning/*` refs name files the import does not write", + ), + ( + "taskboard", + "plan", + "v1.0/02/02-01", + "context_refs", + Absent, + "twin's own paths (RESEARCH D5): the twin names its spec files; the source's `.planning/*` refs name files the import does not write", + ), + ( + "taskboard", + "project", + "taskboard", + "context", + Is( + r#""built to prove the GSD model in SpecForge. Small enough that one person reads all of it""#, + ), + "twin shortens (RESEARCH D2): the twin keeps the first sentence of `PROJECT.md:31`, the import the whole section", + ), + ( + "taskboard", + "project", + "taskboard", + "out_of_scope", + Is( + r#"[{"item":"sharing a board by link","why":"needs accounts, which v1 does not have"}]"#, + ), + "twin gap (RESEARCH D3): `PROJECT.md:25-27` is mapped to `out_of_scope`; the twin carries it as requirement SHARE-01 instead", + ), + ( + "taskboard", + "project", + "taskboard", + "what", + Is( + r#""a small board for tracking tasks from the command line. A user adds a task with a title, marks it complete and lists what is left. It is a Node 20 script with no dependencies, built to prove the GSD model in SpecForge""#, + ), + "twin shortens (RESEARCH D1): the twin keeps the first sentence of `PROJECT.md:5-6`, the import the whole section", + ), + ( + "taskboard", + "requirement", + "SHARE-01", + "text", + Is(r#""share a board by link""#), + "twin invents (RESEARCH D4): an out-of-scope row has no requirement text; the import takes the Feature cell `REQUIREMENTS.md:39`", + ), + ( + "taskboard", + "research", + "v1.0/02/02-RESEARCH", + "summary", + Is( + r#""a board of a few hundred tasks fits in one JSON file. Node's own fs module reads and writes it, and a write to a temporary name followed by a rename keeps the file whole if the process dies mid-write""#, + ), + "twin paraphrases (RESEARCH D8): the import keeps the paragraph `02-RESEARCH.md:34` as written", + ), + ( + "taskboard", + "summary", + "v1.0/01/01-02/01-02-SUMMARY", + "requires", + Is(r#"[{"phase":"01","provides":"createBoard and addTask"}]"#), + "twin gap (RESEARCH D6): the block-form `requires` of `01-02-SUMMARY.md:7-9` is mapped; the twin has none", + ), + ( + "taskboard", + "uat_session", + "v1.0/01/01-UAT", + "source", + Is(r#"["01-01/01-01-SUMMARY","01-02/01-02-SUMMARY"]"#), + "reference spelling: the import writes each summary scope-relative (`01-01/01-01-SUMMARY`), the twin the full path (spec/verify.spec:3); both resolve to the same entity", + ), + // ledger + ( + "ledger", + "plan", + "v1.0/01/01-01", + "context_refs", + Absent, + "twin's own paths (RESEARCH D5): the twin names its spec files; the source's `.planning/*` refs name files the import does not write", + ), + ( + "ledger", + "plan", + "v1.0/01/01-02", + "context_refs", + Absent, + "twin's own paths (RESEARCH D5): the twin names its spec files; the source's `.planning/*` refs name files the import does not write", + ), + ( + "ledger", + "plan", + "v1.0/02/02-01", + "context_refs", + Absent, + "twin's own paths (RESEARCH D5): the twin names its spec files; the source's `.planning/*` refs name files the import does not write", + ), + ( + "ledger", + "project", + "ledger", + "out_of_scope", + Is(r#"[{"item":"currencies other than one","why":"a ledger is one currency"}]"#), + "twin gap (RESEARCH D3): `PROJECT.md:25-27` is mapped to `out_of_scope`; the twin carries it as requirement CURR-01 instead", + ), + ( + "ledger", + "project", + "ledger", + "what", + Is( + r#""a ledger of money on the command line: a user adds an entry in integer cents with a memo, and asks for the total. It is a Rust binary with no dependencies, built to give the GSD A/B a project whose CI is red""#, + ), + "twin shortens (RESEARCH D1): the twin keeps the first sentence of `PROJECT.md:5-6`, the import the whole section", + ), + ( + "ledger", + "requirement", + "CURR-01", + "text", + Is(r#""several currencies""#), + "twin invents (RESEARCH D4): an out-of-scope row has no requirement text; the import takes the Feature cell `REQUIREMENTS.md:37`", + ), + ( + "ledger", + "summary", + "261105-tcl/261105-tcl-SUMMARY", + "subsystem", + Is(r#""quick""#), + "no source (RESEARCH D14): the quick summary has no `subsystem`; the import fills `quick` and reports it, the twin invents `entries`", + ), + ( + "ledger", + "task", + "v1.0/01/01-01/T1", + "action", + Is( + r#""create the ledger package (no dependencies) and src/lib.rs with Entry { cents: i64, memo: String } and add(entries, cents, memo), which refuses a memo holding a tab or a line break; line and parse write and read the store's <cents>\\t<memo> lines""#, + ), + "twin escape: the twin writes `\\t` inside a .spec string, which the parser reads as a tab (spec/plans.spec:18); the import keeps the two characters of `01-01-PLAN.md:42`", + ), + // vault + ( + "vault", + "accepted_risk", + "v1.0/01/01-SECURITY/AR1", + "threat", + Is(r#""01-02/T-01-03""#), + "reference spelling: the import writes the threat scope-relative (`01-02/T-01-03`), the twin the full path (spec/security.spec:7); both resolve to the same entity", + ), + ( + "vault", + "audit_run", + "v1.0/01/01-SECURITY/AU1", + "at", + Is(r#""2026-10-29T00:00:00Z""#), + "no source (RESEARCH D12): `01-SECURITY.md:52` gives a date only; the import fills `T00:00:00Z` and reports it, the twin invents 10:00", + ), + ( + "vault", + "audit_run", + "v1.0/01/01-SECURITY/AU1", + "run_by", + Absent, + "no source (RESEARCH D12): the audit trail names no runner; the twin invents `gsd-security-auditor` (spec/security.spec:19)", + ), + ( + "vault", + "plan", + "v1.0/01/01-01", + "context_refs", + Absent, + "twin's own paths (RESEARCH D5): the twin names its spec files; the source's `.planning/*` refs name files the import does not write", + ), + ( + "vault", + "plan", + "v1.0/01/01-02", + "context_refs", + Absent, + "twin's own paths (RESEARCH D5): the twin names its spec files; the source's `.planning/*` refs name files the import does not write", + ), + ( + "vault", + "plan", + "v1.0/02/02-01", + "context_refs", + Absent, + "twin's own paths (RESEARCH D5): the twin names its spec files; the source's `.planning/*` refs name files the import does not write", + ), + ( + "vault", + "project", + "vault", + "context", + Is( + r#""built to prove the GSD security capability in SpecForge. Small enough that one person reads all of it""#, + ), + "twin shortens (RESEARCH D2): the twin keeps the first sentence of `PROJECT.md:21`, the import the whole section", + ), + ( + "vault", + "project", + "vault", + "what", + Is( + r#""a small encrypted store for secrets, driven from the command line. A user sets a named secret, reads it back and lists the names. It is a Node 20 script with no dependencies, built to prove the GSD security model in SpecForge""#, + ), + "twin shortens (RESEARCH D1): the twin keeps the first sentence of `PROJECT.md:5-6`, the import the whole section", + ), + ( + "vault", + "security_audit", + "v1.0/01/01-SECURITY", + "asvs_level", + Is(r#"1"#), + "twin gap (RESEARCH D12): the frontmatter `asvs_level` of `01-SECURITY.md:7` is mapped (harness, as a peer); the twin has none", + ), + ( + "vault", + "security_audit", + "v1.0/01/01-SECURITY", + "created", + Is(r#""2026-10-30T00:00:00Z""#), + "twin gap (RESEARCH D12): the frontmatter `created` of `01-SECURITY.md:8` is mapped, filled to midnight; the twin has none", + ), + ( + "vault", + "summary", + "v1.0/01/01-02/01-02-SUMMARY", + "threat_flags", + Is( + r#"["threat_flag: information_disclosure | src/cli.js | the secret is an argv entry, visible in ps and in shell history"]"#, + ), + "twin gap (RESEARCH D15): the `## Threat Flags` table of `01-02-SUMMARY.md:45-49` is mapped; the twin has none", + ), + ( + "vault", + "task", + "v1.0/01/01-01/T1", + "action", + Is( + r#""create package.json (ES modules, npm test runs node --test) and src/vault.js: seal(vault, key) encrypts the secrets with AES-256-GCM under a fresh 12-byte IV and returns IV, auth tag and data; open(blob, key) reverses it and throws when the tag does not verify""#, + ), + "twin shortens (RESEARCH D10): the import keeps `01-01-PLAN.md:41` verbatim", + ), + ( + "vault", + "task", + "v1.0/01/01-02/T1", + "verify_text", + Is( + r#""vAULT_KEY=$(node -e \"console.log('07'.repeat(32))\") node src/cli.js set db hunter2 && VAULT_KEY=$(node -e \"console.log('07'.repeat(32))\") node src/cli.js get db""#, + ), + "twin shortens (RESEARCH D10): the import keeps the `<verify>` of `01-02-PLAN.md:42` verbatim", + ), + ( + "vault", + "threat", + "v1.0/01/01-01/T-01-01", + "evidence", + Absent, + "no source (RESEARCH D11): `01-SECURITY.md` records no evidence; the twin holds what an audit would write", + ), + ( + "vault", + "threat", + "v1.0/01/01-01/T-01-01", + "files", + Absent, + "authored after import (RESEARCH D11): `files` is SpecForge-only, with no `.planning/` counterpart (vault README)", + ), + ( + "vault", + "threat", + "v1.0/01/01-01/T-01-02", + "evidence", + Absent, + "no source (RESEARCH D11): `01-SECURITY.md` records no evidence; the twin holds what an audit would write", + ), + ( + "vault", + "threat", + "v1.0/01/01-01/T-01-02", + "files", + Absent, + "authored after import (RESEARCH D11): `files` is SpecForge-only, with no `.planning/` counterpart (vault README)", + ), + ( + "vault", + "threat", + "v1.0/01/01-01/T-01-02", + "status", + Absent, + "no source (RESEARCH D11, D13): `01-SECURITY.md` has no row for plan 01-01's T-01-02 (its one T-01-02 row, line 31, names plan 01-02's component); the import invents no status", + ), + ( + "vault", + "threat", + "v1.0/01/01-01/T-01-SC", + "evidence", + Absent, + "no source (RESEARCH D11): `01-SECURITY.md` records no evidence; the twin holds what an audit would write", + ), + ( + "vault", + "threat", + "v1.0/01/01-01/T-01-SC", + "files", + Absent, + "authored after import (RESEARCH D11): `files` is SpecForge-only, with no `.planning/` counterpart (vault README)", + ), + ( + "vault", + "threat", + "v1.0/01/01-01/T-01-SC", + "status", + Absent, + "no source (RESEARCH D11, D13): `01-SECURITY.md` has no T-01-SC row; the import invents no status", + ), + ( + "vault", + "threat", + "v1.0/01/01-02/T-01-03", + "files", + Absent, + "authored after import (RESEARCH D11): `files` is SpecForge-only, with no `.planning/` counterpart (vault README)", + ), + ( + "vault", + "threat", + "v1.0/01/01-02/T-01-SC", + "evidence", + Absent, + "no source (RESEARCH D11): `01-SECURITY.md` records no evidence; the twin holds what an audit would write", + ), + ( + "vault", + "threat", + "v1.0/01/01-02/T-01-SC", + "files", + Absent, + "authored after import (RESEARCH D11): `files` is SpecForge-only, with no `.planning/` counterpart (vault README)", + ), + ( + "vault", + "threat", + "v1.0/01/01-02/T-01-SC", + "status", + Absent, + "no source (RESEARCH D11, D13): `01-SECURITY.md` has no T-01-SC row; the import invents no status", + ), + ( + "vault", + "trust_boundary", + "v1.0/01/01-02/TB1", + "data_crossing", + Is(r#""secrets and the key, in the clear""#), + "twin gap (RESEARCH D13): the Data Crossing cell of `01-SECURITY.md:22` is mapped; the twin has none", + ), +]; + +/// A fixture's name, its twin, and the same fixture before its import. +type Fixture = (&'static str, fn() -> Project, fn() -> Project); + +/// The vault twin as its parity suite loads it, with `@gsd/security`. +fn secured_vault() -> Project { + vault().with_extension("@gsd/security", "GSD_SECURITY_WASM") +} + +fn imported_taskboard() -> Project { + imported(taskboard()) +} + +fn imported_ledger() -> Project { + imported(ledger()) +} + +fn imported_vault() -> Project { + imported(vault()).with_extension("@gsd/security", "GSD_SECURITY_WASM") +} + +pub const FIXTURES: [Fixture; 3] = [ + ("taskboard", taskboard, imported_taskboard), + ("ledger", ledger, imported_ledger), + ("vault", secured_vault, imported_vault), +]; + +/// `project` once `specforge gsd import` has run on it, which must succeed. +pub fn run_import(project: Project) -> Project { + let run = project.run(&["gsd", "import"]); + assert_eq!(run.code, 0, "{}", run.all()); + project +} + +/// Every node of `project`'s graph, as `specforge export --format graph` writes them. +fn graph(project: &Project) -> Vec<Value> { + let run = project.run(&["export", "--format", "graph"]); + let graph: Value = serde_json::from_str(&run.stdout) + .unwrap_or_else(|e| panic!("export prints JSON ({e}): {}", run.all())); + graph["nodes"].as_array().expect("nodes").clone() +} + +#[test] +fn imported_entities_equal_the_twins() { + let printing = std::env::var_os("GSD_IMPORT_DIFF").is_some(); + let excluded = Excluded::gsd(); + for (name, twin, before) in FIXTURES { + let twin = graph(&twin()); + let import = graph(&run_import(before())); + let pairs: Vec<(&str, &str, &str)> = ID_PAIRS + .iter() + .filter(|(fixture, ..)| *fixture == name) + .map(|(_, kind, from, to)| (*kind, *from, *to)) + .collect(); + let listed: Vec<(&str, &str, &str, Expect)> = DIFFERENCES + .iter() + .filter(|(fixture, ..)| *fixture == name) + .map(|(_, kind, id, field, import, _)| (*kind, *id, *field, *import)) + .collect(); + if printing { + for d in compare::differences(&import, &twin, &pairs, &excluded) { + eprintln!( + "{name}\t{}\t{}\t{}\ttwin={}\timport={}", + d.kind, d.id, d.field, d.twin, d.import + ); + } + continue; + } + let compared = compare::compare(&import, &twin, &pairs, &listed, &excluded); + assert_eq!(compared, compare::Compared::default(), "{name}"); + } +} + +/// The classes a difference's reason opens with (13-RESEARCH "Per-Fixture Mapping"). +const CLASSES: [&str; 9] = [ + "twin shortens", + "twin gap", + "twin invents", + "twin paraphrases", + "twin escape", + "twin's own paths", + "no source", + "authored after import", + "reference spelling", +]; + +/// The lines of the fixture file named `name` (`PROJECT.md`, `spec/plans.spec`) under `root`, if one is there. +fn fixture_lines(root: &std::path::Path, name: &str) -> Option<Vec<String>> { + let base = name.rsplit('/').next().unwrap_or(name); + for entry in std::fs::read_dir(root).ok()? { + let path = entry.ok()?.path(); + let found = if path.is_dir() { + fixture_lines(&path, name) + } else if path.file_name().is_some_and(|f| f == base) && path.ends_with(name) { + std::fs::read_to_string(&path) + .ok() + .map(|t| t.lines().map(str::to_string).collect()) + } else { + None + }; + if found.is_some() { + return found; + } + } + None +} + +/// Each reason names its class and where the difference comes from: a 13-RESEARCH D-number, or a `file:line` that +/// the fixture holds (its `.planning/` source or its twin's spec) at a line that is not blank. +#[test] +fn every_difference_names_its_class_and_a_live_citation() { + let cite = regex::Regex::new(r"([\w./-]+\.(?:md|spec)):(\d+)").expect("a pattern"); + let research = regex::Regex::new(r"RESEARCH D\d+").expect("a pattern"); + let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../parity/fixtures"); + for (fixture, kind, id, field, _, reason) in DIFFERENCES { + let at = format!("{fixture} {kind} {id} {field}"); + assert!( + CLASSES.iter().any(|c| reason.starts_with(c)), + "{at}: `{reason}` names none of {CLASSES:?}" + ); + let cited: Vec<(String, usize)> = cite + .captures_iter(reason) + .map(|c| (c[1].to_string(), c[2].parse().unwrap_or(0))) + .collect(); + assert!( + !cited.is_empty() || research.is_match(reason), + "{at}: `{reason}` cites nothing" + ); + for (file, line) in cited { + let lines = fixture_lines(&fixtures.join(fixture), &file) + .unwrap_or_else(|| panic!("{at}: {fixture} holds no {file}")); + assert!( + line >= 1 && lines.get(line - 1).is_some_and(|l| !l.trim().is_empty()), + "{at}: {file}:{line} is past the file or blank" + ); + } + } +} + +/// The codes a fixture's import is pinned to under every profile: none for taskboard and ledger. +fn pinned(fixture: &str) -> &'static [&'static str] { + match fixture { + "vault" => &IMPORTED_VAULT_CARRIES, + _ => &[], + } +} + +#[test] +fn imported_codes_equal_the_pins() { + for (name, _, before) in FIXTURES { + let p = run_import(before()); + for profile in PROFILES { + p.settings(json!({ "profile": profile })); + let mut codes = p.codes(); + codes.sort(); + assert_eq!(codes, pinned(name), "{name} {profile}"); + } + } +} + +/// `(code, entity)` of every verdict `specforge gsd import --format json` on `project` reports owed, sorted. +fn owed_by_import(project: &Project) -> Vec<(String, String)> { + let run = project.run(&["gsd", "import", "--format", "json"]); + assert_eq!(run.code, 0, "{}", run.all()); + let answer: Value = serde_json::from_str(&run.stdout) + .unwrap_or_else(|e| panic!("the answer is JSON ({e}): {}", run.all())); + let mut owed: Vec<(String, String)> = answer["output"]["owed"] + .as_array() + .expect("the owed list") + .iter() + .map(|o| { + let text = |key: &str| o[key].as_str().expect("a string").to_string(); + (text("code"), text("entity")) + }) + .collect(); + owed.sort(); + owed +} + +/// `check` on an imported fixture exits 1 (ADR 0391 D5, D13; ADR 0392): the judged rules' `no verdict` on exactly the +/// entities core's books say owe one, nothing else but the fixture's pin, and the import's own owed list names the same +/// pairs, with the vault's security verdicts, which core's books do not hold. +#[test] +fn check_owes_exactly_the_judged_codes() { + for (name, _, before) in FIXTURES { + let p = before(); + let owed = owed_by_import(&p); + let run = p.run(&["check"]); + assert_eq!(run.code, 1, "{name}: {}", run.all()); + let report = p.report_all(); + let expected = p.expected_judged(&[]); + assert_eq!(judged(&report), expected, "{name}: {report:#?}"); + assert!( + report + .iter() + .filter(|(code, _)| crate::harness::is_judged(code)) + .all(|(_, message)| message.ends_with(": no verdict")), + "{name}: {report:#?}" + ); + let rest = unjudged(&report); + let mut codes: Vec<&str> = rest.iter().map(|(code, _)| code.as_str()).collect(); + codes.sort(); + assert_eq!(codes, pinned(name), "{name}: {report:#?}"); + let mut owes = expected; + if name == "vault" { + let security: Vec<(String, String)> = rest + .iter() + .filter(|(code, _)| { + matches!(code.as_str(), "gsd.security/W302" | "gsd.security/W303") + }) + .map(|(code, message)| { + let id = message.split('\'').nth(1).unwrap_or_else(|| { + panic!("a security verdict names its entity: {message}") + }); + (code.clone(), id.to_string()) + }) + .collect(); + let pinned: Vec<(String, String)> = VAULT_SECURITY_OWED + .iter() + .map(|(code, entity)| (code.to_string(), entity.to_string())) + .collect(); + let mut found = security; + found.sort(); + assert_eq!(found, pinned, "{report:#?}"); + owes.extend(pinned); + owes.sort(); + } + assert_eq!(owed, owes, "{name}: the import's owed list"); + } +} diff --git a/gsd/import/tests/common/mod.rs b/gsd/import/tests/common/mod.rs new file mode 100644 index 0000000000..02e3b554ee --- /dev/null +++ b/gsd/import/tests/common/mod.rs @@ -0,0 +1,265 @@ +//! Calling `import` in process, as the host would, on a `.planning/` folder on disk. +#![allow(dead_code, reason = "each test crate uses part of it")] + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use specforge_extension_sdk::PlanOp; +use specforge_extension_sdk::prelude::*; +use specforge_extension_sdk::testing::{CommandFeed, MockHost, call_every_command_with}; + +/// `kind.field` (or `kind.block.member`) → its writer (`""` for the author), from one `describe entities` answer. +fn writers(entities: &Value, into: &mut BTreeMap<String, String>) { + let writer = |f: &Value| f["writer"].as_str().unwrap_or_default().to_string(); + for kind in entities["items"].as_array().expect("items") { + let name = kind["name"].as_str().expect("a kind name"); + for field in kind["fields"].as_array().expect("fields") { + let field_name = field["name"].as_str().expect("a field name"); + into.insert(format!("{name}.{field_name}"), writer(field)); + for member in field["members"].as_array().into_iter().flatten() { + let member_name = member["name"].as_str().expect("a member name"); + into.insert(format!("{name}.{field_name}.{member_name}"), writer(member)); + } + } + } +} + +/// The writers of every field of `@gsd/core` (its kinds golden) and of `@gsd/security` (its declaration): the import's +/// peers, whose harness fields it may write (ADR 0391 D7). +pub fn declared() -> BTreeMap<String, String> { + let golden: Value = serde_json::from_str( + &std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../core/tests/golden/kinds.json" + )) + .expect("the kinds golden"), + ) + .expect("the golden is JSON"); + let security: Value = serde_json::from_str( + &MockHost::new(gsd_security::build()) + .describe_json("entities") + .expect("@gsd/security describes its entities"), + ) + .expect("describe answers JSON"); + let mut out = BTreeMap::new(); + writers(&golden["entities"], &mut out); + writers(&security, &mut out); + out +} + +/// A parity fixture's directory. +pub fn fixture(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../parity/fixtures") + .join(name) +} + +/// One served file: `path` with `text`, as a glob with text serves it. +pub fn fact(path: &str, text: &str) -> Value { + json!({ + "path": path, + "exists": true, + "bytes": text.len(), + "lines": text.split('\n').count(), + "text": text, + }) +} + +/// Every file under `dir/.planning`, at any depth, as the facts of the `planning` read, sorted by path. +pub fn planning_facts(dir: &Path) -> Vec<Value> { + let root = dir.join(".planning"); + let mut files = Vec::new(); + let mut dirs = vec![root.clone()]; + while let Some(dir) = dirs.pop() { + let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())); + for path in entries.flatten().map(|entry| entry.path()) { + if path.is_dir() { + dirs.push(path); + } else { + files.push(path); + } + } + } + files.sort(); + files + .iter() + .map(|path| { + let rel = path + .strip_prefix(&root) + .expect("under .planning") + .to_string_lossy() + .replace('\\', "/"); + let text = + std::fs::read_to_string(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + fact(&format!(".planning/{rel}"), &text) + }) + .collect() +} + +/// The feed of `import`: `planning` (facts, and whether the read stopped early) and the manifest's text. +pub fn feed(planning: Vec<Value>, truncated: bool, manifest: Option<&str>) -> CommandFeed { + let manifest: Vec<Value> = manifest + .map(|text| fact("specforge.json", text)) + .into_iter() + .collect(); + CommandFeed { + files: serde_json::from_value(json!({ + "planning": { "facts": planning, "truncated": truncated }, + "manifest": { "facts": manifest }, + })) + .expect("the facts are FileFacts"), + ..Default::default() + } +} + +/// A manifest naming the spec root `spec` and the extensions `loaded`. +pub fn manifest(loaded: &[&str]) -> String { + json!({ "name": "p", "version": "1.0.0", "spec_root": "spec", "extensions": loaded }) + .to_string() +} + +/// `import` over `graph`, fed `feed`. +pub fn import(graph: &CommandGraph, feed: &CommandFeed) -> CommandOutput { + let outputs = + call_every_command_with(&gsd_import::build(), graph, "2026-11-24", feed, |_, _| { + String::new() + }); + let (_, out) = outputs + .into_iter() + .find(|(id, _)| id == "import") + .expect("@gsd/import declares import"); + out +} + +/// The fixture `name`'s `.planning/` imported into an empty graph. +pub fn import_fixture(name: &str) -> CommandOutput { + let dir = fixture(name); + let manifest = + std::fs::read_to_string(dir.join("specforge.json")).expect("the fixture's manifest"); + import( + &CommandGraph::default(), + &feed(planning_facts(&dir), false, Some(&manifest)), + ) +} + +/// The JSON the command printed. +pub fn payload(out: &CommandOutput) -> Value { + serde_json::from_str(&out.stdout).unwrap_or_else(|e| panic!("{e}: {}", out.stdout)) +} + +/// One create of the plan, with its graph path. +#[derive(Debug, Clone)] +pub struct Create { + pub kind: String, + pub path: String, + pub title: String, + pub file: String, + pub fields: Value, +} + +/// Each create of `out`'s plan; its path is its scope reference (`summary`, `plan`, `research`, `session`, `test`, +/// `audit` or `phase`) and its id. +pub fn creates(out: &CommandOutput) -> Vec<Create> { + let plan = out.plan.as_ref().expect("import answers a plan"); + plan.ops + .iter() + .map(|op| match op { + PlanOp::Create { + kind, + id, + title, + file, + fields, + .. + } => { + let fields = json!(fields); + // A research's `summary` is its text, not a scope. + let scope = [ + "summary", "plan", "research", "session", "test", "audit", "phase", + ] + .iter() + .filter(|k| !(kind == "research" && **k == "summary")) + .find_map(|k| fields[*k].as_str()); + Create { + kind: kind.clone(), + path: scope.map_or_else(|| id.clone(), |s| format!("{s}/{id}")), + title: title.clone(), + file: file.clone(), + fields, + } + } + other => panic!("import answers creates only, not {other:?}"), + }) + .collect() +} + +/// The create `kind path`. +pub fn find(all: &[Create], kind: &str, path: &str) -> Create { + all.iter() + .find(|c| c.kind == kind && c.path == path) + .cloned() + .unwrap_or_else(|| panic!("{kind} {path} is created")) +} + +/// The paths of the creates of `kind`, in plan order. +pub fn paths<'c>(all: &'c [Create], kind: &str) -> Vec<&'c str> { + all.iter() + .filter(|c| c.kind == kind) + .map(|c| c.path.as_str()) + .collect() +} + +/// `(line, section, outcome, reason)` of each entry about `file`. +pub fn entries(out: &CommandOutput, file: &str) -> Vec<(u64, String, String, String)> { + payload(out)["entries"] + .as_array() + .expect("entries") + .iter() + .filter(|e| e["file"] == file) + .map(|e| { + let s = |k: &str| e[k].as_str().unwrap_or_default().to_string(); + ( + e["line"].as_u64().unwrap_or(0), + s("section"), + s("outcome"), + s("reason"), + ) + }) + .collect() +} + +/// Whether `entries` holds one at `line` with `outcome` whose reason holds `says`. +pub fn has( + entries: &[(u64, String, String, String)], + line: u64, + outcome: &str, + says: &str, +) -> bool { + entries + .iter() + .any(|(l, _, o, r)| *l == line && o == outcome && r.contains(says)) +} + +/// The manifest of the fixture `name`, listing `@gsd/security` when `security`, as the harness writes it (a fixture's +/// committed manifest lists no extension). +pub fn fixture_manifest(name: &str, security: bool) -> String { + let text = std::fs::read_to_string(fixture(name).join("specforge.json")).expect("a manifest"); + let mut json: Value = serde_json::from_str(&text).expect("JSON"); + if security { + json["extensions"] = json!(["@gsd/core", "@gsd/security=../../security/target/x.wasm"]); + } + json.to_string() +} + +/// The fixture `name` imported, with or without `@gsd/security` in its manifest. +pub fn import_with(name: &str, security: bool) -> CommandOutput { + import( + &CommandGraph::default(), + &feed( + planning_facts(&fixture(name)), + false, + Some(&fixture_manifest(name, security)), + ), + ) +} diff --git a/gsd/import/tests/discuss.rs b/gsd/import/tests/discuss.rs new file mode 100644 index 0000000000..4a756f5185 --- /dev/null +++ b/gsd/import/tests/discuss.rs @@ -0,0 +1,521 @@ +//! A phase's CONTEXT.md, DISCUSSION-LOG.md and RESEARCH.md through the command in process, against the taskboard +//! twin's `discuss.spec`, and hostile cases. +//! +//! Known differences from the twin (13-RESEARCH "Per-Fixture Mapping"): titles are the documents' own (the twin's are +//! hand-made, and titles compare nothing); `discussion.entries[*].notes` is carried, which the twin lacks (D9); the +//! research `summary` is the document's text where the twin paraphrases it (D8); a finding has no `topic` or `sources` +//! (D7); values keep their backticks and trailing periods (the comparator folds them). + +mod common; + +use gsd_import::limits::MAX_OPS; +use serde_json::json; +use specforge_extension_sdk::prelude::*; + +use common::{ + creates, entries, fact, feed, find, has, import, import_fixture, manifest, paths, payload, +}; + +const CONTEXT: &str = ".planning/phases/02-persistence/02-CONTEXT.md"; +const LOG: &str = ".planning/phases/02-persistence/02-DISCUSSION-LOG.md"; +const RESEARCH: &str = ".planning/phases/02-persistence/02-RESEARCH.md"; + +/// The import of a roadmap of phases 1 and 2 and the served `files`. +fn run(files: Vec<(&str, &str)>) -> CommandOutput { + let road = "# Roadmap: X\n\n### Phase 1: One\n**Goal**: g\n**Success Criteria**:\n 1. c\n\n### Phase 2: Two\n**Goal**: h\n**Success Criteria**:\n 1. d\n"; + let mut facts = vec![fact(".planning/ROADMAP.md", road)]; + facts.extend(files.into_iter().map(|(path, text)| fact(path, text))); + import( + &CommandGraph::default(), + &feed(facts, false, Some(&manifest(&["@gsd/core"]))), + ) +} + +#[test] +fn taskboard_context_takes_the_twins_values() { + let out = import_fixture("taskboard"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + let context = find(&all, "context", "v1.0/02/02-CONTEXT"); + assert_eq!( + (context.title.as_str(), context.file.as_str()), + ("Phase 2: Persistence - Context", "spec/gsd/phases/02.spec") + ); + assert_eq!( + context.fields, + json!({ + "phase": "v1.0/02", + "gathered": "2026-03-04", + "boundary": "Tasks are saved to disk after every change and read back when the board starts. Listing and filtering are phase 3.", + "discretion": ["The indent of the JSON file"], + "specifics": "No specific requirements — open to standard approaches", + "canonical_refs": [ + {"topic": "No external specs — requirements are fully captured in decisions above", "paths": []} + ], + "reusable_assets": ["`src/tasks.js`: the task list and its operations"], + "patterns": ["ES modules, no build step"], + "integration_points": ["`src/cli.js` loads the board before each command and saves it after"], + }) + ); + assert_eq!( + paths(&all, "decision"), + [ + "D-01", + "D-02", + "v1.0/02/D-01", + "v1.0/02/D-02", + "v1.0/02/D-03" + ] + ); + for (id, area, text) in [ + ( + "D-01", + "Storage format", + "Tasks are kept in a single JSON file, `tasks.json`, in the working directory", + ), + ( + "D-02", + "Storage format", + "The file is written to a temporary name and renamed over `tasks.json`, so a crash never leaves half a file", + ), + ( + "D-03", + "Titles", + "A title is stored exactly as typed, with no trimming", + ), + ] { + let decision = find(&all, "decision", &format!("v1.0/02/{id}")); + assert_eq!( + decision.fields, + json!({"phase": "v1.0/02", "area": area, "text": text, "origin": "context"}), + "{id}" + ); + } + let idea = find(&all, "deferred_idea", "v1.0/02/DI1"); + assert_eq!( + idea.fields, + json!({ + "phase": "v1.0/02", + "origin": "discussion", + "text": "Keeping the file in step across two machines", + "why": "v2, SYNC-01", + }) + ); + let reported = entries(&out, CONTEXT); + for (line, outcome, says) in [ + (4, "computed", "context.status is computed"), + (17, "filled", "a decision of a phase's CONTEXT.md"), + (38, "ignored", "the template's instruction"), + (61, "filled", "an idea deferred"), + (67, "unmapped", "prose"), + (68, "unmapped", "prose"), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {says}: {reported:#?}" + ); + } + assert!( + !reported + .iter() + .any(|(l, _, _, r)| *l == 0 || r == "unknown file"), + "the file is read, not reported whole: {reported:#?}" + ); +} + +#[test] +fn taskboard_discussion_takes_the_twins_entries() { + let out = import_fixture("taskboard"); + let all = creates(&out); + let discussion = find(&all, "discussion", "v1.0/02/02-DISCUSSION-LOG"); + assert_eq!(discussion.title, "Phase 2: Persistence - Discussion Log"); + // The twin's entries, and the notes it lacks (D9). + assert_eq!( + discussion.fields, + json!({ + "phase": "v1.0/02", + "entries": [ + { + "area": "Storage format", + "options": ["One JSON file", "SQLite"], + "chosen": "One JSON file", + "mode": "interactive", + "notes": "The project ships as one script with no dependencies, so SQLite is out.", + }, + { + "area": "Titles", + "options": ["Stored as typed", "Trimmed"], + "chosen": "Stored as typed", + "mode": "interactive", + "notes": "A title is the user's own words.", + }, + ], + }) + ); + let reported = entries(&out, LOG); + for (line, outcome, says) in [ + (3, "ignored", "the template's instruction"), + (6, "redundant", "the directory and CONTEXT.md"), + (7, "redundant", "the directory and CONTEXT.md"), + (8, "redundant", "the directory and CONTEXT.md"), + (12, "filled", "the only shape a discussion log has"), + (14, "unmapped", "no member of a discussion entry"), + (36, "redundant", "CONTEXT.md gives it"), + (40, "redundant", "CONTEXT.md gives it"), + (46, "unmapped", "prose"), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {says}: {reported:#?}" + ); + } +} + +const PHASE_CONTEXT: &str = ".planning/phases/02-two/02-CONTEXT.md"; + +#[test] +fn a_context_reports_bad_decisions_and_deferred_ideas() { + let text = "# Phase 2: Two - Context\n\n**Gathered:** soon\n\n<domain>\n## Phase Boundary\n\nB.\n</domain>\n\n\ + <decisions>\n## Implementation Decisions\n\n### Area\n- **D-1 x:** bad id\n- **D-01:** first\n\ + - no id here\n- **D-01:** again\n\n</decisions>\n\n<deferred>\n## Deferred Ideas\n\n\ + - An idea with no reason\n- Sharing — v2\n</deferred>\n\n## Odd Section\n\ntext\n"; + let out = run(vec![(PHASE_CONTEXT, text)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!(paths(&all, "decision"), ["v1.0/02/D-01"]); + assert_eq!( + find(&all, "decision", "v1.0/02/D-01").fields["text"], + "first" + ); + assert_eq!(paths(&all, "deferred_idea"), ["v1.0/02/DI1", "v1.0/02/DI2"]); + assert_eq!( + find(&all, "deferred_idea", "v1.0/02/DI1").fields, + json!({"phase": "v1.0/02", "origin": "discussion", "text": "An idea with no reason"}) + ); + let context = find(&all, "context", "v1.0/02/02-CONTEXT"); + assert_eq!( + context.fields, + json!({"phase": "v1.0/02", "boundary": "B."}) + ); + let reported = entries(&out, PHASE_CONTEXT); + for (line, says) in [ + (3, "not a YYYY-MM-DD date"), + (15, "`D-1 x` is no decision"), + (17, "no `**D-NN:**` id"), + (18, "is given twice"), + (25, "no ` — why`"), + (29, "a section no row of the NN-CONTEXT.md table names"), + ] { + assert!( + has(&reported, line, "unmapped", says), + "{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn a_sub_section_is_never_its_parents_field() { + let context = + "# C\n\n## Phase Boundary\n\nB.\n\n### Detail\n\nMore.\n\n## Specific Ideas\n\nS.\n"; + let research = format!("{HEAD}### Detail\n\nMore.\n"); + let out = run(vec![(CONTEXT, context), (RESEARCH, research.as_str())]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!( + find(&all, "context", "v1.0/02/02-CONTEXT").fields, + json!({"phase": "v1.0/02", "boundary": "B.", "specifics": "S."}) + ); + assert_eq!( + find(&all, "research", "v1.0/02/02-RESEARCH").fields["summary"], + "S." + ); + for (file, line, says) in [ + (CONTEXT, 7, "no row of the NN-CONTEXT.md table"), + (RESEARCH, 9, "no row of the NN-RESEARCH.md table"), + ] { + let reported = entries(&out, file); + assert!( + has(&reported, line, "unmapped", says), + "{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn a_context_without_a_boundary_is_dropped_and_its_decisions_kept() { + let text = "# C\n\n<decisions>\n## Implementation Decisions\n\n### A\n- **D-01:** kept\n</decisions>\n"; + let out = run(vec![(PHASE_CONTEXT, text)]); + let all = creates(&out); + assert!(paths(&all, "context").is_empty()); + assert_eq!(paths(&all, "decision"), ["v1.0/02/D-01"]); + assert!(has( + &entries(&out, PHASE_CONTEXT), + 1, + "unmapped", + "required boundary has no source" + )); +} + +#[test] +fn a_context_of_no_roadmap_phase_imports_nothing() { + let out = run(vec![( + ".planning/phases/07-seven/07-CONTEXT.md", + "## Phase Boundary\n\nB.\n", + )]); + assert!(!creates(&out).iter().any(|c| c.kind == "context")); + assert!(has( + &entries(&out, ".planning/phases/07-seven/07-CONTEXT.md"), + 1, + "unmapped", + "phase 07 is no phase of ROADMAP.md" + )); +} + +#[test] +fn a_discussion_with_two_marked_options_takes_the_users_choice() { + let text = "# Log\n\n## Area\n\n| Option | Selected |\n|---|---|\n| A | ✓ |\n| B | ✓ |\n\n\ + **User's choice:** B, after all\n"; + let path = ".planning/phases/02-two/02-DISCUSSION-LOG.md"; + let out = run(vec![(path, text)]); + let all = creates(&out); + assert_eq!( + find(&all, "discussion", "v1.0/02/02-DISCUSSION-LOG").fields["entries"], + json!([{"area": "Area", "options": ["A", "B"], "chosen": "B, after all", "mode": "interactive"}]) + ); + assert!(has( + &entries(&out, path), + 5, + "unmapped", + "2 options are marked ✓" + )); +} + +#[test] +fn taskboard_research_takes_the_twins_values() { + let out = import_fixture("taskboard"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + let research = find(&all, "research", "v1.0/02/02-RESEARCH"); + assert_eq!(research.title, "Phase 2: Persistence - Research"); + assert_eq!( + research.fields, + json!({ + "phase": "v1.0/02", + "researched": "2026-03-04", + "domain": "File-backed storage for a small Node 20 command line tool", + "confidence": "high", + "summary": "A board of a few hundred tasks fits in one JSON file. Node's own `fs` module reads and writes it, and a write to a temporary name followed by a rename keeps the file whole if the process dies mid-write.", + "user_constraints": ["v1.0/02/D-01", "v1.0/02/D-02", "v1.0/02/D-03"], + "responsibility_map": [{"capability": "Persist the board", "tier": "Database/Storage"}], + }) + ); + let item = |kind: &str, id: &str| find(&all, kind, &format!("v1.0/02/02-RESEARCH/{id}")).fields; + let scoped = |mut v: serde_json::Value| { + v["research"] = json!("v1.0/02/02-RESEARCH"); + v + }; + assert_eq!( + item("finding", "F1"), + scoped(json!({ + "text": "`JSON.stringify` the board and `fs.renameSync` a temporary file over `tasks.json`.", + "confidence": "high", + })) + ); + assert_eq!( + item("stack_choice", "SC1"), + scoped( + json!({"name": "node:fs", "version": "20", "purpose": "Read and write `tasks.json`", "tier": "core"}) + ) + ); + assert_eq!( + item("pattern", "P1"), + scoped(json!({ + "name": "Write then rename", + "what": "Write the new content to a temporary file in the same directory, then rename it over the target.", + "when": "Every save.", + })) + ); + assert_eq!( + item("pattern", "P2"), + scoped( + json!({"name": "Writing in place", "what": "a crash mid-write leaves a truncated file.", "anti": true}) + ) + ); + assert_eq!( + item("dont_hand_roll", "DH1"), + scoped(json!({ + "problem": "Two processes saving at once", + "instead": "One process per board", + "why": "Lock files go stale after a crash", + })) + ); + assert_eq!( + item("pitfall", "PF1"), + scoped(json!({ + "name": "Torn writes", + "goes_wrong": "A crash during `writeFileSync` leaves a half-written `tasks.json`.", + "why": "`writeFileSync` truncates the file before it writes.", + "avoid": "Write then rename.", + "warning_signs": "`JSON.parse` throws on start.", + })) + ); + assert_eq!( + item("open_question", "OQ1"), + scoped(json!({ + "question": "Is one file enough for a thousand tasks?", + "known": "a task is a few dozen bytes.", + "unclear": "how large a board grows in practice.", + "recommendation": "revisit if a board passes ten thousand tasks.", + "resolved_by": "v1.0/02/D-01", + })) + ); + assert_eq!( + item("source", "SRC1"), + scoped(json!({ + "url": "https://nodejs.org/docs/latest-v20.x/api/fs.html", + "tier": "primary", + "checked": "`renameSync` replaces the target atomically on one filesystem", + })) + ); + let reported = entries(&out, RESEARCH); + for (line, outcome, says) in [ + (15, "redundant", "the phase's CONTEXT.md gives it"), + (18, "redundant", "the phase's CONTEXT.md gives it"), + (25, "unmapped", "no member of a responsibility map"), + (43, "unmapped", "no field of a stack choice"), + (63, "unmapped", "no field of a don't-hand-roll"), + (97, "unmapped", "prose"), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {says}: {reported:#?}" + ); + } + assert!( + !reported + .iter() + .any(|(_, _, o, r)| o == "unmapped" && r.contains("no row of the")), + "every section is a row: {reported:#?}" + ); +} + +/// The first 8 lines of a research with its two required fields. +const HEAD: &str = "# R\n\n**Confidence:** HIGH\n\n## Summary\n\nS.\n\n"; + +#[test] +fn a_research_leaves_out_decisions_its_context_does_not_give() { + let context = "# C\n\n## Phase Boundary\n\nB.\n\n## Implementation Decisions\n\n### Area\n- **D-01:** one\n"; + let research = format!( + "{HEAD}## User Constraints\n\n### Locked Decisions\n- D-01: one\n- D-09: nine\n\n\ + ## Open Questions\n\n1. **Q?** — RESOLVED: by D-07.\n - Something else: x\n - What we know: k\n\ + \x20 - What's unclear: u\n - Recommendation: r\n\n## Extra\n\ntext\n" + ); + let out = run(vec![(CONTEXT, context), (RESEARCH, research.as_str())]); + let all = creates(&out); + assert_eq!( + find(&all, "research", "v1.0/02/02-RESEARCH").fields, + json!({"phase": "v1.0/02", "confidence": "high", "summary": "S.", "user_constraints": ["v1.0/02/D-01"]}) + ); + assert_eq!( + find(&all, "open_question", "v1.0/02/02-RESEARCH/OQ1").fields, + json!({"research": "v1.0/02/02-RESEARCH", "question": "Q?", "known": "k", "unclear": "u", "recommendation": "r"}) + ); + let reported = entries(&out, RESEARCH); + for (line, says) in [ + (13, "`D-09` names no decision"), + (17, "`D-07` names no decision"), + (18, "no member of an open question"), + (23, "no row of the NN-RESEARCH.md table"), + ] { + assert!( + has(&reported, line, "unmapped", says), + "{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn a_research_of_a_bad_confidence_is_dropped_with_its_items() { + let text = "# R\n\n**Confidence:** Sure\n\n## Summary\n\nS.\n\n## Sources\n\n### Primary\n- https://a.test - n\n"; + let out = run(vec![(RESEARCH, text)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert!( + !all.iter() + .any(|c| c.kind == "research" || c.kind == "source"), + "{all:#?}" + ); + let reported = entries(&out, RESEARCH); + assert!( + has(&reported, 3, "unmapped", "none of high, medium, low"), + "{reported:#?}" + ); + assert!( + has(&reported, 12, "unmapped", "parent not imported"), + "{reported:#?}" + ); +} + +#[test] +fn a_research_source_holding_a_control_character_is_reported_not_created() { + let url = "https://x.test/a\u{7}b"; + let text = format!("{HEAD}## Sources\n\n### Primary\n- {url} - note\n"); + let out = run(vec![(RESEARCH, text.as_str())]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + // No .spec file holds a control character: the host would refuse the whole plan. + assert!( + !creates(&out) + .iter() + .any(|c| c.path == "v1.0/02/02-RESEARCH/SRC1"), + "the source is created" + ); + assert!( + entries(&out, RESEARCH) + .iter() + .any(|(_, _, outcome, reason)| outcome == "unmapped" + && reason.contains("SRC1: its title holds a control or bidirectional character")), + "{:#?}", + entries(&out, RESEARCH) + ); + assert!( + !payload(&out)["entries"].to_string().contains('\u{7}') + && !entries(&out, RESEARCH) + .iter() + .any(|(_, s, _, r)| s.contains('\u{7}') || r.contains('\u{7}')), + "the report holds no raw control character" + ); +} + +#[test] +fn a_research_of_5000_stack_rows_is_truncated() { + let mut text = + "# R\n\n## Standard Stack\n\n### Core\n| Library | Version | Purpose |\n|---|---|---|\n" + .to_string(); + for n in 0..5_000 { + text.push_str(&format!("| lib{n} | 1 | p |\n")); + } + let out = run(vec![(RESEARCH, text.as_str())]); + assert_eq!(out.exit_code, 1, "{}", out.stdout); + assert!(out.plan.is_none()); + assert!( + out.stderr.contains(&format!("truncated at {MAX_OPS}")), + "{}", + out.stderr + ); +} + +#[test] +fn a_context_canonical_ref_takes_its_topic_heading_and_paths() { + let text = "# C\n\n<domain>\n## Phase Boundary\n\nB.\n</domain>\n\n<canonical_refs>\n## Canonical References\n\n\ + **Downstream agents MUST read these before planning or implementing.**\n\n### Feed\n\ + - `docs/feed.md` — Feed rules\n- `docs/adr-1.md`\n</canonical_refs>\n"; + let out = run(vec![(PHASE_CONTEXT, text)]); + let context = find(&creates(&out), "context", "v1.0/02/02-CONTEXT"); + assert_eq!( + context.fields["canonical_refs"], + json!([ + {"topic": "Feed: Feed rules", "paths": ["docs/feed.md"]}, + {"topic": "Feed", "paths": ["docs/adr-1.md"]}, + ]) + ); +} diff --git a/gsd/import/tests/fixtures.rs b/gsd/import/tests/fixtures.rs new file mode 100644 index 0000000000..53b9787142 --- /dev/null +++ b/gsd/import/tests/fixtures.rs @@ -0,0 +1,767 @@ +//! `import`, in process, on the parity fixtures' `.planning/` folders. + +mod common; + +use std::collections::BTreeSet; + +use gsd_import::table; +use serde_json::{Value, json}; +use specforge_extension_sdk::PlanOp; +use specforge_extension_sdk::prelude::CommandOutput; +use specforge_extension_sdk::testing::MockHost; + +use common::{fixture, import_fixture, payload, planning_facts}; + +/// Each create of the plan: `(kind, id, file, revision, fields)`. +fn creates( + out: &specforge_extension_sdk::prelude::CommandOutput, +) -> Vec<(String, String, String, String, Value)> { + let plan = out.plan.as_ref().expect("import answers a plan"); + plan.ops + .iter() + .map(|op| match op { + PlanOp::Create { + kind, + id, + file, + revision, + fields, + .. + } => ( + kind.clone(), + id.clone(), + file.clone(), + revision.clone(), + json!(fields), + ), + other => panic!("import answers creates only, not {other:?}"), + }) + .collect() +} + +/// The creates of `kind`. +fn of_kind( + creates: Vec<(String, String, String, String, Value)>, + kind: &str, +) -> Vec<(String, String, String, String, Value)> { + creates.into_iter().filter(|(k, ..)| k == kind).collect() +} + +#[test] +fn taskboard_requirements_reach_one_plan() { + let out = import_fixture("taskboard"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let creates = of_kind(creates(&out), "requirement"); + let ids: Vec<&str> = creates.iter().map(|(_, id, ..)| id.as_str()).collect(); + assert_eq!( + ids, + [ + "LIST-01", "OOS-01", "STORE-01", "STORE-02", "SYNC-01", "TASK-01", "TASK-02", "TASK-03" + ] + ); + for (kind, id, file, revision, fields) in &creates { + assert_eq!(kind, "requirement", "{id}"); + assert_eq!(file, "spec/gsd/requirements.spec", "{id}"); + assert_eq!(revision, "absent", "{id}"); + assert_eq!(fields["defined"], "2026-03-02", "{id}"); + } + let fields = |id: &str| { + creates + .iter() + .find(|(_, i, ..)| i == id) + .map(|(.., f)| f.clone()) + .expect("created") + }; + assert_eq!( + fields("TASK-01"), + json!({"text": "A user can add a task with a title", "category": "Tasks", "tier": "v1", "defined": "2026-03-02"}) + ); + assert_eq!(fields("SYNC-01")["tier"], "v2"); + assert_eq!(fields("SYNC-01")["category"], "Sync"); + assert_eq!( + fields("OOS-01"), + json!({ + "text": "Share a board by link", + "category": "Out of Scope", + "tier": "out_of_scope", + "reason": "Needs accounts, which v1 does not have", + "defined": "2026-03-02", + }) + ); + let report = payload(&out); + assert_eq!(report["format"], 1); + assert_eq!(report["counts"]["requirement"], 8); + let entries = report["entries"].as_array().expect("entries"); + assert!( + entries + .iter() + .any(|e| e["file"] == ".planning/REQUIREMENTS.md" + && e["line"] == 39 + && e["outcome"] == "filled"), + "the minted OOS-01 is reported filled: {entries:#?}" + ); +} + +#[test] +fn every_other_planning_file_has_one_entry() { + let out = import_fixture("taskboard"); + let report = payload(&out); + let entries = report["entries"].as_array().expect("entries"); + let served: BTreeSet<String> = planning_facts(&fixture("taskboard")) + .iter() + .map(|f| f["path"].as_str().expect("a path").to_string()) + .filter(|p| { + ![ + ".planning/REQUIREMENTS.md", + ".planning/PROJECT.md", + ".planning/ROADMAP.md", + ] + .contains(&p.as_str()) + && !p.ends_with("-PLAN.md") + && !p.ends_with("-SUMMARY.md") + && !p.ends_with("-CONTEXT.md") + && !p.ends_with("-DISCUSSION-LOG.md") + && !p.ends_with("-RESEARCH.md") + && !p.ends_with("-VERIFICATION.md") + && !p.ends_with("-UAT.md") + }) + .collect(); + assert_eq!(served.len(), 5); + for path in &served { + let of_file: Vec<&Value> = entries + .iter() + .filter(|e| e["file"] == *path && e["line"].is_null() && e["section"] == "") + .collect(); + assert_eq!(of_file.len(), 1, "{path}: {of_file:#?}"); + let (_, fate) = table::fate_of(path.trim_start_matches(".planning/")).expect("a fate"); + assert_eq!( + of_file[0]["outcome"], + table::outcome(fate).as_str(), + "{path}" + ); + assert_eq!(of_file[0]["line"], Value::Null, "{path}"); + } + let reason = |path: &str| { + entries + .iter() + .find(|e| e["file"] == path) + .map(|e| e["reason"].clone()) + .expect("an entry") + }; + // The extras give their fate's reason. + assert_eq!( + reason(".planning/state.json"), + "gsd-tools' derived state (`state json`): STATE.md and the graph compute it" + ); + assert_eq!( + reason(".planning/phases/03-listing/.gitkeep"), + "an empty directory's placeholder" + ); +} + +#[test] +fn a_security_file_needs_gsd_security_when_the_project_does_not_load_it() { + let out = import_fixture("vault"); + let entries = payload(&out)["entries"].clone(); + let entry = entries + .as_array() + .expect("entries") + .iter() + .find(|e| e["file"] == ".planning/phases/01-core/01-SECURITY.md") + .cloned() + .expect("an entry"); + assert_eq!(entry["outcome"], "needs-extension"); + assert!( + entry["reason"] + .as_str() + .is_some_and(|r| r.ends_with("@gsd/security's, which the project does not load")), + "{entry}" + ); +} + +#[test] +fn ledger_and_vault_requirements_reach_their_plans() { + let ids = |name: &str| -> Vec<String> { + of_kind(creates(&import_fixture(name)), "requirement") + .into_iter() + .map(|(_, id, ..)| id) + .collect() + }; + assert_eq!( + ids("ledger"), + [ + "LEDG-01", "LEDG-02", "LEDG-03", "LEDG-04", "OOS-01", "REPT-01" + ] + ); + assert_eq!(ids("vault"), ["SEC-01", "SEC-02", "SHARE-01"]); +} + +/// The fields of the create `kind id`, and its file. +fn create_of(out: &CommandOutput, kind: &str, id: &str) -> (String, Value) { + creates(out) + .into_iter() + .find(|(k, i, ..)| k == kind && i == id) + .map(|(_, _, file, _, fields)| (file, fields)) + .unwrap_or_else(|| panic!("{kind} {id} is created")) +} + +#[test] +fn taskboard_project_and_its_decisions_take_the_twins_values() { + let out = import_fixture("taskboard"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let (file, project) = create_of(&out, "project", "taskboard"); + assert_eq!(file, "spec/gsd/project.spec"); + // `what` and `context` hold the whole section; the twin keeps the first sentence (ADR 0391 D13). + assert_eq!( + project, + json!({ + "name": "Taskboard", + "what": "A small board for tracking tasks from the command line. A user adds a task with a title, marks it complete and lists what is left. It is a Node 20 script with no dependencies, built to prove the GSD model in SpecForge.", + "core_value": "A task is never lost.", + "context": "Built to prove the GSD model in SpecForge. Small enough that one person reads all of it.", + "constraints": [{"kind": "tech_stack", "what": "Node 20, no dependencies", "why": "it ships as one script"}], + "out_of_scope": [{"item": "Sharing a board by link", "why": "needs accounts, which v1 does not have"}], + "key_decisions": ["D-01", "D-02"], + }) + ); + // The twin: project.spec and discuss.spec. + let (file, d1) = create_of(&out, "decision", "D-01"); + assert_eq!(file, "spec/gsd/project.spec"); + assert_eq!( + d1, + json!({"text": "ES modules, no build step", "rationale": "`node src/cli.js` must just run", "outcome": "pending", "origin": "project"}) + ); + let (_, d2) = create_of(&out, "decision", "D-02"); + assert_eq!( + d2, + json!({"text": "Tasks keep an integer id", "rationale": "Short to type: `taskboard done 3`", "outcome": "pending", "origin": "project"}) + ); + let entries = payload(&out)["entries"].clone(); + let at = |line: u64| -> Vec<(String, String)> { + entries + .as_array() + .expect("entries") + .iter() + .filter(|e| e["file"] == ".planning/PROJECT.md" && e["line"] == line) + .map(|e| { + ( + e["section"].as_str().expect("a section").to_string(), + e["outcome"].as_str().expect("an outcome").to_string(), + ) + }) + .collect() + }; + assert_eq!( + at(12), + [("Requirements".to_string(), "redundant".to_string())] + ); + assert_eq!(at(14), [("Validated".to_string(), "computed".to_string())]); + assert_eq!(at(16), [("Validated".to_string(), "ignored".to_string())]); + assert_eq!(at(18), [("Active".to_string(), "computed".to_string())]); + assert_eq!( + at(39), + [("Key Decisions".to_string(), "filled".to_string())] + ); + assert_eq!( + at(45), + [("*Last updated:".to_string(), "computed".to_string())] + ); +} + +#[test] +fn ledger_and_vault_projects_read_their_own_shapes() { + let ledger = import_fixture("ledger"); + let (_, project) = create_of(&ledger, "project", "ledger"); + // A constraint with no ` — ` has no `why`, as the twin writes it. + assert_eq!( + project["constraints"], + json!([{"kind": "tech_stack", "what": "Rust 2021, the standard library only"}]) + ); + assert_eq!( + project["out_of_scope"], + json!([{"item": "Currencies other than one", "why": "a ledger is one currency"}]) + ); + let vault = import_fixture("vault"); + let (_, project) = create_of(&vault, "project", "vault"); + assert_eq!(project["key_decisions"], json!(["D-01"])); + assert_eq!(project.get("out_of_scope"), None); + let (_, d1) = create_of(&vault, "decision", "D-01"); + assert_eq!(d1["text"], "AES-256-GCM from `node:crypto`"); +} + +/// The title of the create `kind id`. +fn title_of(out: &CommandOutput, kind: &str, id: &str) -> String { + let plan = out.plan.as_ref().expect("import answers a plan"); + plan.ops + .iter() + .find_map(|op| match op { + PlanOp::Create { + kind: k, + id: i, + title, + .. + } if k == kind && i == id => Some(title.clone()), + _ => None, + }) + .unwrap_or_else(|| panic!("{kind} {id} is created")) +} + +#[test] +fn roadmap_flat_taskboard_gives_the_twins_milestone_and_phases() { + let out = import_fixture("taskboard"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!( + create_of(&out, "milestone", "v1.0"), + ("spec/gsd/v1.0.spec".to_string(), json!({})) + ); + let phase = |id: &str| { + let (file, fields) = create_of(&out, "phase", id); + assert_eq!(file, "spec/gsd/v1.0.spec", "{id}"); + (title_of(&out, "phase", id), fields) + }; + // The twin, v1.0.spec; success criteria verbatim (the twin cuts their backticks: ADR 0391 D13's comparator folds them). + assert_eq!( + phase("01"), + ( + "Core".to_string(), + json!({ + "milestone": "v1.0", + "slug": "core", + "goal": "Tasks can be added and completed", + "requirements": ["TASK-01", "TASK-02"], + "success_criteria": ["A user can add a task with a title", "A user can mark a task complete by its id"], + }) + ) + ); + assert_eq!( + phase("02"), + ( + "Persistence".to_string(), + json!({ + "milestone": "v1.0", + "slug": "persistence", + "goal": "Tasks are saved to disk and read back", + "depends_on": ["v1.0/01"], + "requirements": ["STORE-01", "STORE-02"], + "success_criteria": [ + "Every change to the board is written to `tasks.json`", + "A restarted board shows the tasks it had", + "A title comes back exactly as it was written", + ], + }) + ) + ); + assert_eq!( + phase("02.1"), + ( + "Hotfix: titles survive a reload".to_string(), + json!({ + "milestone": "v1.0", + "slug": "hotfix-titles-survive-a-reload", + "goal": "A title is written to disk and read back unchanged", + "depends_on": ["v1.0/02"], + "success_criteria": [ + "A title with a leading space or a line break comes back unchanged", + "An empty title is refused", + ], + }) + ) + ); + assert_eq!( + phase("03"), + ( + "Listing".to_string(), + json!({ + "milestone": "v1.0", + "slug": "listing", + "goal": "Open tasks are listed and filtered", + "depends_on": ["v1.0/02"], + "requirements": ["TASK-03", "LIST-01"], + "success_criteria": [ + "`taskboard list` shows the open tasks, oldest first", + "`taskboard list <word>` shows only tasks whose title has the word", + ], + }) + ) + ); + let report = payload(&out); + let roadmap: Vec<(u64, String, String)> = lines(&out) + .into_iter() + .zip( + report["entries"] + .as_array() + .expect("entries") + .iter() + .filter(|e| e["line"].is_u64()), + ) + .filter(|(_, e)| e["file"] == ".planning/ROADMAP.md") + .map(|((l, o, _), e)| (l, e["section"].as_str().expect("a section").to_string(), o)) + .collect(); + for want in [ + (1, "Roadmap: Taskboard", "redundant"), + (1, "(no milestone)", "filled"), + (3, "Overview", "unmapped"), + (8, "Phases", "computed"), + (10, "Phase Numbering", "unmapped"), + (25, "Phase 1: Core", "ignored"), + (31, "Phase 1: Core", "computed"), + ( + 52, + "Phase 02.1: Hotfix: titles survive a reload (INSERTED)", + "computed", + ), + ( + 55, + "Phase 02.1: Hotfix: titles survive a reload (INSERTED)", + "ignored", + ), + ( + 64, + "Phase 02.1: Hotfix: titles survive a reload (INSERTED)", + "ignored", + ), + (77, "Progress", "computed"), + ] { + assert!( + roadmap + .iter() + .any(|(l, s, o)| (*l, s.as_str(), o.as_str()) == want), + "{want:?} in {roadmap:#?}" + ); + } + assert!( + report["authored_after_import"] + .as_array() + .expect("authored after import") + .iter() + .any(|l| l == "milestone v1.0: its title") + ); + // The Traceability table agrees with the roadmap: no mismatch is reported. + assert!(!roadmap.iter().any(|(_, s, _)| s == "Traceability")); +} + +#[test] +fn roadmap_flat_ledger_and_vault_give_their_phases() { + for (name, phases) in [("ledger", 3), ("vault", 2)] { + let out = import_fixture(name); + assert_eq!(out.exit_code, 0, "{name}: {}", out.stderr); + assert_eq!(of_kind(creates(&out), "phase").len(), phases, "{name}"); + assert_eq!(of_kind(creates(&out), "milestone").len(), 1, "{name}"); + } +} + +/// `import` of one served file on an empty graph. +fn import_one(path: &str, text: &str) -> CommandOutput { + common::import( + &specforge_extension_sdk::prelude::CommandGraph::default(), + &common::feed( + vec![common::fact(path, text)], + false, + Some(&common::manifest(&["@gsd/core"])), + ), + ) +} + +/// `(line, outcome, reason)` of each entry of `out`. +fn lines(out: &CommandOutput) -> Vec<(u64, String, String)> { + payload(out)["entries"] + .as_array() + .expect("entries") + .iter() + .filter_map(|e| { + Some(( + e["line"].as_u64()?, + e["outcome"].as_str()?.to_string(), + e["reason"].as_str()?.to_string(), + )) + }) + .collect() +} + +#[test] +fn a_project_reports_what_it_cannot_map() { + let text = "# Odd Project\n\n## What This Is\n\nA thing.\n\n## Core Value\n\nIt works.\n\n## Requirements\n\n### Out of Scope\n\n- Teleporting\n\n## Context\n\nNone.\n\n## Constraints\n\n- **Mood**: calm — it helps\n- No label at all\n\n## Key Decisions\n\n| Decision | Rationale | Outcome |\n|---|---|---|\n| Use X | because | Maybe |\n\n## Glossary\n\n### Terms\n"; + let out = import_one(".planning/PROJECT.md", text); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let (_, project) = create_of(&out, "project", "odd-project"); + assert_eq!( + project["constraints"], + json!([ + {"kind": "other", "what": "Mood: calm", "why": "it helps"}, + {"kind": "other", "what": "No label at all"} + ]) + ); + assert_eq!(project.get("out_of_scope"), None); + let (_, d1) = create_of(&out, "decision", "D-01"); + assert_eq!(d1.get("outcome"), None); + let lines = lines(&out); + let has = |line: u64, outcome: &str, says: &str| { + assert!( + lines + .iter() + .any(|(l, o, r)| *l == line && o == outcome && r.contains(says)), + "{line} {outcome} {says}: {lines:#?}" + ); + }; + has(15, "unmapped", "needs a reason"); + has(23, "filled", "keeps its words in `what`"); + has(24, "filled", "keeps its words in `what`"); + has(30, "unmapped", "none of Good, Revisit, Pending"); + has(32, "unmapped", "no row of the PROJECT.md table"); + // `### Terms` sits under the reported `## Glossary`: not reported twice. + assert!(!lines.iter().any(|(l, ..)| *l == 34), "{lines:#?}"); + // A name the id grammar refuses refuses the project, not its decisions. + let out = import_one( + ".planning/PROJECT.md", + &text.replace("# Odd Project", "# 日本"), + ); + assert!(creates(&out).iter().all(|(k, ..)| k != "project")); + assert!(creates(&out).iter().any(|(k, ..)| k == "decision")); + assert!(lines_of(&out, 1, "gives no id")); +} + +/// REQUIREMENTS.md's headings are the family's Markdown reader's: none in a comment, a tab after the marks counts. +#[test] +fn requirements_headings_are_the_markdown_readers() { + let text = "# Requirements: X\n\n## v1 Requirements\n\n<!--\n## Out of Scope\n-->\n\n### Core\n\n- **CORE-01**: one\n\n##\tv2 Requirements\n\n### Later\n\n- **LATER-01**: two\n"; + let out = import_one(".planning/REQUIREMENTS.md", text); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let (_, core) = create_of(&out, "requirement", "CORE-01"); + assert_eq!(core["tier"], "v1"); + let (_, later) = create_of(&out, "requirement", "LATER-01"); + assert_eq!(later["tier"], "v2"); +} + +#[test] +fn a_project_sub_section_is_never_its_parents_field() { + let text = "# Odd Project\n\n## What This Is\n\nA thing.\n\n### Details\n\nMore.\n\n## Constraints\n\n- **Budget**: none — free\n\n### Later\n\n- **Timeline**: soon\n\n## Core Value\n\nIt works.\n\n## Context\n\nNone.\n"; + let out = import_one(".planning/PROJECT.md", text); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let (_, project) = create_of(&out, "project", "odd-project"); + assert_eq!(project["what"], "A thing."); + assert_eq!( + project["constraints"], + json!([{"kind": "budget", "what": "none", "why": "free"}]) + ); + assert!(lines_of(&out, 7, "no row of the PROJECT.md table")); + assert!(lines_of(&out, 15, "no row of the PROJECT.md table")); +} + +#[test] +fn a_second_project_title_covers_nothing_after_it() { + let text = "# Odd Project\n\n## What This Is\n\nA thing.\n\n# Appendix\n\n## Key Decisions\n\n| Decision | Rationale | Outcome |\n|---|---|---|\n| Use X | because | ✓ Good |\n"; + let out = import_one(".planning/PROJECT.md", text); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let (_, d1) = create_of(&out, "decision", "D-01"); + assert_eq!(d1["text"], "Use X"); + assert!(lines_of(&out, 7, "no row of the PROJECT.md table")); + assert!(lines_of(&out, 9, "mapped: each row a decision")); +} + +fn lines_of(out: &CommandOutput, line: u64, says: &str) -> bool { + lines(out) + .iter() + .any(|(l, _, r)| *l == line && r.contains(says)) +} + +#[test] +fn taskboard_state_maps_nothing_and_reports_each_section() { + let out = import_fixture("taskboard"); + let entries = payload(&out)["entries"].clone(); + let of_state: Vec<(Value, String, String)> = entries + .as_array() + .expect("entries") + .iter() + .filter(|e| e["file"] == ".planning/STATE.md") + .map(|e| { + ( + e["line"].clone(), + e["section"].as_str().expect("a section").to_string(), + e["outcome"].as_str().expect("an outcome").to_string(), + ) + }) + .collect(); + let want: Vec<(Value, String, String)> = [ + (Value::Null, "", "runtime"), + (json!(1), "---", "computed"), + (json!(19), "Project State", "unmapped"), + (json!(21), "Project Reference", "unmapped"), + (json!(28), "Current Position", "computed"), + (json!(37), "Performance Metrics", "unmapped"), + (json!(44), "Accumulated Context", "unmapped"), + (json!(46), "Decisions", "unmapped"), + (json!(50), "Pending Todos", "unmapped"), + (json!(56), "Blockers/Concerns", "ignored"), + (json!(58), "Session Continuity", "runtime"), + ] + .into_iter() + .map(|(l, s, o)| (l, s.to_string(), o.to_string())) + .collect(); + assert_eq!(of_state, want); +} + +#[test] +fn a_state_blocker_is_reported_and_a_broken_frontmatter_named() { + let state = "---\nstatus: [open\n---\n# State\n\n### Blockers/Concerns\n\n- The API key is not set\n- None yet.\n"; + let out = import_one(".planning/STATE.md", state); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert!( + out.plan.as_ref().is_none_or(|p| p.ops.is_empty()), + "STATE.md writes nothing" + ); + let entries = payload(&out)["entries"].clone(); + let line = |n: u64| { + entries + .as_array() + .expect("entries") + .iter() + .find(|e| e["line"] == n) + .cloned() + .unwrap_or_else(|| panic!("an entry at {n}: {entries:#?}")) + }; + assert_eq!(line(2)["outcome"], "unmapped"); + assert!( + line(2)["reason"] + .as_str() + .is_some_and(|r| r.starts_with("frontmatter not read")), + "{}", + line(2) + ); + assert_eq!(line(8)["outcome"], "unmapped"); + assert_eq!(line(8)["reason"], table::LATER); + assert_eq!(line(9)["outcome"], "ignored"); +} + +/// Every key of a fixture's `config.json` as a dotted path to a leaf (an empty object is a leaf). +fn config_keys(name: &str) -> Vec<String> { + fn walk(prefix: &str, value: &Value, out: &mut Vec<String>) { + match value.as_object() { + Some(map) if !map.is_empty() => { + for (key, inner) in map { + let path = match prefix { + "" => key.clone(), + _ => format!("{prefix}.{key}"), + }; + walk(&path, inner, out); + } + } + _ => out.push(prefix.to_string()), + } + } + let text = std::fs::read_to_string(fixture(name).join(".planning/config.json")) + .expect("the fixture's config.json"); + let mut out = Vec::new(); + walk("", &serde_json::from_str(&text).expect("JSON"), &mut out); + out +} + +/// `(extension, key)` of each settings line of an import's report. +fn printed(report: &Value) -> Vec<(String, String)> { + report["settings"] + .as_array() + .expect("settings") + .iter() + .map(|line| { + let words: Vec<&str> = line.as_str().expect("a line").split(' ').collect(); + assert_eq!(words[..3], ["specforge", "settings", "set"], "{line}"); + (words[3].to_string(), words[4].to_string()) + }) + .collect() +} + +#[test] +fn every_config_key_has_a_settings_line_or_an_entry() { + for name in ["taskboard", "ledger", "vault"] { + let report = payload(&import_fixture(name)); + let printed = printed(&report); + let reported: BTreeSet<String> = report["entries"] + .as_array() + .expect("entries") + .iter() + .filter(|e| e["file"] == ".planning/config.json") + .map(|e| e["section"].as_str().expect("a section").to_string()) + .collect(); + let keys = config_keys(name); + assert!(keys.len() > 40, "{name}: {}", keys.len()); + for key in keys { + assert!( + printed.iter().any(|(_, k)| *k == key) || reported.contains(&key), + "{name}: {key} has neither a line nor an entry" + ); + } + } +} + +/// Whether the declared setting `name` (`a.*` a family of one segment per `*`) names `key`. +fn declares(name: &str, key: &str) -> bool { + let (names, keys): (Vec<&str>, Vec<&str>) = + (name.split('.').collect(), key.split('.').collect()); + names.len() == keys.len() && names.iter().zip(&keys).all(|(n, k)| *n == "*" || n == k) +} + +#[test] +fn every_printed_core_key_is_declared() { + let host = MockHost::new(gsd_core::build()); + let described: Value = + serde_json::from_str(&host.describe_json("settings").expect("settings")).expect("JSON"); + let declared: Vec<String> = described["items"] + .as_array() + .expect("items") + .iter() + .filter(|item| item["kind"] == "setting") + .map(|item| item["name"].as_str().expect("a name").to_string()) + .collect(); + let mut checked = 0; + for name in ["taskboard", "ledger", "vault"] { + for (extension, key) in printed(&payload(&import_fixture(name))) { + if extension == "@gsd/core" { + checked += 1; + assert!( + declared.iter().any(|d| declares(d, &key)), + "{name}: @gsd/core declares no setting {key}" + ); + } + } + } + assert!(checked > 100, "{checked}"); +} + +#[test] +fn each_fixtures_counts_are_pinned() { + for (name, security, want) in [ + // 13-RESEARCH "Taskboard: twin entity ← source line"; the ledger and the vault per its "adds" line. + ( + "taskboard", + false, + json!({ + "project": 1, "decision": 5, "requirement": 8, "milestone": 1, "phase": 4, "plan": 3, + "task": 6, "truth": 6, "artifact": 3, "key_link": 3, "summary": 2, "deliverable": 3, + "uat_session": 1, "uat_test": 3, "uat_gap": 1, "verification": 1, "context": 1, + "deferred_idea": 1, "discussion": 1, "research": 1, "source": 1, "finding": 1, + "stack_choice": 1, "pattern": 2, "pitfall": 1, "dont_hand_roll": 1, "open_question": 1, + }), + ), + ( + "ledger", + false, + json!({ + "project": 1, "decision": 2, "requirement": 6, "milestone": 1, "phase": 3, "plan": 4, + "task": 7, "truth": 7, "artifact": 4, "key_link": 3, "summary": 3, "deliverable": 3, + "verification": 1, + }), + ), + ( + "vault", + true, + json!({ + "project": 1, "decision": 1, "requirement": 3, "milestone": 1, "phase": 2, "plan": 3, + "task": 5, "truth": 3, "artifact": 3, "key_link": 3, "summary": 2, + "trust_boundary": 2, "threat": 6, "security_audit": 1, "accepted_risk": 1, "audit_run": 1, + }), + ), + ] { + let out = common::import_with(name, security); + assert_eq!(out.exit_code, 0, "{name}: {}", out.stderr); + assert_eq!(payload(&out)["counts"], want, "{name}"); + } +} diff --git a/gsd/import/tests/leftovers.rs b/gsd/import/tests/leftovers.rs new file mode 100644 index 0000000000..5ef48631da --- /dev/null +++ b/gsd/import/tests/leftovers.rs @@ -0,0 +1,139 @@ +//! What a reader leaves of a section it maps in part (ADR 0391 D3, D8): each line no row reads is reported at its line, +//! never dropped silently, in every Tier 1 format that reads key lines, bullets or tables out of its sections. + +mod common; + +use serde_json::json; +use specforge_extension_sdk::prelude::*; + +use common::{creates, entries, fact, feed, find, has, import, manifest, paths}; + +/// What a leftover line's entry says. +const READS: &str = "table reads: no field holds it"; + +/// The import of `files`, with a roadmap of phases 1 and 2 unless `files` serve one. +fn run(files: Vec<(&str, &str)>) -> CommandOutput { + let road = "# Roadmap: X\n\n### Phase 1: One\n**Goal**: g\n**Success Criteria**:\n 1. c\n\n### Phase 2: Two\n**Goal**: h\n**Success Criteria**:\n 1. d\n"; + let mut facts: Vec<_> = files.iter().map(|(path, text)| fact(path, text)).collect(); + if !files.iter().any(|(path, _)| *path == ROADMAP) { + facts.push(fact(ROADMAP, road)); + } + import( + &CommandGraph::default(), + &feed(facts, false, Some(&manifest(&["@gsd/core"]))), + ) +} + +const ROADMAP: &str = ".planning/ROADMAP.md"; + +/// Asserts that `file` has an `unmapped` entry saying `says` at each of `lines`. +fn reported_at(out: &CommandOutput, file: &str, lines: &[u64], says: &str) { + let reported = entries(out, file); + for &line in lines { + assert!( + has(&reported, line, "unmapped", says), + "{file}:{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn a_roadmap_reports_each_phase_line_it_does_not_read() { + let roadmap = "# Roadmap: X\n\nA tagline.\n\n### Phase 1: One\n\nSome prose.\n**Goal**: g\nPlans: 2 plans\n\ + **Success Criteria**:\n\n 1. c\n\n**Plans**: 1 plan\n\n### Phase 2: Two\n\n**Goal**: h\n**Plans**: TBD\n"; + let out = run(vec![(ROADMAP, roadmap)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + // The Success Criteria list a blank line below its key is read. + assert_eq!( + find(&creates(&out), "phase", "01").fields["success_criteria"], + json!(["c"]) + ); + reported_at(&out, ROADMAP, &[3, 7, 9], READS); + // Each `**Plans**` line, not the first alone. + let reported = entries(&out, ROADMAP); + for line in [14, 19] { + assert!( + has(&reported, line, "computed", "plans_complete"), + "{line}: {reported:#?}" + ); + } +} + +#[test] +fn requirements_report_each_line_no_row_reads() { + let path = ".planning/REQUIREMENTS.md"; + let text = "# Requirements: X\n\n## v1 Requirements\n\nIntro.\n\n### Core\n\n- **CORE-01**: one\n\ + - Users can share a board\n\n## Out of Scope\n\n- Sharing — later\n\n---\n*Last updated: 2026-01-01*\n"; + let out = run(vec![(path, text)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!(paths(&creates(&out), "requirement"), ["CORE-01"]); + reported_at(&out, path, &[5, 10, 14], READS); + assert!( + entries(&out, path).iter().any(|(l, ..)| *l == 17), + "the footer has its entry" + ); +} + +#[test] +fn a_project_reports_its_tagline_and_a_constraint_intro() { + let path = ".planning/PROJECT.md"; + let text = "# Odd\n\nA tagline.\n\n## What This Is\n\nW.\n\n## Core Value\n\nC.\n\n## Context\n\nX.\n\n\ + ## Constraints\n\nSome intro.\n\n- **Budget**: none — free\n"; + let out = run(vec![(path, text)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let project = find(&creates(&out), "project", "odd"); + assert_eq!( + project.fields["constraints"], + json!([{"kind": "budget", "what": "none", "why": "free"}]) + ); + reported_at(&out, path, &[3, 19], READS); +} + +#[test] +fn a_context_and_a_research_report_each_line_no_row_reads() { + let context_path = ".planning/phases/02-two/02-CONTEXT.md"; + let research_path = ".planning/phases/02-two/02-RESEARCH.md"; + let context = "# C\n\nA note.\n\n## Phase Boundary\n\nB.\n\n<decisions>\n## Implementation Decisions\n\nIntro prose.\n\n\ + ### Area\n\nArea prose.\n\n- **D-01:** one\n</decisions>\n"; + let research = "# R\n\n**Confidence:** HIGH\n\n## Summary\n\nS.\n\n## Standard Stack\n\n**Installation:**\n\n### Core\n\n\ + | Library | Version | Purpose |\n|---|---|---|\n| a | 1 | b |\n\n## Common Pitfalls\n\nIntro.\n\n\ + ### Pitfall 1: P\n\n**What goes wrong:** w\nMore detail.\n"; + let out = run(vec![(context_path, context), (research_path, research)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!(paths(&all, "decision"), ["v1.0/02/D-01"]); + assert_eq!( + find(&all, "stack_choice", "v1.0/02/02-RESEARCH/SC1").fields["name"], + "a" + ); + reported_at( + &out, + context_path, + &[3, 12, 16], + "text no row of the NN-CONTEXT.md table reads", + ); + reported_at( + &out, + research_path, + &[11, 21, 26], + "text no row of the NN-RESEARCH.md table reads", + ); +} + +#[test] +fn a_summary_title_reports_the_text_past_its_one_liner() { + let plan = ".planning/phases/01-one/01-01-PLAN.md"; + let summary = ".planning/phases/01-one/01-01-SUMMARY.md"; + let plan_text = "---\ntype: execute\nfiles_modified: [a.js]\n---\n\n<objective>\nDo it.\n</objective>\n\n<tasks>\n\ + <task type=\"auto\">\n <name>Task 1: T</name>\n <action>a</action>\n <done>d</done>\n</task>\n</tasks>\n"; + // The one-liner's paragraph runs on to line 12; line 14 is a paragraph of its own. + let summary_text = "---\nphase: 01-one\nplan: 01\nsubsystem: core\nstatus: complete\nrequirements-completed: []\n---\n\n\ + # Plan 01 Summary\n\n**It works.**\nand more.\n\nA tagline.\n\n## Accomplishments\n\nx\n"; + let out = run(vec![(plan, plan_text), (summary, summary_text)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!( + find(&creates(&out), "summary", "v1.0/01/01-01/01-01-SUMMARY").fields["one_liner"], + "It works." + ); + reported_at(&out, summary, &[12, 14], "other than its bold one-liner"); +} diff --git a/gsd/import/tests/measure.rs b/gsd/import/tests/measure.rs new file mode 100644 index 0000000000..61815faaf9 --- /dev/null +++ b/gsd/import/tests/measure.rs @@ -0,0 +1,49 @@ +//! The fate table against what the host accepts (ADR 0391 D3, D7): a home that writes names a field its writer lets +//! `@gsd/import` write, and a computed home names a computed field. A plan writing one field the host refuses is +//! refused whole, so the table is checked here, before any reader writes a row. + +mod common; + +use gsd_import::table::{self, Home, ID, TITLE}; + +use common::declared; + +#[test] +fn every_home_is_declared() { + let declared = declared(); + let (mut writes, mut computed) = (0, 0); + for row in table::rows() { + for home in row.homes { + let (kind, field, want): (&str, &str, &[&str]) = match *home { + Home::To { field, .. } | Home::Filled { field, .. } + if field == ID || field == TITLE => + { + continue; + } + Home::To { kind, field, .. } | Home::Filled { kind, field, .. } => { + writes += 1; + (kind, field, &["", "harness"]) + } + Home::Computed { kind, field } => { + computed += 1; + (kind, field, &["computed"]) + } + Home::Redundant(_) | Home::Reported(_) | Home::Ignored(_) | Home::Runtime(_) => { + continue; + } + }; + let at = format!("{} `{}`: {kind}.{field}", row.file, row.key); + let writer = declared + .get(&format!("{kind}.{field}")) + .unwrap_or_else(|| panic!("{at} is no field of @gsd/core or @gsd/security")); + assert!( + want.contains(&writer.as_str()), + "{at} is written by `{writer}`, not {want:?}" + ); + } + } + assert!( + writes > 100 && computed > 20, + "{writes} writes, {computed} computed" + ); +} diff --git a/gsd/import/tests/plans.rs b/gsd/import/tests/plans.rs new file mode 100644 index 0000000000..69e6950d3f --- /dev/null +++ b/gsd/import/tests/plans.rs @@ -0,0 +1,792 @@ +//! Phase plans, their tasks and must-haves (and, from 13-06 Task 2, summaries and quick plans) through the command in +//! process, against the twins' `plans.spec` and `quick.spec`. +//! +//! Known differences from the twins, asserted as differences (13-RESEARCH "Per-Fixture Mapping", D5): `context_refs` +//! is absent (every fixture's `<context>` names only `.planning/` paths, which are dropped, while the twins name spec +//! files); a truth's title is its text and a key link's `<from> -> <to>` (the twins' titles are hand-made, and titles +//! compare nothing). + +mod common; + +use serde_json::json; +use specforge_extension_sdk::prelude::*; + +use common::{ + creates, declared, entries, fact, feed, find, fixture, has, import, import_fixture, + import_with, manifest, paths, +}; +use gsd_import::limits::MAX_OPS; + +#[test] +fn taskboard_plans_take_the_twins_values() { + let out = import_fixture("taskboard"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!( + paths(&all, "plan"), + ["v1.0/01/01-01", "v1.0/01/01-02", "v1.0/02/02-01"] + ); + for (kind, n) in [("task", 6), ("truth", 6), ("artifact", 3), ("key_link", 3)] { + assert_eq!( + paths(&all, kind).len(), + n, + "{kind}: {:?}", + paths(&all, kind) + ); + } + let plan = find(&all, "plan", "v1.0/01/01-01"); + assert_eq!( + (plan.title.as_str(), plan.file.as_str()), + ("The task model and add", "spec/gsd/phases/01.spec") + ); + // The twin, plans.spec; `context_refs` is a known difference (D5). + assert_eq!( + plan.fields, + json!({ + "phase": "v1.0/01", + "type": "execute", + "files_modified": ["package.json", "src/tasks.js", "test/tasks.test.js"], + "requirements": ["TASK-01"], + "objective": "The task model and `add`.", + "purpose": "every later phase builds on a board of tasks with stable ids.", + "output": "`src/tasks.js` with `createBoard` and `addTask`, and its tests.", + "verification": ["`npm test` passes."], + "success_criteria": ["TASK-01 holds: a user can add a task with a title"], + }) + ); + let plan = find(&all, "plan", "v1.0/01/01-02"); + assert_eq!(plan.title, "complete and the command line"); + assert_eq!(plan.fields["depends_on"], json!(["v1.0/01/01-01"])); + assert_eq!( + find(&all, "plan", "v1.0/02/02-01").fields["requirements"], + json!(["STORE-01", "STORE-02"]) + ); + let task = find(&all, "task", "v1.0/01/01-01/T1"); + assert_eq!(task.title, "The task model"); + assert_eq!( + task.fields, + json!({ + "plan": "v1.0/01/01-01", + "type": "auto", + "files": ["package.json", "src/tasks.js"], + "action": "Create `package.json` (ES modules, `npm test` runs `node --test`) and `src/tasks.js` exporting `createBoard()` returning `{ tasks: [], nextId: 1 }` and `addTask(board, title)` that appends `{ id, title, done: false }` and bumps `nextId`.", + "verify_text": "node -e \"import('./src/tasks.js').then(m => console.log(m.addTask(m.createBoard(), 'x')))\"", + "done": "addTask returns a task with id 1 on an empty board", + }) + ); + let truth = find(&all, "truth", "v1.0/02/02-01/TR3"); + assert_eq!( + truth.fields, + json!({"plan": "v1.0/02/02-01", "text": "A title comes back exactly as it was written (D-03)"}) + ); + // A known difference: the title is the text, the twin's is shortened. + assert_eq!( + truth.title, + "A title comes back exactly as it was written (D-03)" + ); + let artifact = find(&all, "artifact", "v1.0/01/01-01/AR1"); + assert_eq!( + (artifact.title.as_str(), artifact.fields), + ( + "createBoard and addTask", + json!({"plan": "v1.0/01/01-01", "path": "src/tasks.js", "provides": "createBoard and addTask", "contains": "export function addTask"}) + ) + ); + let link = find(&all, "key_link", "v1.0/01/01-02/KL1"); + assert_eq!( + (link.title.as_str(), link.fields), + ( + "src/cli.js -> src/tasks.js", + json!({"plan": "v1.0/01/01-02", "from": "src/cli.js", "to": "src/tasks.js", "via": "import { addTask, completeTask, createBoard }"}) + ) + ); + let reported = entries(&out, ".planning/phases/01-core/01-01-PLAN.md"); + for (line, outcome, says) in [ + (2, "redundant", "the file name gives them"), + (3, "redundant", "the file name gives them"), + (5, "computed", "plan.wave is computed"), + (8, "computed", "plan.autonomous is computed"), + (31, "unmapped", "GSD-internal: the spec replaces it"), + (33, "unmapped", "GSD-internal: the spec replaces it"), + (64, "unmapped", "an instruction to the executor"), + (1, "mapped", "plan v1.0/01/01-01"), + (38, "mapped", "task v1.0/01/01-01/T1"), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {outcome} {says}: {reported:#?}" + ); + } +} + +#[test] +fn ledger_plans_take_the_twins_values() { + let out = import_fixture("ledger"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!( + paths(&all, "plan") + .into_iter() + .filter(|p| p.starts_with("v1.0/")) + .collect::<Vec<_>>(), + ["v1.0/01/01-01", "v1.0/01/01-02", "v1.0/02/02-01"] + ); + let truths: Vec<&str> = paths(&all, "truth") + .into_iter() + .filter(|p| p.starts_with("v1.0/01/")) + .collect(); + assert_eq!( + truths, + [ + "v1.0/01/01-01/TR1", + "v1.0/01/01-01/TR2", + "v1.0/01/01-02/TR1", + "v1.0/01/01-02/TR2" + ] + ); + let plan = find(&all, "plan", "v1.0/01/01-02"); + assert_eq!(plan.title, "The total"); + assert_eq!(plan.fields["depends_on"], json!(["v1.0/01/01-01"])); + // The twin writes the backslashes the source holds. + assert_eq!( + find(&all, "task", "v1.0/01/01-02/T2").fields["verify_text"], + r"printf '100\ta\n250\tb\n' | cargo run -q -- total" + ); +} + +#[test] +fn a_body_with_angle_brackets_and_quotes_is_kept_verbatim() { + let text = std::fs::read_to_string( + fixture("taskboard").join(".planning/phases/01-core/01-02-PLAN.md"), + ) + .expect("the fixture"); + let source = |n: usize| { + let after = text.split("<action>").nth(n).expect("an action"); + after.split("</action>").next().expect("closed").to_string() + }; + let all = creates(&import_fixture("taskboard")); + for (n, task) in [(1, "T1"), (2, "T2")] { + let action = find(&all, "task", &format!("v1.0/01/01-02/{task}")).fields["action"].clone(); + assert_eq!(action, json!(source(n)), "{task}"); + } + assert!(source(1).contains("`no task <id>`") && source(2).contains("`add <title>`")); +} + +/// The import of a roadmap of phases 1 and 2 and the served `files`. +fn run(files: Vec<(&str, &str)>) -> CommandOutput { + let road = "# Roadmap: X\n\n### Phase 1: One\n**Goal**: g\n**Success Criteria**:\n 1. c\n\n### Phase 2: Two\n**Goal**: h\n**Success Criteria**:\n 1. d\n"; + let mut facts = vec![fact(".planning/ROADMAP.md", road)]; + facts.extend(files.into_iter().map(|(path, text)| fact(path, text))); + import( + &CommandGraph::default(), + &feed(facts, false, Some(&manifest(&["@gsd/core"]))), + ) +} + +/// A plan whose frontmatter is `front` and whose body is `body`. +fn plan_text(front: &str, body: &str) -> String { + format!( + "---\ntype: execute\nfiles_modified: [a.js]\n{front}---\n\n<objective>\nDo it.\n</objective>\n\n{body}" + ) +} + +#[test] +fn a_plan_reads_every_task_field_and_reports_the_rest() { + let body = "<execution_context>\n@~/gsd/workflows/execute-plan.md\n</execution_context>\n\n<context>\n@.planning/PROJECT.md\n@src/a.js\n</context>\n\n<interfaces>\nx\n</interfaces>\n\n<tasks>\n<task type=\"tdd\">\n <name>Task 1: Write it</name>\n <files>a.js , b.js</files>\n <read_first>\n - src/a.js (the module)\n - `docs/b.md`\n </read_first>\n <behavior>\n - Test 1: it works\n </behavior>\n <action>Write `a <b>`.</action>\n <verify>\n <automated>npm test</automated>\n <fails_when>a FAIL line</fails_when>\n <automated>npm run lint</automated>\n </verify>\n <acceptance_criteria>\n - `grep -c x a.js` prints 1\n - it builds\n </acceptance_criteria>\n <done>It is written</done>\n</task>\n<task type=\"checkpoint:human-verify\" gate=\"blocking\">\n <what-built>it</what-built>\n</task>\n</tasks>\n"; + let text = plan_text( + "wave: 0\nautonomous: false\nestimate:\n tokens: 10\nuser_setup: []\nodd_key: 1\nmust_haves:\n truths:\n - \"It works\"\n artifacts:\n - path: a.js\n provides: \"it\"\n min_lines: 12\n exports: [run]\n size: big\n prohibitions:\n - \"No b\"\n", + body, + ); + let path = ".planning/phases/01-one/01-01-PLAN.md"; + let out = run(vec![(path, &text)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + let plan = find(&all, "plan", "v1.0/01/01-01"); + assert_eq!(plan.fields["wave0"], true); + assert_eq!(plan.fields["context_refs"], json!(["src/a.js"])); + // The roadmap names no title: the objective's first line, less its period, reported filled. + assert_eq!(plan.title, "Do it"); + let task = find(&all, "task", "v1.0/01/01-01/T1"); + assert_eq!( + task.fields, + json!({ + "plan": "v1.0/01/01-01", + "type": "tdd", + "files": ["a.js", "b.js"], + "read_first": ["src/a.js", "docs/b.md"], + "action": "Write `a <b>`.", + "verify": [ + {"automated": "npm test", "fails_when": "a FAIL line"}, + {"automated": "npm run lint"} + ], + "acceptance": ["`grep -c x a.js` prints 1", "it builds"], + "done": "It is written", + }) + ); + assert_eq!(task.title, "Write it"); + // The checkpoint is no task: only one task is created. + assert_eq!(paths(&all, "task"), ["v1.0/01/01-01/T1"]); + let artifact = find(&all, "artifact", "v1.0/01/01-01/AR1"); + assert_eq!(artifact.fields["min_lines"], 12); + assert_eq!(artifact.fields["exports"], json!(["run"])); + let reported = entries(&out, path); + for (line, outcome, says) in [ + (4, "computed", "plan.wave is computed"), + (5, "computed", "plan.autonomous is computed"), + // A block value is located at its first line. + (7, "unmapped", "a Tier 2 section"), + (8, "unmapped", "a Tier 2 section"), + ( + 9, + "unmapped", + "no row of the NN-MM-PLAN.md table reports odd_key", + ), + (18, "unmapped", "a member `size` no row of the table names"), + (20, "unmapped", "a Tier 2 section"), + (24, "filled", "names no title for 01-01"), + (27, "unmapped", "`specforge gsd reference` serves them"), + (32, "unmapped", "GSD-internal"), + ( + 36, + "unmapped", + "no row of the NN-MM-PLAN.md table reports <interfaces>", + ), + (48, "unmapped", "a TDD task's expected behaviours"), + (63, "unmapped", "a Tier 2 section"), + ( + 64, + "unmapped", + "no row of the NN-MM-PLAN.md table reports <what-built>", + ), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {outcome} {says}: {reported:#?}" + ); + } +} + +#[test] +fn the_file_name_wins_over_the_frontmatter_and_the_directory() { + let text = plan_text("phase: 02-two\nplan: 03\n", ""); + let path = ".planning/phases/02-two/01-01-PLAN.md"; + let out = run(vec![(path, &text)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!(paths(&all, "plan"), ["v1.0/01/01-01"]); + assert_eq!( + find(&all, "plan", "v1.0/01/01-01").file, + "spec/gsd/phases/01.spec" + ); + let reported = entries(&out, path); + assert!( + has( + &reported, + 1, + "unmapped", + "the directory `02-two` names another phase" + ), + "{reported:#?}" + ); + assert!( + has( + &reported, + 4, + "unmapped", + "`phase: 02-two` disagrees with the file name 01-01" + ), + "{reported:#?}" + ); + assert!( + has( + &reported, + 5, + "unmapped", + "`plan: 03` disagrees with the file name 01-01" + ), + "{reported:#?}" + ); + // A file name that gives no plan id, and a phase the roadmap lacks, import nothing. + let out = run(vec![ + (".planning/phases/01-one/1-1-PLAN.md", &text), + (".planning/phases/07-x/07-01-PLAN.md", &text), + ]); + assert!(paths(&creates(&out), "plan").is_empty()); + assert!(has( + &entries(&out, ".planning/phases/01-one/1-1-PLAN.md"), + 1, + "unmapped", + "no plan id" + )); + assert!(has( + &entries(&out, ".planning/phases/07-x/07-01-PLAN.md"), + 1, + "unmapped", + "phase 07 is no phase of ROADMAP.md" + )); +} + +#[test] +fn an_unclosed_task_element_keeps_the_tasks_before_it() { + let body = "<tasks>\n<task type=\"auto\">\n <name>Task 1: One</name>\n <action>a</action>\n <done>d</done>\n</task>\n<task type=\"auto\">\n <name>Task 2: Two</name>\n <action>never closed\n"; + let path = ".planning/phases/01-one/01-01-PLAN.md"; + let out = run(vec![(path, &plan_text("", body))]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!(paths(&creates(&out), "task"), ["v1.0/01/01-01/T1"]); + assert!( + has( + &entries(&out, path), + 16, + "unmapped", + "is not closed by </task>" + ), + "{:#?}", + entries(&out, path) + ); +} + +#[test] +fn a_task_past_max_ops_refuses_the_import() { + let task = "<task type=\"auto\">\n<action>a</action>\n<done>d</done>\n</task>\n"; + let body = task.repeat(MAX_OPS + 1); + let out = run(vec![( + ".planning/phases/01-one/01-01-PLAN.md", + &plan_text("", &body), + )]); + assert_ne!(out.exit_code, 0); + assert!(out.plan.is_none_or(|p| p.ops.is_empty())); + assert!( + out.stderr.contains(&format!("truncated at {MAX_OPS}")), + "{}", + out.stderr + ); +} + +#[test] +fn no_record_holds_a_computed_field() { + let declared = declared(); + let mut checked = 0; + for (name, security) in [ + ("taskboard", false), + ("ledger", false), + ("vault", false), + ("vault", true), + ] { + let out = import_with(name, security); + assert_eq!(out.exit_code, 0, "{name}: {}", out.stderr); + for c in creates(&out) { + for (field, value) in c.fields.as_object().expect("fields") { + let mut keys = vec![format!("{}.{field}", c.kind)]; + for block in value.as_array().into_iter().flatten() { + for member in block.as_object().into_iter().flat_map(|m| m.keys()) { + keys.push(format!("{}.{field}.{member}", c.kind)); + } + } + for key in keys { + checked += 1; + let writer = declared.get(&key).unwrap_or_else(|| { + panic!( + "{name}: {} {} writes {key}, no declared field", + c.kind, c.path + ) + }); + assert!( + matches!(writer.as_str(), "" | "harness"), + "{name}: {} {} writes {key}, whose writer is `{writer}`", + c.kind, + c.path + ); + } + } + } + } + assert!(checked > 200, "{checked}"); +} + +#[test] +fn taskboard_summary_and_deliverable_values_match_the_twin() { + let out = import_fixture("taskboard"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!( + paths(&all, "summary"), + ["v1.0/01/01-01/01-01-SUMMARY", "v1.0/01/01-02/01-02-SUMMARY"] + ); + assert_eq!( + paths(&all, "deliverable"), + [ + "v1.0/01/01-01/01-01-SUMMARY/D1", + "v1.0/01/01-02/01-02-SUMMARY/D1", + "v1.0/01/01-02/01-02-SUMMARY/D2" + ] + ); + let summary = find(&all, "summary", "v1.0/01/01-01/01-01-SUMMARY"); + assert_eq!( + (summary.title.as_str(), summary.file.as_str()), + ("The task model and add: summary", "spec/gsd/phases/01.spec") + ); + // The twin, plans.spec, exactly. + assert_eq!( + summary.fields, + json!({ + "plan": "v1.0/01/01-01", + "status": "complete", + "one_liner": "A board of plain data with `addTask`, ids counting up from 1 and never reused.", + "subsystem": "tasks", + "tags": ["node", "esm"], + "provides": ["createBoard and addTask"], + "affects": ["01-02", "persistence"], + "tech_patterns": ["a board is plain data: { tasks, nextId }"], + "requirements_completed": ["TASK-01"], + }) + ); + // A known difference (D6): the twin carries no `requires`; the block form is imported. + let summary = find(&all, "summary", "v1.0/01/01-02/01-02-SUMMARY"); + assert_eq!( + summary.fields["requires"], + json!([{"phase": "v1.0/01", "provides": "createBoard and addTask"}]) + ); + assert_eq!( + find(&all, "deliverable", "v1.0/01/01-02/01-02-SUMMARY/D1").fields, + json!({ + "summary": "v1.0/01/01-02/01-02-SUMMARY", + "description": "A task is completed by its id, and an unknown id is refused by name", + "requirement": "TASK-02", + "human_judgment": false, + "checks": [ + {"kind": "unit", "ref": "test/tasks.test.js#a task is completed by its id"}, + {"kind": "unit", "ref": "test/tasks.test.js#completing an unknown id throws"} + ], + }) + ); + assert_eq!( + find(&all, "deliverable", "v1.0/01/01-02/01-02-SUMMARY/D2").fields, + json!({ + "summary": "v1.0/01/01-02/01-02-SUMMARY", + "description": "The command line adds and completes tasks", + "human_judgment": true, + "rationale": "The output wording is a judgement a person makes at the terminal", + }) + ); + let reported = entries(&out, ".planning/phases/01-core/01-02-SUMMARY.md"); + for (line, outcome, says) in [ + (2, "redundant", "the file name gives them"), + (20, "computed", "summary.files_created is computed"), + (24, "unmapped", "a Tier 2 section"), + (35, "computed", "deliverable.checks.status is computed"), + (38, "computed", "deliverable.checks.status is computed"), + (46, "computed", "summary.duration is computed"), + ( + 47, + "unmapped", + "a harness timestamp the import does not write", + ), + (51, "redundant", "the plan's title names the summary"), + (55, "unmapped", "prose: no field holds it"), + (65, "unmapped", "git history is the collector's"), + (70, "unmapped", "a Tier 2 section"), + (78, "unmapped", "a Tier 2 section"), + (1, "mapped", "summary v1.0/01/01-02/01-02-SUMMARY"), + (29, "mapped", "deliverable v1.0/01/01-02/01-02-SUMMARY/D1"), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {outcome} {says}: {reported:#?}" + ); + } +} + +#[test] +fn vault_summary_reports_a_requires_of_plan_ids_and_its_threat_flags() { + let path = ".planning/phases/01-core/01-02-SUMMARY.md"; + let out = import_with("vault", false); + let all = creates(&out); + let summary = find(&all, "summary", "v1.0/01/01-02/01-02-SUMMARY"); + assert_eq!(summary.fields.get("requires"), None); + assert_eq!(summary.fields.get("threat_flags"), None); + let reported = entries(&out, path); + assert!( + has(&reported, 7, "unmapped", "names no `provides`"), + "{reported:#?}" + ); + assert!( + has(&reported, 45, "needs-extension", "@gsd/security"), + "{reported:#?}" + ); + // A known difference (D15): with @gsd/security, the twin carries no threat flags; the import does. + let all = creates(&import_with("vault", true)); + assert_eq!( + find(&all, "summary", "v1.0/01/01-02/01-02-SUMMARY").fields["threat_flags"], + json!([ + "threat_flag: information_disclosure | src/cli.js | the secret is an argv entry, visible in `ps` and in shell history" + ]) + ); +} + +#[test] +fn ledger_quick_plan_and_summary_match_the_twin() { + let out = import_fixture("ledger"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + let plan = find(&all, "plan", "261105-tcl"); + assert_eq!( + (plan.title.as_str(), plan.file.as_str()), + ("Show totals in a fixed-width column", "spec/gsd/quick.spec") + ); + // The twin, quick.spec: no phase. + assert_eq!( + plan.fields, + json!({ + "type": "execute", + "slug": "totals-column", + "files_modified": ["src/lib.rs", "src/main.rs", "tests/totals.rs"], + "objective": "Show totals in a fixed-width column.", + "purpose": "totals line up when a user prints several stores one under another.", + "output": "`column(cents)` in `src/lib.rs`, used by `ledger total`.", + "success_criteria": ["A total prints right-aligned in a column of fourteen"], + }) + ); + assert_eq!( + find(&all, "task", "261105-tcl/T1").fields, + json!({ + "plan": "261105-tcl", + "type": "auto", + "files": ["src/lib.rs", "src/main.rs", "tests/totals.rs"], + "action": "Add `column(cents)`: euros and cents, right-aligned in 14 characters; `ledger total` prints through it. Fold the total in an `i32` so the column's width is the value's width.", + "verify_text": "cargo test --test totals a_total_prints_in_a_column_of_fourteen", + "done": "A total prints in a column of fourteen", + }) + ); + assert_eq!( + find(&all, "truth", "261105-tcl/TR1").fields["text"], + "A total prints right-aligned in a column of fourteen" + ); + assert_eq!( + find(&all, "artifact", "261105-tcl/AR1").fields, + json!({"plan": "261105-tcl", "path": "src/lib.rs", "provides": "column", "contains": "pub fn column"}) + ); + let summary = find(&all, "summary", "261105-tcl/261105-tcl-SUMMARY"); + assert_eq!( + summary.title, + "Show totals in a fixed-width column: summary" + ); + // A known difference (D14): the twin's subsystem is `entries`; a quick summary has none, so it is filled. + assert_eq!( + summary.fields, + json!({ + "plan": "261105-tcl", + "status": "complete", + "one_liner": "`ledger total` prints its total right-aligned in a column of fourteen.", + "subsystem": "quick", + "requirements_completed": [], + }) + ); + let reported = entries( + &out, + ".planning/quick/261105-tcl-totals-column/261105-tcl-SUMMARY.md", + ); + for (line, outcome, says) in [ + (1, "filled", "a quick summary has no subsystem"), + (1, "filled", "a quick summary lists no requirements"), + (2, "redundant", "the quick plan gives them"), + (3, "redundant", "the quick plan gives them"), + ( + 28, + "unmapped", + "a section no row of the quick/* table names", + ), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {outcome} {says}: {reported:#?}" + ); + } + let reported = entries( + &out, + ".planning/quick/261105-tcl-totals-column/261105-tcl-PLAN.md", + ); + assert!( + has(&reported, 6, "computed", "plan.autonomous is computed"), + "{reported:#?}" + ); +} + +#[test] +fn a_quick_context_and_research_are_reported_tier_2() { + let dir = ".planning/quick/261201-abc-x"; + let out = run(vec![ + (&format!("{dir}/261201-abc-CONTEXT.md"), "# Context\n"), + (&format!("{dir}/261201-abc-RESEARCH.md"), "# Research\n"), + (&format!("{dir}/notes.md"), "x\n"), + ]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + for name in ["CONTEXT", "RESEARCH"] { + let reported = entries(&out, &format!("{dir}/261201-abc-{name}.md")); + assert_eq!(reported.len(), 1, "{reported:#?}"); + assert!( + has(&reported, 0, "unmapped", "a Tier 2 section"), + "{reported:#?}" + ); + } + assert!(has( + &entries(&out, &format!("{dir}/notes.md")), + 0, + "unmapped", + "no row names it" + )); +} + +/// A summary of the plan 01-01 with `front` added to its frontmatter. +fn summary_text(front: &str) -> String { + format!( + "---\nphase: 01-one\nplan: 01\nsubsystem: core\nstatus: complete\nrequirements-completed: []\n{front}---\n\n# Plan 01 Summary\n\n**It works.**\n" + ) +} + +#[test] +fn a_summary_without_its_plan_is_not_imported() { + let path = ".planning/phases/01-one/01-01-SUMMARY.md"; + let out = run(vec![(path, &summary_text(""))]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert!(paths(&creates(&out), "summary").is_empty()); + assert!(has( + &entries(&out, path), + 1, + "unmapped", + "no plan for this summary" + )); +} + +#[test] +fn a_second_plan_of_one_id_keeps_its_tasks_to_itself() { + let task = |n: u32| { + format!( + "<task type=\"auto\">\n <name>Task {n}: T</name>\n <action>a</action>\n <done>d</done>\n</task>\n" + ) + }; + let (old, one) = ( + ".planning/phases/01-old/01-01-PLAN.md", + ".planning/phases/01-one/01-01-PLAN.md", + ); + let first = plan_text("", &format!("<tasks>\n{}</tasks>\n", task(1))); + let second = plan_text("", &format!("<tasks>\n{}{}</tasks>\n", task(1), task(2))); + // Read in path order: `01-old` claims the plan id first. + let out = run(vec![(old, &first), (one, &second)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!(paths(&creates(&out), "task"), ["v1.0/01/01-01/T1"]); + let reported = entries(&out, one); + assert!( + has(&reported, 1, "unmapped", "is given twice"), + "{reported:#?}" + ); + let orphans = reported + .iter() + .filter(|(_, _, _, r)| r.contains("parent not imported (v1.0/01/01-01, given twice)")) + .count(); + assert_eq!(orphans, 2, "{reported:#?}"); + assert!( + !reported.iter().any(|(_, _, o, _)| o == "mapped"), + "{reported:#?}" + ); +} + +#[test] +fn a_heading_outside_every_element_or_under_a_summary_title_is_reported() { + let plan = ".planning/phases/01-one/01-01-PLAN.md"; + let summary = ".planning/phases/01-one/01-01-SUMMARY.md"; + let body = "# Plan 01-01\n\nIntro prose.\n\n<tasks>\n<task type=\"auto\">\n <name>Task 1: T</name>\n \ + <action>a</action>\n <done>d</done>\n</task>\n</tasks>\n\n## Notes\n\nSome prose\nover two lines.\n"; + let summary_body = format!( + "{}\n### Stray\n\nx\n\n## Accomplishments\n\n### Sub\n", + summary_text("") + ); + let out = run(vec![(plan, &plan_text("", body)), (summary, &summary_body)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!(paths(&creates(&out), "task"), ["v1.0/01/01-01/T1"]); + let reported = entries(&out, plan); + let outside: Vec<u64> = reported + .iter() + .filter(|(_, _, o, r)| o == "unmapped" && r.contains("outside every element")) + .map(|(l, ..)| *l) + .collect(); + assert_eq!(outside, [10, 12, 22, 24], "{reported:#?}"); + let reported = entries(&out, summary); + assert!( + has( + &reported, + 13, + "unmapped", + "a section no row of the NN-MM-SUMMARY.md table" + ), + "{reported:#?}" + ); + assert!(!reported.iter().any(|(l, ..)| *l == 19), "{reported:#?}"); +} + +#[test] +fn a_deliverable_and_a_requires_report_each_member_they_do_not_read() { + let path = ".planning/phases/01-one/01-01-SUMMARY.md"; + let front = "requires:\n - phase: 01-one\n provides: x\n via: y\ncoverage:\n - id: d1\n \ + description: D\n human_judgment: false\n requirement: [A-01, B-02]\n verification:\n \ + - kind: unit\n ref: t1\n command: npm test\n - plain\n - id: d2\n description: E\n \ + human_judgment: false\n verification: npm test\n"; + let out = run(vec![ + (".planning/phases/01-one/01-01-PLAN.md", &plan_text("", "")), + (path, &summary_text(front)), + ]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + let summary = find(&all, "summary", "v1.0/01/01-01/01-01-SUMMARY"); + assert_eq!( + summary.fields["requires"], + json!([{"phase": "v1.0/01", "provides": "x"}]) + ); + let d1 = find(&all, "deliverable", "v1.0/01/01-01/01-01-SUMMARY/d1"); + assert_eq!(d1.fields["checks"], json!([{"kind": "unit", "ref": "t1"}])); + assert_eq!(d1.fields.get("requirement"), None); + let reported = entries(&out, path); + for (line, says) in [ + (10, "a requires member `via` no row of the table names"), + (15, "`requirement` is not one requirement id"), + (19, "a check member `command` no row of the table names"), + (20, "a check that is not a map"), + (24, "`verification` is not a list"), + ] { + assert!( + has(&reported, line, "unmapped", says), + "{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn a_summary_writes_no_harness_timestamp() { + let path = ".planning/phases/01-one/01-01-SUMMARY.md"; + let out = run(vec![ + (".planning/phases/01-one/01-01-PLAN.md", &plan_text("", "")), + ( + path, + &summary_text("started: 2026-03-03\ncompleted: 2026-03-04\n"), + ), + ]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + let summary = find(&all, "summary", "v1.0/01/01-01/01-01-SUMMARY"); + assert_eq!( + summary.fields, + json!({"plan": "v1.0/01/01-01", "status": "complete", "one_liner": "It works.", "subsystem": "core", "requirements_completed": []}) + ); + assert_eq!(summary.title, "Do it: summary"); + let reported = entries(&out, path); + for line in [7, 8] { + assert!( + has( + &reported, + line, + "unmapped", + "a harness timestamp the import does not write" + ), + "{line}: {reported:#?}" + ); + } +} diff --git a/gsd/import/tests/preflight.rs b/gsd/import/tests/preflight.rs new file mode 100644 index 0000000000..10bc748ba0 --- /dev/null +++ b/gsd/import/tests/preflight.rs @@ -0,0 +1,636 @@ +//! What `import` refuses before it plans (ADR 0391 D4, D9, D10), and what it drops and reports, through the command in +//! process. + +mod common; + +use serde_json::{Value, json}; +use specforge_extension_sdk::PlanOp; +use specforge_extension_sdk::prelude::*; +use specforge_extension_sdk::testing::MockHost; + +use common::{fact, feed, import, manifest, payload}; +use gsd_import::kinds::{CORE_KINDS, REQUIRED, REQUIRED_MEMBERS, required}; +use gsd_import::limits::{MAX_ENTRIES, MAX_OPS}; +use gsd_import::records::{Record, Records, Source}; +use gsd_import::report::Report; + +/// A `REQUIREMENTS.md` of one v1 category holding `bullets`, each `- [ ] **<id>**: <text>`; bullet `i` (from 0) is on +/// line `6 + i`. +fn requirements(bullets: &[(&str, &str)]) -> String { + let mut text = "# Requirements\n\n## v1 Requirements\n\n### Core\n".to_string(); + for (id, words) in bullets { + text.push_str(&format!("- [ ] **{id}**: {words}\n")); + } + text +} + +fn planning(text: &str) -> Vec<Value> { + vec![fact(".planning/REQUIREMENTS.md", text)] +} + +/// `import` on an empty graph, the default manifest and `planning`. +fn run(planning: Vec<Value>) -> CommandOutput { + import( + &CommandGraph::default(), + &feed(planning, false, Some(&manifest(&["@gsd/core"]))), + ) +} + +fn created(out: &CommandOutput) -> Vec<String> { + out.plan + .as_ref() + .expect("a plan") + .ops + .iter() + .map(|op| match op { + PlanOp::Create { id, .. } => id.clone(), + other => panic!("import answers creates only, not {other:?}"), + }) + .collect() +} + +fn entries(out: &CommandOutput) -> Vec<Value> { + payload(out)["entries"].as_array().expect("entries").clone() +} + +fn refused(out: &CommandOutput, says: &str) { + assert_eq!(out.exit_code, 1, "{}", out.stdout); + assert!(out.plan.is_none(), "a refusal answers no plan"); + assert!(out.stderr.contains(says), "{says:?} not in {}", out.stderr); +} + +fn node(id: &str, kind: &str, file: &str) -> GraphNode { + GraphNode { + id: id.into(), + kind: kind.into(), + file: Some(file.into()), + ..GraphNode::default() + } +} + +#[test] +fn reimport_is_refused_naming_one_core_entity() { + let graph = CommandGraph::new( + vec![ + node("hello", "spec", "spec/hello.spec"), + node("TASK-01", "requirement", "spec/gsd/requirements.spec"), + ], + Vec::new(), + ); + let out = import( + &graph, + &feed( + planning(&requirements(&[("TASK-02", "b")])), + false, + Some(&manifest(&[])), + ), + ); + refused(&out, "requirement TASK-01 in spec/gsd/requirements.spec"); +} + +#[test] +fn reimport_refusal_ignores_an_entity_of_another_extension() { + let graph = CommandGraph::new(vec![node("hello", "spec", "spec/hello.spec")], Vec::new()); + let out = import( + &graph, + &feed( + planning(&requirements(&[("TASK-02", "b")])), + false, + Some(&manifest(&[])), + ), + ); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!(created(&out), ["TASK-02"]); +} + +#[test] +fn a_spec_root_other_than_spec_is_refused() { + let text = json!({"name": "p", "spec_root": "specs"}).to_string(); + let out = import( + &CommandGraph::default(), + &feed(planning(&requirements(&[])), false, Some(&text)), + ); + refused(&out, "the spec root 'specs'"); +} + +#[test] +fn a_spec_root_absent_is_spec() { + let text = json!({"name": "p"}).to_string(); + let out = import( + &CommandGraph::default(), + &feed( + planning(&requirements(&[("A-01", "a")])), + false, + Some(&text), + ), + ); + assert_eq!(out.exit_code, 0, "{}", out.stderr); +} + +#[test] +fn a_manifest_that_is_not_json_or_missing_is_refused() { + let out = import( + &CommandGraph::default(), + &feed(planning(&requirements(&[])), false, Some("{ not json")), + ); + refused(&out, "specforge.json is not JSON"); + let out = import( + &CommandGraph::default(), + &feed(planning(&requirements(&[])), false, None), + ); + refused(&out, "specforge.json was not read"); +} + +#[test] +fn security_is_a_text_check_of_the_manifest() { + let loaded = |extensions: &[&str]| { + let out = import( + &CommandGraph::default(), + &feed( + planning(&requirements(&[("A-01", "a")])), + false, + Some(&manifest(extensions)), + ), + ); + let security = payload(&out)["security"].clone(); + assert!( + security["check"] + .as_str() + .expect("check") + .contains("text check"), + "{security}" + ); + security["loaded"].clone() + }; + assert_eq!(loaded(&["@gsd/core", "@gsd/security"]), true); + assert_eq!( + loaded(&["@gsd/core", "@gsd/security=../security.wasm"]), + true + ); + assert_eq!(loaded(&["@gsd/core", "@gsd/securityx"]), false); + assert_eq!(loaded(&[]), false); +} + +#[test] +fn no_planning_folder_is_refused() { + refused(&run(Vec::new()), "no .planning/ at the project root"); +} + +#[test] +fn a_truncated_read_is_refused() { + let out = import( + &CommandGraph::default(), + &feed( + planning(&requirements(&[("A-01", "a")])), + true, + Some(&manifest(&[])), + ), + ); + refused(&out, &format!("truncated at {FILE_READ_MAX}")); +} + +#[test] +fn a_read_error_on_a_mapped_file_is_refused() { + for error in [ + "budget", + "too_large", + "not_utf8", + "unreadable", + "outside_project", + ] { + let failed = json!({"path": ".planning/phases/01-core/01-01-PLAN.md", "exists": true, "error": error}); + let out = run(vec![ + fact(".planning/REQUIREMENTS.md", &requirements(&[("A-01", "a")])), + failed, + ]); + refused( + &out, + &format!(".planning/phases/01-core/01-01-PLAN.md was not read ({error})"), + ); + } +} + +#[test] +fn a_read_error_on_another_file_is_reported_and_the_plan_answered() { + // The host answers a secret-looking name with a fact that holds no text (13-02). + let denied = json!({"path": ".planning/.env", "exists": true, "error": "denied"}); + let large = json!({"path": ".planning/notes/big.txt", "exists": true, "error": "too_large"}); + let out = run(vec![ + denied, + large, + fact(".planning/REQUIREMENTS.md", &requirements(&[("A-01", "a")])), + ]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!(created(&out), ["A-01"]); + let entries = entries(&out); + for (path, error) in [ + (".planning/.env", "denied"), + (".planning/notes/big.txt", "too_large"), + ] { + let entry = entries + .iter() + .find(|e| e["file"] == path) + .unwrap_or_else(|| panic!("{path} is reported")); + assert_eq!(entry["outcome"], "unmapped"); + assert!( + entry["reason"].as_str().expect("a reason").contains(error), + "{entry}" + ); + } +} + +#[test] +fn a_plan_past_max_ops_is_truncated() { + let ids: Vec<String> = (1..=MAX_OPS + 1).map(|n| format!("A-{n:04}")).collect(); + let at_cap: Vec<(&str, &str)> = ids[..MAX_OPS].iter().map(|id| (id.as_str(), "x")).collect(); + let out = run(planning(&requirements(&at_cap))); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!(created(&out).len(), MAX_OPS); + + let past: Vec<(&str, &str)> = ids.iter().map(|id| (id.as_str(), "x")).collect(); + refused( + &run(planning(&requirements(&past))), + &format!("truncated at {MAX_OPS}"), + ); +} + +#[test] +fn a_report_past_max_entries_is_truncated() { + let mut files: Vec<Value> = (0..=MAX_ENTRIES) + .map(|n| fact(&format!(".planning/notes/{n:05}.txt"), "")) + .collect(); + files.push(fact(".planning/REQUIREMENTS.md", &requirements(&[]))); + refused(&run(files), &format!("truncated at {MAX_ENTRIES}")); +} + +#[test] +fn a_refused_id_is_reported_at_its_line_and_the_rest_imported() { + let bad = [ + "TASK 01", + "A/B-01", + "..-01", + "T\u{7}-01", + "TASK-\u{661}", + "task-01", + ]; + let mut bullets: Vec<(&str, &str)> = bad.iter().map(|id| (*id, "words")).collect(); + bullets.push(("TASK-02", "kept")); + let out = run(planning(&requirements(&bullets))); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!(created(&out), ["TASK-02"]); + let entries = entries(&out); + for (i, _) in bad.iter().enumerate() { + let line = 6 + i; + let entry = entries + .iter() + .find(|e| e["line"] == line && e["outcome"] == "unmapped") + .unwrap_or_else(|| panic!("line {line} is reported: {entries:#?}")); + let reason = entry["reason"].as_str().expect("a reason"); + assert!(reason.contains("not an id a requirement takes"), "{reason}"); + assert!( + !reason.contains('\u{7}'), + "a control character is escaped: {reason:?}" + ); + } +} + +#[test] +fn a_second_record_of_one_id_is_dropped_and_reported() { + let out = run(planning(&requirements(&[ + ("TASK-01", "first"), + ("TASK-01", "second"), + ]))); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!(created(&out), ["TASK-01"]); + let entries = entries(&out); + assert!( + entries.iter().any(|e| e["line"] == 7 + && e["reason"] + .as_str() + .expect("a reason") + .contains("given twice (first at .planning/REQUIREMENTS.md:6)")), + "{entries:#?}" + ); +} + +/// A record of `kind` holding each of its required fields. +fn record(kind: &'static str, id: &str, refs: &[&str], line: usize) -> Record { + Record { + kind, + id: id.into(), + title: id.into(), + file: "spec/gsd/x.spec".into(), + fields: required(kind) + .iter() + .map(|f| (f.to_string(), json!("x"))) + .collect(), + refs: refs.iter().map(|r| r.to_string()).collect(), + links: Vec::new(), + source: Source { + file: ".planning/x.md".into(), + line, + }, + } +} + +#[test] +fn a_reference_to_nothing_drops_the_record_and_its_children() { + let mut report = Report::default(); + let mut records = Records::default(); + // The plan names a phase nobody creates; its task names the plan; a requirement names a graph node. + records.add(record("plan", "09-01", &["09"], 1), &mut report); + records.add(record("task", "T1", &["09-01"], 2), &mut report); + records.add(record("truth", "TR1", &["T1"], 3), &mut report); + records.add(record("requirement", "A-01", &["outside"], 4), &mut report); + // An id the graph already holds is the host's duplicate: dropped too. + records.add(record("requirement", "B-01", &[], 5), &mut report); + let graph = CommandGraph::new( + vec![ + node("B-01", "spec_item", "spec/x.spec"), + node("outside", "spec_item", "spec/x.spec"), + ], + Vec::new(), + ); + let plan = PlanBuilder::new(Default::default(), Default::default()); + let (plan, counts, _) = + gsd_import::emit::emit(&records, &graph, plan, &mut report).expect("not refused"); + let ids: Vec<String> = plan + .finish() + .ops + .iter() + .map(|op| match op { + PlanOp::Create { id, .. } => id.clone(), + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(ids, ["A-01"]); + assert_eq!(counts.get("requirement"), Some(&1)); + let reason = |line: usize| { + report + .entries() + .into_iter() + .find(|e| e.line == Some(line)) + .map(|e| e.reason.clone()) + .unwrap_or_default() + }; + assert!( + reason(1).contains("names 09, which neither the import nor the graph holds"), + "{}", + reason(1) + ); + assert!( + reason(2).contains("parent not imported (09-01)"), + "{}", + reason(2) + ); + assert!( + reason(3).contains("parent not imported (T1)"), + "{}", + reason(3) + ); + assert!( + reason(5).contains("the graph already holds spec_item B-01"), + "{}", + reason(5) + ); +} + +#[test] +fn the_plan_creates_kinds_in_order_and_ids_within_a_kind() { + let mut report = Report::default(); + let mut records = Records::default(); + records.add(record("task", "T2", &["01-01"], 1), &mut report); + records.add(record("task", "T1", &["01-01"], 2), &mut report); + records.add(record("plan", "01-01", &["01"], 3), &mut report); + records.add(record("phase", "01", &["v1.0"], 4), &mut report); + records.add(record("milestone", "v1.0", &[], 5), &mut report); + records.add(record("requirement", "A-01", &[], 6), &mut report); + let plan = PlanBuilder::new(Default::default(), Default::default()); + let (plan, _, _) = + gsd_import::emit::emit(&records, &CommandGraph::default(), plan, &mut report) + .expect("not refused"); + let ids: Vec<String> = plan + .finish() + .ops + .iter() + .map(|op| match op { + PlanOp::Create { id, .. } => id.clone(), + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(ids, ["v1.0", "A-01", "01", "01-01", "T1", "T2"]); +} + +#[test] +fn core_kinds_are_what_gsd_core_declares() { + let host = MockHost::new(gsd_core::build()); + let entities: Value = + serde_json::from_str(&host.describe_json("entities").expect("the entities")) + .expect("describe answers JSON"); + let mut declared: Vec<&str> = entities["items"] + .as_array() + .expect("items") + .iter() + .map(|kind| kind["name"].as_str().expect("a name")) + .collect(); + declared.sort_unstable(); + assert_eq!(declared, CORE_KINDS); +} + +/// The ids of a plan's creates, in order. +fn create_ids(plan: PlanBuilder) -> Vec<String> { + plan.finish() + .ops + .iter() + .map(|op| match op { + PlanOp::Create { id, .. } => id.clone(), + other => panic!("{other:?}"), + }) + .collect() +} + +#[test] +fn required_fields_are_what_the_kinds_declare() { + let mut declared: Vec<(String, Vec<String>)> = Vec::new(); + for build in [gsd_core::build(), gsd_security::build()] { + let entities: Value = serde_json::from_str( + &MockHost::new(build) + .describe_json("entities") + .expect("the entities"), + ) + .expect("describe answers JSON"); + for kind in entities["items"].as_array().expect("items") { + let fields: Vec<String> = kind["fields"] + .as_array() + .expect("fields") + .iter() + .filter(|f| { + f["required"] == true + && !matches!(f["writer"].as_str(), Some("computed" | "harness")) + }) + .map(|f| f["name"].as_str().expect("a name").to_string()) + .collect(); + if !fields.is_empty() { + declared.push((kind["name"].as_str().expect("a name").to_string(), fields)); + } + } + } + let listed: Vec<(String, Vec<String>)> = REQUIRED + .iter() + .map(|(k, f)| (k.to_string(), f.iter().map(|f| f.to_string()).collect())) + .collect(); + assert_eq!(listed, declared); +} + +#[test] +fn required_members_are_what_the_kinds_declare() { + let author = |f: &Value| !matches!(f["writer"].as_str(), Some("computed" | "harness")); + let mut declared: Vec<(String, String, Vec<String>)> = Vec::new(); + for build in [gsd_core::build(), gsd_security::build()] { + let entities: Value = serde_json::from_str( + &MockHost::new(build) + .describe_json("entities") + .expect("the entities"), + ) + .expect("describe answers JSON"); + for kind in entities["items"].as_array().expect("items") { + for field in kind["fields"].as_array().expect("fields") { + let members: Vec<String> = field["members"] + .as_array() + .into_iter() + .flatten() + .filter(|m| m["required"] == true && author(m)) + .map(|m| m["name"].as_str().expect("a name").to_string()) + .collect(); + if author(field) && !members.is_empty() { + declared.push(( + kind["name"].as_str().expect("a name").to_string(), + field["name"].as_str().expect("a name").to_string(), + members, + )); + } + } + } + } + let listed: Vec<(String, String, Vec<String>)> = REQUIRED_MEMBERS + .iter() + .map(|(k, b, m)| { + ( + k.to_string(), + b.to_string(), + m.iter().map(|m| m.to_string()).collect(), + ) + }) + .collect(); + assert_eq!(listed, declared); +} + +#[test] +fn a_record_missing_a_required_field_is_dropped_with_its_children() { + let mut report = Report::default(); + let mut records = Records::default(); + let mut phase = record("phase", "v1.0/01", &["v1.0"], 2); + phase.fields.remove("goal"); + records.add(record("milestone", "v1.0", &[], 1), &mut report); + records.add(phase, &mut report); + records.add( + record("plan", "v1.0/01/01-01", &["v1.0/01"], 3), + &mut report, + ); + let plan = PlanBuilder::new(Default::default(), Default::default()); + let (plan, _, _) = + gsd_import::emit::emit(&records, &CommandGraph::default(), plan, &mut report) + .expect("not refused"); + assert_eq!(create_ids(plan), ["v1.0"]); + let reasons: Vec<(Option<usize>, String)> = report + .entries() + .into_iter() + .map(|e| (e.line, e.reason.clone())) + .collect(); + assert!( + reasons.contains(&( + Some(2), + "phase v1.0/01: required goal has no source: not imported".to_string() + )), + "{reasons:#?}" + ); + assert!( + reasons.contains(&( + Some(3), + "plan v1.0/01/01-01: parent not imported (v1.0/01): not imported".to_string() + )), + "{reasons:#?}" + ); +} + +#[test] +fn a_scoped_record_is_created_with_its_own_id() { + let mut report = Report::default(); + let mut records = Records::default(); + records.add(record("milestone", "v1.0", &[], 1), &mut report); + records.add(record("phase", "v1.0/02.1", &["v1.0"], 2), &mut report); + records.add(record("phase", "v1.0/0 2", &["v1.0"], 3), &mut report); + let plan = PlanBuilder::new(Default::default(), Default::default()); + let (plan, _, _) = + gsd_import::emit::emit(&records, &CommandGraph::default(), plan, &mut report) + .expect("not refused"); + assert_eq!(create_ids(plan), ["v1.0", "02.1"]); + assert!( + report + .entries() + .iter() + .any(|e| e.line == Some(3) && e.reason.contains("not an id a phase takes")) + ); +} + +#[test] +fn a_record_holding_text_no_spec_file_holds_is_dropped_with_its_children() { + let mut report = Report::default(); + let mut records = Records::default(); + records.add(record("milestone", "v1.0", &[], 1), &mut report); + let mut phase = record("phase", "v1.0/01", &["v1.0"], 2); + phase.title = "Core\u{1b}[31m".into(); + records.add(phase, &mut report); + records.add( + record("plan", "v1.0/01/01-01", &["v1.0/01"], 3), + &mut report, + ); + let mut bidi = record("requirement", "A-01", &[], 4); + bidi.fields + .insert("text".into(), json!(["fine", {"note": "x\u{202e}y"}])); + records.add(bidi, &mut report); + // A tab and a line break, CRLF included, are a .spec file's own. + let mut lines = record("requirement", "A-02", &[], 5); + lines.title = "a\tb".into(); + lines + .fields + .insert("text".into(), json!("one\r\ntwo\nthree")); + records.add(lines, &mut report); + let plan = PlanBuilder::new(Default::default(), Default::default()); + let (plan, _, _) = + gsd_import::emit::emit(&records, &CommandGraph::default(), plan, &mut report) + .expect("not refused"); + assert_eq!(create_ids(plan), ["v1.0", "A-02"]); + let reason = |line: usize| { + report + .entries() + .into_iter() + .find(|e| e.line == Some(line)) + .map(|e| e.reason.clone()) + .unwrap_or_default() + }; + let unwritable = "holds a control or bidirectional character, which no .spec file holds"; + assert_eq!( + reason(2), + format!("phase v1.0/01: its title {unwritable}: not imported") + ); + assert!( + reason(3).contains("parent not imported (v1.0/01)"), + "{}", + reason(3) + ); + assert_eq!( + reason(4), + format!("requirement A-01: its text {unwritable}: not imported") + ); +} diff --git a/gsd/import/tests/roadmap.rs b/gsd/import/tests/roadmap.rs new file mode 100644 index 0000000000..5e750bbb48 --- /dev/null +++ b/gsd/import/tests/roadmap.rs @@ -0,0 +1,408 @@ +//! `ROADMAP.md` in its milestone-grouped form, and hostile roadmaps, through the command in process. + +mod common; + +use serde_json::{Value, json}; +use specforge_extension_sdk::PlanOp; +use specforge_extension_sdk::prelude::*; + +use common::{fact, feed, import, manifest, payload}; +use gsd_import::limits::MAX_OPS; +use gsd_import::read::roadmap; +use gsd_import::records::Records; +use gsd_import::report::Report; + +/// GSD's milestone-grouped roadmap (gsd-core templates/roadmap.md, "Milestone-Grouped Roadmap"). +const GROUPED: &str = "# Roadmap: Shop + +## Milestones + +- ✅ **v1.0 MVP** - Phases 1-2 (shipped 2026-01-10) +- 🚧 **v1.1 Search** - Phase 3 (in progress) +- 📋 **v2.0 Teams** - Phase 4 (planned) + +## Phases + +<details> +<summary>✅ v1.0 MVP (Phases 1-2) - SHIPPED 2026-01-10</summary> + +### Phase 1: Catalog +**Goal**: Products can be listed +**Success Criteria** (what must be TRUE): + 1. A product shows its price +**Plans**: 1 plan + +Plans: +- [x] 01-01: The `catalog` model + +### Phase 2: Cart +**Goal**: A cart holds products +**Depends on**: Phase 1 +**Success Criteria** (what must be TRUE): + 1. A cart sums its products +**Plans**: 1 plan + +</details> + +### 🚧 v1.1 Search (In Progress) + +**Milestone Goal:** Products can be found by name + +#### Phase 3: Search +**Goal**: A word finds its products +**Depends on**: Phase 2 +**Success Criteria** (what must be TRUE): + 1. A search for `mug` lists the mugs + +### 📋 v2.0 Teams (Planned) + +**Milestone Goal:** A team shares one shop + +#### Phase 4: Teams +**Goal**: A team has members +**Depends on**: Phase 3 +**Success Criteria** (what must be TRUE): + 1. An owner invites a member + +## Progress + +| Phase | Milestone | Plans Complete | Status | Completed | +|-------|-----------|----------------|--------|-----------| +| 1. Catalog | v1.0 | 1/1 | Complete | 2026-01-10 | +"; + +fn run(files: Vec<Value>) -> CommandOutput { + import( + &CommandGraph::default(), + &feed(files, false, Some(&manifest(&["@gsd/core"]))), + ) +} + +/// `(kind, id, file, fields)` of each create. +fn creates(out: &CommandOutput) -> Vec<(String, String, String, Value)> { + out.plan + .as_ref() + .expect("a plan") + .ops + .iter() + .map(|op| match op { + PlanOp::Create { + kind, + id, + file, + fields, + .. + } => (kind.clone(), id.clone(), file.clone(), json!(fields)), + other => panic!("{other:?}"), + }) + .collect() +} + +/// `(line, section, outcome, reason)` of each entry about `ROADMAP.md`. +fn entries(out: &CommandOutput) -> Vec<(u64, String, String, String)> { + payload(out)["entries"] + .as_array() + .expect("entries") + .iter() + .filter(|e| e["file"] == ".planning/ROADMAP.md") + .filter_map(|e| { + Some(( + e["line"].as_u64()?, + e["section"].as_str()?.to_string(), + e["outcome"].as_str()?.to_string(), + e["reason"].as_str()?.to_string(), + )) + }) + .collect() +} + +#[test] +fn roadmap_grouped_gives_one_milestone_per_version_and_scopes_each_phase() { + let out = run(vec![fact(".planning/ROADMAP.md", GROUPED)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let creates = creates(&out); + let milestones: Vec<(&str, &str, &Value)> = creates + .iter() + .filter(|(k, ..)| k == "milestone") + .map(|(_, id, file, fields)| (id.as_str(), file.as_str(), fields)) + .collect(); + assert_eq!( + milestones, + [ + ("v1.0", "spec/gsd/v1.0.spec", &json!({})), + ( + "v1.1", + "spec/gsd/v1.1.spec", + &json!({"goal": "Products can be found by name"}) + ), + ( + "v2.0", + "spec/gsd/v2.0.spec", + &json!({"goal": "A team shares one shop"}) + ), + ] + ); + let phases: Vec<(&str, &str, Value, Value)> = creates + .iter() + .filter(|(k, ..)| k == "phase") + .map(|(_, id, file, f)| { + ( + id.as_str(), + file.as_str(), + f["milestone"].clone(), + f["depends_on"].clone(), + ) + }) + .collect(); + assert_eq!( + phases, + [ + ("01", "spec/gsd/v1.0.spec", json!("v1.0"), Value::Null), + ( + "02", + "spec/gsd/v1.0.spec", + json!("v1.0"), + json!(["v1.0/01"]) + ), + ( + "03", + "spec/gsd/v1.1.spec", + json!("v1.1"), + json!(["v1.0/02"]) + ), + ( + "04", + "spec/gsd/v2.0.spec", + json!("v2.0"), + json!(["v1.1/03"]) + ), + ] + ); + let search = creates + .iter() + .find(|(k, id, ..)| k == "phase" && id == "03") + .map(|(.., f)| f.clone()) + .expect("phase 03"); + assert_eq!(search["slug"], "search"); + assert_eq!( + search["success_criteria"], + json!(["A search for `mug` lists the mugs"]) + ); + let entries = entries(&out); + let status: Vec<&(u64, String, String, String)> = entries + .iter() + .filter(|(_, _, o, r)| o == "computed" && r.starts_with("milestone.state")) + .collect(); + assert_eq!(status.len(), 1, "the status is reported once: {entries:#?}"); + assert_eq!(status[0].0, 5); + assert!( + !payload(&out)["entries"] + .as_array() + .expect("entries") + .iter() + .any(|e| e["reason"] + .as_str() + .is_some_and(|r| r.contains("(no milestone)"))), + ); +} + +#[test] +fn roadmap_grouped_gives_its_plan_titles_to_the_plan_reader() { + let mut records = Records::default(); + let mut report = Report::default(); + let read = roadmap::read( + ".planning/ROADMAP.md", + GROUPED, + &[], + &mut records, + &mut report, + ); + assert_eq!( + read.plan_titles.into_iter().collect::<Vec<_>>(), + [("01-01".to_string(), "The catalog model".to_string())] + ); + assert_eq!(read.phases.get("03").map(String::as_str), Some("v1.1/03")); +} + +#[test] +fn roadmap_hostile_headings_and_references_are_reported_at_their_lines() { + let text = "# Roadmap: X + +### Phase 1: One +**Goal**: g +**Depends on**: Phase 99 +**Requirements**: [NOPE-01] +**Success Criteria**: + 1. c + +### Phase 1.2.3: Bad + +### Phase: Nameless + +### Phase 7 Seven + +### Phase 8: No goal +**Success Criteria**: + 1. c +"; + let out = run(vec![fact(".planning/ROADMAP.md", text)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let phases: Vec<(String, Value)> = creates(&out) + .into_iter() + .filter(|(k, ..)| k == "phase") + .map(|(_, id, _, f)| (id, f)) + .collect(); + assert_eq!( + phases, + [( + "01".to_string(), + json!({"milestone": "v1.0", "slug": "one", "goal": "g", "success_criteria": ["c"]}) + )] + ); + let entries = entries(&out); + let has = |line: u64, says: &str| { + assert!( + entries + .iter() + .any(|(l, _, o, r)| *l == line && o == "unmapped" && r.contains(says)), + "{line} {says}: {entries:#?}" + ); + }; + has(5, "`Phase 99`, which is no phase of the roadmap"); + has(6, "NOPE-01, which REQUIREMENTS.md does not define"); + has(10, "`1.2.3` is not a phase number"); + has(12, "with no number"); + has(14, "neither form"); + has(16, "required goal has no source"); +} + +#[test] +fn roadmap_grouped_version_heading_naming_no_version_is_reported_at_its_line() { + let text = GROUPED + .replace("### 🚧 v1.1 Search", "### 🚧 v1.1.x Search") + .replace("<summary>✅ v1.0 MVP", "<summary>✅ v1.0a MVP"); + let out = run(vec![fact(".planning/ROADMAP.md", &text)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let phases: Vec<String> = creates(&out) + .into_iter() + .filter(|(k, ..)| k == "phase") + .map(|(_, id, ..)| id) + .collect(); + // Phases 1 to 3 stand in no milestone; phase 4 depends on phase 3, which the roadmap does not hold. + assert_eq!(phases, ["04"]); + let entries = entries(&out); + for (line, says) in [ + ( + 12, + "`v1.0a` names no version vX.Y: the phases under it are not imported", + ), + ( + 32, + "`v1.1.x` names no version vX.Y: the phases under it are not imported", + ), + (36, "a phase outside any milestone's heading"), + ] { + assert!( + entries + .iter() + .any(|(l, _, o, r)| *l == line && o == "unmapped" && r.contains(says)), + "{line} {says}: {entries:#?}" + ); + } +} + +#[test] +fn roadmap_any_title_and_an_unknown_section_keep_every_phase() { + let text = "# Project Roadmap + +### Phase 1: One +**Goal**: g +**Success Criteria**: + 1. c + +## Roadmap Notes + +Some notes. + +### Phase 2: Two +**Goal**: h +**Success Criteria**: + 1. d +"; + let out = run(vec![fact(".planning/ROADMAP.md", text)]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let phases: Vec<String> = creates(&out) + .into_iter() + .filter(|(k, ..)| k == "phase") + .map(|(_, id, ..)| id) + .collect(); + assert_eq!(phases, ["01", "02"]); + let entries = entries(&out); + assert!( + entries + .iter() + .any(|(l, _, o, r)| *l == 1 && o == "redundant" && r.contains("# Name")), + "{entries:#?}" + ); + assert!( + entries + .iter() + .any(|(l, _, o, r)| *l == 8 && o == "unmapped" && r.contains("no row")), + "{entries:#?}" + ); +} + +#[test] +fn roadmap_past_max_ops_is_truncated() { + let mut text = "# Roadmap: Big\n\n".to_string(); + for n in 1..=9_000 { + text.push_str(&format!( + "### Phase {n}: P{n}\n**Goal**: g\n**Success Criteria**:\n 1. c\n\n" + )); + } + let out = run(vec![fact(".planning/ROADMAP.md", &text)]); + assert_eq!(out.exit_code, 1, "{}", out.stdout); + assert!(out.plan.is_none()); + assert!( + out.stderr.contains(&format!("truncated at {MAX_OPS}")), + "{}", + out.stderr + ); +} + +#[test] +fn roadmap_wins_over_a_traceability_row_that_disagrees() { + let requirements = "# Requirements\n\n## v1 Requirements\n\n### Core\n- [ ] **A-01**: one\n- [ ] **A-02**: two\n\n## Traceability\n\n| Requirement | Phase | Status |\n|---|---|---|\n| A-01 | Phase 2 | Pending |\n| A-02 | Phase 1 | Pending |\n"; + let road = "# Roadmap: X\n\n### Phase 1: One\n**Goal**: g\n**Requirements**: [A-01, A-02]\n**Success Criteria**:\n 1. c\n"; + let out = run(vec![ + fact(".planning/REQUIREMENTS.md", requirements), + fact(".planning/ROADMAP.md", road), + ]); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let phase = creates(&out) + .into_iter() + .find(|(k, ..)| k == "phase") + .map(|(.., f)| f) + .expect("phase 01"); + assert_eq!(phase["requirements"], json!(["A-01", "A-02"])); + let mismatches: Vec<(Value, String)> = payload(&out)["entries"] + .as_array() + .expect("entries") + .iter() + .filter(|e| e["section"] == "Traceability" && e["line"].is_u64() && e["line"] != 9) + .map(|e| { + ( + e["line"].clone(), + e["reason"].as_str().expect("a reason").to_string(), + ) + }) + .collect(); + assert_eq!( + mismatches, + [( + json!(13), + "Traceability puts A-01 in `Phase 2`, the roadmap's **Requirements** in phase 01: the roadmap wins" + .to_string() + )] + ); +} diff --git a/gsd/import/tests/security.rs b/gsd/import/tests/security.rs new file mode 100644 index 0000000000..b8879a95da --- /dev/null +++ b/gsd/import/tests/security.rs @@ -0,0 +1,466 @@ +//! A plan's `<threat_model>` through the command in process: `@gsd/security`'s trust boundaries and threats when the +//! manifest loads it, against the vault twin's `plans.spec`; one needs-extension entry per element when it does not. +//! +//! Then `01-SECURITY.md`, against the twin's `security.spec`: the audit, the statuses it records, its accepted risk and +//! its audit run. +//! +//! Known differences from the twin (13-RESEARCH D5, D11-D13): a boundary's title is its `Boundary` cell and a threat's +//! its `Component` (the twin's titles are hand-made); `data_crossing` and `status` come from `SECURITY.md`, never from +//! the plan, and only where a row names the entity: the twin's `files`, `evidence` and three more statuses have no +//! `.planning` source (D11); the audit's `asvs_level` and `created`, which the twin omits, are carried, and the run's +//! `at` is the heading's date at midnight with no `run_by` (D12); `01-02/TB1.data_crossing` is carried (D13). + +mod common; + +use serde_json::{Value, json}; +use specforge_extension_sdk::prelude::*; + +use common::{ + creates, entries, fact, feed, find, fixture, fixture_manifest, has, import, import_with, + manifest, paths, planning_facts, +}; +use gsd_import::limits::MAX_OPS; + +const SECURITY: &str = ".planning/phases/01-core/01-SECURITY.md"; + +/// The threat statuses `01-SECURITY.md` records: a row matching the threat's id and component. +const STATUSES: &[(&str, &str)] = &[ + ("v1.0/01/01-01/T-01-01", "closed"), + ("v1.0/01/01-02/T-01-02", "open"), + ("v1.0/01/01-02/T-01-03", "closed"), +]; + +#[test] +fn vault_threat_models_match_the_twin_with_security_loaded() { + let out = import_with("vault", true); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!( + paths(&all, "trust_boundary"), + ["v1.0/01/01-01/TB1", "v1.0/01/01-02/TB1"] + ); + // `data_crossing` is SECURITY.md's; the twin lacks 01-02's (D13). + for (path, boundary, description, crossing) in [ + ( + "v1.0/01/01-01/TB1", + "process → vault.bin", + "the sealed file is on a disk other users can read and write", + "encrypted secrets", + ), + ( + "v1.0/01/01-02/TB1", + "shell → process", + "the secret is typed as an argument and the key is an environment variable", + "secrets and the key, in the clear", + ), + ] { + let tb = find(&all, "trust_boundary", path); + let plan = path.rsplit_once('/').map(|(p, _)| p); + assert_eq!( + tb.fields, + json!({ + "plan": plan, + "boundary": boundary, + "description": description, + "data_crossing": crossing, + }) + ); + assert_eq!(tb.title, boundary); + } + let mut threats = paths(&all, "threat"); + threats.sort_unstable(); + assert_eq!( + threats, + [ + "v1.0/01/01-01/T-01-01", + "v1.0/01/01-01/T-01-02", + "v1.0/01/01-01/T-01-SC", + "v1.0/01/01-02/T-01-02", + "v1.0/01/01-02/T-01-03", + "v1.0/01/01-02/T-01-SC", + ] + ); + let supply = ( + "tampering", + "npm/pip/cargo installs", + "high", + "mitigate", + "package-legitimacy gate + blocking human checkpoint for [ASSUMED]/[SUS]", + ); + for (path, (category, component, severity, disposition, mitigation)) in [ + ( + "v1.0/01/01-01/T-01-01", + ( + "information_disclosure", + "src/vault.js seal", + "high", + "mitigate", + "AES-256-GCM under a key that never reaches the disk", + ), + ), + ( + "v1.0/01/01-01/T-01-02", + ( + "tampering", + "src/vault.js open", + "high", + "mitigate", + "the GCM auth tag is verified; a tampered file throws", + ), + ), + ("v1.0/01/01-01/T-01-SC", supply), + ( + "v1.0/01/01-02/T-01-02", + ( + "information_disclosure", + "src/cli.js argv", + "high", + "mitigate", + "accept the secret on stdin instead of argv", + ), + ), + ( + "v1.0/01/01-02/T-01-03", + ( + "information_disclosure", + "src/cli.js list", + "low", + "accept", + "list prints names only, never values", + ), + ), + ("v1.0/01/01-02/T-01-SC", supply), + ] { + let threat = find(&all, "threat", path); + let plan = path.rsplit_once('/').map(|(p, _)| p); + let mut want = json!({ + "plan": plan, + "category": category, + "component": component, + "severity": severity, + "disposition": disposition, + "mitigation": mitigation, + }); + // The status is SECURITY.md's, set only where a row names the threat's id and component. + if let Some(status) = STATUSES.iter().find(|(p, _)| *p == path).map(|(_, s)| *s) { + want["status"] = json!(status); + } + assert_eq!(threat.fields, want, "{path}"); + assert_eq!(threat.title, component); + } +} + +#[test] +fn vault_threat_models_need_the_extension_without_it() { + let out = import_with("vault", false); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert!(paths(&all, "trust_boundary").is_empty()); + assert!(paths(&all, "threat").is_empty()); + for (file, line) in [ + (".planning/phases/01-core/01-01-PLAN.md", 56), + (".planning/phases/01-core/01-02-PLAN.md", 48), + ] { + let reported = entries(&out, file); + let needs: Vec<_> = reported + .iter() + .filter(|(_, s, _, _)| s == "<threat_model>") + .collect(); + assert_eq!(needs.len(), 1, "{reported:#?}"); + assert!( + has(&reported, line, "needs-extension", "@gsd/security"), + "{reported:#?}" + ); + } +} + +/// The import of a roadmap of phase 1 and the plan 01-01 whose body is `body`, `@gsd/security` loaded. +fn secure(body: &str) -> CommandOutput { + let road = "# Roadmap: X\n\n### Phase 1: One\n**Goal**: g\n**Success Criteria**:\n 1. c\n"; + let plan = format!( + "---\ntype: execute\nfiles_modified: [a.js]\n---\n\n<objective>\nDo it.\n</objective>\n\n{body}" + ); + let facts = vec![fact(".planning/ROADMAP.md", road), fact(PLAN, &plan)]; + import( + &CommandGraph::default(), + &feed( + facts, + false, + Some(&manifest(&["@gsd/core", "@gsd/security"])), + ), + ) +} + +const PLAN: &str = ".planning/phases/01-one/01-01-PLAN.md"; + +#[test] +fn a_hostile_register_reports_each_row_it_refuses() { + // The body starts at line 10: the register's header at 13, its rows from 15, the other table at 23. + let body = "<threat_model>\n## STRIDE Threat Register\n\n\ + | Threat ID | Category | Component | Severity | Disposition | Mitigation Plan | Owner |\n\ + |---|---|---|---|---|---|---|\n\ + | T 01 | S | a | high | mitigate | m | x |\n\ + | T-01-02 | X | b | high | mitigate | m | x |\n\ + | T-01-03 | Denial of service | c | High | accept | m | x |\n\ + | T-01-03 | E | d | low | transfer | m | x |\n\ + | T-01-04 | S | e | severe | mitigate | m | x |\n\ + \n## Other\n\n| A |\n|---|\n| b |\n</threat_model>\n"; + let out = secure(body); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!(paths(&all, "threat"), ["v1.0/01/01-01/T-01-03"]); + assert_eq!( + find(&all, "threat", "v1.0/01/01-01/T-01-03").fields, + json!({ + "plan": "v1.0/01/01-01", + "category": "denial_of_service", + "component": "c", + "severity": "high", + "disposition": "accept", + "mitigation": "m", + }) + ); + let reported = entries(&out, PLAN); + for (line, says) in [ + (13, "a column `Owner`"), + (15, "the Threat ID `T 01`"), + (16, "the Category `X`"), + (18, "is given twice"), + (19, "the Severity `severe`"), + (23, "a table no row"), + ] { + assert!( + has(&reported, line, "unmapped", says), + "{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn a_register_past_max_ops_refuses_the_import() { + let rows: String = (1..=10_001) + .map(|n| format!("| T-{n} | S | c | low | accept | m |\n")) + .collect(); + let body = format!( + "<threat_model>\n## STRIDE Threat Register\n\n\ + | Threat ID | Category | Component | Severity | Disposition | Mitigation Plan |\n\ + |---|---|---|---|---|---|\n{rows}</threat_model>\n" + ); + let out = secure(&body); + assert_ne!(out.exit_code, 0); + assert!(out.plan.is_none_or(|p| p.ops.is_empty())); + assert!( + out.stderr.contains(&format!("truncated at {MAX_OPS}")), + "{}", + out.stderr + ); +} + +/// The paths of the threats of `out` whose status is `status` (`Value::Null`: none). +fn with_status(out: &CommandOutput, status: Value) -> Vec<String> { + let mut found: Vec<String> = creates(out) + .into_iter() + .filter(|c| c.kind == "threat" && c.fields["status"] == status) + .map(|c| c.path) + .collect(); + found.sort_unstable(); + found +} + +#[test] +fn vault_closes_exactly_two_threats() { + let out = import_with("vault", true); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!( + with_status(&out, json!("closed")), + ["v1.0/01/01-01/T-01-01", "v1.0/01/01-02/T-01-03"] + ); + assert_eq!(with_status(&out, json!("open")), ["v1.0/01/01-02/T-01-02"]); + // No row names these by id and component: no status is invented (D11). + assert_eq!( + with_status(&out, Value::Null), + [ + "v1.0/01/01-01/T-01-02", + "v1.0/01/01-01/T-01-SC", + "v1.0/01/01-02/T-01-SC" + ] + ); + let reported = entries(&out, SECURITY); + for (line, says) in [ + (30, "threat v1.0/01/01-01/T-01-01: status closed"), + (31, "threat v1.0/01/01-02/T-01-02: status open"), + (32, "threat v1.0/01/01-02/T-01-03: status closed"), + (21, "trust_boundary v1.0/01/01-01/TB1: data_crossing"), + (22, "trust_boundary v1.0/01/01-02/TB1: data_crossing"), + ] { + assert!( + has(&reported, line, "mapped", says), + "{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn vault_security_audit_matches_the_twin() { + let out = import_with("vault", true); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + let audit = find(&all, "security_audit", "v1.0/01/01-SECURITY"); + assert_eq!( + audit.fields, + json!({ "phase": "v1.0/01", "asvs_level": 1, "created": "2026-10-30T00:00:00Z" }) + ); + assert_eq!(audit.file, "spec/gsd/phases/01.spec"); + assert_eq!(paths(&all, "accepted_risk"), ["v1.0/01/01-SECURITY/AR1"]); + assert_eq!( + find(&all, "accepted_risk", "v1.0/01/01-SECURITY/AR1").fields, + json!({ + "audit": "v1.0/01/01-SECURITY", + "threat": "v1.0/01/01-02/T-01-03", + "rationale": "the names are not secret; the values are never printed", + "accepted_by": "maintainer", + "at": "2026-10-30", + }) + ); + assert_eq!(paths(&all, "audit_run"), ["v1.0/01/01-SECURITY/AU1"]); + assert_eq!( + find(&all, "audit_run", "v1.0/01/01-SECURITY/AU1").fields, + json!({ + "audit": "v1.0/01/01-SECURITY", + "at": "2026-10-29T00:00:00Z", + "total": 3, + "closed": 1, + "open": 2, + }) + ); + let reported = entries(&out, SECURITY); + for (line, outcome, says) in [ + (2, "redundant", "the file name gives the phase"), + (3, "redundant", "the file name gives the phase"), + (4, "computed", "security_audit.status is computed"), + (6, "computed", "security_audit.threats_open is computed"), + (8, "filled", "the frontmatter gives a date only"), + (11, "mapped", "security_audit v1.0/01/01-SECURITY"), + (13, "ignored", "the template's instruction"), + (17, "mapped", "each row sets data_crossing"), + (26, "mapped", "each row sets status"), + (34, "unmapped", "prose"), + (40, "mapped", "each row is an accepted_risk"), + (44, "mapped", "accepted_risk v1.0/01/01-SECURITY/AR1"), + (46, "unmapped", "prose"), + (50, "ignored", "a heading over the audit runs"), + (52, "filled", "the heading gives a date only"), + (52, "mapped", "audit_run v1.0/01/01-SECURITY/AU1"), + (62, "unmapped", "prose"), + (69, "unmapped", "prose"), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn vault_security_needs_the_extension_without_it() { + let out = import_with("vault", false); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + for kind in ["security_audit", "accepted_risk", "audit_run", "threat"] { + assert!(paths(&all, kind).is_empty(), "{kind}"); + } + let reported = entries(&out, SECURITY); + assert_eq!(reported.len(), 1, "{reported:#?}"); + assert_eq!(reported[0].2, "needs-extension"); +} + +#[test] +fn a_hostile_security_audit_sets_nothing_it_cannot_match() { + let text = "---\nphase: \"02\"\nslug: core\nasvs_level: 7\ncreated: someday\n---\n\n\ + # Phase 1 — Security\n\n\ + ## Trust Boundaries\n\n\ + | Boundary | Description | Data Crossing |\n|---|---|---|\n| nowhere → here | d | x |\n\n\ + ## Threat Register\n\n\ + | Threat ID | Category | Component | Severity | Disposition | Mitigation | Status |\n\ + |---|---|---|---|---|---|---|\n\ + | T-01-01\u{202e} | I | src/vault.js seal | high | mitigate | m | closed |\n\ + | T-01-02 | I | src/nowhere | high | mitigate | m | closed |\n\ + | T-01-SC | T | npm/pip/cargo installs | high | mitigate | x | closed |\n\ + | T-01-01 | I | src/vault.js seal | high | mitigate | m | fixed |\n\ + | T-01-03 | I | src/cli.js list | low | accept | another mitigation | closed |\n\n\ + ## Accepted Risks Log\n\n\ + | Risk ID | Threat Ref | Rationale | Accepted By | Date |\n|---|---|---|---|---|\n\ + | AR-1 | T-09-99 | r | me | 2026-10-30 |\n\ + | AR-2 | T-01-03 | r | me | 2026-13-45 |\n\ + | Risk 3 | T-01-03 | r | me | 2026-10-30 |\n\n\ + ## Security Audit 2026-13-45\n\n\ + | Metric | Count |\n|---|---|\n| Threats found | three |\n| Elapsed | 4 |\n"; + let facts: Vec<Value> = planning_facts(&fixture("vault")) + .into_iter() + .map(|f| { + if f["path"] == SECURITY { + fact(SECURITY, text) + } else { + f + } + }) + .collect(); + let out = import( + &CommandGraph::default(), + &feed(facts, false, Some(&fixture_manifest("vault", true))), + ); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + assert_eq!( + with_status(&out, json!("closed")), + ["v1.0/01/01-02/T-01-03"] + ); + assert!(with_status(&out, json!("open")).is_empty()); + let all = creates(&out); + assert_eq!( + find(&all, "security_audit", "v1.0/01/01-SECURITY").fields, + json!({ "phase": "v1.0/01" }) + ); + assert_eq!(paths(&all, "accepted_risk"), ["v1.0/01/01-SECURITY/AR2"]); + assert_eq!( + find(&all, "accepted_risk", "v1.0/01/01-SECURITY/AR2").fields, + json!({ + "audit": "v1.0/01/01-SECURITY", + "threat": "v1.0/01/01-02/T-01-03", + "rationale": "r", + "accepted_by": "me", + }) + ); + assert_eq!( + find(&all, "audit_run", "v1.0/01/01-SECURITY/AU1").fields, + json!({ "audit": "v1.0/01/01-SECURITY" }) + ); + let reported = entries(&out, SECURITY); + for (line, says) in [ + (2, "names another phase than the file name's 01"), + (4, "is no level 1 to 3"), + (5, "is no date or RFC 3339 timestamp"), + ( + 14, + "no plan of the phase holds the boundary `nowhere → here`", + ), + (20, "no plan of the phase holds the threat `T-01-01"), + (21, "the component `src/nowhere`: no status set"), + (22, "2 plans' entities match the threat `T-01-SC`"), + (23, "is none of open, closed: no status set"), + (24, "differs from the plan's"), + ( + 30, + "no plan of the phase holds the threat `T-09-99`: not imported", + ), + (31, "the Date `2026-13-45` is no YYYY-MM-DD date"), + (32, "the Risk ID `Risk 3` is no `AR-<n>`"), + (34, "`at` left out"), + (38, "the Count of `Threats found` is no whole number"), + (39, "the metric `Elapsed` is no field of an audit run"), + ] { + assert!( + has(&reported, line, "unmapped", says), + "{line} {says}: {reported:#?}" + ); + } +} diff --git a/gsd/import/tests/verify.rs b/gsd/import/tests/verify.rs new file mode 100644 index 0000000000..30c93db3b2 --- /dev/null +++ b/gsd/import/tests/verify.rs @@ -0,0 +1,310 @@ +//! `NN-VERIFICATION.md` and `NN-UAT.md` through the command in process, against the taskboard twin's `verify.spec` +//! (its verdict blocks excluded: verdicts are never imported, ADR 0391 D5). +//! +//! Known differences from the twin: the session's and the verification's titles are the import's (the file stem, the +//! document's title); the twin's are hand-made. + +mod common; + +use serde_json::{Value, json}; +use specforge_extension_sdk::prelude::*; + +use common::{ + creates, entries, fact, feed, find, fixture, has, import, import_fixture, paths, planning_facts, +}; + +const VERIFICATION: &str = ".planning/phases/01-core/01-VERIFICATION.md"; +const UAT: &str = ".planning/phases/01-core/01-UAT.md"; + +#[test] +fn taskboard_verification_is_its_phase_and_nothing_the_verifier_recorded() { + let out = import_fixture("taskboard"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!(paths(&all, "verification"), ["v1.0/01/01-VERIFICATION"]); + let v = find(&all, "verification", "v1.0/01/01-VERIFICATION"); + assert_eq!(v.fields, json!({ "phase": "v1.0/01" })); + assert_eq!(v.title, "Phase 1: Core Verification Report"); + assert_eq!(v.file, "spec/gsd/phases/01.spec"); + let reported = entries(&out, VERIFICATION); + for (line, outcome, says) in [ + (2, "redundant", "the file name gives the phase"), + (3, "computed", "verification.verified is computed"), + (4, "computed", "verification.status is computed"), + (5, "computed", "verification.score is computed"), + // A block value is located at its first item. + (7, "computed", "verification.covered_files is computed"), + (15, "computed", "verification.covered_digest is computed"), + (16, "unmapped", "no field of a verification holds it"), + (19, "mapped", "verification v1.0/01/01-VERIFICATION"), + (21, "redundant", "ROADMAP.md gives the phase goal"), + (22, "computed", "verification.verified is computed"), + (23, "computed", "verification.status is computed"), + (25, "ignored", "a heading over the verifier's tables"), + (27, "unmapped", "verdicts, never imported (ADR 0391 D5)"), + (37, "unmapped", "verdicts, never imported (ADR 0391 D5)"), + (46, "redundant", "requirements-completed give it"), + (53, "ignored", "an empty placeholder"), + (58, "unmapped", "prose"), + (59, "unmapped", "prose"), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn taskboard_uat_matches_the_twin() { + let out = import_fixture("taskboard"); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + let session = find(&all, "uat_session", "v1.0/01/01-UAT"); + assert_eq!( + session.fields, + json!({ + "phase": "v1.0/01", + "source": ["v1.0/01/01-01/01-01-SUMMARY", "v1.0/01/01-02/01-02-SUMMARY"], + "started": "2026-03-03T10:30:00Z", + }) + ); + assert_eq!( + paths(&all, "uat_test"), + [ + "v1.0/01/01-UAT/U1", + "v1.0/01/01-UAT/U2", + "v1.0/01/01-UAT/U3" + ] + ); + for (id, title, fields) in [ + ( + "U1", + "Add a task", + json!({ + "expected": "`node src/cli.js add \"Write the roadmap\"` prints `added 1: Write the roadmap`", + "result": "pass", + }), + ), + ( + "U2", + "Complete a task that does not exist", + json!({ + "expected": "`node src/cli.js done 7` fails and names the id 7", + "result": "issue", + "reported": "it prints a stack trace before the message, which is noisy", + "severity": "cosmetic", + }), + ), + ( + "U3", + "Usage text", + json!({ + "expected": "`node src/cli.js` with no command prints the usage line and exits 2", + "result": "pass", + }), + ), + ] { + let test = find(&all, "uat_test", &format!("v1.0/01/01-UAT/{id}")); + let mut want = fields; + want["session"] = json!("v1.0/01/01-UAT"); + assert_eq!(test.fields, want, "{id}"); + assert_eq!(test.title, title); + } + let gaps: Vec<_> = all.iter().filter(|c| c.kind == "uat_gap").collect(); + assert_eq!(gaps.len(), 1); + assert_eq!(gaps[0].path, "v1.0/01/01-UAT/U2/G1"); + assert_eq!( + gaps[0].fields, + json!({ + "test": "v1.0/01/01-UAT/U2", + "truth": "Completing an unknown id fails with a one-line message", + "reason": "User reported: it prints a stack trace before the message, which is noisy", + "severity": "cosmetic", + }) + ); + let reported = entries(&out, UAT); + for (line, outcome, says) in [ + (2, "computed", "uat_session.status is computed"), + (3, "redundant", "the file name gives the phase"), + (6, "unmapped", "the session's last edit"), + (9, "unmapped", "a runtime state"), + (13, "ignored", "a heading over the tests"), + (15, "mapped", "uat_test v1.0/01/01-UAT/U1"), + (29, "computed", "uat_session.totals is computed"), + (38, "mapped", "each item is a uat_gap"), + (40, "mapped", "uat_gap v1.0/01/01-UAT/U2/G1"), + (41, "computed", "uat_gap.status is computed"), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {says}: {reported:#?}" + ); + } +} + +/// The taskboard imported with its `01-UAT.md` replaced by `uat`. +fn with_uat(uat: &str) -> CommandOutput { + let facts: Vec<Value> = planning_facts(&fixture("taskboard")) + .into_iter() + .map(|f| if f["path"] == UAT { fact(UAT, uat) } else { f }) + .collect(); + let manifest = + std::fs::read_to_string(fixture("taskboard").join("specforge.json")).expect("a manifest"); + import( + &CommandGraph::default(), + &feed(facts, false, Some(&manifest)), + ) +} + +#[test] +fn a_hostile_uat_reports_what_it_cannot_write() { + let uat = "---\nphase: 01-core\nsource: [01-01-SUMMARY.md, 07-01-SUMMARY.md]\nstarted: yesterday\n---\n\n\ + ## Tests\n\n\ + ### 1. Odd result\nexpected: |\n two\n lines\nresult: maybe\nseverity: cosmetic\n\n\ + ### Not a test\nexpected: x\n\n\ + ## Gaps\n\n\ + - truth: \"A gap of no test\"\n test: 9\n- truth: \"A gap of test 1\"\n test: 1\n root_cause: \"\"\n \ + artifacts: []\n debug_session: \"dbg-1\"\n\n## Notes\n"; + let out = with_uat(uat); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!( + find(&all, "uat_session", "v1.0/01/01-UAT").fields, + json!({ "phase": "v1.0/01", "source": ["v1.0/01/01-01/01-01-SUMMARY"] }) + ); + // The test keeps every field but its result. + assert_eq!( + find(&all, "uat_test", "v1.0/01/01-UAT/U1").fields, + json!({ "session": "v1.0/01/01-UAT", "expected": "two\nlines", "severity": "cosmetic" }) + ); + assert_eq!(paths(&all, "uat_test"), ["v1.0/01/01-UAT/U1"]); + assert_eq!(paths(&all, "uat_gap"), ["v1.0/01/01-UAT/U1/G2"]); + assert_eq!( + find(&all, "uat_gap", "v1.0/01/01-UAT/U1/G2").fields, + json!({ "test": "v1.0/01/01-UAT/U1", "truth": "A gap of test 1" }) + ); + let reported = entries(&out, UAT); + for (line, outcome, says) in [ + ( + 3, + "unmapped", + "`07-01-SUMMARY.md` names no NN-MM-SUMMARY.md of a roadmap phase", + ), + (4, "unmapped", "not an RFC 3339 timestamp"), + ( + 13, + "unmapped", + "`result: maybe` is none of pending, pass, issue, skipped, blocked", + ), + (16, "unmapped", "a test heading is `### N. Title`"), + ( + 22, + "unmapped", + "the gap names no test of this file (`test: 9`)", + ), + (27, "unmapped", "`uat_gap.debug`"), + ( + 29, + "unmapped", + "a section no row of the NN-UAT.md table names", + ), + ] { + assert!( + has(&reported, line, outcome, says), + "{line} {says}: {reported:#?}" + ); + } +} + +/// GSD's diagnosed gap (gsd-core templates/UAT.md): `artifacts` as `path`/`issue` maps. +#[test] +fn a_diagnosed_gap_keeps_its_artifacts() { + let uat = "---\nphase: 01-core\nsource: [01-01-SUMMARY.md]\n---\n\n## Tests\n\n### 1. One\nexpected: e\n\n\ + ## Gaps\n\n\ + - truth: \"A gap\"\n test: 1\n artifacts:\n - path: \"src/a.js\"\n issue: \"never saves\"\n \ + - \"src/b.js\"\n - path: \"src/c.js\"\n note: \"n\"\n - note: \"only\"\n missing:\n - \"add w\"\n \ + - [x]\n\ + - truth: \"Another\"\n test: 1\n artifacts: src/x.js\n missing: {a: b}\n reason: [x]\n"; + let out = with_uat(uat); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!( + find(&all, "uat_gap", "v1.0/01/01-UAT/U1/G1").fields, + json!({ + "test": "v1.0/01/01-UAT/U1", + "truth": "A gap", + "artifacts": [ + {"path": "src/a.js", "issue": "never saves"}, + {"path": "src/b.js"}, + {"path": "src/c.js"} + ], + "missing": ["add w"] + }) + ); + assert_eq!( + find(&all, "uat_gap", "v1.0/01/01-UAT/U1/G2").fields, + json!({ "test": "v1.0/01/01-UAT/U1", "truth": "Another" }) + ); + let reported = entries(&out, UAT); + for (line, says) in [ + ( + 20, + "an artifact member `note` no row of the ## Gaps table names", + ), + (21, "an artifact member `note` no row"), + (21, "an artifact with neither a path nor an issue"), + (24, "a `missing` item that is not one text"), + (27, "`artifacts` is not a list"), + (28, "`missing` is not a list"), + (29, "`reason` is not one text"), + ] { + assert!( + has(&reported, line, "unmapped", says), + "{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn a_uat_testing_no_imported_summary_is_no_session() { + let uat = "---\nphase: 01-core\nsource: [07-01-SUMMARY.md]\n---\n\n## Tests\n\n### 1. One\nexpected: e\n"; + let out = with_uat(uat); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert!(paths(&all, "uat_session").is_empty()); + assert!(paths(&all, "uat_test").is_empty()); + let reported = entries(&out, UAT); + for (line, says) in [ + ( + 1, + "uat_session v1.0/01/01-UAT: no item of its source is imported", + ), + ( + 8, + "uat_test v1.0/01/01-UAT/U1: parent not imported (v1.0/01/01-UAT)", + ), + ] { + assert!( + has(&reported, line, "unmapped", says), + "{line} {says}: {reported:#?}" + ); + } +} + +#[test] +fn a_uat_of_two_hundred_tests_imports_each() { + let tests: String = (1..=200) + .map(|n| format!("### {n}. Test {n}\nexpected: e{n}\nresult: pass\n\n")) + .collect(); + let uat = + format!("---\nphase: 01-core\nsource: [01-01-SUMMARY.md]\n---\n\n## Tests\n\n{tests}"); + let out = with_uat(&uat); + assert_eq!(out.exit_code, 0, "{}", out.stderr); + let all = creates(&out); + assert_eq!(paths(&all, "uat_test").len(), 200); + assert_eq!( + find(&all, "uat_test", "v1.0/01/01-UAT/U200").fields, + json!({ "session": "v1.0/01/01-UAT", "expected": "e200", "result": "pass" }) + ); +} diff --git a/gsd/import/wasm/gsd_import.wasm b/gsd/import/wasm/gsd_import.wasm new file mode 100644 index 0000000000..e49fa86422 Binary files /dev/null and b/gsd/import/wasm/gsd_import.wasm differ diff --git a/gsd/import/wasm/inputs.json b/gsd/import/wasm/inputs.json new file mode 100644 index 0000000000..547418e889 --- /dev/null +++ b/gsd/import/wasm/inputs.json @@ -0,0 +1,127 @@ +{ + "artifact": "gsd_import.wasm", + "artifact_sha256": "61330ffa53dc1e9da28cf5444a05d194022fdedd61a31e36897fd825b3d2a9e2", + "built_with": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "inputs": { + "Cargo.toml#workspace-inherited": "9e0489b27be2c7fd7820cd1d3b2e145c1a7793b4d2dca8320df80d1c29c0e984", + "crates/leaf/protocol-types/Cargo.toml": "e8afa3ac4c33d7a09f8c9879d9d87ca2cc0e8d23961abdf867051496f874c176", + "crates/leaf/protocol-types/src/calls.rs": "39f197fe1698bbb655c58b2db4fc2dcf87308087a225273cbb4d4ba355a930ab", + "crates/leaf/protocol-types/src/calls/collect.rs": "9d92a592fc80149dcff4e8be7366096d8580ccf5ed8daa7a453950d9ffe5a7ef", + "crates/leaf/protocol-types/src/calls/evidence.rs": "f10687676e8c14a0cf4046bf35e57366087df4b698104329efd164e707a4d983", + "crates/leaf/protocol-types/src/calls/facts.rs": "9aa11df0902f2393c0f758d2ddb0e8747cc4d4afda5a0faff8b20e31ec6d710e", + "crates/leaf/protocol-types/src/capability.rs": "4627081c09404e932df880773cfc6dc9784b443866228b02c25e6248cc68b59e", + "crates/leaf/protocol-types/src/checks.rs": "ee4ed29565dc59dcfd60d7b024f2353c0786cee4bbadb444fbe3a9ef42fbfe66", + "crates/leaf/protocol-types/src/code_catalog.rs": "407ac84e356f90f3244ccc057fb22bad9717ec2c03357e8471bfd967d243ac26", + "crates/leaf/protocol-types/src/command_args.rs": "ec81e38e7b000cc15b4b7c26e9fe5de602f0d98764c3af4f466e6225c41866b1", + "crates/leaf/protocol-types/src/context.rs": "021031ef574b54813a7b407c26fb9cfd03eb03028a27f9881f0d12c008e05b79", + "crates/leaf/protocol-types/src/contrib.rs": "85269d1993bdfdfda5aae190f5702a645e8a570cc0deb91941b30600f00e9c50", + "crates/leaf/protocol-types/src/decimal.rs": "0a603f97eee8f30bc3d5aacfe50f0fa1988386e1a4c64da30be317a707c01204", + "crates/leaf/protocol-types/src/declaration.rs": "18175c760d067247a089ded8ca770fca8f8825d20ae329e35eb52f114b9e7963", + "crates/leaf/protocol-types/src/delta.rs": "5258e08c3ae8d1cd7eba86e3e387328b0ee4222ff3d787a0bda7471d9d03ace6", + "crates/leaf/protocol-types/src/effects.rs": "19cee647a338e945f09183c126e2dc8790b59c02bc44b18b17c088bb6c29af7c", + "crates/leaf/protocol-types/src/engine_tools.rs": "4973ba639e2c824e15b4f18bfad4d31dba44cb352a8c7f4bf7f8b502f5a64bdd", + "crates/leaf/protocol-types/src/field.rs": "d1b4dfecfa9de527add0ada5ac8eadb429ebcc76d15bc2ff34b7939e8f41633f", + "crates/leaf/protocol-types/src/inputs.rs": "97c49952e96648e37eeb69965ca3d2fad4dda05bbc1515032d69102e918311ed", + "crates/leaf/protocol-types/src/judged.rs": "9e7f691b8b9d646332518c093757645a7c1672132ef0c95b516b9c3e25f6e317", + "crates/leaf/protocol-types/src/lib.rs": "64926b885431e304bbe057d60822ff73e8a834a76017e8d10f8f1cc77bf8cc7f", + "crates/leaf/protocol-types/src/operation.rs": "55e6b1e358c026ca56d6324410806f8cd4cce697f1f361abfe9ad624985012a5", + "crates/leaf/protocol-types/src/plan.rs": "7a41d42b439411283e08ef8fc270b6fdd86eedf8aceea6b190264fe11e4ff54a", + "crates/leaf/protocol-types/src/ports.rs": "fe253dac3665743f6cd9435f38410a211f914a3f46cb3a7469071b9ed76106dd", + "crates/leaf/protocol-types/src/prompt.rs": "bf7b8aac6fa77da1df46b14eaa14f81c1e98bfeae4a97b2c582878765b36d20e", + "crates/leaf/protocol-types/src/reads.rs": "7926b241e6328bb05bf340ccf51ea6dba2814de5076eb7ca8ddd1d86d40c7da7", + "crates/leaf/protocol-types/src/rooted.rs": "86750cd009adf6daed8a9309fc0c95384b5661e28abadf37b1a00bbc5a10e9a4", + "crates/leaf/protocol-types/src/route.rs": "18163bb5eda662886c28521fb36ec253ee0150f95a891c2123a85bb2477e9953", + "crates/leaf/protocol-types/src/settings.rs": "9967d358e7bade6d700be42855f79bb55c6df0d8a98ad0d9a815dcb6befecfeb", + "crates/leaf/protocol-types/src/shell.rs": "17adad7ef5dd6b4a2ae1b3f8c99dd0ce95be7a1c510b3daef8b4235c7e9c1e52", + "crates/leaf/protocol-types/src/surface.rs": "536385a07cb018908470d224e540b650bd6616729cfafdc3b55794f46f9098cc", + "crates/leaf/protocol-types/src/syntax.rs": "167d2a7600196ad82db794459ba78ab6f9880ab2c4293e4a4cdf1e2d2762264c", + "crates/leaf/protocol-types/src/tokens.rs": "712d002d00fec879b8f594f775bb25513ead53ee61d11978478c36d83bfbe9b1", + "crates/leaf/protocol-types/src/tool_input.rs": "0e7e9603b820339efea2266baafcd42ba39323b287b0f682a2bb509227590b17", + "crates/leaf/protocol-types/src/trigger.rs": "4e76e4d280ed72934f33b823c9c2bb2a80648b1fb227c594ba9385ee2c60d422", + "crates/leaf/protocol-types/src/version.rs": "76d50e9491f4e5d55e1e060bf8b65cc0115400a348a66a85931794a61b75797e", + "crates/leaf/protocol-types/src/vocabulary.rs": "c3bea56db4bb5cfc84ce400db7750b2eb33c58dcbf11e5b3f2761683341675b5", + "crates/runtime/extension-sdk-macros/Cargo.toml": "2845656f0847efeddb37aecc91031adc3396747949aa0e090cdad31644824544", + "crates/runtime/extension-sdk-macros/src/lib.rs": "05b9dfd092444a55acc0993f35172ee3d0e4db9b6b1bed77682ce912ba54f67a", + "crates/runtime/extension-sdk/Cargo.toml": "41c03d21f457d3e7394d86a625742a525700ac1ddcb92b49487e0fc5dcaa2797", + "crates/runtime/extension-sdk/src/builders.rs": "214ef27f2a26c94c10c0544916612da935add463c2b6eb99208e79109cd282ca", + "crates/runtime/extension-sdk/src/capability.rs": "e6c88ecbe2e9ce2a5c6da397559ec9f846183bb9142f37765b1b329a0bf16667", + "crates/runtime/extension-sdk/src/checker.rs": "4d89b64155c3a6fce020c07e432eb9f6d38320e14b3d4623fd89a3f7ae7ea3e7", + "crates/runtime/extension-sdk/src/command_graph.rs": "e88d26d3134c7591aa1afeee1f432ecdf0437a191c23b5d2eb50a50a0b7e5562", + "crates/runtime/extension-sdk/src/context.rs": "a4c25a5f8ae610ac6a24c0e493729c7c2e206d43fc716a67c9f346dc023fc1d1", + "crates/runtime/extension-sdk/src/contrib.rs": "68d63b1213a97250f15f6483640adff7aa887c10bb862db47d8bbfc476f10a68", + "crates/runtime/extension-sdk/src/guest.rs": "e18eb17771e02eedc6e907d4fd31a0f7987e1a68cbe07470acf3cc5efdc74280", + "crates/runtime/extension-sdk/src/host.rs": "0a93b725e2c10697667feb0df0728651d58ea8eebad2f879906d87779494928a", + "crates/runtime/extension-sdk/src/host/convert.rs": "13df3e7295cbfaea3a686c0c9b5a2d1b926bfc1c1b76251077d03f031d3c364b", + "crates/runtime/extension-sdk/src/host/in_process.rs": "9989b8fb1f2b6a92fda3029ad9fb940c600b06ac891cb6c65fdc7e7674d7872c", + "crates/runtime/extension-sdk/src/host_contrib.rs": "2c0b76df6d103d35986481e5228af74c30b2155c7004493fb7984255baeb6c04", + "crates/runtime/extension-sdk/src/judged.rs": "4d5ca738008c0aaa9cc88e70de2051778928021efe2c2b251ae6f4fcfd57190c", + "crates/runtime/extension-sdk/src/lib.rs": "6f6361825973281f8c8992096af6bfd09ec5cafe8b4e572069313addf2eaa16f", + "crates/runtime/extension-sdk/src/operations.rs": "231bea810e55f51e00d818843b75aa64013afd16a40f3a088a55fee9a2b68b50", + "crates/runtime/extension-sdk/src/plan.rs": "858a4310f5d5dc861aa135f126d499ef01eedd201565bc5b96ba305d7d1180af", + "crates/runtime/extension-sdk/src/prompt.rs": "bf47ef66a158c9830beff1570619fc16029b8a8589bfde475eb4741a09034c95", + "crates/runtime/extension-sdk/src/reads.rs": "613b6f504d2fd32b8b379f2edc6ced862bb2480f55d6193a9b6bfc0891541818", + "crates/runtime/extension-sdk/src/route.rs": "a81851e96dc1df5b2b325497e34f301f016e15b6743fd9a49eef9aeb9b8f80f6", + "crates/runtime/extension-sdk/src/settings.rs": "a805f2a5f6d6ca123e0a11f2abca300f83c40a66c7a52d773338fddf9a586500", + "crates/runtime/extension-sdk/src/surface.rs": "b45e09d291b75e5efc51ccc3260a0890fe36774e885e2e4dbc2ca5d523716af7", + "crates/runtime/extension-sdk/src/surface/call.rs": "47937f382d26ac3de60d0ab6a9b39babb78edb564d70ec78de10a4676e9a1282", + "crates/runtime/extension-sdk/src/vocabulary.rs": "93f85b5300e870259d78823b33cc19639aac0c30d966e934d9125e693fc94281", + "crates/runtime/extension-sdk/wit/host.wit": "fc297976ff03eab250e76d7c4a01f5bc89124406fc7c8bc08802eb2417895472", + "gsd/.cargo/config.toml": "746bbb5a5d288839f912d2560de084edb16df1e63508fd815e1ff81f3a894ef6", + "gsd/Cargo.lock": "17cd94254b2c7dc2e6dc04245e6bc391ab87a3db043aaff232371e49973b1f03", + "gsd/import/Cargo.toml": "f262f272eff25938b50ff5e759fbc270c487ca64f36d9fd45bc610786e9503ea", + "gsd/import/src/command.rs": "b3e5978a1cffeb372ca7806bd3b8c26b514048232f762d504ef5d6e055314c0c", + "gsd/import/src/emit.rs": "d2b4e31f5fb25577b4ae050509bb643232e8bc2b91bc9f4cca25ba46f88906dc", + "gsd/import/src/frontmatter.rs": "1fa0ad4749fe451772818432a4349ee7afd72031c9e62045b5f6e0cede3b1cce", + "gsd/import/src/ids.rs": "d23fd25482a77f02d453b838cd8aaad25e64c508683155f775d046be9d380774", + "gsd/import/src/kinds.rs": "ccb23fbeb0448591e73e9a14fe221d25baee518121f17cbf70c2570db39bb697", + "gsd/import/src/lib.rs": "8716dcf9c27da9c31d948b499f57b12fb6c370eb5de6a6a980d996572b5c6e30", + "gsd/import/src/limits.rs": "e8d7fdc6a23b5abe8f74025e9af230612ff10fa75dc025898c7ff1d546d831f8", + "gsd/import/src/owed.rs": "79cef5a1f443201ba60bcb0e5a8894050cb6aac6a1537ee23066d4f69dccae50", + "gsd/import/src/paths.rs": "2ba85f39a16fa2268fe337751a2d6f9c498d528ae37750ad2a9b29f3dcce0003", + "gsd/import/src/preflight.rs": "0cd30c644dddc2174347ebb6e86512e602490fd1ecef7e1cf4d554eb7c5acbdc", + "gsd/import/src/read/context.rs": "be9017e3cff3ef4baa104bd5f06de32fc4f88263440ee1ba16feedee7f93d1aa", + "gsd/import/src/read/discussion.rs": "1562ca28ec30d133ace9374a5e3d2e4ac92de8a847e3b030d2df95d2fb4c77e5", + "gsd/import/src/read/mod.rs": "a2ad989a85f34063b9a165cbd2f7d163351e687cc02df663ac59c60010791aee", + "gsd/import/src/read/plan.rs": "77ccfd1d5f00c161b1e722193ea8a5ec0fe0972294b45dfd8fe889470937f1ae", + "gsd/import/src/read/project.rs": "e488d91ef6ea491879e29163a10bf812d199ff52bea767b33232a0eea8a04220", + "gsd/import/src/read/quick.rs": "a14c42cf05f3a895176e6c0f36b49c226241b617c1ccefec00c4b697fc5fd65a", + "gsd/import/src/read/requirements.rs": "e34c9cde60b992c32c4d78e3a6ceb1c68aa03a500eb26711ede8cba167adcc7c", + "gsd/import/src/read/research.rs": "20d4eb725d5383acca5b5f086053fcf5dd55a14ab13445d5c0db940329651b02", + "gsd/import/src/read/roadmap.rs": "73946f45ae6350d498852b4aff24fef5cf19cad2b6e1fe0988e47b9de066d2b0", + "gsd/import/src/read/security.rs": "49047b9552a7a192b89e64f55c8d131971f05debedd445826e2316f2fa6d0842", + "gsd/import/src/read/state.rs": "79285e87ebd81edc787c1c77f89a666b5b4e0ea468db7b5667063a2b2daab7f2", + "gsd/import/src/read/summary.rs": "5363bd03468f3536c5a78a5e9a1973439bd7d49ea5ae8e6175609e74c12926c7", + "gsd/import/src/read/tasks.rs": "b2fc7102bed1191d943e4c0b7972447e548fe29208e3a2a93791eaecc818210d", + "gsd/import/src/read/threats.rs": "0f7c32eae39ec358d7d4cd3a7d55da3cd5e394e2d8213313ce1e66045dc74fd7", + "gsd/import/src/read/uat.rs": "86d52cffc02ba019e4f2b35d34b7bd4fb3d64a60de0a48727a69f52b1592ca4f", + "gsd/import/src/read/verification.rs": "828414ae49e1956de104f3e47fc08414b8d795800f2d78bd462a54d4580e62fc", + "gsd/import/src/records.rs": "674fb6b496de9495ace5e8a6fc22729e43a50170f11d97f26dacd40ac3b47b31", + "gsd/import/src/report.rs": "845f31f7f337a6a4bb6bc6aed79fcca2409077076beb6443c515c48b1f8eb8f0", + "gsd/import/src/sections.rs": "4164d5de999cfe2272b08882ed9fa182983a6c5943c298631944b3ec1409a6db", + "gsd/import/src/settings.rs": "a9be335082f60e1841d7a35cfd046e587b1e160fba36989d4db19899052a0351", + "gsd/import/src/table.rs": "53d9e0089ae288d678189854ad3a3df2df8618b93c77f963bb85283c0e5c296e", + "gsd/import/src/table/sections.rs": "3b40e9677e84bd60d9cb9b206c09d7dd2594435c4596e65c986854287cc50a1b", + "gsd/import/src/xmltags.rs": "5f1e4ec6ccc3f9bf1e48a02e5e9022d5ff31b46595e2937fd2ffd311700d26f3", + "gsd/kit/Cargo.toml": "781ee881790d5b6923177d78d11ad13033eecd5a04aa6c3dc8a7e35dab225094", + "gsd/kit/src/agent.rs": "6bbca2b6c8e83d80179c10914c54fe96bcd404c23d519110998af2d0175b970b", + "gsd/kit/src/capability.rs": "b406fe48a9db5e42183cdddca550efcc3d365b084206ae82fd2fbf255f3971d0", + "gsd/kit/src/dsl.rs": "34d1b34a17a04467c9a6461d3e3e8a8f981615306d9bbe8a7a02069e4fe6c864", + "gsd/kit/src/files.rs": "18f51e12f43ba47ee911ec3e5a3d37da7ca702f907ff686e246dbfea2381c51a", + "gsd/kit/src/judged.rs": "5dede3d81904cd2e03c759c263743f146000da1b982160a071d4cb42c3be0a82", + "gsd/kit/src/judged/record.rs": "13ad01c1c91949dc241fb349e95af9f1124a0feacb175a7a572f1cad446593e0", + "gsd/kit/src/lib.rs": "6972cba47d094891c80c5d846eafd097bdd48e6a4776acf1e7c17a5079308c1f", + "gsd/kit/src/markdown.rs": "a1544e5bd0041256ea527ef07b10f87949b697d8d293e892250854ddb2e8d5f1", + "gsd/kit/src/prompt/args.rs": "a0eff63b22fae5fc16ecb4b0defb3c07783eae3048740b439bda5d3949a83b18", + "gsd/kit/src/prompt/compose.rs": "929f8737d33d410d27f480b65e909712040278ec9aeccce52d5e034d6ff88bdb", + "gsd/kit/src/prompt/host.rs": "3fcf9c030703485679c5bb7bac15a8803ca9e61d97e4314d08b6ec780f822e0f", + "gsd/kit/src/prompt/host/headers.rs": "a4b0d718ca4f17046b7370c0cdbe5b9b1048bf0dd58a0e572a63eb236c282442", + "gsd/kit/src/prompt/mod.rs": "f9ff660ec868881ce87b0694a1be78932980d2c4a87829b46b30b93c9651f6d1", + "gsd/kit/src/prompt/preamble.rs": "25cb54712c27658bb192d4fcfc46516132e638da32322422ea50d5024ea5bc29", + "gsd/kit/src/prompt/render.rs": "72a7b4c4e487b3e2dc300f137e5095a6cb86535e4c6b943dd555eb224fc8605d", + "gsd/kit/src/prompt/repoint.rs": "735233cf09180d81cd6541a0b8ccfb447917610cf9f237f420c021387547c68a", + "gsd/kit/src/prompt/setting.rs": "182997a0ee2138814feb89baf319dc18b3ea15ee9cd8a96a4f683cb371335d60", + "gsd/kit/src/prompt/shell.rs": "3130d96472ad065bd4a7d839d103a8dcdc71cc3b6cd0719a35b0e61453e3ab51", + "gsd/kit/src/prompt/token.rs": "b818233a9b11d206f6a275d7cc575e5b357bdcf9d3d02d8a9016d03498e5acb3", + "gsd/kit/src/spelling.rs": "afc428afb2461e557a6161a97f9f41a2ea96945d2eae48b526920df3fe150ddc" + } +} diff --git a/gsd/kit/src/markdown.rs b/gsd/kit/src/markdown.rs index cd4a04fd72..0ecc3cbf6f 100644 --- a/gsd/kit/src/markdown.rs +++ b/gsd/kit/src/markdown.rs @@ -46,6 +46,17 @@ pub struct Table { pub line: usize, } +/// An ATX or setext heading. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Heading { + /// 1 for `#`, up to 6. + pub level: u8, + /// Its text, trimmed, its code spans kept in backticks. + pub text: String, + /// Its first line. + pub line: usize, +} + /// The inline text of one leaf block: a paragraph, a heading, a list item's own text, or the lines of an HTML block /// that are not read again as Markdown. #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -92,6 +103,12 @@ pub fn inline_blocks(text: &str) -> Vec<InlineBlock> { read(text, Options::ENABLE_TABLES).blocks } +/// Every heading of `text` outside a fence and a comment, from every level, in line order: a `#` line inside a fence +/// is code, and a heading under an XML section tag is read again as Markdown. +pub fn headings(text: &str) -> Vec<Heading> { + read(text, Options::empty()).headings +} + /// Every GFM table of `text`, from every level, in line order. A cell is its source text, trimmed, its code spans /// kept in backticks and each `\|` unescaped, as GFM reads a cell. pub fn tables(text: &str) -> Vec<Table> { @@ -106,6 +123,7 @@ struct Reading { tables: Vec<Table>, links: Vec<(Range<usize>, String)>, blocks: Vec<InlineBlock>, + headings: Vec<Heading>, /// The text of the last heading read, kept across the fragments read again. heading: String, } @@ -127,6 +145,7 @@ fn read_at(frag: &str, base: usize, at: usize, options: Options, out: &mut Readi let mut fence: Option<Fence> = None; let mut html: Option<usize> = None; let mut heading: Option<String> = None; + let mut heading_at: (u8, usize) = (0, 0); let mut table: Option<Table> = None; let mut row: Vec<String> = Vec::new(); let mut block = InlineBlock::default(); @@ -151,10 +170,18 @@ fn read_at(frag: &str, base: usize, at: usize, options: Options, out: &mut Readi _ => {} } match event { - Event::Start(Tag::Heading { .. }) => heading = Some(String::new()), + Event::Start(Tag::Heading { level, .. }) => { + heading = Some(String::new()); + heading_at = (level as u8, here); + } Event::End(TagEnd::Heading(_)) => { if let Some(h) = heading.take() { out.heading = h.trim().to_string(); + out.headings.push(Heading { + level: heading_at.0, + text: out.heading.clone(), + line: heading_at.1, + }); } } Event::Text(text) if heading.is_some() => { @@ -309,7 +336,24 @@ fn tag_only(line: &str) -> bool { #[cfg(test)] mod tests { - use super::{fences, html_blocks, inline_blocks, inline_code, links, tables}; + use super::{fences, headings, html_blocks, inline_blocks, inline_code, links, tables}; + + #[test] + fn headings_skip_fences_and_comments_and_read_setext_and_tagged_ones() { + let text = "# Title\n\n```md\n# not a heading\n```\n<!--\n## nor this\n-->\nSetext `x`\n---\n\n<objective>\n## Inside\ntext\n</objective>\n"; + let found: Vec<(u8, String, usize)> = headings(text) + .into_iter() + .map(|h| (h.level, h.text, h.line)) + .collect(); + assert_eq!( + found, + [ + (1, "Title".to_string(), 0), + (2, "Setext `x`".to_string(), 8), + (2, "Inside".to_string(), 12) + ] + ); + } #[test] fn a_fence_under_a_section_tag_is_a_fence() { diff --git a/gsd/parity/ACCEPTANCE.md b/gsd/parity/ACCEPTANCE.md index b0af89db67..d6435b70d5 100644 --- a/gsd/parity/ACCEPTANCE.md +++ b/gsd/parity/ACCEPTANCE.md @@ -17,7 +17,7 @@ disagrees. Every row but Capabilities is computed from tables of code; Capabilit | CLI modules | 288 | 170 | 21 | 97 | 0 | `core/tests/parity_roster/modules.rs` | | Config keys | 212 | 161 | 35 | 16 | 0 | `core/spec/settings.md` | | Gate-cutover verdicts | 171 | 93 | 51 | 14 | 13 | `core/tests/parity_rules/cutover.rs` | -| Codes | 73 | 73 | 0 | 0 | 0 | `core/tests/parity_rules/evidence.rs` | +| Codes | 75 | 75 | 0 | 0 | 0 | `core/tests/parity_rules/evidence.rs` | Concepts (the model: phases, plans, milestones, requirements, decisions, UAT, verification) are the kinds of `core/spec/*.md`; they have no inventory family, so no count. They are exercised by every row above. @@ -48,7 +48,7 @@ Concepts (the model: phases, plans, milestones, requirements, decisions, UAT, ve argument shape); 51 belong to an extension, 14 are the gate engine, and 13 are core codes whose verdict is not reproduced: 10 that no twin reaches, and 3 that a twin reaches and answers differently (`Diverges`, below). Each is named, with its reason, in `core/tests/parity_rules/cutover.rs`. -- Codes: 73 of the 73 codes fire and stay silent in a named test. +- Codes: 75 of the 75 codes fire and stay silent in a named test. - Verification: the verifier's `gsd/E501` verdict on a truth reads what it cites, files and tests, and one that cites nothing is refused; an artifact's reads its `path` and a key link's its `from` and `to` (ADR 0377). A must-have owes its verdict once its plan is complete, a plan check while its plan is open, and a judgment-tier prohibition owes @@ -220,6 +220,11 @@ Not verified: - W514 fires on every `check`, once per open deviation window that names a proposal, while `workflow.windows_enforce` is off; upstream warns once per triggering `refactor evaluate` (also when broken-windows is absent). The text and the remediation match. E515 is SpecForge's own, on under gsd-strict and gsd-plus, and has no upstream. +- E533 (a breaking API change without a major version bump, ADR 0390) is SpecForge's own, a gate code of the milestone + close on under gsd-strict and gsd-plus (`specforge.interface_gate`), and has no upstream: upstream reads no API facts. +- E535 (release evidence that does not match the milestone, ADR 0390) is SpecForge's own, a gate code of the milestone + close on under gsd-strict and gsd-plus (`specforge.release_gate`): upstream tags the release after the close and reads + no package version. - A threshold's bounds are whole numbers (D-K20a-9): a warning between 0 and 1 and a critical between 99 and 100 are refused (`hooks.context_critical_threshold` refuses `99.5`), which GSD accepts. - Three gate-cutover verdicts are divergences: `tdd-review-checkpoint-red-only` and `tdd-review-checkpoint-mixed-violation` @@ -228,7 +233,7 @@ Not verified: judgment-tier prohibition without evidence and halts or marks it unverified; here W525 warns at `check` until the verifier records a fresh verdict, which is a model's and not authoritative, so it never halts). - The 10 other unreached verdicts are named in `cutover.rs`. -- The "silent" evidence of 39 of the 73 built codes is the unedited twin (`rules_silent.rs`): it proves the code is not +- The "silent" evidence of 39 of the 75 built codes is the unedited twin (`rules_silent.rs`): it proves the code is not raised there, not that the rule judged a clean case. - `[agent-namespace-one-rule]` `workflow_guard` reads the agent namespace as `worktree_path_guard` does, with `worktree-wf_` and the charset; upstream's workflow guard has the two prefixes `agent-` and `worktree-agent-`. - `[protected-set]` `branch_check` protects `main`, `master`, `develop`, `trunk`, `release/…`, `git.protected_branches` and `git.base_branch`, and `git.allow_default_branch_commits` changes `blocks_commit`, not `protected`, so ship's and the `none` strategy's warnings still show on `main`. Upstream also reads the real default branch; the git port answers no remotes, so `origin/HEAD` is not read here. diff --git a/gsd/parity/README.md b/gsd/parity/README.md index 2c0a57c276..2b3f9eb6c9 100644 --- a/gsd/parity/README.md +++ b/gsd/parity/README.md @@ -58,6 +58,36 @@ The recipe needs node 24 or later (the tag's `engines.node`). The script refuses repository (so `validate health` does not report the machine's worktrees), runs the fixture's `npm test` (node's JUnit reporter) for `junit.xml`, and normalises timestamps, hashes, paths and timings, so a second run changes nothing. +### Recorded tool reports + +`record-reports.sh` records the reports the fixtures' report packs read, into `goldens/<fixture>/reports/`: `cargo +gate`'s dogfood check collects taskboard, ledger and vault with every pack each one detects from these files, with +`--no-run --report`, and fails when a collect answers a Warning or an Error (ADR 0393 D9). Nothing runs the tools in +the gate. Re-record by hand on a machine with Docker, then review the diff: + +```sh +gsd/parity/record-reports.sh # or name fixtures: taskboard vault ledger +git diff --exit-code gsd/parity/goldens +``` + +Each tool runs in a `--platform linux/amd64` container of the image below, pinned by digest, on a copy of the fixture's +tracked files at `/project`, copied in and out by tar streams (no volume); the fixtures are never touched, and one +holding an uncommitted or untracked file is refused. Each fixture's `reports/` is replaced as a whole. Only c8 itself +is pinned: npm resolves its dependency tree at record time. A leading `SF:/project/` in an LCOV becomes `SF:`, and +the SBOM's `serialNumber` and `metadata.timestamp` become `urn:uuid:00000000-0000-0000-0000-000000000000` and +`1970-01-01T00:00:00Z`, so a re-run on the same tools gives the same bytes (the ledger's five reports were recorded +twice and compared). `scenario`'s count skips `goldens/taskboard/reports/`. + +| Fixture | File | Tool | Image | Command | +|---|---|---|---|---| +| taskboard | `javascript-coverage.lcov` | c8 12.0.0, node v26.13.1 | `node:26-bookworm-slim@sha256:0042e17d232a87a2cd485be1da7900fca4d10a4ad11b29e9285da1d2e54798c9` | `npx --no -- c8 --reporter=lcovonly --reports-dir=.specforge/reports/javascript-coverage npm test` | +| vault | `javascript-coverage.lcov` | c8 12.0.0, node v26.13.1 | `node:26-bookworm-slim@sha256:0042e17d232a87a2cd485be1da7900fca4d10a4ad11b29e9285da1d2e54798c9` | `npx --no -- c8 --reporter=lcovonly --reports-dir=.specforge/reports/javascript-coverage npm test` | +| ledger | `rust-coverage.lcov` | cargo-llvm-cov 0.9.2, cargo-nextest 0.9.146, rustc 1.99.1 | `rust:1.99.1@sha256:8a4e90c7946b74626488b1446f712c0fe0ed1a596cbd3d871684bc9c5433ae07` | `cargo llvm-cov nextest --workspace --ignore-run-fail --lcov --output-path <file>` (the red-by-design test fails; coverage is still written) | +| ledger | `rust-lint.jsonl` | clippy 0.1.99 (rustc 1.99.1) | `rust:1.99.1@sha256:8a4e90c7946b74626488b1446f712c0fe0ed1a596cbd3d871684bc9c5433ae07` | `cargo clippy --workspace --all-targets --message-format=json` (standard output) | +| ledger | `rust-sbom.cdx.json` | cargo-cyclonedx 0.5.10 | `rust:1.99.1@sha256:8a4e90c7946b74626488b1446f712c0fe0ed1a596cbd3d871684bc9c5433ae07` | `cargo cyclonedx --format json --spec-version 1.5 --all-features --override-filename rust-sbom.cdx` (the pack's argv; the tool appends `.json`); `serialNumber` and `timestamp` fixed | +| ledger | `rust-osv.json` | osv-scanner 2.7.1 | `ghcr.io/google/osv-scanner:v2.7.1@sha256:a70ffffc2bfd33482953e5d6b64c6fcdb30239717a07b0f0d3ab2859ce3e4cde` | `osv-scanner scan source --lockfile Cargo.lock --format json --output-file <file>` (sends `ledger 0.1.0` to osv.dev) | +| ledger | `rust-api.txt` | cargo-public-api 0.52.0, nightly-2025-11-22 (rustc 1.93.0-nightly 27b076af7) | `rust:1.99.1@sha256:8a4e90c7946b74626488b1446f712c0fe0ed1a596cbd3d871684bc9c5433ae07` | `RUSTUP_TOOLCHAIN=nightly-2025-11-22 cargo public-api --color never -ss` (standard output) | + ### To track a newer release As the move from 1.18.0 to 1.19.0 did it (round `gsd-upgrade-1.19.0`): diff --git a/gsd/parity/fixtures/ledger/specforge.json b/gsd/parity/fixtures/ledger/specforge.json new file mode 100644 index 0000000000..52d0646bdc --- /dev/null +++ b/gsd/parity/fixtures/ledger/specforge.json @@ -0,0 +1,11 @@ +{ + "name": "ledger", + "version": "0.1.0", + "spec_root": "spec", + "settings": { + "@gsd/core": { + "specforge.task_commits": false, + "specforge.release_exempt": ["ledger"] + } + } +} diff --git a/gsd/parity/fixtures/taskboard/specforge.json b/gsd/parity/fixtures/taskboard/specforge.json new file mode 100644 index 0000000000..57532f6363 --- /dev/null +++ b/gsd/parity/fixtures/taskboard/specforge.json @@ -0,0 +1,10 @@ +{ + "name": "taskboard", + "version": "1.0.0", + "spec_root": "spec", + "settings": { + "@gsd/core": { + "specforge.task_commits": false + } + } +} diff --git a/gsd/parity/fixtures/vault/specforge.json b/gsd/parity/fixtures/vault/specforge.json new file mode 100644 index 0000000000..a1c6e1f032 --- /dev/null +++ b/gsd/parity/fixtures/vault/specforge.json @@ -0,0 +1,10 @@ +{ + "name": "vault", + "version": "1.0.0", + "spec_root": "spec", + "settings": { + "@gsd/core": { + "specforge.task_commits": false + } + } +} diff --git a/gsd/parity/goldens/ledger/reports/rust-api.txt b/gsd/parity/goldens/ledger/reports/rust-api.txt new file mode 100644 index 0000000000..aaea1ef8ee --- /dev/null +++ b/gsd/parity/goldens/ledger/reports/rust-api.txt @@ -0,0 +1,17 @@ +pub mod ledger +pub struct ledger::Entry +pub ledger::Entry::cents: i64 +pub ledger::Entry::memo: alloc::string::String +impl core::clone::Clone for ledger::Entry +pub fn ledger::Entry::clone(&self) -> ledger::Entry +impl core::cmp::Eq for ledger::Entry +impl core::cmp::PartialEq for ledger::Entry +pub fn ledger::Entry::eq(&self, &ledger::Entry) -> bool +impl core::fmt::Debug for ledger::Entry +pub fn ledger::Entry::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::marker::StructuralPartialEq for ledger::Entry +pub fn ledger::add(&mut alloc::vec::Vec<ledger::Entry>, i64, &str) -> core::result::Result<(), alloc::string::String> +pub fn ledger::column(i64) -> alloc::string::String +pub fn ledger::line(&ledger::Entry) -> alloc::string::String +pub fn ledger::parse(&str) -> core::result::Result<alloc::vec::Vec<ledger::Entry>, alloc::string::String> +pub fn ledger::total(&[ledger::Entry]) -> i64 diff --git a/gsd/parity/goldens/ledger/reports/rust-coverage.lcov b/gsd/parity/goldens/ledger/reports/rust-coverage.lcov new file mode 100644 index 0000000000..b65593a1a6 --- /dev/null +++ b/gsd/parity/goldens/ledger/reports/rust-coverage.lcov @@ -0,0 +1,128 @@ +SF:src/lib.rs +FN:11,_RNvCsd5mIoaO0ND7_6ledger3add +FN:41,_RNvCsd5mIoaO0ND7_6ledger4line +FN:46,_RNvCsd5mIoaO0ND7_6ledger5parse +FN:23,_RNvCsd5mIoaO0ND7_6ledger5total +FN:32,_RNvCsd5mIoaO0ND7_6ledger6column +FN:52,_RNCNCNvCsd5mIoaO0ND7_6ledger5parses_00B5_ +FN:53,_RNCNCNvCsd5mIoaO0ND7_6ledger5parses_0s_0B5_ +FN:48,_RNCNvCsd5mIoaO0ND7_6ledger5parse0B3_ +FN:49,_RNCNvCsd5mIoaO0ND7_6ledger5parses_0B3_ +FN:52,_RNCNCNvCs2gWKccma74L_6ledger5parses_00B5_ +FN:53,_RNCNCNvCs2gWKccma74L_6ledger5parses_0s_0B5_ +FN:48,_RNCNvCs2gWKccma74L_6ledger5parse0B3_ +FN:49,_RNCNvCs2gWKccma74L_6ledger5parses_0B3_ +FN:11,_RNvCs2gWKccma74L_6ledger3add +FN:41,_RNvCs2gWKccma74L_6ledger4line +FN:46,_RNvCs2gWKccma74L_6ledger5parse +FN:23,_RNvCs2gWKccma74L_6ledger5total +FN:32,_RNvCs2gWKccma74L_6ledger6column +FNDA:3,_RNvCsd5mIoaO0ND7_6ledger3add +FNDA:1,_RNvCsd5mIoaO0ND7_6ledger4line +FNDA:1,_RNvCsd5mIoaO0ND7_6ledger5parse +FNDA:2,_RNvCsd5mIoaO0ND7_6ledger5total +FNDA:1,_RNvCsd5mIoaO0ND7_6ledger6column +FNDA:0,_RNCNCNvCsd5mIoaO0ND7_6ledger5parses_00B5_ +FNDA:0,_RNCNCNvCsd5mIoaO0ND7_6ledger5parses_0s_0B5_ +FNDA:1,_RNCNvCsd5mIoaO0ND7_6ledger5parse0B3_ +FNDA:1,_RNCNvCsd5mIoaO0ND7_6ledger5parses_0B3_ +FNDA:0,_RNCNCNvCs2gWKccma74L_6ledger5parses_00B5_ +FNDA:0,_RNCNCNvCs2gWKccma74L_6ledger5parses_0s_0B5_ +FNDA:0,_RNCNvCs2gWKccma74L_6ledger5parse0B3_ +FNDA:0,_RNCNvCs2gWKccma74L_6ledger5parses_0B3_ +FNDA:0,_RNvCs2gWKccma74L_6ledger3add +FNDA:0,_RNvCs2gWKccma74L_6ledger4line +FNDA:0,_RNvCs2gWKccma74L_6ledger5parse +FNDA:0,_RNvCs2gWKccma74L_6ledger5total +FNDA:0,_RNvCs2gWKccma74L_6ledger6column +FNF:9 +FNH:7 +DA:11,3 +DA:12,3 +DA:13,1 +DA:14,2 +DA:15,2 +DA:16,2 +DA:17,2 +DA:18,2 +DA:19,2 +DA:20,3 +DA:23,2 +DA:24,2 +DA:25,5 +DA:26,5 +DA:27,5 +DA:28,2 +DA:29,2 +DA:32,1 +DA:33,1 +DA:34,1 +DA:36,1 +DA:38,1 +DA:41,1 +DA:42,1 +DA:43,1 +DA:46,1 +DA:47,1 +DA:48,1 +DA:49,1 +DA:50,1 +DA:51,1 +DA:52,1 +DA:53,1 +DA:54,1 +DA:55,1 +DA:56,1 +DA:57,1 +DA:58,1 +DA:59,1 +DA:60,1 +BRF:0 +BRH:0 +LF:44 +LH:42 +end_of_record +SF:src/main.rs +FN:7,_RNvCsgX3xlPyiyFX_6ledger4main +FN:7,_RNvCsbal4zFZueKU_6ledger4main +FNDA:0,_RNvCsgX3xlPyiyFX_6ledger4main +FNDA:0,_RNvCsbal4zFZueKU_6ledger4main +FNF:1 +FNH:0 +DA:7,0 +DA:8,0 +DA:9,0 +DA:10,0 +DA:11,0 +DA:12,0 +DA:13,0 +DA:15,0 +DA:16,0 +DA:17,0 +DA:18,0 +DA:20,0 +DA:21,0 +DA:22,0 +DA:23,0 +DA:24,0 +DA:25,0 +DA:27,0 +DA:28,0 +DA:29,0 +DA:30,0 +DA:31,0 +DA:32,0 +DA:33,0 +DA:34,0 +DA:35,0 +DA:36,0 +DA:37,0 +DA:42,0 +DA:43,0 +DA:46,0 +DA:47,0 +BRF:0 +BRH:0 +LF:32 +LH:0 +end_of_record \ No newline at end of file diff --git a/gsd/parity/goldens/ledger/reports/rust-lint.jsonl b/gsd/parity/goldens/ledger/reports/rust-lint.jsonl new file mode 100644 index 0000000000..39480c4ee4 --- /dev/null +++ b/gsd/parity/goldens/ledger/reports/rust-lint.jsonl @@ -0,0 +1,7 @@ +{"reason":"compiler-artifact","package_id":"path+file:///project#ledger@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"ledger","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":true},"features":[],"filenames":["/project/target/debug/deps/libledger-b97ccb43898388e3.rmeta"],"executable":null,"fresh":false} +{"reason":"compiler-artifact","package_id":"path+file:///project#ledger@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"ledger","src_path":"/project/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/project/target/debug/deps/libledger-c50da65a0b8a32cc.rmeta"],"executable":null,"fresh":false} +{"reason":"compiler-artifact","package_id":"path+file:///project#ledger@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["bin"],"crate_types":["bin"],"name":"ledger","src_path":"/project/src/main.rs","edition":"2021","doc":true,"doctest":false,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/project/target/debug/deps/libledger-cb7840ce4da9cae5.rmeta"],"executable":null,"fresh":false} +{"reason":"compiler-artifact","package_id":"path+file:///project#ledger@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["test"],"crate_types":["bin"],"name":"totals","src_path":"/project/tests/totals.rs","edition":"2021","doc":false,"doctest":false,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":true},"features":[],"filenames":["/project/target/debug/deps/libtotals-04e51b515b2ea863.rmeta"],"executable":null,"fresh":false} +{"reason":"compiler-artifact","package_id":"path+file:///project#ledger@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["bin"],"crate_types":["bin"],"name":"ledger","src_path":"/project/src/main.rs","edition":"2021","doc":true,"doctest":false,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":true},"features":[],"filenames":["/project/target/debug/deps/libledger-2ddd6f0d1997a992.rmeta"],"executable":null,"fresh":false} +{"reason":"compiler-artifact","package_id":"path+file:///project#ledger@0.1.0","manifest_path":"/project/Cargo.toml","target":{"kind":["test"],"crate_types":["bin"],"name":"entries","src_path":"/project/tests/entries.rs","edition":"2021","doc":false,"doctest":false,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":true},"features":[],"filenames":["/project/target/debug/deps/libentries-ffecabafd35033c9.rmeta"],"executable":null,"fresh":false} +{"reason":"build-finished","success":true} diff --git a/gsd/parity/goldens/ledger/reports/rust-osv.json b/gsd/parity/goldens/ledger/reports/rust-osv.json new file mode 100644 index 0000000000..939d28473f --- /dev/null +++ b/gsd/parity/goldens/ledger/reports/rust-osv.json @@ -0,0 +1,9 @@ +{ + "results": [], + "experimental_config": { + "licenses": { + "summary": false, + "allowlist": null + } + } +} diff --git a/gsd/parity/goldens/ledger/reports/rust-sbom.cdx.json b/gsd/parity/goldens/ledger/reports/rust-sbom.cdx.json new file mode 100644 index 0000000000..7039769b0a --- /dev/null +++ b/gsd/parity/goldens/ledger/reports/rust-sbom.cdx.json @@ -0,0 +1,68 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "serialNumber": "urn:uuid:00000000-0000-0000-0000-000000000000", + "metadata": { + "timestamp": "1970-01-01T00:00:00Z", + "tools": [ + { + "vendor": "CycloneDX", + "name": "cargo-cyclonedx", + "version": "0.5.10" + } + ], + "component": { + "type": "application", + "bom-ref": "path+file:///project#ledger@0.1.0", + "name": "ledger", + "version": "0.1.0", + "description": "A ledger of entries in integer cents, on the command line", + "scope": "required", + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/ledger@0.1.0?download_url=file://.", + "components": [ + { + "type": "library", + "bom-ref": "path+file:///project#ledger@0.1.0 bin-target-0", + "name": "ledger", + "version": "0.1.0", + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/ledger@0.1.0?download_url=file://.#src/lib.rs" + }, + { + "type": "application", + "bom-ref": "path+file:///project#ledger@0.1.0 bin-target-1", + "name": "ledger", + "version": "0.1.0", + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/ledger@0.1.0?download_url=file://.#src/main.rs" + } + ] + }, + "properties": [ + { + "name": "cdx:rustc:sbom:target:triple", + "value": "x86_64-unknown-linux-gnu" + } + ] + }, + "components": [], + "dependencies": [ + { + "ref": "path+file:///project#ledger@0.1.0" + } + ] +} \ No newline at end of file diff --git a/gsd/parity/goldens/taskboard/reports/javascript-coverage.lcov b/gsd/parity/goldens/taskboard/reports/javascript-coverage.lcov new file mode 100644 index 0000000000..89053d826a --- /dev/null +++ b/gsd/parity/goldens/taskboard/reports/javascript-coverage.lcov @@ -0,0 +1,40 @@ +TN: +SF:src/tasks.js +FN:3,createBoard +FN:7,addTask +FN:14,completeTask +FNF:3 +FNH:3 +FNDA:3,createBoard +FNDA:3,addTask +FNDA:2,completeTask +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,3 +DA:5,3 +DA:6,1 +DA:7,1 +DA:8,3 +DA:9,3 +DA:10,3 +DA:11,3 +DA:12,3 +DA:13,1 +DA:14,1 +DA:15,2 +DA:16,2 +DA:17,1 +DA:18,1 +DA:19,2 +LF:19 +LH:19 +BRDA:1,0,0,1 +BRDA:3,1,0,3 +BRDA:7,2,0,3 +BRDA:14,3,0,2 +BRDA:16,4,0,1 +BRDA:15,5,0,1 +BRF:6 +BRH:6 +end_of_record diff --git a/gsd/parity/goldens/vault/reports/javascript-coverage.lcov b/gsd/parity/goldens/vault/reports/javascript-coverage.lcov new file mode 100644 index 0000000000..771cfc8229 --- /dev/null +++ b/gsd/parity/goldens/vault/reports/javascript-coverage.lcov @@ -0,0 +1,39 @@ +TN: +SF:src/vault.js +FN:4,createVault +FN:8,seal +FN:15,open +FNF:3 +FNH:3 +FNDA:3,createVault +FNDA:3,seal +FNDA:3,open +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,3 +DA:6,3 +DA:7,1 +DA:8,1 +DA:9,3 +DA:10,3 +DA:11,3 +DA:12,3 +DA:13,3 +DA:14,1 +DA:15,1 +DA:16,3 +DA:17,3 +DA:18,3 +DA:19,3 +DA:20,3 +LF:20 +LH:20 +BRDA:1,0,0,1 +BRDA:4,1,0,3 +BRDA:8,2,0,3 +BRDA:15,3,0,3 +BRF:4 +BRH:4 +end_of_record diff --git a/gsd/parity/record-reports.sh b/gsd/parity/record-reports.sh new file mode 100755 index 0000000000..37d8f83776 --- /dev/null +++ b/gsd/parity/record-reports.sh @@ -0,0 +1,153 @@ +#!/usr/bin/env bash +# Records the tool reports the parity fixtures' report packs read into goldens/<fixture>/reports/, for `cargo gate`'s +# dogfood check, which collects each fixture with every pack it detects from these files (ADR 0393 D9). Run by hand on +# a machine with Docker, never in CI: +# +# gsd/parity/record-reports.sh # every fixture +# gsd/parity/record-reports.sh ledger # one or more of: taskboard vault ledger +# +# Each tool runs in a `--platform linux/amd64` container of an image pinned by digest, on a copy of the fixture's +# tracked files at /project: the copy goes in as a tar stream on standard input and the reports come out as a tar on +# standard output, so no volume is created or mounted and the fixture itself is never touched. A fixture holding an +# uncommitted or untracked file is refused before anything runs: its reports would be ones the committed tree cannot +# reproduce. The tools are installed in the container at the exact versions below and print their versions to standard +# error; only c8 itself is pinned, npm resolves its dependency tree at record time. Each named fixture's reports +# directory is replaced as a whole (a report no longer produced goes) only when every step of every named fixture +# succeeded; a step that fails fails the script. osv-scanner sends the ledger lockfile's package names (`ledger 0.1.0`, +# it has no dependency) to osv.dev; nothing else leaves the machine but the images' and tools' downloads. +# +# Recorded, each with the pack's own argv: +# taskboard, vault javascript-coverage.lcov c8 around the fixture's `npm test` (`@javascript/coverage`) +# ledger rust-coverage.lcov cargo llvm-cov over nextest (`@rust/coverage`; the ledger has a test +# that fails by design, which `--ignore-run-fail` lets through) +# rust-lint.jsonl cargo clippy's JSON messages (`@rust/lint`) +# rust-sbom.cdx.json cargo cyclonedx (`@rust/deps`, rust-sbom) +# rust-osv.json osv-scanner over Cargo.lock (`@rust/deps`, rust-osv) +# rust-api.txt cargo public-api on its pinned nightly (`@rust/api`) +# +# Normalised, so a re-run on the same tools gives the same bytes: a leading `SF:/project/` in an LCOV becomes `SF:` +# (a path outside the project is W203 to the pack; c8 writes relative paths already), and the SBOM's `serialNumber` +# and `timestamp` become `urn:uuid:00000000-0000-0000-0000-000000000000` and `1970-01-01T00:00:00Z`. +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) + +NODE_IMAGE=node:26-bookworm-slim@sha256:0042e17d232a87a2cd485be1da7900fca4d10a4ad11b29e9285da1d2e54798c9 +C8=12.0.0 +RUST_IMAGE=rust:1.99.1@sha256:8a4e90c7946b74626488b1446f712c0fe0ed1a596cbd3d871684bc9c5433ae07 +# The nightly cargo public-api 0.52 builds rustdoc JSON with (its README's compatibility matrix). +NIGHTLY=nightly-2025-11-22 +LLVM_COV=0.9.2 +NEXTEST=0.9.146 +CYCLONEDX=0.5.10 +PUBLIC_API=0.52.0 +OSV_IMAGE=ghcr.io/google/osv-scanner:v2.7.1@sha256:a70ffffc2bfd33482953e5d6b64c6fcdb30239717a07b0f0d3ab2859ce3e4cde + +# Everything the script writes but the reports lives in one directory, removed on exit. +root=$(mktemp -d) +staged="$root/staged" +trap 'rm -rf "$root"' EXIT +# git never reads the operator's configuration or runs their hooks, as seed.py. +quiet_git() { + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 git -c core.hooksPath=/dev/null "$@" +} +# The fixture $1's tracked files as a tar on standard output (no macOS metadata: COPYFILE_DISABLE). +tracked() { + quiet_git -C "$here/fixtures/$1" ls-files -z --cached --others --exclude-standard | + COPYFILE_DISABLE=1 tar -C "$here/fixtures/$1" -c --null -T - -f - +} +# Runs the script $2 with `sh -euc` in a fresh container of image $1 holding the fixture $3's copy at /project; the +# script's standard output is a tar of the reports, unpacked into the fixture's staged directory. Further arguments are +# the script's `$1`... +container() { + image=$1 script=$2 fixture=$3 + shift 3 + mkdir -p "$staged/$fixture" + tracked "$fixture" | + docker run --rm -i --platform linux/amd64 --workdir /project --entrypoint sh "$image" -euc \ + "tar -x --no-same-owner; $script" sh "$@" | + tar -x -C "$staged/$fixture" +} + +# taskboard, vault: c8 around the fixture's own `npm test`, exactly `@javascript/coverage`'s argv. The tests pass, so +# c8's exit status (the test command's) is the script's. +javascript() { + container "$NODE_IMAGE" ' + echo "node $(node --version)" >&2 + npm install --no-save --no-audit --no-fund --no-update-notifier --loglevel=error "c8@$1" >&2 + npm ls --depth=0 c8 >&2 + npx --no -- c8 --reporter=lcovonly --reports-dir=.specforge/reports/javascript-coverage npm test >&2 + sed "s|^SF:/project/|SF:|" .specforge/reports/javascript-coverage/lcov.info >javascript-coverage.lcov + tar -c javascript-coverage.lcov + ' "$1" "$C8" +} + +taskboard() { javascript taskboard; } +vault() { javascript vault; } + +# ledger: the Rust tools in one container (installed with --locked; the pinned nightly is active for cargo public-api +# only, every other tool runs on the image's stable), then osv-scanner in its own image. +ledger() { + container "$RUST_IMAGE" ' + rustup component add llvm-tools-preview clippy >&2 + rustup toolchain install "$1" --profile minimal >&2 + cargo install --locked "cargo-llvm-cov@$2" "cargo-nextest@$3" "cargo-cyclonedx@$4" "cargo-public-api@$5" >&2 + for tool in "rustc --version" "rustc +$1 --version" "cargo clippy --version" "cargo llvm-cov --version" \ + "cargo nextest --version" "cargo cyclonedx --version" "cargo public-api --version"; do + $tool >&2 + done + mkdir /reports + cargo llvm-cov nextest --workspace --ignore-run-fail --lcov --output-path /reports/lcov.info >&2 + sed "s|^SF:/project/|SF:|" /reports/lcov.info >/reports/rust-coverage.lcov + cargo clippy --workspace --all-targets --message-format=json >/reports/rust-lint.jsonl + cargo cyclonedx --format json --spec-version 1.5 --all-features --override-filename rust-sbom.cdx >&2 + sed -e "s|\"serialNumber\": *\"[^\"]*\"|\"serialNumber\": \"urn:uuid:00000000-0000-0000-0000-000000000000\"|" \ + -e "s|\"timestamp\": *\"[^\"]*\"|\"timestamp\": \"1970-01-01T00:00:00Z\"|" rust-sbom.cdx.json \ + >/reports/rust-sbom.cdx.json + # cargo public-api finds a toolchain named `nightly` by itself; a dated one must be the active toolchain. + RUSTUP_TOOLCHAIN="$1" cargo public-api --color never -ss >/reports/rust-api.txt + cd /reports + tar -c rust-coverage.lcov rust-lint.jsonl rust-sbom.cdx.json rust-api.txt + ' ledger "$NIGHTLY" "$LLVM_COV" "$NEXTEST" "$CYCLONEDX" "$PUBLIC_API" + # Exit 1 is "vulnerabilities found", a report like any other; every other non-zero is a failure. + container "$OSV_IMAGE" ' + /osv-scanner --version >&2 + status=0 + /osv-scanner scan source --lockfile Cargo.lock --format json --output-file rust-osv.json >&2 || status=$? + [ "$status" -le 1 ] || { echo "record-reports.sh: osv-scanner exited $status" >&2; exit 1; } + tar -c rust-osv.json + ' ledger +} + +fixtures=("$@") +[ ${#fixtures[@]} -gt 0 ] || fixtures=(taskboard vault ledger) +for fixture in "${fixtures[@]}"; do + case $fixture in + taskboard | vault | ledger) ;; + *) echo "record-reports.sh: no fixture '$fixture' (taskboard, vault, ledger)" >&2; exit 1 ;; + esac + if [ -n "$(quiet_git -C "$here/fixtures/$fixture" status --porcelain -- .)" ]; then + echo "record-reports.sh: fixtures/$fixture holds uncommitted or untracked files; commit or remove them" >&2 + exit 1 + fi +done +for fixture in "${fixtures[@]}"; do + "$fixture" +done + +# A container's tar may hold a symlink (or a device, a FIFO, a directory) that a copy would follow out to a host file +# or trip on halfway: the reports are regular files directly in staged/<fixture>, so anything else refuses every +# fixture before a reports directory is touched. +odd=$(find "$staged" -mindepth 2 ! -type f) +if [ -n "$odd" ]; then + echo "record-reports.sh: a container wrote something other than a regular report file, nothing recorded:" >&2 + echo "$odd" >&2 + exit 1 +fi +for fixture in "${fixtures[@]}"; do + out="$here/goldens/$fixture/reports" + rm -rf "$out" + mkdir -p "$out" + cp -P "$staged/$fixture"/* "$out"/ + echo "recorded $(ls "$staged/$fixture" | wc -l | tr -d ' ') reports in $out" +done diff --git a/spec/extensions/code/core/features.spec b/spec/extensions/code/core/features.spec index 49589b28c6..0d87fecba2 100644 --- a/spec/extensions/code/core/features.spec +++ b/spec/extensions/code/core/features.spec @@ -1,3 +1,22 @@ +requirement FEATURE-155 "An API Entry Judged Against Its Accepted Report" { + category "Feature" + tier v2 + text """ + An api_item fact said what a run's public API holds, but not what + changed since the API a project committed, so no guard could name a + break. + + @code/core 1.4.0 adds four optional api_item fields (ADR 0390 D3): + change, one of added, unchanged, changed, narrowed or removed; + accepted_signature and accepted_tag, what the committed accepted report + wrote; and accepted_visibility, its visibility when it differs. A pack + judges only a crate or package present in both the run and the accepted + report; any other entry carries no change. Entries pair by id, then by + comparable signature, never by repeat suffix. A removed entry cites no + item, and W104 does not report it. + """ +} + requirement FEATURE-004 "Test Facts a Spec Can Cite" { category "Feature" tier v2 diff --git a/spec/extensions/javascript/api/features.spec b/spec/extensions/javascript/api/features.spec new file mode 100644 index 0000000000..ea0fac65fb --- /dev/null +++ b/spec/extensions/javascript/api/features.spec @@ -0,0 +1,35 @@ +requirement FEATURE-149 "API Snapshot Facts (JavaScript)" { + category "Feature" + tier v2 + text """ + A JavaScript package's public API became facts only from an + api-extractor doc model someone else had written: no JavaScript pack + ran api-extractor. + + @javascript/api runs api-extractor through npx --no, which never + downloads it, when the project has a tsconfig.json. The pack owns the + config file the host writes for the run: its entry is the built + dist/index.d.ts, so the project builds its declarations first, and it + writes only the doc model, to the report path; no API report, rollup + or metadata file lands in the project. The pack reads the doc model + with the API library and answers an api_item fact per member, citing + the one @javascript/source item of the package with that name path. + + The accepted API is the report the project commits for review, + read beside the run (files up to 4 MiB): api-extractor's + etc/<package>.api.md (glob **/etc/*.api.md) or rush's + common/reviews/api/<package>.api.md. api-extractor's temp/ copy, + the fresh run's own, and the alpha, beta and public report variants + are never read. Only the package the run read is judged: each + api_item then carries its change (added, unchanged, changed, + narrowed, removed) against its report; without one the facts carry + none. A report of the package that does not parse, or two reports + of the package, is the collector's error naming them; a file the + host did not serve, with no report title, or of another package, + broken or not, is one warning naming it (W203) and the collect goes + on. + Accepting a break is committing the updated report, written by the + project's own api-extractor run --local with the report enabled and + the pack's entry. + """ +} diff --git a/spec/extensions/javascript/coverage/features.spec b/spec/extensions/javascript/coverage/features.spec new file mode 100644 index 0000000000..0d1c86fe5d --- /dev/null +++ b/spec/extensions/javascript/coverage/features.spec @@ -0,0 +1,16 @@ +requirement FEATURE-144 "LCOV Coverage Facts (JavaScript)" { + category "Feature" + tier v2 + text """ + A JavaScript project's coverage became facts only from an LCOV file + someone else had written: no JavaScript pack ran a coverage tool. + + @javascript/coverage runs c8 around the project's own npm test, so the + project's test command decides what runs, through npx --no, which never + downloads c8. It reads c8's LCOV with the LCOV library and answers a + coverage fact per @javascript/source item its lines reach, one per file + for what no item holds. A file outside the project is skipped and + counted, and the pack names the report and the skipped paths in one + warning, W203 (ADR 0389 D7). + """ +} diff --git a/spec/extensions/javascript/deps/features.spec b/spec/extensions/javascript/deps/features.spec new file mode 100644 index 0000000000..5a123fbb29 --- /dev/null +++ b/spec/extensions/javascript/deps/features.spec @@ -0,0 +1,24 @@ +requirement FEATURE-147 "Dependency and Vulnerability Facts (JavaScript)" { + category "Feature" + tier v2 + text """ + A JavaScript project's dependencies and their known vulnerabilities + became facts only from a CycloneDX bill of materials or an osv-scanner + report someone else had written: no JavaScript pack ran either tool. + + @javascript/deps runs cyclonedx-npm when the project has a + package-lock.json, through npx --no, which never downloads it, and + with --package-lock-only, which reads the lockfile alone. It reads the + bill of materials with the CycloneDX library and answers a dependency + fact per component, citing the @javascript/source package the bill's + root names. A bill whose root names no collected package is an error + naming the report. + + A second collector runs osv-scanner on the same lockfile and answers a + vulnerability fact per OSV record, citing the npm package at or under + the lockfile's directory. osv-scanner exiting 1 because it found + vulnerabilities is no failure: the pack reads the report. Every package + the scan lists that no collected package holds is named in a warning, + W203 (ADR 0389 D7), never dropped. + """ +} diff --git a/spec/extensions/javascript/jest/features.spec b/spec/extensions/javascript/jest/features.spec new file mode 100644 index 0000000000..0759c3e6dc --- /dev/null +++ b/spec/extensions/javascript/jest/features.spec @@ -0,0 +1,18 @@ +requirement FEATURE-152 "jest Test Facts" { + category "Feature" + tier v2 + text """ + A JavaScript project tested with jest had no runner pack: its tests + never became test facts a spec could cite by id. + + @javascript/jest runs the project's jest through node --env-file, the + file being the pack's config, which the host writes for the run and + which sets jest-junit's options: the report path, the file attribute + and the test naming. jest-junit is a dev dependency of the project. The + pack answers a test and a test_run fact per test, named + js:<package>/<file>#<describe > test> after the nearest named + package.json, as @javascript/node-test names a test; a failed, skipped + or passed test keeps its status and time, and a test no named package + owns, or with no file, is the collector's error. + """ +} diff --git a/spec/extensions/javascript/lint/features.spec b/spec/extensions/javascript/lint/features.spec new file mode 100644 index 0000000000..b69d5e6038 --- /dev/null +++ b/spec/extensions/javascript/lint/features.spec @@ -0,0 +1,18 @@ +requirement FEATURE-145 "SARIF Lint Facts (JavaScript)" { + category "Feature" + tier v2 + text """ + A JavaScript project's lint findings became facts only from a SARIF log + someone else had written: no JavaScript pack ran a linter. + + @javascript/lint runs ESLint with the @microsoft/eslint-formatter-sarif + formatter when the project has an eslint.config file, through npx --no, + which never downloads ESLint, so the project's own config decides the + rules. It reads the SARIF with the SARIF library and answers a + static_finding fact per result, citing the innermost + @javascript/source item holding its line, else the package holding its + file. A result in a file outside the project is skipped and counted, + and the pack names the report and the skipped paths in one warning, + W203 (ADR 0389 D7). + """ +} diff --git a/spec/extensions/javascript/playwright/features.spec b/spec/extensions/javascript/playwright/features.spec new file mode 100644 index 0000000000..3b51c7297e --- /dev/null +++ b/spec/extensions/javascript/playwright/features.spec @@ -0,0 +1,19 @@ +requirement FEATURE-153 "Playwright Test Facts" { + category "Feature" + tier v2 + text """ + A JavaScript project tested with Playwright had no runner pack: its + end-to-end tests never became test facts a spec could cite by id. + + @javascript/playwright runs Playwright through npx --no, which never + downloads it, when the project has a Playwright config, with its JUnit + reporter; Playwright writes that report to standard output, which the + host captures for the pack, and a saved report reads the same. The pack + answers a test and a test_run fact per test, named + js:<package>/<file>#<describe > test> after the nearest named + package.json, as @javascript/node-test names a test; the file is + relative to Playwright's testDir, as Playwright writes it. A failed, + skipped or passed test keeps its status and time, and a test no named + package owns is the collector's error. + """ +} diff --git a/spec/extensions/javascript/source/features.spec b/spec/extensions/javascript/source/features.spec index 11ec9dddd7..df50f22c26 100644 --- a/spec/extensions/javascript/source/features.spec +++ b/spec/extensions/javascript/source/features.spec @@ -8,11 +8,18 @@ requirement FEATURE-056 "JavaScript Item Facts" { requirement names was a string no check could resolve. @javascript/source has the host's reader parse each source file a - named package owns, test files and generated output left out, with the - pack's query: the typescript grammar for .ts .mts .cts, tsx for the - rest. Every declaration at item scope and every member of a class or - an interface there becomes an item fact - js:<package>/<file>::<name>[.<member>] minted by specforge-code-facts, - and every named package a pkg:npm/<name> package fact (ADR 0347). + named package owns, generated output left out, with the pack's query: + the typescript grammar for .ts .mts .cts, tsx for the rest. Every + declaration at item scope and every member of a class or an interface + there becomes an item fact js:<package>/<file>::<name>[.<member>] + minted by specforge-code-facts, and every named package a + pkg:npm/<name> package fact (ADR 0347). A test file is read through a + second query for its statically named test calls only: each is a + function item with the attribute test. A call node reports as a test + case carries the test_id js:<package>/<file>#<suite > ... > name> + node-test gives it: a skipped call, or one with no test, suite or + subtest call inside it. A test or suite holding one is reported as a + suite and carries none, and nothing inside a skipped call is an item + (ADR 0393). """ } diff --git a/spec/extensions/javascript/vitest/features.spec b/spec/extensions/javascript/vitest/features.spec new file mode 100644 index 0000000000..ca30d75b79 --- /dev/null +++ b/spec/extensions/javascript/vitest/features.spec @@ -0,0 +1,18 @@ +requirement FEATURE-151 "vitest Test Facts" { + category "Feature" + tier v2 + text """ + A JavaScript project tested with vitest had no runner pack for @code/core: + the legacy @specforge/vitest gives entity results from vitest's JSON + report, never test facts a spec could cite by id. + + @javascript/vitest runs vitest through npx --no, which never downloads + it, when the project has a vitest config, with its JUnit reporter + writing the report the pack reads. The pack answers a test and a + test_run fact per test, named js:<package>/<file>#<describe > test> + after the nearest named package.json, as @javascript/node-test names a + test; a failed, skipped or passed test keeps its status and time, and a + test no named package owns is the collector's error. The legacy pack + keeps its collector vitest; this one is javascript-vitest. + """ +} diff --git a/spec/extensions/rust/api/features.spec b/spec/extensions/rust/api/features.spec new file mode 100644 index 0000000000..1e1bea63ae --- /dev/null +++ b/spec/extensions/rust/api/features.spec @@ -0,0 +1,34 @@ +requirement FEATURE-150 "API Snapshot Facts (Rust)" { + category "Feature" + tier v2 + text """ + A Rust crate's public API became facts only from a cargo public-api + snapshot someone else had written: no Rust pack ran the tool. + + @rust/api runs cargo public-api when the project has a Cargo.toml, + omitting blanket and auto-trait impls. The tool prints to standard + output only, which the host captures for the pack. It reads one + package per run: the root package, unless the caller's filter names + another, which the host passes as --package. It builds the crate's + rustdoc JSON with a nightly toolchain it finds by itself. The pack + reads the text with the API library and answers an api_item fact per + public entry, citing the one @rust/source item of the library crate + its path names. A run that read no entry, as when the nightly + toolchain is missing and the error went to stderr, gives a warning + that nothing was recorded (W203) instead of looking like a clean run. + + The accepted API is a committed public-api.txt, read beside the run + (glob **/public-api.txt, files up to 4 MiB) and written with the + pack's own flags (cargo public-api --color never -ss). Only a crate + on both sides is judged: each api_item then carries its change + (added, unchanged, changed, narrowed, removed) against the accepted + file; without one the facts carry none. A snapshot of the run's + crate that does not parse, or two files naming one crate, is the + collector's error naming them; a file the host did not serve, or + naming no crate the run read, broken or not, is one warning naming + it (W203) and the collect goes on, so + an unusable baseline never passes silently. Accepting a break is + committing the updated file. A narrowing to pub(crate) reads as + removed, as the tool lists public items only. + """ +} diff --git a/spec/extensions/rust/coverage/features.spec b/spec/extensions/rust/coverage/features.spec new file mode 100644 index 0000000000..7f2aa847be --- /dev/null +++ b/spec/extensions/rust/coverage/features.spec @@ -0,0 +1,17 @@ +requirement FEATURE-143 "LCOV Coverage Facts (Rust)" { + category "Feature" + tier v2 + text """ + A Rust project's coverage became facts only from an LCOV file someone + else had written: no Rust pack ran a coverage tool, and the LCOV reader + failed the whole report when one file lay outside the project. + + @rust/coverage runs cargo-llvm-cov over nextest for the workspace, with + failing tests still writing the report, reads its LCOV with the LCOV + library and answers a coverage fact per @rust/source item its lines + reach, one per file for what no item holds. A file outside the project, + a path dependency beside the workspace, is skipped and counted, and the + pack names the report and the skipped paths in one warning, W203 + (ADR 0389 D7). + """ +} diff --git a/spec/extensions/rust/deps/features.spec b/spec/extensions/rust/deps/features.spec new file mode 100644 index 0000000000..7eb7bec24b --- /dev/null +++ b/spec/extensions/rust/deps/features.spec @@ -0,0 +1,24 @@ +requirement FEATURE-148 "Dependency and Vulnerability Facts (Rust)" { + category "Feature" + tier v2 + text """ + A Rust project's dependencies and their known vulnerabilities became + facts only from a CycloneDX bill of materials or an osv-scanner report + someone else had written: no Rust pack ran either tool. + + @rust/deps runs cargo-cyclonedx when the project has a Cargo.toml. + cargo-cyclonedx writes one bill of materials beside each workspace + member's manifest and takes no output path, so the collector's report + is the glob **/rust-sbom.cdx.json, read fresh after the run. Every + bill the glob finds becomes a dependency fact per component, citing + the @rust/cargo package its root names; a bill whose root names no + collected package is an error naming that report. + + A second collector runs osv-scanner on Cargo.lock and answers a + vulnerability fact per OSV record, citing the cargo packages at or + under the lockfile's directory. osv-scanner exiting 1 because it found + vulnerabilities is no failure: the pack reads the report. Every package + the scan lists that no collected package holds is named in a warning, + W203 (ADR 0389 D7), never dropped. + """ +} diff --git a/spec/extensions/rust/lint/features.spec b/spec/extensions/rust/lint/features.spec new file mode 100644 index 0000000000..c07df2d085 --- /dev/null +++ b/spec/extensions/rust/lint/features.spec @@ -0,0 +1,24 @@ +requirement FEATURE-146 "Clippy Lint Facts (Rust)" { + category "Feature" + tier v2 + text """ + A Rust project's clippy diagnostics became facts only from a SARIF log + someone else had converted: no Rust pack ran clippy, and clippy writes + no SARIF. + + @rust/lint runs cargo clippy over the whole workspace and all targets + with cargo's JSON messages, and the host captures its standard output. + The pack converts each diagnostic's primary span into a SARIF result, + keeps one of the copies --all-targets writes for a library checked as + lib and as lib test, and answers a static_finding fact per diagnostic, + citing the innermost @rust/source item holding its line, else the + package holding its file. A cut-off capture is an error: a line cut + inside names its number, and a capture with no build-finished record, + which cargo writes last on every run that ends, is a run cut off. + A span in a file outside the project is skipped and counted, and the + pack names the capture and the skipped paths in one warning, W203 + (ADR 0389 D7). A span naming no file, such as rustc's <std macros>, + is skipped and counted the same way in a warning of its own, never + minted at a file no one can open. + """ +} diff --git a/spec/extensions/rust/proof/features.spec b/spec/extensions/rust/proof/features.spec new file mode 100644 index 0000000000..809eceaf5b --- /dev/null +++ b/spec/extensions/rust/proof/features.spec @@ -0,0 +1,29 @@ +requirement FEATURE-154 "Kani Proof Facts" { + category "Feature" + tier v2 + text """ + A Kani proof harness left no trace in the graph: no pack ran Kani, and + no reader read what it prints. + + @rust/proof runs cargo-kani over the workspace when the project has a + Cargo.toml and reads Kani's regular output, which the host captures + from standard output. Each proof harness becomes a test and its run, + named rust:<crate>#<harness path>, passed when Kani says SUCCESSFUL + and failed when it says FAILED, placed at the item @rust/source + answered for the harness function. The crate is found from the served + items, as Kani prints harness paths without it. An output cut off + before Kani's Complete line, or whose Complete totals disagree with + the harnesses read, is the collector's error, never a dropped proof. + An output with no harness at all reads the same whether the crate has + none or Kani stopped at the build, so the pack warns that nothing was + checked (W203) instead of looking like a clean run. + + Kani verifies Rust only and runs on Linux x86_64 and macOS, not on + Windows. There is no JavaScript proof pack: no JavaScript tool proves + a property of all inputs and reports a verdict per harness the way + Kani does. Property-based testing samples inputs and already reports + through the runner packs, and TypeScript's checker proves types, not + behaviour, so a JavaScript proof pack would be a test runner under + another name. + """ +} diff --git a/specforge.json b/specforge.json index a5884090b6..76e2c4bdae 100644 --- a/specforge.json +++ b/specforge.json @@ -10,5 +10,18 @@ "@rust/cargo", "@rust/source", "@rust/test" - ] + ], + "settings": { + "@rust/cargo": { + "exclude": [ + "crates/app/ops/tests/fixtures", + "examples", + "extensions/rust/manifest/fixtures", + "fixtures", + "gsd/core/tests/projects", + "gsd/parity/fixtures", + "xtask/tests/fixtures" + ] + } + } } diff --git a/xtask/src/revendor.rs b/xtask/src/revendor.rs index 7b08e4a0e9..15a0f1e330 100644 --- a/xtask/src/revendor.rs +++ b/xtask/src/revendor.rs @@ -523,7 +523,7 @@ mod tests { /// The step takes `@gsd/core`'s kinds, read from the tracked golden, beside the pinned builtins. /// It runs in every test run; the vocabulary drift test of `specforge-project` holds the step's - /// output over the fifteen pinned builtins, the vendored `@gsd/core` among them. + /// output over every pinned builtin, the vendored `@gsd/core` among them. #[test] fn the_vocabulary_step_takes_gsd_cores_kinds_golden_beside_the_builtins() { the_step_takes_gsd_core_beside_the_builtins(gsd_core_kinds_golden());