diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab8ae483e7..c8bbbc7865 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,7 @@ jobs: outputs: rust: ${{ steps.groups.outputs.rust }} windows: ${{ steps.groups.outputs.windows }} + static: ${{ steps.groups.outputs.static }} xtask: ${{ steps.groups.outputs.xtask }} node: ${{ steps.groups.outputs.node }} eval: ${{ steps.groups.outputs.eval }} @@ -71,6 +72,29 @@ jobs: run: cargo install --jobs 2 --locked cargo-deny --version '=0.20.2' - name: Check dependency advisories and licenses run: cargo deny --locked check advisories licenses + static-checks: + needs: changes + if: needs.changes.outputs.static == 'true' + runs-on: [self-hosted, linux, x64] + timeout-minutes: 10 + env: + CARGO_INCREMENTAL: "0" + CARGO_TARGET_DIR: ${{ github.workspace }}/target + RUSTC_WRAPPER: "" + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - uses: actions-rust-lang/setup-rust-toolchain@c8ff772090ab9d00f7f7bd7b388f3c3032282e3b + with: + cache: false + build-warnings: "" + - name: Run pure static repository checks + run: | + cargo fmt --all -- --check --config error_on_line_overflow=true + cargo clippy --locked -p xtask-check --all-targets -- -D warnings + cargo test --locked -p xtask-check + cargo run --locked -p xtask-check windows-cli: needs: changes if: needs.changes.outputs.windows == 'true' @@ -377,7 +401,7 @@ jobs: retention-days: 1 ci-ok: # The one check to require: it passes when every selected job passed and skipped jobs were not needed. - needs: [changes, dependencies, windows-cli, web, verify, macos-native, acp-registry] + needs: [changes, dependencies, static-checks, windows-cli, web, verify, macos-native, acp-registry] if: always() runs-on: self-hosted timeout-minutes: 5 diff --git a/AGENTS.md b/AGENTS.md index 1a1a7a2a13..3f8fcc897a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,7 +80,8 @@ Run at the workspace root: | `./dev check` | Daily: formatting and Clippy for the CLI and App Server | | `cargo clippy --workspace --all-targets --locked -- -D warnings` | Before merging | | `cargo test --workspace --locked` | Before merging | -| `cargo run --locked -p xtask -- check` | After changing capabilities, assembly or crate dependencies | +| `cargo run --locked -p xtask-check` | Pure static repository checks only (crate/module boundaries, plugin docs, `npm/branch-services.d.ts`, plugin locks, comment links, `literal_main`), without compiling business crates | +| `cargo run --locked -p xtask -- check` | After changing capabilities, assembly or crate dependencies (runs `xtask-check` plus runtime-assembled `catalog.md`) | | `node --test scripts/*.test.mjs` | After changing development or release scripts | | `cargo build --locked -p dimcode -p dim-app-server && node scripts/tui-tmux/run.mjs` | Before and after changing terminal UI behavior; local only, never in CI ([suite](docs/architecture/tui-e2e.md)) | @@ -94,7 +95,8 @@ Assembly graphs and crate dependencies are computed from the actual code by `xta | --- | --- | | `cargo run --locked -p xtask -- graph` | Regenerate `docs/architecture/rust-agent/generated/`: `services.mmd` / `services.md` (service assembly), `instances.mmd` (instance keys), `crates.mmd` (crate dependencies) and their `.json` snapshots, and `catalog.md` (the service catalog and the parts that are Capabilities) | | `cargo run --locked -p xtask -- module-graph DIR` | Emit `modules.json` and `modules.mmd` into `DIR` on demand for local inspection without committing them | -| `cargo run --locked -p xtask -- check` | Verify crate and module source boundaries live from code, that `crates.*` under `generated/` match the code (read-only: a stale file fails and names it; only `graph` writes them), that `catalog.md` matches the real assembly, and that `npm/branch-services.d.ts` matches the services marked `#[rutis::service]` | +| `cargo run --locked -p xtask-check` | Run the pure static checks without compiling workspace runtime crates (crate/module boundaries, `crates.*` freshness, plugin pages, `npm/branch-services.d.ts`, plugin locks, comment links, `literal_main`); also supports `module-graph DIR` and `types` | +| `cargo run --locked -p xtask -- check` | Run `xtask-check` plus the runtime-assembled `catalog.md` check against the real App Server assembly | | `cargo run --locked -p xtask -- types` | Regenerate `npm/branch-services.d.ts`, the TypeScript declarations of the services marked `#[rutis::service]`, after changing one of them or a type it uses | | `cargo run --release --locked -p xtask -- measure` | Resource measurement; pass `--model-config PATH` (e.g. `crates/dim-agent-aimux/examples/offline.json`) | | `cargo run --release --locked -p xtask -- context-replay` | Opt-in context memory baseline: 100 mock turns against a temporary SQLite store | diff --git a/Cargo.lock b/Cargo.lock index d156118a37..dd7cb22b64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6052,17 +6052,25 @@ dependencies = [ "dim-session-title", "futures-util", "libc", - "proc-macro2", "rusqlite", "rutis", "rutis-bridge", "rutis-loader", - "rutis-types", "serde", "serde_json", - "syn 2.0.119", "tokio", "tokio-util", + "xtask-check", +] + +[[package]] +name = "xtask-check" +version = "0.1.0-alpha.27" +dependencies = [ + "proc-macro2", + "rutis-types", + "serde_json", + "syn 2.0.119", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 33a3e8285d..e0c4d26ce9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["crates/dim-agent-types", "crates/dim-agent-runtime", "crates/dim-agent-capabilities", "crates/dim-agent-aimux", "crates/dim-agent-attachments", "crates/dim-agent-questions", "crates/dim-agent-scheduler", "crates/dim-event-hub", "crates/dim-app-server", "crates/dim-client", "crates/dim-acp", "crates/dim-cli", "crates/dim-oauth", "crates/dim-session-title", "crates/dim-goal", "crates/dim-report", "crates/dim-codemode", "crates/dim-modality", "crates/dim-image-understanding", "crates/dim-ocr", "crates/dim-modality-aimux", "crates/dimcode", "crates/dim-migration", "xtask", "tests/extension-a", "tests/extension-b", "tests/integration"] +members = ["crates/dim-agent-types", "crates/dim-agent-runtime", "crates/dim-agent-capabilities", "crates/dim-agent-aimux", "crates/dim-agent-attachments", "crates/dim-agent-questions", "crates/dim-agent-scheduler", "crates/dim-event-hub", "crates/dim-app-server", "crates/dim-client", "crates/dim-acp", "crates/dim-cli", "crates/dim-oauth", "crates/dim-session-title", "crates/dim-goal", "crates/dim-report", "crates/dim-codemode", "crates/dim-modality", "crates/dim-image-understanding", "crates/dim-ocr", "crates/dim-modality-aimux", "crates/dimcode", "crates/dim-migration", "xtask", "xtask/check", "tests/extension-a", "tests/extension-b", "tests/integration"] exclude = ["vendor/grok-build"] [workspace.package] diff --git a/docs/design/branch-typescript.md b/docs/design/branch-typescript.md index 521db102ab..2328ee3996 100644 --- a/docs/design/branch-typescript.md +++ b/docs/design/branch-typescript.md @@ -88,7 +88,7 @@ closures stay as they are for Rust callers: part write, so the branch `Timeline` is exported as is. Native serde forms stay authoritative (`InputMessageData`, `BranchOptions`, `TimelineInfo`, -`AgentEvent`). `AgentEvent`'s TypeScript is declared in [`xtask types`](../../xtask/src/types.rs) with the `npm/plugin.d.ts` shape, +`AgentEvent`). `AgentEvent`'s TypeScript is declared in [`xtask types`](../../xtask/check/src/types.rs) with the `npm/plugin.d.ts` shape, because its sequence fields use custom serde. Sequences cross as `number | bigint`; do not coerce them through `Number`. @@ -203,5 +203,5 @@ Existing C4 tools, methods, observation and Settings flows keep their own `node_ - [Dispatcher](../../crates/dim-agent-runtime/src/core/dispatcher.rs), [Timeline](../../crates/dim-agent-runtime/src/core/timeline.rs), [TimelineIdentity and BranchLifecycle](../../crates/dim-agent-runtime/src/config.rs) - [TimelineTree / TreeCommands](../../crates/dim-agent-capabilities/src/timeline_tree.rs) - [InputQueue rebuild](../../crates/dim-agent-capabilities/src/input_queue.rs) -- [Declaration generator](../../xtask/src/types.rs) and [row placement](../../crates/dim-app-server/src/session_typescript.rs) +- [Declaration generator](../../xtask/check/src/types.rs) and [row placement](../../crates/dim-app-server/src/session_typescript.rs) - [Goal consumer contracts](plugins/Goal.md) diff --git a/docs/release/README.md b/docs/release/README.md index ae1e0288d8..a72fd88bfd 100644 --- a/docs/release/README.md +++ b/docs/release/README.md @@ -180,7 +180,7 @@ release packages use the ordinary Cargo executable. `ci.yml` runs on pull requests, pushes to `main`, and manual dispatch. A pull request runs the groups its changed paths need, as decided by `scripts/ci-changes.mjs`. A push to `main` runs only `changes` and `ci-ok` when its entire push range changes only documentation paths that select no check group. Architecture pages checked by `xtask` and the native storage format document retain the full main run, as do mixed pushes and pushes whose base cannot be compared. Manual dispatch selects every group. Every push to `main` runs its selected jobs to completion: a later push does not cancel them, so each merge has its own result and the `main CI` badge in the [README](../../README.md) reports the latest finished one. -CI builds the workspace, checks formatting and Clippy, runs workspace tests and boundary checks, runs the packaging/development script tests, and exercises the ignored actual CLI profile and public Node-backed flows. `ci-ok` passes when every selected gating job passes, so it is the check to require. CI builds without debug info (`CARGO_PROFILE_DEV_DEBUG=0`). The [build environment](../architecture/build.md) describes test artifact reuse, concurrency limits, and target deadlines. Cargo runs documentation tests with the same features, and ignored CLI and Node flows reuse the recorded binaries without package-scoped recompilation. Web source changes also run the `xtask` check, which reads them for branch id literals. Node-backed checks run for runtime, binding and service-contract paths, and CLI-only changes retain their ordinary and actual-profile flows. Evaluation tests use `xtask/eval-tests` for `xtask/` changes, and the wall-clock handoff runs for execution-related changes. PRs run `verify (linux)` for the selected groups. Rust changes also run `macos-native` on Apple Silicon, and changes affecting native packaging or code layout select its macOS script checks. Both jobs feed `ci-ok`. Full `main` pushes run `verify (macos)`, and manual dispatch runs full verification on both Linux and macOS. The `web` job runs on self-hosted Windows x64. It stages the frontend package, verifies generated declarations and bundled dependency notices, and runs the Web tests. +CI builds the workspace, checks formatting and Clippy, runs workspace tests and boundary checks, runs the packaging/development script tests, and exercises the ignored actual CLI profile and public Node-backed flows. `ci-ok` passes when every selected gating job passes, so it is the check to require. CI builds without debug info (`CARGO_PROFILE_DEV_DEBUG=0`). The [build environment](../architecture/build.md) describes test artifact reuse, concurrency limits, and target deadlines. Cargo runs documentation tests with the same features, and ignored CLI and Node flows reuse the recorded binaries without package-scoped recompilation. Web source changes, plugin pages and static generated graphs run the lightweight `static-checks` job (`xtask-check`) on Linux x64 without compiling business runtime crates, while `catalog.md` changes retain the runtime-assembled `xtask` check. Node-backed checks run for runtime, binding and service-contract paths, and CLI-only changes retain their ordinary and actual-profile flows. Evaluation tests use `xtask/eval-tests` for `xtask/` changes, and the wall-clock handoff runs for execution-related changes. PRs run `verify (linux)` for the selected groups. Rust changes also run `macos-native` on Apple Silicon, and changes affecting native packaging or code layout select its macOS script checks. Both jobs feed `ci-ok`. Full `main` pushes run `verify (macos)`, and manual dispatch runs full verification on both Linux and macOS. The `web` job runs on self-hosted Windows x64. It stages the frontend package, verifies generated declarations and bundled dependency notices, and runs the Web tests. The `Verify Python plugins` step is off by default. When a Python plugin ships, set the repository Actions variable `DIM_CI_PYTHON_PLUGINS` to `true` to run it whenever the Node check group is selected. It prepares CPython for the `python_plugin_` flows and reuses the App Server test binary from the workspace build. See the [App Server verification commands](../../crates/dim-app-server/README.md#verification) to run the suites locally. diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index fc6a4b54f0..309b23374d 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -1,19 +1,20 @@ import {execFileSync,spawnSync} from 'node:child_process'; import {appendFileSync} from 'node:fs'; -export const groups=['rust','windows','xtask','node','eval','execution','web','scripts','macos_scripts','dependencies']; +export const groups=['rust','windows','static','xtask','node','eval','execution','web','scripts','macos_scripts','dependencies']; const everything=Object.fromEntries(groups.map(group=>[group,true])); const documentation=/^docs\/|^[^/]+\.md$/; const rules=[ [/^benchmarks\/baselines\/[^/]+\.json$/,[]], - [/^docs\/architecture\/rust-agent\/(plugins|generated)\//,['xtask']], + [/^docs\/architecture\/rust-agent\/generated\/catalog\.md$/,['xtask']], + [/^docs\/architecture\/rust-agent\/(plugins|generated)\//,['static']], [/^docs\/design\/appserver\/native-storage-format\.md$/,['rust']], // The ADR check runs in the changes job; docs alone need no build group. [documentation,[]], [/^deny\.toml$|^LICENSE$/,['dependencies']], [/^web\/src\/features\/chat\/quote-cases\.json$/,['web','rust','windows']], - [/^web\/src\/.*\.(ts|vue|mjs|js)$/,['web','xtask']], + [/^web\/src\/.*\.(ts|vue|mjs|js)$/,['web','static']], [/^web\//,['web']], [/^scripts\/run-rust-test\.mjs$/,groups], [/^scripts\/test-macos-native(?:\.test)?\.mjs$/,['rust','scripts','web']], @@ -26,6 +27,7 @@ const rules=[ [/^crates\/dimcode\//,['rust']], [/^crates\/dim-agent-capabilities\/src\/(background_exec|workspace_tools\/exec|host_platform)/,['rust','node','execution']], [/^tests\/integration\/tests\/(local_execution|local_support|minimal_execution)/,['rust','node','execution']], + [/^xtask\/check\//,['static','xtask']], [/^xtask\//,['rust','node','eval']], [/^(crates|tests|vendor|runtime|npm)\//,['rust','node']], ]; diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index 9bdbecadc9..c1dbaace75 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -32,13 +32,15 @@ test('documentation-only changes need no build group',()=>{ }); test('documents that code reads keep their checks',()=>{ - assert.deepEqual(classify(['docs/architecture/rust-agent/plugins/goal.md']),only('xtask')); + assert.deepEqual(classify(['docs/architecture/rust-agent/plugins/goal.md']),only('static')); + assert.deepEqual(classify(['docs/architecture/rust-agent/generated/crates.mmd']),only('static')); + assert.deepEqual(classify(['docs/architecture/rust-agent/generated/catalog.md']),only('xtask')); assert.deepEqual(classify(['docs/design/appserver/native-storage-format.md']),only('rust')); }); -test('Web sources that xtask reads keep its check',()=>{ +test('Web sources that static checks read avoid the heavy xtask build',()=>{ for (const file of ['web/src/main.ts','web/src/chat-ui/WebChatTimeline.vue','web/src/rpc/protocol.ts','web/src/a.mjs','web/src/a.js']) - assert.deepEqual(classify([file]),only('web','xtask'),file); + assert.deepEqual(classify([file]),only('web','static'),file); }); test('dependency policy changes select the scan without compiling the workspace',()=>{ @@ -67,6 +69,7 @@ test('bridge, evaluation and wall-clock flows follow their owning paths',()=>{ assert.deepEqual(classify(['crates/dim-cli/src/ui/tui.rs']),only('rust','windows')); assert.deepEqual(classify(['crates/dimcode/tests/cli_flow/models.rs']),only('rust')); assert.deepEqual(classify(['crates/dim-agent-types/src/tool.rs']),only('rust','windows','node')); + assert.deepEqual(classify(['xtask/check/src/literal_main.rs']),only('static','xtask')); assert.deepEqual(classify(['xtask/src/scenario_eval.rs']),only('rust','node','eval')); assert.deepEqual(classify(['xtask/scenario-eval/case.json']),only('rust','node','eval')); assert.deepEqual(classify(['crates/dim-agent-capabilities/src/workspace_tools/exec.rs']),only('rust','node','execution')); diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 564553d221..2ce75fdb05 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -26,16 +26,13 @@ dim-agent-types.workspace = true dim-client.workspace = true rutis.workspace = true rutis-bridge.workspace = true -rutis-types = "0.23.0" rutis-loader.workspace = true tokio.workspace = true tokio-util.workspace = true serde.workspace = true serde_json.workspace = true futures-util.workspace = true -syn = { version = "2", features = ["full", "visit"] } -# The literal-main rule reads a literal's line from its span. -proc-macro2 = { version = "1", features = ["span-locations"] } +xtask-check = { path = "check" } axum = { workspace = true, features = ["json"] } # The run child's process group: a cancelled run kills the group, so the # Node plugin runtimes it started go with it. std starts the group diff --git a/xtask/check/Cargo.toml b/xtask/check/Cargo.toml new file mode 100644 index 0000000000..0846b22c95 --- /dev/null +++ b/xtask/check/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "xtask-check" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish = false + +[dependencies] +proc-macro2 = { version = "1", features = ["span-locations"] } +rutis-types = "0.23.0" +serde_json.workspace = true +syn = { version = "2", features = ["full", "visit"] } + +[lints] +workspace = true diff --git a/xtask/check/src/boundaries.rs b/xtask/check/src/boundaries.rs new file mode 100644 index 0000000000..6036ca4dce --- /dev/null +++ b/xtask/check/src/boundaries.rs @@ -0,0 +1,113 @@ +//! Crate dependency boundaries from `cargo metadata`, live syn-AST module +//! boundaries, committed `crates.*` freshness, and plugin-document checks. + +use crate::{modules, plugin_docs}; +use serde_json::{Value, json}; +use std::path::Path; + +type Result = std::result::Result>; + +/// Verifies crate/module boundaries, `crates.*` freshness and plugin documents. +pub fn check(root: &Path) -> Result<()> { + run(root, false) +} + +/// Verifies crate/module boundaries, writes `crates.*`, and checks plugin documents. +pub fn write(root: &Path) -> Result<()> { + run(root, true) +} + +fn check_dependency(name: &str, dep: &str) -> Result<()> { + if name == "dim-agent-types" && !modules::TYPES_VALUE_DEPENDENCIES.contains(&dep) { + return Err("types must not depend on runtime/capabilities".into()); + } + if name == "dim-agent-runtime" && (dep == "dim-agent-capabilities" || dep == "dim-app-server") { + return Err("runtime must not depend on capabilities/server".into()); + } + if name == "dim-agent-capabilities" && dep == "dim-app-server" { + return Err("capabilities must not depend on server".into()); + } + if name == "xtask-check" && (dep.starts_with("dim-") || dep == "rutis") { + return Err(format!("xtask-check must stay free of business/runtime crate {dep}").into()); + } + Ok(()) +} + +fn run(root: &Path, write: bool) -> Result<()> { + let output = std::process::Command::new("cargo") + .args([ + "metadata", + "--locked", + "--offline", + "--no-deps", + "--format-version", + "1", + ]) + .current_dir(root) + .output()?; + if !output.status.success() { + return Err(String::from_utf8_lossy_owned(output.stderr).into()); + } + let metadata: Value = serde_json::from_slice(&output.stdout)?; + let mut edges = vec![]; + let mut graph = String::from("%% Generated from cargo metadata; do not edit.\nflowchart LR\n"); + for p in metadata["packages"].as_array().unwrap() { + let name = p["name"].as_str().unwrap(); + for d in p["dependencies"].as_array().unwrap() { + let dep = d["name"].as_str().unwrap(); + check_dependency(name, dep)?; + if dep.starts_with("dim-") || dep == "rutis" { + edges.push(json!({"from":name,"to":dep})); + graph += &format!( + " {}[\"{name}\"] --> {}[\"{dep}\"]\n", + name.replace('-', "_"), + dep.replace('-', "_") + ); + } + } + } + let out = root.join("docs/architecture/rust-agent/generated"); + let files = [ + ("crates.json", serde_json::to_string_pretty(&edges)? + "\n"), + ("crates.mmd", graph), + ]; + modules::check(root)?; + if write { + std::fs::create_dir_all(&out)?; + for (name, text) in &files { + std::fs::write(out.join(name), text)?; + } + } else { + let stale: Vec<_> = files + .iter() + .filter(|(name, text)| { + std::fs::read_to_string(out.join(name)).ok().as_ref() != Some(text) + }) + .map(|(name, _)| out.join(name).display().to_string()) + .collect(); + if !stale.is_empty() { + return Err(format!( + "generated architecture files are stale: {}; run `cargo run -p xtask -- graph`", + stale.join(", ") + ) + .into()); + } + } + println!("crate and module boundaries passed"); + plugin_docs::check(root)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::check_dependency; + + #[test] + fn xtask_check_rejects_business_and_runtime_crates() { + assert!(check_dependency("xtask-check", "dim-agent-types").is_err()); + assert!(check_dependency("xtask-check", "dim-app-server").is_err()); + assert!(check_dependency("xtask-check", "rutis").is_err()); + assert!(check_dependency("xtask-check", "rutis-types").is_ok()); + assert!(check_dependency("xtask-check", "syn").is_ok()); + } +} diff --git a/xtask/src/comment_links.rs b/xtask/check/src/comment_links.rs similarity index 100% rename from xtask/src/comment_links.rs rename to xtask/check/src/comment_links.rs diff --git a/xtask/check/src/lib.rs b/xtask/check/src/lib.rs new file mode 100644 index 0000000000..239cbe9052 --- /dev/null +++ b/xtask/check/src/lib.rs @@ -0,0 +1,34 @@ +//! Pure static repository checks with no dependency on compiling business +//! runtime crates (ADR 026 D2, D4). + +pub mod boundaries; +pub mod comment_links; +pub mod literal_main; +pub mod modules; +pub mod npm; +pub mod plugin_docs; +pub mod types; + +use std::path::{Path, PathBuf}; + +type Result = std::result::Result>; + +/// Workspace root resolved from this crate's manifest directory (`xtask/check`). +pub fn root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .parent() + .unwrap() + .to_path_buf() +} + +/// Runs every pure static repository check against `root`. +pub fn check_all(root: &Path) -> Result<()> { + boundaries::check(root)?; + types::check(root)?; + npm::check(root)?; + comment_links::check(root)?; + literal_main::check(root)?; + Ok(()) +} diff --git a/xtask/src/literal_main.rs b/xtask/check/src/literal_main.rs similarity index 100% rename from xtask/src/literal_main.rs rename to xtask/check/src/literal_main.rs diff --git a/xtask/check/src/main.rs b/xtask/check/src/main.rs new file mode 100644 index 0000000000..5a4a093b0f --- /dev/null +++ b/xtask/check/src/main.rs @@ -0,0 +1,28 @@ +use std::path::PathBuf; + +fn main() -> Result<(), Box> { + let root = xtask_check::root(); + match std::env::args().nth(1).as_deref() { + None | Some("check") => xtask_check::check_all(&root)?, + Some("module-graph") => { + let mut args = std::env::args().skip(2); + let Some(out) = args.next() else { + return Err("usage: cargo run -p xtask-check -- module-graph DIR".into()); + }; + if args.next().is_some() { + return Err("module-graph takes one output directory".into()); + } + let out = PathBuf::from(out); + std::fs::create_dir_all(&out)?; + for (name, text) in xtask_check::modules::generate(&root)? { + std::fs::write(out.join(name), text)?; + } + println!("generated {}", out.display()); + } + Some("types") => xtask_check::types::write(&root)?, + _ => { + return Err("usage: cargo run -p xtask-check -- [check|module-graph DIR|types]".into()); + } + } + Ok(()) +} diff --git a/xtask/src/modules.rs b/xtask/check/src/modules.rs similarity index 100% rename from xtask/src/modules.rs rename to xtask/check/src/modules.rs diff --git a/xtask/src/npm.rs b/xtask/check/src/npm.rs similarity index 100% rename from xtask/src/npm.rs rename to xtask/check/src/npm.rs diff --git a/xtask/check/src/plugin_docs.rs b/xtask/check/src/plugin_docs.rs new file mode 100644 index 0000000000..518e5cc93c --- /dev/null +++ b/xtask/check/src/plugin_docs.rs @@ -0,0 +1,408 @@ +//! Static checks and block rewriting for plugin documents under +//! `docs/architecture/rust-agent/plugins/` against the recorded local graph. + +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::{Path, PathBuf}, +}; + +type Result = std::result::Result>; + +const BEGIN: &str = ""; +const INFRASTRUCTURE: [&str; 12] = [ + "rutis-loader", + "session", + "branch", + "SessionScope", + "BranchScope", + // The instances' mounters (ADR 006 D3); the parts they mount have pages. + "SessionParts", + "SessionOptionalParts", + "BranchParts", + "BranchOptionalParts", + "SessionBroadcast", + "SessionBroadcastEnd", + "PrepareModelHost", +]; + +fn docs_dir(root: &Path) -> PathBuf { + root.join("docs/architecture/rust-agent/plugins") +} + +pub fn graph_file(root: &Path) -> PathBuf { + root.join("docs/architecture/rust-agent/generated/local/services.json") +} + +/// Rewrites every plugin document's generated blocks from `graphs`. +pub fn rewrite>(root: &Path, graphs: &BTreeMap) -> Result<()> { + let facts = Facts::new(graphs); + for (path, names) in documents(root)? { + let mut text = std::fs::read_to_string(&path)?; + for name in names { + let (before, _, after) = split_block(&text, &name, &path)?; + text = format!("{before}{}{after}", facts.block(&name)?); + } + std::fs::write(&path, text)?; + } + Ok(()) +} + +/// Checks every plugin document against the recorded local graph. +pub fn check(root: &Path) -> Result<()> { + let documents = documents(root)?; + if documents.is_empty() { + return Err(format!("{}: no plugin documents", docs_dir(root).display()).into()); + } + let graphs: BTreeMap = + serde_json::from_str(&std::fs::read_to_string(graph_file(root))?)?; + let facts = Facts::new(&graphs); + let mut errors = Vec::new(); + let documented: BTreeSet<_> = documents + .iter() + .flat_map(|(_, names)| names.iter().map(String::as_str)) + .collect(); + for (_, plugin) in &facts.plugins { + let name = plugin["name"].as_str().ok_or("plugin graph has no name")?; + if !INFRASTRUCTURE.contains(&name) && !documented.contains(name) { + errors.push(format!( + "business plugin `{name}` has no document in {}", + docs_dir(root).display() + )); + } + } + for (path, name, section) in documents + .iter() + .map(|(path, names)| Ok((path, names, std::fs::read_to_string(path)?))) + .collect::>>()? + .iter() + .flat_map(|(path, names, text)| { + sections(text, names).map(move |(name, section)| (*path, name, section)) + }) + { + let (_, block, _) = split_block(section, name, path)?; + match facts.block(name) { + Err(error) => errors.push(error.to_string()), + Ok(expected) if expected != block => errors.push(format!( + "{}: `{name}`: generated block is stale; run `cargo run -p xtask -- graph`", + path.display() + )), + Ok(_) => {} + } + let injected: BTreeSet = facts + .plugin(name) + .map(|plugin| facts.injects(plugin).into_iter().collect()) + .unwrap_or_default(); + let explained = dependency_rows(section); + for missing in injected.difference(&explained) { + errors.push(format!( + "{}: `{name}`: dependency table does not explain injected `{missing}`", + path.display() + )); + } + for extra in explained.difference(&injected) { + errors.push(format!( + "{}: `{name}`: dependency table explains `{extra}`, which it does not inject", + path.display() + )); + } + } + if errors.is_empty() { + println!("plugin documents passed ({} documents)", documents.len()); + Ok(()) + } else { + Err(errors.join("\n").into()) + } +} + +/// Each part a page documents with the text that documents it: from the end +/// of the previous part's block, or the start, to the end of its own block. +fn sections<'a>( + text: &'a str, + names: &'a [String], +) -> impl Iterator + 'a { + let mut start = 0; + names.iter().map(move |name| { + let marker = format!("{BEGIN}{name} "); + let end = text[start..] + .find(&marker) + .and_then(|at| { + text[start + at..] + .find(END) + .map(|end| start + at + end + END.len()) + }) + .unwrap_or(text.len()); + let section = &text[start..end]; + start = end; + (name, section) + }) +} + +/// The parts or process plugins a page documents: the names of its +/// generated blocks, in order. +fn documented(text: &str) -> Vec { + text.match_indices(BEGIN) + .filter_map(|(at, _)| { + text[at + BEGIN.len()..] + .split_whitespace() + .next() + .map(str::to_owned) + }) + .collect() +} + +/// `(path, documented names)` of every page; a page documents at least one. +fn documents(root: &Path) -> Result)>> { + let dir = docs_dir(root); + let entries = std::fs::read_dir(&dir).map_err(|error| format!("{}: {error}", dir.display()))?; + let mut documents = Vec::new(); + for entry in entries { + let path = entry?.path(); + let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else { + continue; + }; + if path.extension().is_some_and(|ext| ext == "md") && stem != "README" { + let names = documented(&std::fs::read_to_string(&path)?); + if names.is_empty() { + return Err(format!("{}: no generated block", path.display()).into()); + } + documents.push((path.clone(), names)); + } + } + documents.sort(); + Ok(documents) +} + +/// `(before, block, after)`; the block spans both markers. +fn split_block<'a>(text: &'a str, name: &str, path: &Path) -> Result<(&'a str, &'a str, &'a str)> { + let marker = format!("{BEGIN}{name} "); + let start = text + .find(&marker) + .ok_or_else(|| format!("{}: missing `{marker}...` block", path.display()))?; + let end = text[start..] + .find(END) + .map(|offset| start + offset + END.len()) + .ok_or_else(|| format!("{}: unterminated generated block", path.display()))?; + Ok((&text[..start], &text[start..end], &text[end..])) +} + +/// First-column codes of the hand-written dependency table. +fn dependency_rows(text: &str) -> BTreeSet { + let mut rows = BTreeSet::new(); + let mut inside = false; + for line in text.lines() { + if let Some(heading) = line.strip_prefix("##") { + inside = matches!( + heading.trim_start_matches('#').trim(), + "Dependencies" | "依赖" + ); + continue; + } + let Some(cell) = line + .strip_prefix('|') + .and_then(|rest| rest.split('|').next()) + else { + continue; + }; + let cell = cell.trim(); + if inside && cell.starts_with('`') && cell.ends_with('`') && cell.len() > 2 { + rows.insert(cell.trim_matches('`').to_owned()); + } + } + rows +} + +/// `dim_agent_x::m::Name#key@main` → `B:Name#key`. +fn code(service: &str) -> String { + let (path, scope) = match service.rsplit_once('@') { + Some((path, "main")) => (path, "B"), + Some((path, "session")) => (path, "S"), + Some((path, _)) => (path, "?"), + None => (service, "P"), + }; + let mut short = String::new(); + let mut segment = String::new(); + let mut chars = path.chars().peekable(); + while let Some(ch) = chars.next() { + if ch == ':' && chars.peek() == Some(&':') { + chars.next(); + segment.clear(); + continue; + } + if ch.is_alphanumeric() || ch == '_' { + segment.push(ch); + continue; + } + short.push_str(&segment); + segment.clear(); + short.push(ch); + } + short.push_str(&segment); + format!("{scope}:{short}") +} + +struct Facts<'a> { + /// `(scope, plugin)` of every plugin in the profile. + plugins: Vec<(&'a str, &'a Value)>, + bindings: Vec<&'a Value>, +} +impl<'a> Facts<'a> { + fn new>(graphs: &'a BTreeMap) -> Self { + let mut plugins = Vec::new(); + let mut bindings = Vec::new(); + for (scope, graph) in graphs { + for plugin in graph["plugins"].as_array().into_iter().flatten() { + plugins.push((scope.as_ref(), plugin)); + } + bindings.extend(graph["bindings"].as_array().into_iter().flatten()); + } + Self { plugins, bindings } + } + fn plugin(&self, name: &str) -> Option<&(&'a str, &'a Value)> { + self.plugins + .iter() + .find(|(_, plugin)| plugin["name"] == name) + } + fn injects(&self, (_, plugin): &(&str, &Value)) -> Vec { + plugin["injects"] + .as_array() + .into_iter() + .flatten() + .map(|inject| code(inject["service"].as_str().unwrap_or_default())) + .collect() + } + fn block(&self, name: &str) -> Result { + let found = self + .plugin(name) + .ok_or_else(|| format!("plugin `{name}` is not in the local execution profile"))?; + let (scope, plugin) = found; + let id = &plugin["id"]; + let scope = match *scope { + "process" => "进程", + "session" => "Session", + _ => "分支", + }; + let list = |items: BTreeSet| { + if items.is_empty() { + "—".to_owned() + } else { + items + .into_iter() + .map(|item| format!("`{item}`")) + .collect::>() + .join("、") + } + }; + let injects = list(self.injects(found).into_iter().collect()); + let provides = list( + self.bindings + .iter() + .filter(|binding| binding["provider"] == *id) + .map(|binding| code(binding["service"].as_str().unwrap_or_default())) + .collect(), + ); + let dependents = list( + self.plugins + .iter() + .filter(|(_, other)| { + other["resolved"] + .as_array() + .into_iter() + .flatten() + .any(|edge| edge["provider"] == *id) + }) + .map(|(_, other)| other["name"].as_str().unwrap_or_default().to_owned()) + .collect(), + ); + Ok(format!( + "{BEGIN}{name} — 由 `cargo run -p xtask -- graph` 从真实装配生成,勿手改 -->\n| 项 | 值 |\n| --- | --- |\n| 作用域 | {scope} |\n| 注入 | {injects} |\n| 提供 | {provides} |\n| 被注入于 | {dependents} |\n{END}" + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write_fixture(root: &Path, graphs: &BTreeMap<&'static str, Value>) -> Result<()> { + let file = graph_file(root); + std::fs::create_dir_all(file.parent().unwrap())?; + std::fs::write(&file, serde_json::to_string_pretty(graphs)? + "\n")?; + rewrite(root, graphs) + } + + #[test] + fn documentation_check_requires_complete_profile_and_exact_dependencies() { + let root = std::env::temp_dir().join(format!( + "dim-plugin-doc-check-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&root).unwrap(); + let result = (|| -> Result<()> { + assert!(check(&root).is_err(), "missing directory must not pass"); + std::fs::create_dir_all(docs_dir(&root))?; + let mut graphs = BTreeMap::from([( + "main", + serde_json::json!({ + "plugins": [ + {"id":1,"name":"branch","injects":[],"resolved":[]}, + {"id":2,"name":"Example","injects":[{"service":"crate::Timeline@main"}],"resolved":[]} + ], + "bindings":[] + }), + )]); + write_fixture(&root, &graphs)?; + assert!(check(&root).is_err(), "empty document set must not pass"); + let path = docs_dir(&root).join("Example.md"); + let page = format!( + "# Example\n\n## Dependencies\n\n| Service | Purpose |\n| --- | --- |\n| `B:Timeline` | Commit results |\n\n{BEGIN}Example -->\n{END}\n" + ); + std::fs::write(&path, &page)?; + write_fixture(&root, &graphs)?; + check(&root)?; + let valid = std::fs::read_to_string(&path)?; + std::fs::write( + &path, + valid.replace("| `B:Timeline` | Commit results |", ""), + )?; + assert!( + check(&root).is_err(), + "a missing dependency explanation must fail" + ); + std::fs::write(&path, &valid)?; + graphs.get_mut("main").unwrap()["plugins"] + .as_array_mut() + .unwrap() + .push( + serde_json::json!({"id":3,"name":"NewCapability","injects":[],"resolved":[]}), + ); + write_fixture(&root, &graphs)?; + assert!( + check(&root).is_err(), + "new business plugins require documentation" + ); + graphs.get_mut("main").unwrap()["plugins"] + .as_array_mut() + .unwrap() + .pop(); + write_fixture(&root, &graphs)?; + std::fs::write( + docs_dir(&root).join("Removed.md"), + page.replace("Example", "Removed"), + )?; + assert!( + check(&root).is_err(), + "removed plugins must not retain orphan documents" + ); + std::fs::remove_file(docs_dir(&root).join("Removed.md"))?; + check(&root) + })(); + std::fs::remove_dir_all(root).unwrap(); + result.unwrap(); + } +} diff --git a/xtask/src/types.rs b/xtask/check/src/types.rs similarity index 100% rename from xtask/src/types.rs rename to xtask/check/src/types.rs diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 1f1fbe0200..6d43b57b05 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,16 +1,11 @@ mod allocation; mod app_server; mod catalog; -mod comment_links; -mod literal_main; -mod modules; -mod npm; mod plugins; mod prompt_eval; mod rule; mod scenario_eval; mod summary_eval; -mod types; #[global_allocator] static ALLOCATOR: allocation::MeasuredAllocator = allocation::MeasuredAllocator; use dim_agent_runtime::{testing::MinimalHost, *}; @@ -66,14 +61,10 @@ async fn run() -> std::result::Result<(), Box> { Some("scenario-eval-serve") => scenario_eval::serve_entry(std::env::args().nth(2)).await?, Some("prompt-eval") => prompt_eval::run().await?, Some("check") => { - boundaries(false)?; + xtask_check::check_all(&root())?; catalog::check(&root()).await?; - types::check(&root())?; - npm::check(&root())?; - comment_links::check(&root())?; - literal_main::check(&root())?; } - Some("types") => types::write(&root())?, + Some("types") => xtask_check::types::write(&root())?, _ => { return Err( "usage: cargo run -p xtask -- graph|module-graph DIR|measure [--model-config PATH]|context-replay|restore-replay DB SESSION|context-breakdown DB SESSION|migrate-prompt-references DB SESSION BRANCH|summary-eval [OPTIONS]|scenario-eval [OPTIONS]|check|types" @@ -93,7 +84,7 @@ fn module_graph() -> std::result::Result<(), Box> { } let out = PathBuf::from(out); std::fs::create_dir_all(&out)?; - for (name, text) in modules::generate(&root())? { + for (name, text) in xtask_check::modules::generate(&root())? { std::fs::write(out.join(name), text)?; } println!("generated {}", out.display()); @@ -360,78 +351,10 @@ async fn graph() -> std::result::Result<(), Box> { app_server::write(&root(), app_server::graph().await?)?; catalog::write(&root()).await?; } - boundaries(true)?; + xtask_check::boundaries::write(&root())?; println!("generated {}", out.display()); Ok(()) } -/// `graph` writes the generated architecture files; `check` renders them again and fails when the committed bytes differ. -fn boundaries(write: bool) -> std::result::Result<(), Box> { - let output = std::process::Command::new("cargo") - .args(["metadata", "--no-deps", "--format-version", "1"]) - .current_dir(root()) - .output()?; - if !output.status.success() { - return Err(String::from_utf8_lossy_owned(output.stderr).into()); - } - let metadata: Value = serde_json::from_slice(&output.stdout)?; - let mut edges = vec![]; - let mut graph = String::from("%% Generated from cargo metadata; do not edit.\nflowchart LR\n"); - for p in metadata["packages"].as_array().unwrap() { - let name = p["name"].as_str().unwrap(); - for d in p["dependencies"].as_array().unwrap() { - let dep = d["name"].as_str().unwrap(); - if name == "dim-agent-types" && !modules::TYPES_VALUE_DEPENDENCIES.contains(&dep) { - return Err("types must not depend on runtime/capabilities".into()); - } - if name == "dim-agent-runtime" - && (dep == "dim-agent-capabilities" || dep == "dim-app-server") - { - return Err("runtime must not depend on capabilities/server".into()); - } - if name == "dim-agent-capabilities" && dep == "dim-app-server" { - return Err("capabilities must not depend on server".into()); - } - if dep.starts_with("dim-") || dep == "rutis" { - edges.push(json!({"from":name,"to":dep})); - graph += &format!( - " {}[\"{name}\"] --> {}[\"{dep}\"]\n", - name.replace('-', "_"), - dep.replace('-', "_") - ); - } - } - } - let out = root().join("docs/architecture/rust-agent/generated"); - let files = [ - ("crates.json", serde_json::to_string_pretty(&edges)? + "\n"), - ("crates.mmd", graph), - ]; - modules::check(&root())?; - if write { - std::fs::create_dir_all(&out)?; - for (name, text) in &files { - std::fs::write(out.join(name), text)?; - } - } else { - let stale: Vec<_> = files - .iter() - .filter(|(name, text)| { - std::fs::read_to_string(out.join(name)).ok().as_ref() != Some(text) - }) - .map(|(name, _)| out.join(name).display().to_string()) - .collect(); - if !stale.is_empty() { - return Err(format!( - "generated architecture files are stale: {}; run `cargo run -p xtask -- graph`", - stale.join(", ") - ) - .into()); - } - } - println!("crate and module boundaries passed"); - plugins::check(&root())?; - Ok(()) -} async fn measure() -> std::result::Result<(), Box> { let before = tokio::runtime::Handle::current() .metrics() diff --git a/xtask/src/plugins.rs b/xtask/src/plugins.rs index 6b5305750a..f7ba5ccdf9 100644 --- a/xtask/src/plugins.rs +++ b/xtask/src/plugins.rs @@ -1,12 +1,9 @@ -//! Plugin documents under `docs/architecture/rust-agent/plugins/`. +//! Local execution profile graph generation for plugin documents under +//! `docs/architecture/rust-agent/plugins/`. //! //! `graph` assembles the local execution profile, records its live rutis -//! diagnostics in `generated/local/services.json`, and rewrites the generated -//! blocks of every plugin document from them. A document is a plugin's page: -//! it holds one generated block for each part or process plugin it documents, -//! each after its own `Dependencies` (or `依赖`) table. `check` requires every -//! business plugin and part in that profile to be documented and checks each -//! block and table against the diagnostics. +//! diagnostics in `generated/local/services.json`, and delegates generated +//! block updates and static document checks to `xtask_check::plugin_docs`. use dim_agent_capabilities::{ defaults, execution_settings::ExecutionSettingsHost, @@ -37,26 +34,9 @@ use std::{ type Result = std::result::Result>; -const BEGIN: &str = ""; const TOOLS: [&str; 8] = [ "read", "write", "edit", "glob", "grep", "exec", "wait", "skill", ]; -const INFRASTRUCTURE: [&str; 12] = [ - "rutis-loader", - "session", - "branch", - "SessionScope", - "BranchScope", - // The instances' mounters (ADR 006 D3); the parts they mount have pages. - "SessionParts", - "SessionOptionalParts", - "BranchParts", - "BranchOptionalParts", - "SessionBroadcast", - "SessionBroadcastEnd", - "PrepareModelHost", -]; /// Graph-only host facts. Keep real local-execution dependencies but never scan /// the developer's home or make the graph depend on their installed skills. @@ -166,13 +146,6 @@ impl SessionFilesService for GraphFiles { } } -fn docs_dir(root: &Path) -> PathBuf { - root.join("docs/architecture/rust-agent/plugins") -} -fn graph_file(root: &Path) -> PathBuf { - root.join("docs/architecture/rust-agent/generated/local/services.json") -} - /// Assembles the local execution profile as the product composition root /// does, with scripted model hosts, and returns its diagnostics per scope. pub async fn local_graph() -> Result> { @@ -290,7 +263,7 @@ pub async fn local_graph() -> Result> { /// Writes the local graph and rewrites every plugin document's block. pub fn write(root: &Path, graphs: &BTreeMap<&'static str, Value>) -> Result<()> { - let file = graph_file(root); + let file = xtask_check::plugin_docs::graph_file(root); std::fs::create_dir_all(file.parent().unwrap())?; std::fs::write(&file, serde_json::to_string_pretty(graphs)? + "\n")?; let mermaid = crate::mermaid(graphs); @@ -301,365 +274,6 @@ pub fn write(root: &Path, graphs: &BTreeMap<&'static str, Value>) -> Result<()> "# 本地执行运行组合\n\n由真实 rutis 装配 `defaults::install_local_execution` 生成(模型为脚本化 mock)。重新生成:`cargo run -p xtask -- graph`。\n\n```mermaid\n{mermaid}```\n" ), )?; - let facts = Facts::new(graphs); - for (path, names) in documents(root)? { - let mut text = std::fs::read_to_string(&path)?; - for name in names { - let (before, _, after) = split_block(&text, &name, &path)?; - text = format!("{before}{}{after}", facts.block(&name)?); - } - std::fs::write(&path, text)?; - } + xtask_check::plugin_docs::rewrite(root, graphs)?; Ok(()) } - -/// Checks every plugin document against the recorded local graph. -pub fn check(root: &Path) -> Result<()> { - let documents = documents(root)?; - if documents.is_empty() { - return Err(format!("{}: no plugin documents", docs_dir(root).display()).into()); - } - let graphs: BTreeMap = - serde_json::from_str(&std::fs::read_to_string(graph_file(root))?)?; - let facts = Facts::new(&graphs); - let mut errors = Vec::new(); - let documented: BTreeSet<_> = documents - .iter() - .flat_map(|(_, names)| names.iter().map(String::as_str)) - .collect(); - for (_, plugin) in &facts.plugins { - let name = plugin["name"].as_str().ok_or("plugin graph has no name")?; - if !INFRASTRUCTURE.contains(&name) && !documented.contains(name) { - errors.push(format!( - "business plugin `{name}` has no document in {}", - docs_dir(root).display() - )); - } - } - for (path, name, section) in documents - .iter() - .map(|(path, names)| Ok((path, names, std::fs::read_to_string(path)?))) - .collect::>>()? - .iter() - .flat_map(|(path, names, text)| { - sections(text, names).map(move |(name, section)| (*path, name, section)) - }) - { - let (_, block, _) = split_block(section, name, path)?; - match facts.block(name) { - Err(error) => errors.push(error.to_string()), - Ok(expected) if expected != block => errors.push(format!( - "{}: `{name}`: generated block is stale; run `cargo run -p xtask -- graph`", - path.display() - )), - Ok(_) => {} - } - let injected: BTreeSet = facts - .plugin(name) - .map(|plugin| facts.injects(plugin).into_iter().collect()) - .unwrap_or_default(); - let explained = dependency_rows(section); - for missing in injected.difference(&explained) { - errors.push(format!( - "{}: `{name}`: dependency table does not explain injected `{missing}`", - path.display() - )); - } - for extra in explained.difference(&injected) { - errors.push(format!( - "{}: `{name}`: dependency table explains `{extra}`, which it does not inject", - path.display() - )); - } - } - if errors.is_empty() { - println!("plugin documents passed ({} documents)", documents.len()); - Ok(()) - } else { - Err(errors.join("\n").into()) - } -} - -/// Each part a page documents with the text that documents it: from the end -/// of the previous part's block, or the start, to the end of its own block. -fn sections<'a>( - text: &'a str, - names: &'a [String], -) -> impl Iterator + 'a { - let mut start = 0; - names.iter().map(move |name| { - let marker = format!("{BEGIN}{name} "); - let end = text[start..] - .find(&marker) - .and_then(|at| { - text[start + at..] - .find(END) - .map(|end| start + at + end + END.len()) - }) - .unwrap_or(text.len()); - let section = &text[start..end]; - start = end; - (name, section) - }) -} - -/// The parts or process plugins a page documents: the names of its -/// generated blocks, in order. -fn documented(text: &str) -> Vec { - text.match_indices(BEGIN) - .filter_map(|(at, _)| { - text[at + BEGIN.len()..] - .split_whitespace() - .next() - .map(str::to_owned) - }) - .collect() -} - -/// `(path, documented names)` of every page; a page documents at least one. -fn documents(root: &Path) -> Result)>> { - let dir = docs_dir(root); - let entries = std::fs::read_dir(&dir).map_err(|error| format!("{}: {error}", dir.display()))?; - let mut documents = Vec::new(); - for entry in entries { - let path = entry?.path(); - let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else { - continue; - }; - if path.extension().is_some_and(|ext| ext == "md") && stem != "README" { - let names = documented(&std::fs::read_to_string(&path)?); - if names.is_empty() { - return Err(format!("{}: no generated block", path.display()).into()); - } - documents.push((path.clone(), names)); - } - } - documents.sort(); - Ok(documents) -} - -/// `(before, block, after)`; the block spans both markers. -fn split_block<'a>(text: &'a str, name: &str, path: &Path) -> Result<(&'a str, &'a str, &'a str)> { - let marker = format!("{BEGIN}{name} "); - let start = text - .find(&marker) - .ok_or_else(|| format!("{}: missing `{marker}...` block", path.display()))?; - let end = text[start..] - .find(END) - .map(|offset| start + offset + END.len()) - .ok_or_else(|| format!("{}: unterminated generated block", path.display()))?; - Ok((&text[..start], &text[start..end], &text[end..])) -} - -/// First-column codes of the hand-written dependency table. -fn dependency_rows(text: &str) -> BTreeSet { - let mut rows = BTreeSet::new(); - let mut inside = false; - for line in text.lines() { - if let Some(heading) = line.strip_prefix("##") { - inside = matches!( - heading.trim_start_matches('#').trim(), - "Dependencies" | "依赖" - ); - continue; - } - let Some(cell) = line - .strip_prefix('|') - .and_then(|rest| rest.split('|').next()) - else { - continue; - }; - let cell = cell.trim(); - if inside && cell.starts_with('`') && cell.ends_with('`') && cell.len() > 2 { - rows.insert(cell.trim_matches('`').to_owned()); - } - } - rows -} - -/// `dim_agent_x::m::Name#key@main` → `B:Name#key`. -fn code(service: &str) -> String { - let (path, scope) = match service.rsplit_once('@') { - Some((path, "main")) => (path, "B"), - Some((path, "session")) => (path, "S"), - Some((path, _)) => (path, "?"), - None => (service, "P"), - }; - let mut short = String::new(); - let mut segment = String::new(); - let mut chars = path.chars().peekable(); - while let Some(ch) = chars.next() { - if ch == ':' && chars.peek() == Some(&':') { - chars.next(); - segment.clear(); - continue; - } - if ch.is_alphanumeric() || ch == '_' { - segment.push(ch); - continue; - } - short.push_str(&segment); - segment.clear(); - short.push(ch); - } - short.push_str(&segment); - format!("{scope}:{short}") -} - -struct Facts<'a> { - /// `(scope, plugin)` of every plugin in the profile. - plugins: Vec<(&'a str, &'a Value)>, - bindings: Vec<&'a Value>, -} -impl<'a> Facts<'a> { - fn new>(graphs: &'a BTreeMap) -> Self { - let mut plugins = Vec::new(); - let mut bindings = Vec::new(); - for (scope, graph) in graphs { - for plugin in graph["plugins"].as_array().into_iter().flatten() { - plugins.push((scope.as_ref(), plugin)); - } - bindings.extend(graph["bindings"].as_array().into_iter().flatten()); - } - Self { plugins, bindings } - } - fn plugin(&self, name: &str) -> Option<&(&'a str, &'a Value)> { - self.plugins - .iter() - .find(|(_, plugin)| plugin["name"] == name) - } - fn injects(&self, (_, plugin): &(&str, &Value)) -> Vec { - plugin["injects"] - .as_array() - .into_iter() - .flatten() - .map(|inject| code(inject["service"].as_str().unwrap_or_default())) - .collect() - } - fn block(&self, name: &str) -> Result { - let found = self - .plugin(name) - .ok_or_else(|| format!("plugin `{name}` is not in the local execution profile"))?; - let (scope, plugin) = found; - let id = &plugin["id"]; - let scope = match *scope { - "process" => "进程", - "session" => "Session", - _ => "分支", - }; - let list = |items: BTreeSet| { - if items.is_empty() { - "—".to_owned() - } else { - items - .into_iter() - .map(|item| format!("`{item}`")) - .collect::>() - .join("、") - } - }; - let injects = list(self.injects(found).into_iter().collect()); - let provides = list( - self.bindings - .iter() - .filter(|binding| binding["provider"] == *id) - .map(|binding| code(binding["service"].as_str().unwrap_or_default())) - .collect(), - ); - let dependents = list( - self.plugins - .iter() - .filter(|(_, other)| { - other["resolved"] - .as_array() - .into_iter() - .flatten() - .any(|edge| edge["provider"] == *id) - }) - .map(|(_, other)| other["name"].as_str().unwrap_or_default().to_owned()) - .collect(), - ); - Ok(format!( - "{BEGIN}{name} — 由 `cargo run -p xtask -- graph` 从真实装配生成,勿手改 -->\n| 项 | 值 |\n| --- | --- |\n| 作用域 | {scope} |\n| 注入 | {injects} |\n| 提供 | {provides} |\n| 被注入于 | {dependents} |\n{END}" - )) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn documentation_check_requires_complete_profile_and_exact_dependencies() { - let root = std::env::temp_dir().join(format!( - "dim-plugin-doc-check-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - std::fs::create_dir_all(&root).unwrap(); - let result = (|| -> Result<()> { - assert!(check(&root).is_err(), "missing directory must not pass"); - std::fs::create_dir_all(docs_dir(&root))?; - let mut graphs = BTreeMap::from([( - "main", - serde_json::json!({ - "plugins": [ - {"id":1,"name":"branch","injects":[],"resolved":[]}, - {"id":2,"name":"Example","injects":[{"service":"crate::Timeline@main"}],"resolved":[]} - ], - "bindings":[] - }), - )]); - write(&root, &graphs)?; - assert!(check(&root).is_err(), "empty document set must not pass"); - let path = docs_dir(&root).join("Example.md"); - let page = format!( - "# Example\n\n## Dependencies\n\n| Service | Purpose |\n| --- | --- |\n| `B:Timeline` | Commit results |\n\n{BEGIN}Example -->\n{END}\n" - ); - std::fs::write(&path, &page)?; - write(&root, &graphs)?; - check(&root)?; - let valid = std::fs::read_to_string(&path)?; - std::fs::write( - &path, - valid.replace("| `B:Timeline` | Commit results |", ""), - )?; - assert!( - check(&root).is_err(), - "a missing dependency explanation must fail" - ); - std::fs::write(&path, &valid)?; - graphs.get_mut("main").unwrap()["plugins"] - .as_array_mut() - .unwrap() - .push( - serde_json::json!({"id":3,"name":"NewCapability","injects":[],"resolved":[]}), - ); - write(&root, &graphs)?; - assert!( - check(&root).is_err(), - "new business plugins require documentation" - ); - graphs.get_mut("main").unwrap()["plugins"] - .as_array_mut() - .unwrap() - .pop(); - write(&root, &graphs)?; - std::fs::write( - docs_dir(&root).join("Removed.md"), - page.replace("Example", "Removed"), - )?; - assert!( - check(&root).is_err(), - "removed plugins must not retain orphan documents" - ); - std::fs::remove_file(docs_dir(&root).join("Removed.md"))?; - check(&root) - })(); - std::fs::remove_dir_all(root).unwrap(); - result.unwrap(); - } -}