diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 12471fdf..ea91d6ca 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1033,18 +1033,14 @@ version = "0.1.0" dependencies = [ "ignore", "lithe-core-rules", - "lithe-diagnostics", "lithe-platform", "lithe-plugin-model", "lithe-protocol", "lithe-toolchain", "lithe-workspace", - "regex", "serde", "serde_json", - "serde_yaml_ng", "sha2", - "toml", ] [[package]] @@ -2092,19 +2088,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_yaml_ng" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" -dependencies = [ - "indexmap", - "itoa", - "ryu", - "serde", - "unsafe-libyaml", -] - [[package]] name = "sha2" version = "0.10.9" @@ -2508,12 +2491,6 @@ dependencies = [ "tinyvec", ] -[[package]] -name = "unsafe-libyaml" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" - [[package]] name = "url" version = "2.5.8" diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 2d621ce3..3f880784 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -429,7 +429,7 @@ replace those channels or swallow real source changes mixed with build output. Run configuration behavior is exposed through the `runConfig.*` commands. Platform clients coordinate inspection, generation, resolution, typed document edits, and launch planning, but must not implement a second JSON merger, -toolchain matcher, ID generator, or argument parser. Ecosystem-specific +ID generator, or argument parser. Ecosystem-specific arguments are built by the plugin that declared the run. Opening a project inspects existing files without writing; generation is an explicit user action. Shared project overrides stay in `.lithe/run/configurations.json`. Machine-local overrides may live in @@ -437,11 +437,10 @@ is an explicit user action. Shared project overrides stay in `localDocument`; absolute toolchain paths belong only in that local layer and are excluded from project visibility and Git by default. Generic runtime executables such as Node are selected in `.lithe/toolchains/local.json`; this -machine-local document is also excluded from Git by default. Missing or -incompatible toolchains block only configurations that consume the affected -toolchain, while diagnostics without a configuration ID apply to the project. -Runtime consumption is declared by the detector from the actual command rather -than inferred from the provider namespace. An automatically discovered runtime +machine-local document is also excluded from Git by default. Core discovers +no runnable entries and infers no runtime: generated configurations are the runs +build provider plugins declare, and a runtime binding is one a saved +configuration declares. An automatically discovered runtime path is session-effective: validation and launch share it, but persistence still requires an explicit user selection. diff --git a/rust/contracts/run-configuration-v2.schema.json b/rust/contracts/run-configuration-v2.schema.json index e33c6077..74e98598 100644 --- a/rust/contracts/run-configuration-v2.schema.json +++ b/rust/contracts/run-configuration-v2.schema.json @@ -8,17 +8,8 @@ "version": { "const": 2 }, "generator": { "type": "object", - "required": ["fingerprint"], "properties": { - "fingerprint": { "type": "string", "pattern": "^sha256:" }, - "providerFingerprint": { "type": "string", "pattern": "^sha256:[a-f0-9]{64}$" }, - "providerRunFingerprint": { "type": "string", "pattern": "^sha256:[a-f0-9]{64}$" }, - "unreadablePaths": { "type": "array", "items": { "type": "string" }, "uniqueItems": true }, - "inputs": { - "type": "object", - "propertyNames": { "type": "string", "minLength": 1 }, - "additionalProperties": { "type": "string", "pattern": "^(sha256:.+|path)$" } - } + "providerRunFingerprint": { "type": "string", "pattern": "^sha256:[a-f0-9]{64}$" } }, "additionalProperties": false }, diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 0d266286..10b53a4b 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -698,7 +698,7 @@ or removing a command fails until the table changes in the same commit. | `lsp.destroyServer` | Remove a terminal session handle from the registry | | `runConfig.inspect` | Inspect `.lithe` run documents, versions, and staleness without writing files | | `runConfig.projectToolchain` | Read saved project tool paths for one Provider root, with the nearest path override | -| `runConfig.generate` | Regenerate detected run configurations | +| `runConfig.generate` | Regenerate the provider run configurations | | `runConfig.argumentText` | Format a batch of exact argument vectors as reversible editor text | | `runConfig.resolve` | Merge generated, project, and local layers and return diagnostics | | `runConfig.selectContextConfiguration` | Choose a matching effective configuration for a provider-supplied source and entry identity | @@ -3442,78 +3442,43 @@ stored paths or documents fail without changing source bytes. The command does not discover, probe or run any tool, inspect project descriptors, or write files. `runConfig.inspect` also returns the local document-level `toolchain`, including -when no generated configuration exists (`status: "missing"`). Settings, -toolchain-only callers, and initial run-panel presentation may send -`checkFingerprint: false` to validate documents without traversing or hashing -project sources. Omission preserves full inspection. The Windows run panel -publishes readable configurations first, then performs full inspection and -reports freshness failures without discarding those configurations. -The input fingerprint covers what generation reads: the manifests the built-in -detectors consume (package and lock files, Compose files, Procfiles, task-runner -files and runtime version files) by content (`sha256:` in -`generator.inputs`), plus the detector revision. When the stored inputs no longer -reproduce the stored fingerprint, the document came from another generator -revision and the diagnostic says so instead of listing modified files. -Automatic run discovery, fingerprint traversal and Node manifest discovery use -Core's shared scan policy. Known caches/build outputs -are pruned before descending; other hidden source directories remain visible and -symlinks are not followed. Automatic run discovery and `build.detect` search at -most 6 levels and also prune directories Git ignores, using the `.gitignore` -files they pass and the `info/exclude` of each repository whose root lies in the -workspace (a linked worktree reads the main repository's shared one); a nested -repository starts its own rules. Nothing above the workspace root is read, nor -`core.excludesFile` or the index. `build.detect` additionally prunes the -workspace's ignored paths (see the Build table below), which decide before Git's -rules. Fingerprint traversal and Node manifest -discovery keep ignored directories. Failure to read the workspace root is an error. An -unreadable optional child or fingerprint input is recorded in -`generator.unreadablePaths`; generation retains previous configurations and input -hashes beneath those unknown paths. Inspection returns `incompleteProjectScan` -instead of claiming fingerprint freshness or inferred removals when either the -current scan or saved baseline is incomplete. The persisted diagnostic also appears -with `checkFingerprint: false`; a successful complete regeneration clears it. +when no generated configuration exists (`status: "missing"`). Project environment saves use the existing local `runConfig.updateOptions` toolchain payload with an empty `configurationId`; service overrides are untouched. The `runConfig.*` commands implement the versioned project protocol described -by the JSON Schemas in this directory. `runConfig.inspect` accepts `root` and -optional `checkFingerprint`, `localDocument` and `providerRuns`, and never -writes files. `runConfig.generate` accepts `root`, optional `providerRuns` and -an optional `cacheDirectory`, and returns `{ generated, toolchainRequirements, -entryCount }`. - -`runConfig.generate` and `runConfig.inspect` also accept optional `providerRuns`: -a complete list of `{projectPath,name,reference}`. The native host matches current -model targets against enabled public run declarations; `reference` has exactly the -`extensions.build` selector shape below, with empty model `userArguments`. Core validates -at most 10,000 unique selectors, provider-root/project containment and bounded labels, -then creates `build.provider` entries without interpreting target IDs, tool names, -frameworks, commands or debug adapters. An explicit `[]` withdraws generated runs; -omission preserves older callers. +by the JSON Schemas in this directory. Core discovers no runnable entries +itself: every generated configuration is a run that a build provider plugin +declares (`buildSystems[].run`), and each provider names the inputs that make its +model stale through `sync.watch`. `runConfig.inspect` accepts `root` and +optional `localDocument` and `providerRuns`, and never writes files. +`runConfig.generate` accepts `root` and optional `providerRuns`, and returns +`{ generated, entryCount }`. + +`providerRuns` is a complete list of `{projectPath,name,reference}`. The host +matches current model targets against enabled public run declarations; +`reference` has exactly the `extensions.build` selector shape below, with empty +model `userArguments`. Core validates at most 10,000 unique selectors, +provider-root/project containment and bounded labels, then creates +`build.provider` entries without interpreting target IDs, tool names, +frameworks, commands or debug adapters. Generating without `providerRuns` is +the same as `[]`: the generated layer is empty. IDs hash plugin/build/root/run/project/target identity, so changed labels or execution kind retain user overrides. Current declarations still validate the execution kind before preparation. `generator.providerRunFingerprint` hashes the complete sorted -snapshot; changed or missing metadata yields `staleProviderModel`, including when -file fingerprinting is disabled. Withdrawn entries cannot be restored from cached -configurations; unmatched overrides stay in their user-owned layer and are diagnosed. -See `fixtures/run-configuration/build-provider-stable-identities.json`. macOS supplies this -snapshot; Windows retains its existing generator until its Provider host is migrated. - -Generation keeps the generated configuration and toolchain requirement -documents in memory as the workspace's detected layer for `inspect` and -`resolve`; nothing is written into the workspace. With `cacheDirectory` (an -application cache root outside the workspace) it also records the result under -`run-configurations/`, so retained entries keep their IDs and the Run list is -complete before providers answer again; failing to read or write that cache -changes nothing else. The previous generation, used only to retain entries -beneath unreadable paths, is this process's last generation, else the cached -result, else read-only a `.lithe/run/generated.json` that older versions wrote. -`inspect` returns `requiresGeneration: true` while this process has -no detected layer. Hosts identify the workspace when this flag is true or the -status is `missing`; a saved provider task can make `status` be `ready` before -detection, and must not suppress discovery of the remaining entries. Generated -fingerprints include both project inputs and the detector revision; either -changing marks the detected layer stale and requires regeneration. +snapshot; when `runConfig.inspect` receives `providerRuns` and the generated layer +was made from a different snapshot, it reports `staleProviderModel`. Withdrawn +entries cannot be restored from an earlier generation; unmatched overrides stay in +their user-owned layer and are diagnosed. +See `fixtures/run-configuration/build-provider-stable-identities.json`. + +Generation keeps the generated document in memory as the workspace's generated +layer for `inspect` and `resolve`; nothing is written into the workspace or a +cache, and the `.lithe/run/generated.json` that older versions wrote is not read. +`inspect` returns `requiresGeneration: true` while this process has no generated +layer. Hosts generate when this flag is true or the status is `missing`; a saved +provider task can make `status` be `ready` before generation, and must not +suppress generation of the remaining entries. `runConfig.decideTitleAction { action, trigger, currentFileChosen, settled, configuration? }` decides what a press on the title bar's Run or Debug button does. `action` is @@ -3542,54 +3507,38 @@ Windows compares paths case-insensitively and treats both separators alike; case-sensitive hosts compare the supplied path exactly. Discovery remains with the provider, and clients must reject results made stale by workspace changes. -`runConfig.resolve` accepts `root`, optional local `toolchainCandidates`, and -optional `localDocument` / `teamDocument`. A supplied document replaces that layer +`runConfig.resolve` accepts `root` and optional `localDocument` / `teamDocument`. +A supplied document replaces that layer for this read-only resolution; omitted layers come from `.lithe/run/local.json` / `.lithe/run/configurations.json`. Hosts can preflight a complete two-file transaction -against the current detected layer without publishing either file. Core never writes +against the current generated layer without publishing either file. Core never writes these documents; hosts still own source-identity checks, cancellation, conditional publication and readback. It merges configurations by stable ID using this precedence: -`local.json > configurations.json > detected layer`. Scalars and arrays are +`local.json > configurations.json > generated layer`. Scalars and arrays are replaced by the higher layer, while toolchain maps merge by key. It returns effective configurations, their source, the default (the team default from -`.lithe/project.json`, else the first detected service, else the first -detected entry other than Current File), structured -diagnostics for stale, orphaned, missing, disabled, and toolchain mismatch -states, the effective global `toolchain`, and the machine-local -`localToolchains` document. Toolchain diagnostics carry the affected run -configuration ID when a requirement is consumed by one or more configurations; -requirements with no configuration consumer do not emit a blocking diagnostic. +`.lithe/project.json`, else the first generated service, else the first +generated entry other than Current File), structured diagnostics for orphaned +overrides, missing working directories, disabled entries and an unavailable +default, the effective global `toolchain`, and the machine-local +`localToolchains` document. Core does not match toolchain versions or vendors. Each configuration carries a `category` of `project` or `infrastructure`. -Docker Compose detections are `infrastructure`: a Compose file in an application -repository declares the databases and brokers the project runs against, not the -project itself. The field is omitted for `project`, which is the default, so -existing generated documents keep their exact shape. Hosts present -infrastructure apart from the project's own services and must not include it in -"run all services" or in the default service selection. - -Windows implements this grouping. During the macOS transition, Compose entries -remain in its execution-based Services scope; category-based grouping and service -selection filtering are pending there. +`infrastructure` marks the external services the project runs against, such as +a database or a message broker, rather than the project itself. Generated +provider entries are `project`; a saved configuration may declare +`infrastructure`. The field is omitted for `project`, which is the default. +Hosts present infrastructure apart from the project's own services and must not +include it in "run all services" or in the default service selection. Display names that repeat are qualified by Core, because hosts show the name -alone: the first candidate that separates every entry in the group wins, trying -the working directory (when it is not the workspace root), then the source -manifest. Three -Compose files each declaring `compose up` become `compose up (script/docker)` -and so on, while a name that occurs once is never decorated. Ids are unaffected. - -A process detector declares a runtime binding only when that command genuinely -consumes the runtime. npm, pnpm, and Yarn scripts consume `project-node`; Bun -scripts keep their independent `bun` command and do not acquire a Node -requirement. Go, Python, and Cargo remain command-based until every host -provides the corresponding configurable runtime registry, so their PATH-based -launch behavior is not blocked by an unavailable platform selector. -During resolution, Core also reconciles npm, pnpm, and Yarn commands from older -v2 generated documents with the same `project-node` binding. This compatibility -normalization is based on the effective command, does not mutate the stored -document, and keeps legacy hybrid projects scoped without requiring regeneration. +alone: when the working directories of the repeated entries all differ and none +is the workspace root, each name gains its directory, so two modules declaring +`serve` become `serve (services/api)` and `serve (services/worker)`. Otherwise +the names stay as they are, and a name that occurs once is never decorated. Ids +are unaffected. + The document-level `toolchain` object in the local layer holds generic `preferences`; other fields there belong to whichever host or plugin wrote them, and Core preserves them unchanged. @@ -3618,8 +3567,8 @@ entry also makes a team-only workspace runnable before generation, while still r When generation contains that selector, resolution suppresses its duplicate automatic entry, retains all explicitly saved configurations, and resolves defaults through the same effective selector. Local selector patches update the effective claim, so an -older team target does not accidentally hide a different auto entry. Detection -fingerprints and the detected document remain unchanged by user-layer resolution. +older team target does not accidentally hide a different auto entry. The +generated layer and its fingerprint remain unchanged by user-layer resolution. See `fixtures/run-configuration/build-provider-stable-identities.json`. The platform guards the source snapshot, atomically writes only the local layer, @@ -3715,9 +3664,8 @@ writing, or post-save reload failed; a reload failure keeps the last usable UI snapshot and states that the documents were already saved. Automatic runtime discovery produces an effective executable path for the -current session. Platforms use that same path both to construct -`toolchainCandidates` and to resolve the launch command. An automatic path is -not a persisted user selection and is written to `.lithe/toolchains/local.json` +current session. Platforms use that same path to resolve the launch command. +An automatic path is not a persisted user selection and is written to `.lithe/toolchains/local.json` only after an explicit editor save. On Windows, Node-backed commands resolve their package-manager shim from the selected Node installation. They do not fall back to a PATH shim from another @@ -4713,6 +4661,19 @@ version to stderr. The definition's `version.pattern` alone captures the version, including any tool-specific numbering such as a legacy `1.` prefix; Core never branches on a tool name. +`build.detect` walks the workspace with Core's shared scan policy. It searches at +most 6 levels and does not follow symlinks. It skips the directories the +default visibility rules hide (Core's own folders and the folder names enabled +plugins declare) and the directories Git ignores, using the `.gitignore` files +it passes and the `info/exclude` of each repository whose root lies in the +workspace (a linked worktree reads the main repository's shared one); a nested +repository starts its own rules. Nothing above the workspace root is read, nor +`core.excludesFile` or the index. The workspace's ignored paths (see +`build.detect` below) decide before Git's rules. Failure to read the workspace +root fails detection, and so does a remote link that drops during the scan; a +deeper directory that cannot be read contributes nothing, and the scan lists at +most 4,000 directories. + Paths in requests are workspace-relative with `/` unless named absolute. `root` is the instance root from detection. Selected entities are `{ name, path?, tags?, execution?, properties? }` as the decoded model diff --git a/rust/contracts/toolchain-requirements-v1.schema.json b/rust/contracts/toolchain-requirements-v1.schema.json deleted file mode 100644 index 0a316112..00000000 --- a/rust/contracts/toolchain-requirements-v1.schema.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://lithe.dev/contracts/toolchain-requirements-v1.schema.json", - "title": "Lithe Toolchain Requirements v1", - "type": "object", - "required": ["version", "toolchains"], - "properties": { - "version": { "const": 1 }, - "toolchains": { - "type": "object", - "additionalProperties": { "$ref": "#/$defs/requirement" } - } - }, - "$defs": { - "requirement": { - "type": "object", - "required": ["type"], - "properties": { - "type": { "type": "string", "pattern": "^[a-z][a-z0-9-]*$" }, - "minimumVersion": { "type": "string", "minLength": 1 }, - "preferredVendor": { "type": "string", "minLength": 1 }, - "version": { "type": "string", "minLength": 1 } - }, - "additionalProperties": false - } - }, - "additionalProperties": false -} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index c3f0da0a..077a6b73 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -706,7 +706,7 @@ pub enum RunConfigCommand { Inspect, /// Reads effective saved tool paths for one Provider root (`runConfig.projectToolchain`). ProjectToolchain, - /// Regenerates detected run configurations (`runConfig.generate`). + /// Regenerates the provider run configurations (`runConfig.generate`). Generate, /// Formats argument vectors as reversible editor text (`runConfig.argumentText`). ArgumentText, diff --git a/rust/crates/core/src/tests/build_systems.rs b/rust/crates/core/src/tests/build_systems.rs index b7e11868..e79e2afb 100644 --- a/rust/crates/core/src/tests/build_systems.rs +++ b/rust/crates/core/src/tests/build_systems.rs @@ -190,23 +190,6 @@ fn detect(workspace: &TemporaryWorkspace, manifests: Vec, options: Value) outcome["detection"].clone() } -fn generated_configurations(workspace: &TemporaryWorkspace) -> Vec { - let response: Value = serde_json::from_str(&crate::execute_json( - &json!({ - "id": "generate", - "command": "runConfig.generate", - "payload": { "root": workspace.root() }, - }) - .to_string(), - )) - .unwrap(); - assert_eq!(response["ok"], true, "{response}"); - response["data"]["generated"]["configurations"] - .as_array() - .cloned() - .unwrap() -} - fn instance<'a>(detection: &'a Value, id: &str) -> &'a Value { detection["instances"] .as_array() @@ -367,9 +350,6 @@ fn instance_options_drive_static_run_entries_without_crossing_roots_or_scopes() assert_eq!(options["options"]["options"][0]["scope"], "instance"); } -/// The Cargo plugin reproduces the built-in Cargo detector's run entries -/// field for field, so moving Cargo onto the plugin model keeps every stored -/// run configuration. #[test] fn provider_test_reports_are_inline_bounded_and_keep_project_identity() { let workspace = TemporaryWorkspace::new("provider-test-reports"); @@ -537,9 +517,11 @@ fn opaque_test_selectors_require_a_declared_namespace_and_never_become_host_filt ); } +/// A static-file provider plans one run entry per binary target, carrying the +/// root, command and source each entry needs, beside the rest of the model. #[test] -fn cargo_run_entries_match_the_builtin_detector() { - let workspace = TemporaryWorkspace::new("build-cargo-parity"); +fn static_cargo_model_plans_a_run_entry_per_binary_target() { + let workspace = TemporaryWorkspace::new("build-cargo-run-entries"); workspace .write( "rust/Cargo.toml", @@ -561,32 +543,35 @@ fn cargo_run_entries_match_the_builtin_detector() { .iter() .flat_map(|instance| instance["model"]["run"].as_array().unwrap().clone()) .collect(); - let mut builtin: Vec = generated_configurations(&workspace) - .into_iter() - .filter(|configuration| configuration["provider"] == "cargo.binary") - .collect(); planned.sort_by_key(|entry| entry["id"].to_string()); - builtin.sort_by_key(|entry| entry["id"].to_string()); - assert_eq!(planned.len(), 3, "{planned:?}"); - assert_eq!(planned.len(), builtin.len(), "{planned:?} vs {builtin:?}"); - for (plan, configuration) in planned.iter().zip(&builtin) { - for field in [ - "id", - "name", - "provider", - "execution", - "command", - "args", - "cwd", - "env", - "source", - "extensions", - ] { - assert_eq!( - plan[field], configuration[field], - "{field}: {plan} vs {configuration}" - ); - } + let expected = [ + ("rust", "rust-app", "cargo:rust/rust-app"), + ("tools", "gen", "cargo:tools/tools"), + ("tools", "lint", "cargo:tools/tools"), + ]; + assert_eq!(planned.len(), expected.len(), "{planned:?}"); + for (entry, (root, bin, project)) in planned.iter().zip(expected) { + assert_eq!(entry["id"], format!("cargo.binary:{root}/{bin}"), "{entry}"); + assert_eq!(entry["name"], bin, "{entry}"); + assert_eq!(entry["provider"], "cargo.binary", "{entry}"); + assert_eq!(entry["execution"], "application", "{entry}"); + assert_eq!(entry["command"], "cargo", "{entry}"); + assert_eq!(entry["args"], json!(["run", "--bin", bin]), "{entry}"); + assert_eq!(entry["cwd"], root, "{entry}"); + assert_eq!(entry["env"], json!({}), "{entry}"); + assert_eq!(entry["source"], format!("{root}/Cargo.toml"), "{entry}"); + assert_eq!( + entry["extensions"], + json!({"cargo": {"bin": bin}}), + "{entry}" + ); + assert_eq!(entry["buildSystem"]["root"], root, "{entry}"); + assert_eq!(entry["buildSystem"]["projectID"], project, "{entry}"); + assert_eq!( + entry["buildSystem"]["targetID"], + format!("cargo.application:{root}/{bin}"), + "{entry}" + ); } let rust = instance(&detection, "cargo:rust"); diff --git a/rust/crates/core/src/tests/detectors.rs b/rust/crates/core/src/tests/detectors.rs deleted file mode 100644 index 090e19e5..00000000 --- a/rust/crates/core/src/tests/detectors.rs +++ /dev/null @@ -1,708 +0,0 @@ -use super::support::{seed_generated, temporary_root}; -use crate::execute_json; -use serde_json::Value; -use std::fs; -use std::path::Path; - -/// Builds a project that mixes six ecosystems in one tree, including the -/// traps that break naive detectors: a lockfile that is not npm's, a -/// nested worktree full of decoy manifests, and a Go command in a -/// subdirectory with no manifest of its own. -fn multi_language_project(root: &Path) { - for directory in ["frontend/.worktrees/decoy", "api", "cmd/gateway"] { - fs::create_dir_all(root.join(directory)).unwrap(); - } - fs::write( - root.join("frontend/package.json"), - r#"{"name":"web","scripts":{"dev":"vite","build":"vite build"}}"#, - ) - .unwrap(); - fs::write(root.join("frontend/pnpm-lock.yaml"), "lockfileVersion: 9\n").unwrap(); - fs::write( - root.join("frontend/.worktrees/decoy/package.json"), - r#"{"scripts":{"dev":"should-never-appear"}}"#, - ) - .unwrap(); - fs::write( - root.join("api/pyproject.toml"), - "[tool.poetry]\nname = \"api\"\n[tool.poetry.scripts]\napi-server = \"api.main:run\"\n", - ) - .unwrap(); - fs::write( - root.join("api/main.py"), - "from fastapi import FastAPI\napp = FastAPI()\n", - ) - .unwrap(); - fs::write(root.join("go.mod"), "module example.com/gw\ngo 1.22\n").unwrap(); - fs::write( - root.join("cmd/gateway/main.go"), - "package main\nfunc main() {}\n", - ) - .unwrap(); - fs::write( - root.join("docker-compose.yml"), - "services:\n db:\n image: postgres\n cache:\n image: redis\n", - ) - .unwrap(); - fs::write( - root.join("Procfile"), - "worker: python worker/run.py\nweb: gunicorn api.main:app\n", - ) - .unwrap(); - fs::write( - root.join("Makefile"), - "run:\n\techo run\nclean:\n\techo clean\n", - ) - .unwrap(); -} - -fn generated_configurations(root: &Path) -> Vec { - let response: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ - "id": "generate", - "command": "runConfig.generate", - "payload": {"root": root} - }) - .to_string(), - )) - .unwrap(); - assert_eq!(response["ok"], true, "{response}"); - response["data"]["generated"]["configurations"] - .as_array() - .cloned() - .unwrap() -} - -/// The headline behaviour: one project, six ecosystems, every service found -/// without the user configuring anything. -#[test] -fn detectors_find_services_across_unrelated_ecosystems() { - let root = temporary_root("detect-multi"); - fs::create_dir_all(&root).unwrap(); - multi_language_project(&root); - - let ids = generated_configurations(&root) - .iter() - .map(|item| item["id"].as_str().unwrap().to_string()) - .collect::>(); - - for expected in [ - "npm.script:frontend/dev", - "python.script:api/api-server", - "python.uvicorn:api/main", - "go.command:cmd/gateway/gateway", - "compose.service:db", - "compose.stack:compose up", - "procfile.process:web", - "make.target:run", - ] { - assert!( - ids.contains(&expected.to_string()), - "missing {expected} in {ids:?}" - ); - } - - fs::remove_dir_all(root).unwrap(); -} - -/// A worktree container repeats every manifest of the project. Descending into it -/// would both bury the real services and make project open unusably slow. -#[test] -fn detectors_never_descend_into_hidden_folders() { - let root = temporary_root("detect-prune"); - fs::create_dir_all(&root).unwrap(); - multi_language_project(&root); - fs::create_dir_all(root.join(".worktree/feature")).unwrap(); - fs::write( - root.join(".worktree/feature/package.json"), - r#"{"scripts":{"dev":"vite"}}"#, - ) - .unwrap(); - fs::create_dir_all(root.join(".worktrees/bugfix")).unwrap(); - fs::write( - root.join(".worktrees/bugfix/package.json"), - r#"{"scripts":{"dev":"vite"}}"#, - ) - .unwrap(); - - let sources = generated_configurations(&root) - .iter() - .filter_map(|item| item["source"].as_str().map(str::to_string)) - .collect::>(); - - assert!( - !sources - .iter() - .any(|source| source.contains(".worktrees/decoy")), - "{sources:?}" - ); - assert!( - !sources.iter().any(|source| { - source.starts_with(".worktree/") || source.starts_with(".worktrees/") - }), - "{sources:?}" - ); - - fs::remove_dir_all(root).unwrap(); -} - -/// Running `npm run dev` in a pnpm workspace fails at spawn time with an -/// error that points nowhere useful, so the lockfile decides the command. -#[test] -fn npm_detector_uses_the_package_manager_the_lockfile_names() { - let root = temporary_root("detect-pnpm"); - fs::create_dir_all(&root).unwrap(); - multi_language_project(&root); - - let dev = generated_configurations(&root) - .into_iter() - .find(|item| item["id"] == "npm.script:frontend/dev") - .unwrap(); - - assert_eq!(dev["command"], "pnpm"); - assert_eq!(dev["args"], serde_json::json!(["run", "dev"])); - assert_eq!(dev["cwd"], "frontend"); - assert_eq!(dev["execution"], "service"); - - fs::remove_dir_all(root).unwrap(); -} - -#[test] -fn npm_detector_inherits_the_workspace_package_manager() { - let root = temporary_root("detect-pnpm-workspace"); - fs::create_dir_all(root.join("apps/web")).unwrap(); - fs::write(root.join("pnpm-lock.yaml"), "lockfileVersion: 9\n").unwrap(); - fs::write( - root.join("apps/web/package.json"), - r#"{"scripts":{"dev":"vite"}}"#, - ) - .unwrap(); - - let dev = generated_configurations(&root) - .into_iter() - .find(|item| item["id"] == "npm.script:apps/web/dev") - .unwrap(); - assert_eq!(dev["command"], "pnpm"); - assert_eq!(dev["execution"], "service"); - - fs::remove_dir_all(root).unwrap(); -} - -#[test] -fn bun_scripts_keep_the_bun_command_without_consuming_node() { - let root = temporary_root("detect-bun-runtime"); - fs::create_dir_all(&root).unwrap(); - fs::write(root.join("bun.lock"), "").unwrap(); - fs::write( - root.join("package.json"), - r#"{"packageManager":"bun@1.2.0","scripts":{"dev":"vite"}}"#, - ) - .unwrap(); - - let dev = generated_configurations(&root) - .into_iter() - .find(|item| item["id"] == "npm.script:dev") - .unwrap(); - assert_eq!(dev["command"], "bun"); - assert!(dev["toolchains"].as_object().unwrap().is_empty(), "{dev}"); - let generated: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ - "id": "generate-bun-runtime", - "command": "runConfig.generate", - "payload": {"root": root} - }) - .to_string(), - )) - .unwrap(); - assert!( - generated["data"]["toolchainRequirements"]["toolchains"]["project-node"].is_null(), - "{generated}" - ); - - fs::remove_dir_all(root).unwrap(); -} - -#[test] -fn detectors_preserve_application_service_and_task_semantics() { - let root = temporary_root("detect-execution-semantics"); - fs::create_dir_all(&root).unwrap(); - multi_language_project(&root); - let configurations = generated_configurations(&root); - let execution = |id: &str| { - configurations - .iter() - .find(|item| item["id"] == id) - .and_then(|item| item["execution"].as_str()) - }; - - assert_eq!(execution("npm.script:frontend/dev"), Some("service")); - assert_eq!(execution("npm.script:frontend/build"), Some("task")); - assert_eq!( - execution("python.script:api/api-server"), - Some("application") - ); - assert_eq!( - execution("go.command:cmd/gateway/gateway"), - Some("application") - ); - assert_eq!(execution("compose.stack:compose up"), Some("service")); - - fs::remove_dir_all(root).unwrap(); -} - -/// Detected entries are process-based, so they must survive the same launch -/// path as any other configuration without acquiring Java assumptions. -#[test] -fn detected_services_produce_runnable_launch_plans() { - let root = temporary_root("detect-launch"); - fs::create_dir_all(&root).unwrap(); - multi_language_project(&root); - let generated = serde_json::json!({ - "version": 2, - "configurations": generated_configurations(&root) - }); - fs::create_dir_all(root.join(".lithe/run")).unwrap(); - seed_generated(&root, serde_json::to_string(&generated).unwrap()); - - let plan: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ - "id": "plan", - "command": "runConfig.createLaunchPlan", - "payload": {"root": root, "configurationId": "npm.script:frontend/dev"} - }) - .to_string(), - )) - .unwrap(); - - assert_eq!(plan["ok"], true, "{plan}"); - assert_eq!(plan["data"]["executable"]["command"], "pnpm"); - assert!(plan["data"]["executable"]["toolchain"].is_null()); - assert_eq!(plan["data"]["workingDirectory"], "frontend"); - assert!(plan["data"]["environment"]["JAVA_HOME"].is_null()); - - fs::remove_dir_all(root).unwrap(); -} - -#[test] -fn every_builtin_detector_produces_a_launch_plan() { - let root = temporary_root("detect-all-launch-plans"); - for directory in ["node", "python", "rust/src", "go"] { - fs::create_dir_all(root.join(directory)).unwrap(); - } - fs::write( - root.join("node/package.json"), - r#"{"scripts":{"dev":"node server.js"}}"#, - ) - .unwrap(); - fs::write( - root.join("python/pyproject.toml"), - "[project]\nname = \"python-app\"\n[project.scripts]\npython-app = \"app:main\"\n", - ) - .unwrap(); - fs::write( - root.join("rust/Cargo.toml"), - "[package]\nname = \"rust-app\"\nversion = \"0.1.0\"\n", - ) - .unwrap(); - fs::write(root.join("rust/src/main.rs"), "fn main() {}\n").unwrap(); - fs::write( - root.join("go/go.mod"), - "module example.com/go-app\ngo 1.22\n", - ) - .unwrap(); - fs::write(root.join("go/main.go"), "package main\nfunc main() {}\n").unwrap(); - fs::write( - root.join("compose.yml"), - "services:\n database:\n image: postgres\n", - ) - .unwrap(); - fs::write(root.join("Procfile"), "worker: python worker.py\n").unwrap(); - fs::write(root.join("Makefile"), "serve:\n\t@echo serve\n").unwrap(); - fs::write(root.join("justfile"), "watch:\n echo watch\n").unwrap(); - - let configurations = generated_configurations(&root); - fs::create_dir_all(root.join(".lithe/run")).unwrap(); - seed_generated( - &root, - serde_json::json!({"version": 2, "configurations": configurations}).to_string(), - ); - - for (provider, id) in [ - ("npm.script", "npm.script:node/dev"), - ("compose.service", "compose.service:database"), - ("procfile.process", "procfile.process:worker"), - ("python.script", "python.script:python/python-app"), - ("cargo.binary", "cargo.binary:rust/rust-app"), - ("go.main", "go.main:go/go"), - ("make.target", "make.target:serve"), - ("just.recipe", "just.recipe:watch"), - ] { - assert!( - configurations - .iter() - .any(|item| item["provider"] == provider), - "missing provider {provider} in {configurations:?}" - ); - let response: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ - "id": format!("plan-{provider}"), - "command": "runConfig.createLaunchPlan", - "payload": {"root": root, "configurationId": id} - }) - .to_string(), - )) - .unwrap(); - assert_eq!( - response["ok"], true, - "{provider} launch plan failed: {response}" - ); - } - - fs::remove_dir_all(root).unwrap(); -} - -/// The panel needs to say *what* a service is, not just that a script exists. -/// The framework comes from the declared dependencies, which is the only place -/// a JavaScript project states it. -#[test] -fn npm_detector_names_the_framework_from_the_dependencies() { - let root = temporary_root("detect-npm-framework"); - fs::create_dir_all(&root).unwrap(); - fs::write( - root.join("package.json"), - r#"{"dependencies":{"vue":"^3.4.0"},"devDependencies":{"vite":"^5.0.0"},"scripts":{"dev":"vite"}}"#, - ) - .unwrap(); - - let dev = generated_configurations(&root) - .into_iter() - .find(|item| item["id"] == "npm.script:dev") - .unwrap(); - - assert_eq!(dev["extensions"]["npm"]["framework"], "vue"); - assert_eq!(dev["extensions"]["npm"]["server"], "vite"); - assert_eq!(dev["execution"], "service"); - // Reading the script body is real evidence, unlike matching the name `dev`. - assert_eq!(dev["confidence"], "declared"); - - fs::remove_dir_all(root).unwrap(); -} - -/// A meta-framework depends on the framework it is built on, so a Nuxt app -/// declares Vue as well. Reporting `vue` there is true and useless. -#[test] -fn npm_detector_prefers_the_most_specific_framework() { - let root = temporary_root("detect-npm-meta-framework"); - for (directory, manifest) in [ - ( - "web", - r#"{"dependencies":{"nuxt":"^3.11.0","vue":"^3.4.0"},"scripts":{"dev":"nuxt dev"}}"#, - ), - ( - "site", - r#"{"dependencies":{"next":"^14.2.0","react":"^18.3.0"},"scripts":{"dev":"next dev"}}"#, - ), - ( - "app", - r#"{"devDependencies":{"@sveltejs/kit":"^2.5.0","svelte":"^4.2.0"},"scripts":{"dev":"vite dev"}}"#, - ), - ] { - fs::create_dir_all(root.join(directory)).unwrap(); - fs::write(root.join(directory).join("package.json"), manifest).unwrap(); - } - - let configurations = generated_configurations(&root); - let framework = |id: &str| { - configurations - .iter() - .find(|item| item["id"] == id) - .and_then(|item| item["extensions"]["npm"]["framework"].as_str()) - }; - - assert_eq!(framework("npm.script:web/dev"), Some("nuxt")); - assert_eq!(framework("npm.script:site/dev"), Some("next")); - assert_eq!(framework("npm.script:app/dev"), Some("sveltekit")); - - fs::remove_dir_all(root).unwrap(); -} - -/// Script names are a convention, not a declaration. What the script actually -/// runs decides whether it is a service, so a `start` that builds is a task and -/// a `local` that serves is a service. -#[test] -fn npm_detector_classifies_scripts_by_what_they_run() { - let root = temporary_root("detect-npm-script-bodies"); - fs::create_dir_all(&root).unwrap(); - fs::write( - root.join("package.json"), - r#"{"scripts":{ - "start":"tsc -p .", - "local":"NODE_ENV=development npx vite --port 3000", - "api":"nodemon src/index.js", - "staged":"rimraf dist && vite build", - "e2e":"vite build && vite preview" - }}"#, - ) - .unwrap(); - - let configurations = generated_configurations(&root); - let execution = |id: &str| { - configurations - .iter() - .find(|item| item["id"] == id) - .and_then(|item| item["execution"].as_str()) - }; - - // A build tool named `start` is still a build. - assert_eq!(execution("npm.script:start"), Some("task")); - // Environment assignments and `npx` wrap the program without changing it. - assert_eq!(execution("npm.script:local"), Some("service")); - assert_eq!(execution("npm.script:api"), Some("service")); - // `vite build` terminates; only the serving subcommands are services. - assert_eq!(execution("npm.script:staged"), Some("task")); - // A script that prepares and then serves is still a service. - assert_eq!(execution("npm.script:e2e"), Some("service")); - - fs::remove_dir_all(root).unwrap(); -} - -/// When a script shells out to something unrecognised the name is all there is, -/// so the guess stays available but is marked `Heuristic`. Dedup then lets any -/// detector holding real evidence for the same service win. -#[test] -fn npm_detector_demotes_service_names_it_cannot_verify() { - let root = temporary_root("detect-npm-heuristic"); - fs::create_dir_all(&root).unwrap(); - fs::write( - root.join("package.json"), - r#"{"scripts":{"dev":"./scripts/dev.sh","build":"./scripts/build.sh"}}"#, - ) - .unwrap(); - fs::write(root.join("Procfile"), "dev: python worker.py\n").unwrap(); - - let configurations = generated_configurations(&root); - let build = configurations - .iter() - .find(|item| item["id"] == "npm.script:build") - .unwrap(); - assert_eq!(build["execution"], "task"); - - // The Procfile declares the command for `dev`, so it outranks the guess the - // script name supports. Both share an identity of (cwd, name). - let dev = configurations - .iter() - .filter(|item| item["name"] == "dev") - .collect::>(); - assert_eq!(dev.len(), 1, "{configurations:?}"); - assert_eq!(dev[0]["provider"], "procfile.process"); - assert_eq!(dev[0]["command"], "python"); - - fs::remove_dir_all(root).unwrap(); -} - -/// Starlette and Litestar applications are served the same way FastAPI ones are, -/// and the panel needs the framework name to label them apart. -#[test] -fn python_detector_names_asgi_frameworks_it_serves_through_uvicorn() { - let root = temporary_root("detect-python-asgi"); - for (directory, source) in [ - ( - "edge", - "from starlette.applications import Starlette\napp = Starlette()\n", - ), - ( - "orders", - "from litestar import Litestar\napp = Litestar()\n", - ), - ] { - fs::create_dir_all(root.join(directory)).unwrap(); - fs::write(root.join(directory).join("asgi.py"), source).unwrap(); - } - - let configurations = generated_configurations(&root); - let framework = |id: &str| { - configurations - .iter() - .find(|item| item["id"] == id) - .and_then(|item| item["extensions"]["python"]["framework"].as_str()) - }; - - assert_eq!(framework("python.uvicorn:edge/asgi"), Some("starlette")); - assert_eq!(framework("python.uvicorn:orders/asgi"), Some("litestar")); - let edge = configurations - .iter() - .find(|item| item["id"] == "python.uvicorn:edge/asgi") - .unwrap(); - assert_eq!(edge["command"], "uvicorn"); - assert_eq!(edge["args"], serde_json::json!(["asgi:app", "--reload"])); - assert_eq!(edge["execution"], "service"); - - fs::remove_dir_all(root).unwrap(); -} - -/// Which file holds the application is a guess, but the framework itself is -/// declared. A project that lists its framework gets `Declared`, so the entry -/// survives against a lower-confidence detection of the same service. -#[test] -fn python_detector_trusts_a_declared_framework_over_a_bare_file_name() { - let root = temporary_root("detect-python-declared"); - for (directory, files) in [ - ( - "declared", - vec![ - ("pyproject.toml", "[project]\nname = \"declared\"\ndependencies = [\"fastapi>=0.110\", \"uvicorn[standard]\"]\n"), - ("main.py", "from fastapi import FastAPI\napp = FastAPI()\n"), - ], - ), - ( - "guessed", - vec![("main.py", "from fastapi import FastAPI\napp = FastAPI()\n")], - ), - ( - "pinned", - vec![ - ("requirements.txt", "# runtime\nflask==3.0.2\ngunicorn\n"), - ("app.py", "from flask import Flask\napp = Flask(__name__)\n"), - ], - ), - ] { - fs::create_dir_all(root.join(directory)).unwrap(); - for (file, source) in files { - fs::write(root.join(directory).join(file), source).unwrap(); - } - } - - let configurations = generated_configurations(&root); - let confidence = |id: &str| { - configurations - .iter() - .find(|item| item["id"] == id) - .and_then(|item| item["confidence"].as_str()) - }; - - assert_eq!(confidence("python.uvicorn:declared/main"), Some("declared")); - // No dependency list means the framework import in one file is all there is. - assert_eq!(confidence("python.uvicorn:guessed/main"), Some("heuristic")); - // A requirements file is a declaration too, version specifier and all. - assert_eq!(confidence("python.flask:pinned/app"), Some("declared")); - - fs::remove_dir_all(root).unwrap(); -} - -/// Django's entry point is `manage.py` by convention, so the framework name is -/// what tells the panel this is a Django service rather than a loose script. -#[test] -fn python_detector_labels_a_declared_django_project() { - let root = temporary_root("detect-python-django"); - fs::create_dir_all(&root).unwrap(); - fs::write( - root.join("pyproject.toml"), - "[tool.poetry]\nname = \"site\"\n[tool.poetry.dependencies]\ndjango = \"^5.0\"\n", - ) - .unwrap(); - fs::write(root.join("manage.py"), "import django\n").unwrap(); - - let runserver = generated_configurations(&root) - .into_iter() - .find(|item| item["id"] == "python.django:runserver") - .unwrap(); - - assert_eq!(runserver["extensions"]["python"]["framework"], "django"); - assert_eq!(runserver["confidence"], "declared"); - assert_eq!(runserver["execution"], "service"); - - fs::remove_dir_all(root).unwrap(); -} - -/// Issue follow-up: a Java repository's Compose files declare the databases the -/// project runs against. They stay runnable, but they are reported as -/// infrastructure so hosts can keep them out of the project's service list. -#[test] -fn compose_detections_are_reported_as_infrastructure() { - let root = temporary_root("detect-compose-category"); - fs::create_dir_all(root.join("script/docker")).unwrap(); - fs::create_dir_all(root.join("sql/tools")).unwrap(); - fs::write( - root.join("script/docker/docker-compose.yml"), - "services:\n mysql:\n image: mysql\n server:\n image: app\n", - ) - .unwrap(); - fs::write( - root.join("sql/tools/docker-compose.yaml"), - "services:\n mysql:\n image: mysql\n", - ) - .unwrap(); - fs::write(root.join("Makefile"), "run:\n\techo run\n").unwrap(); - - let configurations = generated_configurations(&root); - let category = |id: &str| { - configurations - .iter() - .find(|item| item["id"] == id) - .unwrap_or_else(|| panic!("{id} should be generated: {configurations:?}"))["category"] - .clone() - }; - assert_eq!( - category("compose.service:script/docker/mysql"), - "infrastructure" - ); - assert_eq!( - category("compose.stack:sql/tools/compose up"), - "infrastructure" - ); - // Project entries keep the default category, which Core omits entirely so - // existing generated documents do not churn. - assert_eq!(category("make.target:run"), Value::Null); - - fs::remove_dir_all(root).unwrap(); -} - -/// Three Compose files each contribute `compose up`, and two of them declare -/// `mysql`. Ids differ, but the Run list shows only names, so Core qualifies -/// the repeated ones with the directory they run in. -#[test] -fn repeated_detection_names_are_qualified_by_directory() { - let root = temporary_root("detect-duplicate-names"); - fs::create_dir_all(root.join("script/docker")).unwrap(); - fs::create_dir_all(root.join("sql/tools")).unwrap(); - for directory in ["script/docker", "sql/tools"] { - fs::write( - root.join(directory).join("docker-compose.yml"), - "services:\n mysql:\n image: mysql\n", - ) - .unwrap(); - } - fs::write( - root.join("script/docker/docker-compose.yml"), - "services:\n mysql:\n image: mysql\n redis:\n image: redis\n", - ) - .unwrap(); - - let configurations = generated_configurations(&root); - let name = |id: &str| { - configurations - .iter() - .find(|item| item["id"] == id) - .unwrap_or_else(|| panic!("{id} should be generated: {configurations:?}"))["name"] - .as_str() - .unwrap() - .to_string() - }; - assert_eq!( - name("compose.service:script/docker/mysql"), - "mysql (script/docker)" - ); - assert_eq!(name("compose.service:sql/tools/mysql"), "mysql (sql/tools)"); - assert_eq!( - name("compose.stack:script/docker/compose up"), - "compose up (script/docker)" - ); - assert_eq!( - name("compose.stack:sql/tools/compose up"), - "compose up (sql/tools)" - ); - // A name that appears once is never decorated. - assert_eq!(name("compose.service:script/docker/redis"), "redis"); - - fs::remove_dir_all(root).unwrap(); -} diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 6ad9c866..a0037b35 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -5,7 +5,6 @@ mod build_runtime_versions; mod build_systems; mod core_request_traces; mod declarative_plugins; -mod detectors; mod diagnostics_dispatch; mod directory_actions; mod document_uri; diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index af229124..0ae6388c 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -743,11 +743,13 @@ fn remote_workspace_file_limits_preserve_host_content_and_report_disconnects() { assert_eq!(std::fs::read_dir(local).unwrap().count(), 0); } -// `runConfig.inspect` has no remote adapter yet; this pins the shared traversal's -// remote contract so enabling it cannot read the placeholder or accept a dead link. +// Build detection walks a remote project through the workspace adapter; this pins +// that the shared traversal reads the host's tree, never the placeholder, and +// fails instead of shrinking when the link drops. #[test] -fn shared_run_scan_reads_the_host_tree_and_stops_when_the_link_drops() { - use crate::execution::workspace_scan::{scan_run_workspace, scan_with_reader}; +fn shared_workspace_scan_reads_the_host_tree_and_stops_when_the_link_drops() { + use crate::execution::workspace_scan::{scan_with_reader, scan_workspace}; + use crate::execution::IgnoredPaths; use lithe_workspace::{self as workspace, fs}; let host = HostFixture::new(); @@ -767,9 +769,8 @@ fn shared_run_scan_reads_the_host_tree_and_stops_when_the_link_drops() { .unwrap(); let _workspace = workspace::Scope::begin(Some(workspace)).unwrap(); - let scan = scan_run_workspace(&local, Some(3)).unwrap(); + let scan = scan_workspace(&local, 3, &IgnoredPaths::default()).unwrap(); let files: Vec<_> = scan - .directories .iter() .map(|directory| { let relative = directory.path.strip_prefix(&local).unwrap(); @@ -790,12 +791,11 @@ fn shared_run_scan_reads_the_host_tree_and_stops_when_the_link_drops() { ("service/api".into(), Vec::new()), ] ); - assert!(scan.unreadable_paths.is_empty()); assert_eq!(std::fs::read_dir(&local).unwrap().count(), 0); - // A directory the host reports as unreadable is incomplete-scan evidence, - // while the same session keeps serving its siblings. - let unreadable = scan_with_reader(&local, Some(3), &|path| { + // A directory the host reports as unreadable is skipped, while the same + // session keeps serving the rest of the tree. + let unreadable = scan_with_reader(&local, 3, &|path| { if path.ends_with("service") { return Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)); } @@ -808,14 +808,15 @@ fn shared_run_scan_reads_the_host_tree_and_stops_when_the_link_drops() { .collect() }) .unwrap(); - assert_eq!( - unreadable.unreadable_paths, - std::collections::BTreeSet::from(["service".to_owned()]) - ); + let listed: Vec<_> = unreadable + .iter() + .map(|directory| directory.path.strip_prefix(&local).unwrap().to_owned()) + .collect(); + assert_eq!(listed, [std::path::PathBuf::new()]); // The link dropping after the root was listed must fail the whole scan, // not publish the root alone as if the project had no modules. - let dropped = scan_with_reader(&local, Some(3), &|path| { + let dropped = scan_with_reader(&local, 3, &|path| { let entries = fs::read_dir(path)? .map(|entry| { let entry = entry?; @@ -830,7 +831,7 @@ fn shared_run_scan_reads_the_host_tree_and_stops_when_the_link_drops() { dropped.is_err(), "a dropped link must not look like a smaller project" ); - assert!(scan_run_workspace(&local, Some(3)).is_err()); + assert!(scan_workspace(&local, 3, &IgnoredPaths::default()).is_err()); assert_eq!(std::fs::read_dir(local).unwrap().count(), 0); } diff --git a/rust/crates/core/src/tests/run_configuration.rs b/rust/crates/core/src/tests/run_configuration.rs index 10b5b2ee..07015e69 100644 --- a/rust/crates/core/src/tests/run_configuration.rs +++ b/rust/crates/core/src/tests/run_configuration.rs @@ -1,4 +1,4 @@ -use super::support::{seed_generated, seed_requirements, temporary_root}; +use super::support::{seed_generated, temporary_root}; use crate::execute_json; use serde_json::Value; use std::fs; @@ -447,181 +447,41 @@ fn run_configuration_inspect_reports_malformed_and_unsupported_documents() { } #[test] -fn run_configuration_inspection_summarizes_changed_inputs() { - let root = temporary_root("run-config-input-summary"); - fs::create_dir_all(root.join("src")).unwrap(); - fs::write(root.join("src/app.txt"), "app").unwrap(); - fs::write(root.join("package.json"), r#"{"name":"demo"}"#).unwrap(); - let generated = generate_run_configuration(&root, &["src/app.txt"]); - let generated_again = generate_run_configuration(&root, &["src/app.txt"]); - assert_eq!(generated, generated_again); - write_generated_run_document(&root, &generated); - fs::write(root.join("package.json"), r#"{"name":"renamed"}"#).unwrap(); - - let inspected = inspect_run_configuration(&root); - assert_eq!( - inspected["diagnostics"][0]["message"], - "Project inputs changed: 0 added, 0 removed, 1 modified" - ); - - fs::remove_dir_all(root).unwrap(); -} - -fn generate_run_configuration(root: &std::path::Path, paths: &[&str]) -> Value { - let payload = serde_json::json!({ "root": root, "paths": paths, "modulePaths": [] }); - let response: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ "id": "generate", "command": "runConfig.generate", "payload": payload }) - .to_string(), - )) - .unwrap(); - assert_eq!(response["ok"], true, "{response}"); - response["data"]["generated"].clone() -} - -fn write_generated_run_document(root: &std::path::Path, generated: &Value) { - fs::create_dir_all(root.join(".lithe/run")).unwrap(); - seed_generated(root, serde_json::to_string(generated).unwrap()); -} - -fn inspect_run_configuration(root: &std::path::Path) -> Value { - let payload = serde_json::json!({ "root": root }); - let response: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ "id": "inspect", "command": "runConfig.inspect", "payload": payload }) - .to_string(), - )) - .unwrap(); - assert_eq!(response["ok"], true, "{response}"); - response["data"].clone() -} - -#[test] -fn run_configuration_resolve_matches_toolchains_and_rejects_unsafe_paths() { - let root = temporary_root("run-config-toolchain-resolution"); +fn run_configuration_resolve_rejects_unsafe_working_directories() { + let root = temporary_root("run-config-unsafe-paths"); fs::create_dir_all(root.join(".lithe/run")).unwrap(); - fs::create_dir_all(root.join(".lithe/toolchains")).unwrap(); seed_generated( &root, r#"{"version":1,"configurations":[{"id":"current-file","name":"Current File","type":"example.current-file","toolchains":{"runtime":"project-runtime"}}]}"#, ); - seed_requirements( - &root, - r#"{"version":1,"toolchains":{"project-runtime":{"type":"runtime","minimumVersion":"21","preferredVendor":"temurin"}}}"#, - ); - let resolve = |version: &str, vendor: &str| -> Value { + let resolve = || -> Value { serde_json::from_str(&execute_json( &serde_json::json!({ - "id": "resolve-toolchains", + "id": "resolve-unsafe-paths", "command": "runConfig.resolve", - "payload": { - "root": root, - "toolchainCandidates": [{ - "id": "project-runtime", - "type": "runtime", - "version": version, - "vendor": vendor - }] - } + "payload": {"root": root} }) .to_string(), )) .unwrap() }; - let mismatch = resolve("17.0.12", "Zulu"); - assert!(mismatch["data"]["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|value| value["code"] == "toolchainVersionMismatch")); - assert!(mismatch["data"]["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|value| value["code"] == "toolchainVendorMismatch")); - - let matching = resolve("21.0.5", "Eclipse Temurin"); - assert!(matching["data"]["diagnostics"] - .as_array() - .unwrap() - .is_empty()); + let safe = resolve(); + assert_eq!(safe["ok"], true, "{safe}"); + assert!(safe["data"]["diagnostics"].as_array().unwrap().is_empty()); fs::write( root.join(".lithe/run/local.json"), r#"{"version":1,"configurations":[{"id":"current-file","workingDirectory":"../outside"}]}"#, ) .unwrap(); - let unsafe_path = resolve("21.0.5", "Eclipse Temurin"); + let unsafe_path = resolve(); assert_eq!(unsafe_path["ok"], false); assert_eq!(unsafe_path["error"]["code"], "invalid_request"); fs::remove_dir_all(root).unwrap(); } -#[test] -fn legacy_v2_runtime_requirements_are_reconciled_without_regeneration() { - let root = temporary_root("run-config-legacy-runtime-consumption"); - fs::create_dir_all(root.join(".lithe/run")).unwrap(); - fs::create_dir_all(root.join(".lithe/toolchains")).unwrap(); - fs::create_dir_all(root.join("web")).unwrap(); - fs::create_dir_all(root.join("bun-web")).unwrap(); - seed_generated( - &root, - r#"{"version":2,"configurations":[ - {"id":"service","name":"backend","provider":"build.service","execution":"service","cwd":".","toolchains":{"runtime":"project-runtime","build":"project-build"}}, - {"id":"npm","name":"web","provider":"npm.script","execution":"service","command":"npm","args":["run","dev"],"cwd":"web","toolchains":{}}, - {"id":"bun","name":"bun web","provider":"npm.script","execution":"service","command":"bun","args":["run","dev"],"cwd":"bun-web","toolchains":{"runtime":"project-node"}} - ]}"#, - ); - seed_requirements( - &root, - r#"{"version":1,"toolchains":{ - "project-runtime":{"type":"runtime"}, - "project-build":{"type":"build-tool"}, - "project-node":{"type":"node","minimumVersion":"22"} - }}"#, - ); - - let resolved: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ - "id": "resolve-legacy-runtime-consumption", - "command": "runConfig.resolve", - "payload": { - "root": root, - "toolchainCandidates": [ - {"id":"project-runtime","type":"runtime","version":"21","vendor":"Example"}, - {"id":"project-build","type":"build-tool","version":"3.9.9","vendor":""} - ] - } - }) - .to_string(), - )) - .unwrap(); - assert_eq!(resolved["ok"], true, "{resolved}"); - let node_diagnostics = resolved["data"]["diagnostics"] - .as_array() - .unwrap() - .iter() - .filter(|diagnostic| diagnostic["toolchain"] == "project-node") - .collect::>(); - assert_eq!(node_diagnostics.len(), 1, "{resolved}"); - assert_eq!(node_diagnostics[0]["id"], "npm"); - let configurations = resolved["data"]["configurations"].as_array().unwrap(); - assert_eq!( - configurations - .iter() - .find(|configuration| configuration["id"] == "npm") - .unwrap()["toolchains"]["runtime"], - "project-node" - ); - assert!(configurations - .iter() - .find(|configuration| configuration["id"] == "bun") - .unwrap()["toolchains"]["runtime"] - .is_null()); - - fs::remove_dir_all(root).unwrap(); -} - #[test] fn shared_run_configuration_fixtures_have_the_versioned_contract_shape() { let directory = @@ -644,68 +504,6 @@ fn shared_run_configuration_fixtures_have_the_versioned_contract_shape() { assert!(fixture_count >= 6); } -#[test] -fn shared_hybrid_fixture_executes_scoped_toolchain_expectations() { - let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/run-configuration/hybrid-service-web.json"); - let fixture: Value = serde_json::from_str(&fs::read_to_string(fixture_path).unwrap()).unwrap(); - let root = temporary_root("run-config-hybrid-fixture"); - fs::create_dir_all(root.join(".lithe/run")).unwrap(); - fs::create_dir_all(root.join(".lithe/toolchains")).unwrap(); - seed_generated(&root, serde_json::to_string(&fixture["generated"]).unwrap()); - seed_requirements( - &root, - serde_json::to_string(&fixture["requirements"]).unwrap(), - ); - - let resolved: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ - "id": "resolve-hybrid-fixture", - "command": "runConfig.resolve", - "payload": { - "root": root, - "toolchainCandidates": [ - {"id":"project-runtime","type":"runtime","version":"21","vendor":"Example"}, - {"id":"project-build","type":"build-tool","version":"3.9.9","vendor":""} - ] - } - }) - .to_string(), - )) - .unwrap(); - assert_eq!(resolved["ok"], true, "{resolved}"); - let missing_node_ids = resolved["data"]["diagnostics"] - .as_array() - .unwrap() - .iter() - .filter(|diagnostic| diagnostic["toolchain"] == "project-node") - .filter_map(|diagnostic| diagnostic["id"].as_str()) - .collect::>(); - assert_eq!( - missing_node_ids, - fixture["expected"]["missingNodeDiagnosticConfigurationIds"] - .as_array() - .unwrap() - .iter() - .filter_map(Value::as_str) - .collect::>() - ); - for id in fixture["expected"]["unblockedConfigurationIds"] - .as_array() - .unwrap() - .iter() - .filter_map(Value::as_str) - { - assert!(resolved["data"]["diagnostics"] - .as_array() - .unwrap() - .iter() - .all(|diagnostic| diagnostic["id"] != id)); - } - - fs::remove_dir_all(root).unwrap(); -} - #[test] fn shared_editor_save_fixture_executes_the_document_contract() { let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) @@ -751,7 +549,11 @@ fn migration_leaves_sidecar_documents_at_their_own_version() { r#"{"version":1,"defaultRunConfiguration":"current-file"}"#, ) .unwrap(); - seed_requirements(&root, r#"{"version":1,"toolchains":{}}"#); + fs::write( + root.join(".lithe/toolchains/local.json"), + r#"{"version":1,"toolchains":{}}"#, + ) + .unwrap(); let resolved: Value = serde_json::from_str(&execute_json( &serde_json::json!({ @@ -845,96 +647,6 @@ fn toolchain_backed_process_uses_the_generic_runtime_binding() { fs::remove_dir_all(root).unwrap(); } -#[test] -fn pure_go_generation_adds_no_current_file_configuration() { - let root = temporary_root("pure-go-generation"); - fs::create_dir_all(&root).unwrap(); - fs::write(root.join("go.mod"), "module example.com/api\n\ngo 1.24\n").unwrap(); - fs::write(root.join("main.go"), "package main\nfunc main() {}\n").unwrap(); - - let generated: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ - "id": "generate-pure-go", - "command": "runConfig.generate", - "payload": {"root": root, "paths": ["go.mod", "main.go"], "modulePaths": []} - }) - .to_string(), - )) - .unwrap(); - assert_eq!(generated["ok"], true, "{generated}"); - let configurations = generated["data"]["generated"]["configurations"] - .as_array() - .unwrap(); - assert!(configurations - .iter() - .any(|value| value["provider"] == "go.main")); - assert!(!configurations - .iter() - .any(|value| value["id"] == "current-file")); - - fs::remove_dir_all(root).unwrap(); -} - -#[test] -fn multi_language_generation_declares_only_consumed_runtime_requirements() { - let root = temporary_root("generic-toolchain-requirements"); - for directory in ["python", "web", "worker/src"] { - fs::create_dir_all(root.join(directory)).unwrap(); - } - fs::write(root.join("go.mod"), "module example.com/api\n\ngo 1.24\n").unwrap(); - fs::write(root.join("main.go"), "package main\nfunc main() {}\n").unwrap(); - fs::write( - root.join("python/pyproject.toml"), - "[project]\nname = \"api\"\nrequires-python = \">=3.12\"\n[project.scripts]\napi = \"api:main\"\n", - ) - .unwrap(); - fs::write( - root.join("web/package.json"), - r#"{"engines":{"node":">=22.4"},"scripts":{"dev":"vite"}}"#, - ) - .unwrap(); - fs::write( - root.join("worker/Cargo.toml"), - "[package]\nname = \"worker\"\nversion = \"0.1.0\"\nrust-version = \"1.82\"\n", - ) - .unwrap(); - fs::write(root.join("worker/src/main.rs"), "fn main() {}\n").unwrap(); - - let generated: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ - "id": "generate-generic-requirements", - "command": "runConfig.generate", - "payload": {"root": root} - }) - .to_string(), - )) - .unwrap(); - assert_eq!(generated["ok"], true, "{generated}"); - let requirements = &generated["data"]["toolchainRequirements"]["toolchains"]; - assert_eq!( - requirements["project-node"]["type"], "node", - "{requirements}" - ); - assert_eq!( - requirements["project-node"]["minimumVersion"], "22.4", - "{requirements}" - ); - for id in ["project-go", "project-python", "project-cargo"] { - assert!(requirements[id].is_null(), "{id}: {requirements}"); - } - for provider in ["go.main", "python.script", "cargo.binary"] { - let configuration = generated["data"]["generated"]["configurations"] - .as_array() - .unwrap() - .iter() - .find(|configuration| configuration["provider"] == provider) - .unwrap(); - assert!(configuration["toolchains"].as_object().unwrap().is_empty()); - } - - fs::remove_dir_all(root).unwrap(); -} - #[test] fn unknown_provider_without_an_executable_is_rejected() { let root = temporary_root("run-config-unknown-provider"); @@ -1065,11 +777,11 @@ fn process_configurations_reject_path_qualified_commands() { fs::remove_dir_all(root).unwrap(); } -/// Without a default in `.lithe/project.json`, a framework service is chosen -/// before a plain main class; a project default still wins when available. +/// Without a default in `.lithe/project.json`, a generated service is chosen +/// before a plain application; a project default still wins when available. #[test] -fn resolve_chooses_detected_default_unless_the_project_names_one() { - let root = temporary_root("run-config-detected-default"); +fn resolve_chooses_generated_default_unless_the_project_names_one() { + let root = temporary_root("run-config-generated-default"); struct Cleanup(PathBuf); impl Drop for Cleanup { fn drop(&mut self) { @@ -1089,10 +801,10 @@ fn resolve_chooses_detected_default_unless_the_project_names_one() { "execution": "service", "toolchains": {}} ]}), ); - let detected = run_config_command("runConfig.resolve", serde_json::json!({ "root": root })); - assert_eq!(detected["ok"], true, "{detected}"); + let generated = run_config_command("runConfig.resolve", serde_json::json!({ "root": root })); + assert_eq!(generated["ok"], true, "{generated}"); assert_eq!( - detected["data"]["defaultRunConfiguration"], + generated["data"]["defaultRunConfiguration"], "build.service:." ); @@ -1184,77 +896,6 @@ fn working_directory_override_must_name_an_existing_project_directory() { assert_eq!(document["configurations"][0]["cwd"], "backend"); } -#[test] -fn shared_run_scan_excludes_hidden_folders_and_keeps_dot_named_sources() { - let root = temporary_root("shared-run-scan"); - struct Cleanup(PathBuf); - impl Drop for Cleanup { - fn drop(&mut self) { - fs::remove_dir_all(&self.0).unwrap(); - } - } - fs::create_dir_all(&root).unwrap(); - let _cleanup = Cleanup(root.clone()); - // Core scans the workspace itself: the folders it hides are left out at any - // depth, a dot-named source directory stays. - for path in [ - ".sources/Makefile", - "src/Makefile", - ".git/Makefile", - ".worktrees/feature/Makefile", - "app/.worktree/Makefile", - ] { - let file = root.join(path); - fs::create_dir_all(file.parent().unwrap()).unwrap(); - fs::write(file, "all:\n\ttrue\n").unwrap(); - } - let call = |command, payload| -> Value { - let response: Value = serde_json::from_str(&execute_json( - &serde_json::json!({ - "id": "scan", "command": command, "payload": payload - }) - .to_string(), - )) - .unwrap(); - assert_eq!(response["ok"], true, "{response}"); - response["data"].clone() - }; - let generated = call("runConfig.generate", serde_json::json!({"root": root})); - let inputs = generated["generated"]["generator"]["inputs"] - .as_object() - .unwrap(); - assert!(inputs.contains_key(".sources/Makefile")); - assert!(inputs.contains_key("src/Makefile")); - assert!(!inputs.keys().any(|path| { - path.starts_with(".git/") - || path.starts_with(".worktrees/") - || path.starts_with("app/.worktree/") - })); - let mut document = generated["generated"].clone(); - // A persisted incomplete baseline cannot certify freshness or infer deletion, - // even after the previously inaccessible directory becomes readable again. - document["generator"]["unreadablePaths"] = serde_json::json!(["blocked"]); - fs::create_dir_all(root.join(".lithe/run")).unwrap(); - seed_generated(&root, document.to_string()); - for full in [false, true] { - let inspected = call( - "runConfig.inspect", - serde_json::json!({"root": root, "checkFingerprint": full}), - ); - assert_eq!(inspected["status"], "ready"); - assert!(inspected["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|d| d["code"] == "incompleteProjectScan")); - assert!(!inspected["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|d| d["code"] == "staleFingerprint")); - } -} - /// Saving a selector never stores an executable, generates a model, or loses local defaults. #[test] fn build_provider_configurations_persist_before_generation_and_reuse_identity() { @@ -1305,10 +946,7 @@ fn build_provider_configurations_persist_before_generation_and_reuse_identity() document["configurations"][0]["extensions"]["annotations"] = serde_json::json!({"label":"keep user metadata"}); fs::write(&local, document.to_string()).unwrap(); - let inspected = call( - "runConfig.inspect", - serde_json::json!({"root":root,"checkFingerprint":false}), - ); + let inspected = call("runConfig.inspect", serde_json::json!({"root":root})); assert_eq!( inspected["data"]["status"], fixture["expected"]["inspectionStatus"], "{inspected}" @@ -1317,10 +955,7 @@ fn build_provider_configurations_persist_before_generation_and_reuse_identity() inspected["data"]["requiresGeneration"], fixture["expected"]["requiresGeneration"] ); - let resolved = call( - "runConfig.resolve", - serde_json::json!({"root":root,"toolchainCandidates":[]}), - ); + let resolved = call("runConfig.resolve", serde_json::json!({"root":root})); assert_eq!(resolved["ok"], true, "{resolved}"); assert_eq!( resolved["data"]["configurations"].as_array().unwrap().len(), @@ -1428,10 +1063,7 @@ fn explicit_provider_references_keep_arbitrary_ids_and_shadow_only_current_selec let team_path = root.join(".lithe/run/configurations.json"); let local_path = root.join(".lithe/run/local.json"); fs::write(&team_path, team.to_string()).unwrap(); - let inspected = call( - "runConfig.inspect", - serde_json::json!({"root":root,"checkFingerprint":false}), - ); + let inspected = call("runConfig.inspect", serde_json::json!({"root":root})); assert_eq!(inspected["status"], "ready"); assert_eq!(inspected["requiresGeneration"], true); let before = call("runConfig.resolve", serde_json::json!({"root":root})); @@ -1445,7 +1077,7 @@ fn explicit_provider_references_keep_arbitrary_ids_and_shadow_only_current_selec second["targetID"] = serde_json::json!("another/opaque-target"); let generated = call( "runConfig.generate", - serde_json::json!({"root":root,"paths":[],"projectOwnership":[],"providerRuns":[ + serde_json::json!({"root":root,"providerRuns":[ {"projectPath":"app","name":"Auto A","reference":reference},{"projectPath":"app","name":"Auto B","reference":second} ]}), ); @@ -1727,7 +1359,7 @@ fn provider_run_options_reject_malformed_or_oversized_values() { } /// A build provider owns discovery; regenerating labels must retain user choices, -/// while withdrawing a target must not resurrect it from the previous detected layer. +/// while withdrawing a target must not resurrect it from the previous generated layer. #[test] fn generic_provider_runs_regenerate_without_language_facts_and_keep_stable_overrides() { let root = temporary_root("generic-provider-generation"); @@ -1752,7 +1384,7 @@ fn generic_provider_runs_regenerate_without_language_facts_and_keep_stable_overr call( "runConfig.generate", serde_json::json!({ - "root":root,"paths":[],"projectOwnership":[],"providerRuns":runs + "root":root,"providerRuns":runs }), ) }; @@ -1868,7 +1500,7 @@ fn provider_launch_inputs_preserve_document_layers_and_current_selector() { let inspect = || -> Value { serde_json::from_str(&execute_json( &serde_json::json!({"id":"inspect-launch-inputs","command":"runConfig.inspect", - "payload":{"root":root,"checkFingerprint":false}}) + "payload":{"root":root}}) .to_string(), )) .unwrap() @@ -1933,3 +1565,82 @@ fn provider_launch_inputs_require_a_typed_reference_after_domain_migration() { } assert!(!root.join(".lithe/run/local.json").exists()); } + +/// Generation materializes only the provider runs. Names that repeat across +/// roots are qualified by the root they run in, and inspection reports a layer +/// generated from another provider snapshot as stale. +#[test] +fn provider_run_generation_qualifies_repeated_names_and_reports_stale_snapshots() { + let root = temporary_root("provider-run-generation"); + for directory in ["services/api", "services/worker", "tools"] { + fs::create_dir_all(root.join(directory)).unwrap(); + } + struct Cleanup(PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + let _cleanup = Cleanup(root.clone()); + let call = |command: &str, payload: Value| -> Value { + let result: Value = serde_json::from_str(&execute_json( + &serde_json::json!({"id":"provider-runs","command":command,"payload":payload}) + .to_string(), + )) + .unwrap(); + assert_eq!(result["ok"], true, "{result}"); + result["data"].clone() + }; + let run = |root: &str, name: &str, target: &str| { + serde_json::json!({"projectPath":root,"name":name,"reference":{ + "pluginID":"dev.lithe.test.engine","buildSystemID":"engine","root":root, + "run":"serve","projectID":root,"targetID":target,"userArguments":[]}}) + }; + let runs = serde_json::json!([ + run("services/api", "serve", "api"), + run("services/worker", "serve", "worker"), + run("tools", "lint", "lint"), + ]); + + let generated = call( + "runConfig.generate", + serde_json::json!({"root":root,"providerRuns":runs}), + ); + assert_eq!(generated["entryCount"], 3); + let mut names = generated["generated"]["configurations"] + .as_array() + .unwrap() + .iter() + .map(|item| { + assert_eq!(item["provider"], "build.provider"); + item["name"].as_str().unwrap().to_string() + }) + .collect::>(); + names.sort(); + assert_eq!( + names, + ["lint", "serve (services/api)", "serve (services/worker)"] + ); + + let stale = |runs: Value| -> bool { + call( + "runConfig.inspect", + serde_json::json!({"root":root,"providerRuns":runs}), + )["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|item| item["code"] == "staleProviderModel") + }; + assert!(!stale(runs.clone())); + assert!(stale(serde_json::json!([run("tools", "lint", "lint")]))); + + // Without a provider snapshot Core has nothing to generate. + let empty = call("runConfig.generate", serde_json::json!({"root":root})); + assert_eq!(empty["entryCount"], 0); + assert!(empty["generated"]["configurations"] + .as_array() + .unwrap() + .is_empty()); + assert!(!root.join(".lithe").exists()); +} diff --git a/rust/crates/core/src/tests/support.rs b/rust/crates/core/src/tests/support.rs index b64e4d51..1cbb348c 100644 --- a/rust/crates/core/src/tests/support.rs +++ b/rust/crates/core/src/tests/support.rs @@ -18,14 +18,7 @@ pub(super) fn fixture() -> Value { /// this session. `root` must exist: the layer is keyed by its canonical path. pub(crate) fn seed_generated(root: &Path, document: impl ToString) { let document = serde_json::from_str(&document.to_string()).expect("generated fixture"); - crate::execution::generated_layer::seed(root, Some(document), None); -} - -/// Installs `requirements` as the toolchain requirements generated for `root`. -pub(crate) fn seed_requirements(root: &Path, requirements: impl ToString) { - let requirements = - serde_json::from_str(&requirements.to_string()).expect("requirements fixture"); - crate::execution::generated_layer::seed(root, None, Some(requirements)); + crate::execution::generated_layer::seed(root, document); } pub(crate) fn temporary_root(label: &str) -> PathBuf { diff --git a/rust/crates/core/tests/configure_visibility.rs b/rust/crates/core/tests/configure_visibility.rs index 62c13deb..ff178075 100644 --- a/rust/crates/core/tests/configure_visibility.rs +++ b/rust/crates/core/tests/configure_visibility.rs @@ -186,19 +186,6 @@ fn content_matches(root: &Path) -> Vec { paths } -fn run_scan_inputs(root: &Path) -> Vec { - let generated = data("runConfig.generate", json!({ "root": root })); - let mut inputs: Vec = generated["generated"]["generator"]["inputs"] - .as_object() - .expect("generation should list its inputs") - .keys() - .filter(|path| path.ends_with("Makefile")) - .cloned() - .collect(); - inputs.sort(); - inputs -} - fn build_instances(root: &Path) -> Vec { let detected = data( "build.detect", @@ -290,7 +277,6 @@ fn plugin_declared_folders_are_hidden_by_every_walk_until_cleared() { "target/debug/Report.txt", ]; assert_eq!(file_names(&root, false), everything); - assert_eq!(run_scan_inputs(&root), ["Makefile", "target/Makefile"]); assert_eq!(build_instances(&root), ["cargo:.", "cargo:target/debug"]); assert_eq!(vcs_roots(&root), ["legacy", "target/checkout"]); assert_eq!( @@ -395,7 +381,6 @@ fn plugin_declared_folders_are_hidden_by_every_walk_until_cleared() { assert!(lithe_core::is_workspace_event_relevant("src/Report.txt")); // Run discovery, build detection, VCS roots and Git repositories skip them too. - assert_eq!(run_scan_inputs(&root), ["Makefile"]); assert_eq!(build_instances(&root), ["cargo:."]); assert_eq!(vcs_roots(&root), ["legacy"]); assert_eq!(repositories(&root), [checkout(".")]); diff --git a/rust/crates/execution/Cargo.toml b/rust/crates/execution/Cargo.toml index 2463284a..aba61b7d 100644 --- a/rust/crates/execution/Cargo.toml +++ b/rust/crates/execution/Cargo.toml @@ -3,7 +3,7 @@ name = "lithe-execution" version = "0.1.0" edition = "2021" license = "Apache-2.0" -description = "Run configurations for Lithe: generation, resolution, launch environments and project run discovery" +description = "Run configurations for Lithe: generation, resolution, launch planning and environments" [features] # Lets lithe-core's tests seed the generated layer as if a host had generated it. @@ -12,16 +12,12 @@ test-support = [] [dependencies] ignore = "=0.4.33" lithe-core-rules = { path = "../core-rules" } -lithe-diagnostics = { path = "../diagnostics" } lithe-platform = { path = "../platform" } lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } lithe-toolchain = { path = "../toolchain" } lithe-workspace = { path = "../workspace" } -regex = "1.11" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } -serde_yaml_ng = "0.10.0" sha2 = "0.10" -toml = { version = "1.1.4", default-features = false, features = ["parse", "serde"] } diff --git a/rust/crates/execution/src/configuration.rs b/rust/crates/execution/src/configuration.rs index bfa83114..bd328d23 100644 --- a/rust/crates/execution/src/configuration.rs +++ b/rust/crates/execution/src/configuration.rs @@ -3,7 +3,7 @@ mod project_toolchain; pub use project_toolchain::{project_toolchain, ProjectToolchainRequest}; -use super::generated_layer::{self, GeneratedLayer}; +use super::generated_layer; use super::types::{Confidence, Execution, RunCategory}; use lithe_platform::paths::{ invalid_native_relative_path, invalid_portable_relative_path, slash_separated_path, @@ -12,7 +12,6 @@ use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::{Path, PathBuf}; @@ -20,24 +19,20 @@ use std::path::{Path, PathBuf}; mod document; mod editing; mod generation; -mod inputs; mod launch; mod layers; mod merge; mod requests; -mod requirements; mod resolve; mod validation; pub use document::*; pub use editing::*; pub use generation::*; -pub(crate) use inputs::*; pub use launch::*; pub(crate) use layers::*; pub(crate) use merge::*; pub use requests::*; -pub use requirements::*; pub use resolve::*; pub use validation::*; @@ -45,49 +40,7 @@ const VERSION: u32 = 2; const LEGACY_VERSION: u32 = 1; -// Bumped when the detected layer changes; stale cached facts must regenerate. -const GENERATOR_REVISION: &str = "20"; - -/// Toolchain requirements and `project.json` are separate documents that happen +/// Local toolchains and `project.json` are separate documents that happen /// to live under `.lithe`. Their schema did not change with run-config v2, so /// they keep their own version and must not be validated against `VERSION`. const SIDECAR_VERSION: u32 = 1; - -#[cfg(test)] -mod incomplete_scan_tests { - use super::*; - - #[test] - fn unknown_inputs_retain_only_affected_configurations_and_hashes() { - let previous: RunConfigurationDocument = serde_json::from_value(json!({ - "version": 2, - "generator": {"fingerprint": "old", "inputs": { - "blocked/package.json": "old-blocked", "removed/package.json": "old-removed" - }}, - "configurations": [ - {"id":"blocked", "name":"Blocked", "provider":"npm.script", "source":"blocked/package.json"}, - {"id":"removed", "name":"Removed", "provider":"npm.script", "source":"removed/package.json"} - ] - })).unwrap(); - let mut configurations = Vec::new(); - let mut snapshot = ProjectInputs { - inputs: BTreeMap::from([("visible/package.json".into(), "new".into())]), - unreadable_paths: BTreeSet::from(["blocked".into()]), - }; - retain_unknown_inputs(&mut configurations, &mut snapshot, previous); - assert_eq!(configurations.len(), 1); - assert_eq!(configurations[0].id, "blocked"); - assert_eq!( - snapshot - .inputs - .get("blocked/package.json") - .map(String::as_str), - Some("old-blocked") - ); - assert!(!snapshot.inputs.contains_key("removed/package.json")); - assert!(!under_unknown( - "blocked-sibling/package.json", - &snapshot.unreadable_paths - )); - } -} diff --git a/rust/crates/execution/src/configuration/document.rs b/rust/crates/execution/src/configuration/document.rs index 167aee4f..dc8a9bb5 100644 --- a/rust/crates/execution/src/configuration/document.rs +++ b/rust/crates/execution/src/configuration/document.rs @@ -1,4 +1,4 @@ -//! The stored run-configuration document, its migrations and toolchain requirements. +//! The stored run-configuration document and its migrations. use super::*; @@ -135,22 +135,12 @@ fn migrate_configuration_value(item: &mut Value) { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -/// Fingerprint and inputs used to decide whether generated output is stale. -/// -/// `inputs` maps each workspace-relative input to `sha256:` of its bytes. +/// What a generation was derived from, to decide whether its output is stale. pub struct GeneratorMetadata { - /// Combined hash over `inputs` and the generator revision. - pub fingerprint: String, - /// Identity of generic run declarations and opaque targets, separate from - /// the file inputs so a provider answer alone can mark the layer stale. + /// Identity of the provider run snapshot the generation materialized; a + /// different snapshot from the providers marks the layer stale. #[serde(default, skip_serializing_if = "Option::is_none")] pub provider_run_fingerprint: Option, - /// Unreadable inputs retained as unknown; a partial baseline cannot prove freshness. - #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] - pub unreadable_paths: BTreeSet, - /// Workspace-relative input path mapped to `sha256:` of its bytes. - #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] - pub inputs: BTreeMap, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -169,7 +159,7 @@ pub struct RunConfiguration { pub id: String, /// Display name shown in the Run list. pub name: String, - /// Open namespaced discriminator, e.g. `npm.script`, `cargo.run`. + /// Open namespaced discriminator, e.g. `build.provider`. /// Deliberately not an enum: new ecosystems must not require a contract change. pub provider: String, /// How the entry behaves once started. @@ -194,8 +184,8 @@ pub struct RunConfiguration { /// How the entry was discovered; higher confidence wins deduplication. #[serde(default)] pub confidence: Confidence, - /// Toolchain role mapped to the requirement identity it consumes, such as - /// `runtime` to `project-node`. + /// Toolchain role mapped to the local toolchain identity it consumes. A + /// `runtime` binding names the executable when `command` is absent. #[serde(default)] pub toolchains: BTreeMap, /// Debug adapter that can launch this entry, when one is declared. @@ -204,7 +194,7 @@ pub struct RunConfiguration { /// Configuration identities started together when `execution` is `group`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub members: Vec, - /// Ecosystem-specific payload keyed by namespace (`npm`, `build`, ...). + /// Provider-specific payload keyed by namespace, such as `build`. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub extensions: BTreeMap, /// Hidden from the resolved list; set by a user or when the working directory is missing. @@ -218,32 +208,3 @@ pub struct RunConfiguration { fn dot() -> String { ".".to_string() } - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Versioned requirements written separately from run configurations. -pub struct ToolchainRequirementsDocument { - /// Document version the reader must accept before trusting any requirement. - pub version: u32, - /// Requirement per toolchain kind, keyed by the kind the caller asks about. - #[serde(default)] - pub toolchains: BTreeMap, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Constraints the host uses when selecting one toolchain candidate. -pub struct ToolchainRequirement { - /// Toolchain role matched against [`ToolchainCandidate::kind`]. - #[serde(rename = "type")] - pub kind: String, - /// Lowest acceptable version; newer releases also satisfy it. - #[serde(default)] - pub minimum_version: Option, - /// Vendor preferred when several candidates satisfy the version. - #[serde(default)] - pub preferred_vendor: Option, - /// Exact version prefix; [`Self::minimum_version`] accepts newer releases. - #[serde(default)] - pub version: Option, -} diff --git a/rust/crates/execution/src/configuration/editing.rs b/rust/crates/execution/src/configuration/editing.rs index 09155b9f..722f9370 100644 --- a/rust/crates/execution/src/configuration/editing.rs +++ b/rust/crates/execution/src/configuration/editing.rs @@ -139,7 +139,6 @@ fn update_configuration_options( let resolved = resolve(ResolveRequest { team_document: None, root: request.root.clone(), - toolchain_candidates: Vec::new(), local_document: request.local_document.clone(), })?; let provider = resolved["configurations"] @@ -263,7 +262,7 @@ fn create_build_provider_configuration( validate_version_value(&document)?; let mut ids: std::collections::BTreeSet = configuration_ids(&document)?.into_keys().collect(); - ids.extend(detected_ids(root)); + ids.extend(generated_ids(root)); if let Some(other) = read_document_value(root, "run/configurations.json")? { validate_version_value(&other)?; ids.extend(configuration_ids(&other)?.into_keys()); diff --git a/rust/crates/execution/src/configuration/generation.rs b/rust/crates/execution/src/configuration/generation.rs index 238ce1c8..a5a15b43 100644 --- a/rust/crates/execution/src/configuration/generation.rs +++ b/rust/crates/execution/src/configuration/generation.rs @@ -1,4 +1,4 @@ -//! Inspecting a project and generating its detected configurations. +//! Inspecting a project and generating its provider run configurations. use super::*; @@ -6,8 +6,7 @@ use super::*; pub fn inspect(request: InspectRequest) -> Result { let root = existing_root(&request.root)?; let layer = generated_layer::get(&root); - let generated = layer.as_ref().map(|layer| &layer.document); - let requirements = layer.as_ref().map(|layer| &layer.requirements); + let generated = layer.as_deref(); let local_toolchains = read_local_toolchains(&root)?; for relative in [ "run/configurations.json", @@ -44,48 +43,10 @@ pub fn inspect(request: InspectRequest) -> Result { } } } - let mut diagnostics = Vec::new(); - if request.check_fingerprint == Some(false) { - if let Some(metadata) = generated.and_then(|document| document.generator.as_ref()) { - if !metadata.unreadable_paths.is_empty() { - diagnostics.push(incomplete_scan_diagnostic(&metadata.unreadable_paths)); - } - } - } let local = local_layer_document(&root, request.local_document.clone())?; let team = read_document_value(&root, "run/configurations.json")? .unwrap_or_else(|| json!({"version": VERSION, "configurations": []})); - if let Some(metadata) = generated - .and_then(|document| document.generator.as_ref()) - .filter(|_| request.check_fingerprint != Some(false)) - { - let current_inputs = project_inputs(&root)?; - if !current_inputs.unreadable_paths.is_empty() || !metadata.unreadable_paths.is_empty() { - let unknown = current_inputs - .unreadable_paths - .union(&metadata.unreadable_paths) - .cloned() - .collect(); - diagnostics.push(incomplete_scan_diagnostic(&unknown)); - } else if metadata.fingerprint != fingerprint_from_inputs(¤t_inputs.inputs) { - // Stored inputs that no longer reproduce the stored fingerprint were - // recorded by another generator revision, whose input rules (such - // as which manifests are hashed) may differ from today's. - let generator_changed = - fingerprint_from_inputs(&metadata.inputs) != metadata.fingerprint; - let message = if metadata.inputs.is_empty() { - "Project inputs changed after run configuration generation".to_string() - } else if generator_changed || metadata.inputs == current_inputs.inputs { - "Run configuration generator changed; regenerate configurations".to_string() - } else { - input_change_summary(&metadata.inputs, ¤t_inputs.inputs) - }; - diagnostics.push(json!({ - "code": "staleFingerprint", - "message": message - })); - } - } + let mut diagnostics = Vec::new(); if let Some(runs) = &request.provider_runs { crate::provider_runs::validate(runs)?; if let Some(document) = generated { @@ -102,11 +63,10 @@ pub fn inspect(request: InspectRequest) -> Result { } Ok(json!({ "status": if generated.is_some() || has_saved_build_run(&local) || has_saved_build_run(&team) { "ready" } else { "missing" }, - // Saved provider tasks remain runnable before detection, but must not - // suppress discovery of the other entries after a process restart. + // Saved provider tasks remain runnable before generation, but must not + // suppress generation of the other entries after a process restart. "requiresGeneration": generated.is_none(), "generated": generated, - "toolchainRequirements": requirements, "localToolchains": local_toolchains, "toolchain": local.get("toolchain"), "diagnostics": diagnostics, @@ -114,115 +74,40 @@ pub fn inspect(request: InspectRequest) -> Result { })) } -/// Detects runnable project entries and replaces the workspace's detected layer. +/// Materializes the provider run snapshot and replaces the workspace's +/// generated layer. /// -/// The layer is held in memory (and in the host's cache directory when given), -/// never written into the workspace. +/// Core discovers nothing itself: every generated entry is a run a build +/// provider plugin declared. The layer is held in memory, never written into +/// the workspace. pub fn generate(request: GenerateRequest) -> Result { let root = existing_root(&request.root)?; - let cache_directory = request.cache_directory.map(PathBuf::from); - let previous = previous_generation(&root, cache_directory.as_deref()); - let mut configurations = detected_configurations(&root)?; - if let Some(runs) = &request.provider_runs { - crate::provider_runs::validate(runs)?; - let claimed = configurations - .iter() - .map(|item| item.id.clone()) - .collect::>(); - configurations.extend( - crate::provider_runs::configurations(runs) - .into_iter() - .filter(|item| !claimed.contains(&item.id)), - ); - } - let mut snapshot = project_inputs(&root)?; - // Unknown subtrees cannot delete known configurations or baseline inputs. - // Invalid required documents still fail instead of being silently overwritten. - let authoritative_service_ids = request.provider_runs.as_ref().map(|_| { - configurations - .iter() - .filter(|item| item.provider == "build.provider") - .map(|item| item.id.clone()) - .collect::>() - }); - - if !snapshot.unreadable_paths.is_empty() { - if let Some(previous) = previous { - retain_unknown_inputs(&mut configurations, &mut snapshot, previous); - } - } - if let Some(ids) = authoritative_service_ids { - configurations.retain(|item| item.provider != "build.provider" || ids.contains(&item.id)); - } + let runs = request.provider_runs.unwrap_or_default(); + crate::provider_runs::validate(&runs)?; + let mut configurations = crate::provider_runs::configurations(&runs); disambiguate_configuration_names(&mut configurations); let entry_count = configurations.len(); - let requirements = detect_requirements(&root, &configurations)?; let generated = RunConfigurationDocument { version: VERSION, generator: Some(GeneratorMetadata { - provider_run_fingerprint: request - .provider_runs - .as_deref() - .map(crate::provider_runs::fingerprint), - fingerprint: fingerprint_from_inputs(&snapshot.inputs), - inputs: snapshot.inputs, - unreadable_paths: snapshot.unreadable_paths, + provider_run_fingerprint: Some(crate::provider_runs::fingerprint(&runs)), }), configurations, }; let response = json!({ "generated": generated, - "toolchainRequirements": requirements, "entryCount": entry_count }); - if let Some(cache_directory) = cache_directory.as_deref() { - generated_layer::cache_document(cache_directory, &root, &generated); - } - generated_layer::store( - &root, - GeneratedLayer { - document: generated, - requirements, - }, - ); + generated_layer::store(&root, generated); Ok(response) } -/// The detected layer the previous generation produced: this session's, else -/// the one cached by an earlier session, else the `.lithe/run/generated.json` -/// older Lithe versions wrote into the workspace (read, never written). -/// -/// Generation uses it only to keep entries under a subtree it cannot read: -/// replaying them keeps ids and user overrides attached until the subtree is -/// readable again. An unreadable or invalid previous document contributes -/// nothing, because this generation replaces it. -fn previous_generation( - root: &Path, - cache_directory: Option<&Path>, -) -> Option { - if let Some(layer) = generated_layer::get(root) { - return Some(layer.document.clone()); - } - let mut document = cache_directory - .and_then(|directory| generated_layer::cached_document(directory, root)) - .or_else(|| { - read_document_value(root, "run/generated.json") - .ok() - .flatten() - })?; - migrate_document_value(&mut document); - serde_json::from_value::(document) - .ok() - .filter(|document| validate_version(document.version).is_ok()) -} - -/// Qualifies display names that repeat across directories or modules. +/// Qualifies display names that repeat across provider roots. /// -/// Ids already carry the directory, but the Run list shows only the name: three -/// Compose files each contributing `compose up` are otherwise -/// indistinguishable. The qualifier is the first -/// candidate that separates every entry in the group, so the shortest useful -/// label wins and unique names are never decorated. +/// Ids already carry the selector, but the Run list shows only the name: three +/// modules that each declare a `serve` entry are otherwise indistinguishable. +/// A repeated name gains its working directory when that separates every entry +/// in the group, so unique names are never decorated. fn disambiguate_configuration_names(configurations: &mut [RunConfiguration]) { let mut groups: BTreeMap> = BTreeMap::new(); for (index, configuration) in configurations.iter().enumerate() { @@ -232,54 +117,18 @@ fn disambiguate_configuration_names(configurations: &mut [RunConfiguration]) { .push(index); } for indexes in groups.into_values().filter(|indexes| indexes.len() > 1) { - let candidates: [fn(&RunConfiguration) -> Option; 2] = [ - |configuration| Some(configuration.cwd.clone()).filter(|cwd| cwd != "."), - |configuration| configuration.source.clone(), - ]; - let Some(qualifier) = candidates.into_iter().find(|candidate| { - let values = indexes - .iter() - .map(|index| candidate(&configurations[*index])) - .collect::>>(); - values.is_some_and(|values| values.len() == indexes.len()) - }) else { + let directories = indexes + .iter() + .map(|index| configurations[*index].cwd.as_str()) + .filter(|cwd| *cwd != ".") + .collect::>() + .len(); + if directories != indexes.len() { continue; - }; + } for index in indexes { - if let Some(value) = qualifier(&configurations[index]) { - configurations[index].name = format!("{} ({value})", configurations[index].name); - } + let configuration = &mut configurations[index]; + configuration.name = format!("{} ({})", configuration.name, configuration.cwd); } } } - -/// Translates detector output into the run-configuration contract. -/// -/// Nearly every detection is process-based: the detector resolved the command, -/// so there is no ecosystem-specific launch assembly. A process may still name -/// a runtime requirement for scoped compatibility diagnostics; a detection that -/// transfers executable ownership to toolchains carries no command. -fn detected_configurations(root: &Path) -> Result, CoreError> { - Ok(crate::detectors::detect_all(root)? - .into_iter() - .map(|item| RunConfiguration { - id: item.id(), - name: item.name, - provider: item.provider, - execution: item.execution, - category: item.category, - command: item.command, - args: item.args, - cwd: item.cwd, - env: item.env, - confidence: item.confidence, - toolchains: item.toolchains, - debug: None, - members: Vec::new(), - extensions: item.extensions, - disabled: false, - source: Some(item.source), - }) - .filter(|item| validate_configuration(item).is_ok()) - .collect()) -} diff --git a/rust/crates/execution/src/configuration/inputs.rs b/rust/crates/execution/src/configuration/inputs.rs deleted file mode 100644 index d9e43abe..00000000 --- a/rust/crates/execution/src/configuration/inputs.rs +++ /dev/null @@ -1,208 +0,0 @@ -//! Project inputs that fingerprint generated configurations. - -use super::*; - -/// Collects generation inputs; every input is hashed by content. -pub(crate) struct ProjectInputs { - pub(crate) inputs: BTreeMap, - pub(crate) unreadable_paths: BTreeSet, -} - -// Retention is independent of filesystem permissions so both hosts preserve the -// same last-known configuration when an optional subtree becomes unreadable. -pub(crate) fn retain_unknown_inputs( - configurations: &mut Vec, - snapshot: &mut ProjectInputs, - previous: RunConfigurationDocument, -) { - for configuration in previous.configurations { - let source = configuration.source.as_deref(); - if source.is_some_and(|path| under_unknown(path, &snapshot.unreadable_paths)) - && !configurations - .iter() - .any(|current| current.id == configuration.id) - { - configurations.push(configuration); - } - } - if let Some(metadata) = previous.generator { - for (path, hash) in metadata.inputs { - if under_unknown(&path, &snapshot.unreadable_paths) { - snapshot.inputs.entry(path).or_insert(hash); - } - } - } -} - -pub(crate) fn under_unknown(path: &str, unknown: &BTreeSet) -> bool { - unknown - .iter() - .any(|prefix| path == prefix || path.starts_with(&format!("{prefix}/"))) -} - -pub(crate) fn incomplete_scan_diagnostic(paths: &BTreeSet) -> Value { - json!({"code": "incompleteProjectScan", "message": format!( - "Project scan is incomplete; freshness and removals could not be verified. Unreadable inputs: {}", - paths.iter().cloned().collect::>().join(", "))}) -} - -pub(crate) fn project_inputs(root: &Path) -> Result { - let scan = crate::workspace_scan::scan_run_workspace(root, None)?; - let mut result = ProjectInputs { - inputs: BTreeMap::new(), - unreadable_paths: scan.unreadable_paths, - }; - for directory in scan.directories { - for name in directory.files { - let path = directory.path.join(name); - if !fingerprint_input(&path) { - continue; - } - let relative = slash_separated_path( - path.strip_prefix(root).expect("scan stays within root"), - Platform::HOST, - ); - lithe_protocol::cancellation::check()?; - // The scan lists files through the workspace adapter, so content reads - // must use the same adapter or remote projects look permanently unreadable. - match lithe_workspace::fs::read(&path) { - Ok(bytes) => { - result - .inputs - .insert(relative, format!("sha256:{:x}", Sha256::digest(bytes))); - } - Err(_) => { - result.unreadable_paths.insert(relative); - } - } - } - } - Ok(result) -} - -pub(crate) fn fingerprint_from_inputs(inputs: &BTreeMap) -> String { - let mut digest = Sha256::new(); - // Detection changes invalidate persisted output even when project files are - // unchanged, so an application upgrade cannot keep launching a stale plan. - digest.update(GENERATOR_REVISION.as_bytes()); - digest.update([0]); - for (relative, content_hash) in inputs { - digest.update(relative.as_bytes()); - digest.update([0]); - digest.update(content_hash.as_bytes()); - digest.update([0]); - } - format!("sha256:{:x}", digest.finalize()) -} - -pub(crate) fn input_change_summary( - previous: &BTreeMap, - current: &BTreeMap, -) -> String { - let added = current - .keys() - .filter(|path| !previous.contains_key(*path)) - .count(); - let removed = previous - .keys() - .filter(|path| !current.contains_key(*path)) - .count(); - let changed = current - .iter() - .filter(|(path, hash)| previous.get(*path).is_some_and(|old| old != *hash)) - .count(); - format!("Project inputs changed: {added} added, {removed} removed, {changed} modified") -} - -fn fingerprint_input(path: &Path) -> bool { - matches!( - path.file_name().and_then(|name| name.to_str()), - Some( - "mise.toml" - | "package.json" - | "package-lock.json" - | "pnpm-lock.yaml" - | "yarn.lock" - | "bun.lock" - | "bun.lockb" - | "docker-compose.yml" - | "docker-compose.yaml" - | "compose.yml" - | "compose.yaml" - | "pyproject.toml" - | "manage.py" - | "Cargo.toml" - | "rust-toolchain" - | "rust-toolchain.toml" - | "go.mod" - | "Procfile" - | "Procfile.dev" - | "Procfile.local" - | "Makefile" - | "makefile" - | "GNUmakefile" - | "justfile" - | "Justfile" - | ".justfile" - ) - ) -} - -pub(crate) fn declared_node_version(root: &Path) -> Option { - highest_version( - project_manifest_paths(root, &["package.json"]) - .into_iter() - .filter_map(|path| lithe_workspace::fs::read_to_string(path).ok()) - .filter_map(|text| serde_json::from_str::(&text).ok()) - .filter_map(|document| { - document - .get("engines")? - .get("node")? - .as_str() - .and_then(first_numeric_version) - }) - .collect(), - ) -} - -fn first_numeric_version(value: &str) -> Option { - regex::Regex::new(r"[0-9]+(?:\.[0-9]+)+") - .ok()? - .find(value) - .map(|value| value.as_str().to_string()) -} - -fn highest_version(versions: Vec) -> Option { - versions - .into_iter() - .max_by(|left, right| version_parts(left).cmp(&version_parts(right))) -} - -fn project_manifest_paths(root: &Path, names: &[&str]) -> Vec { - // This heuristic only supplements declared toolchain requirements. Fingerprint - // scanning separately reports unknown subtrees to both product hosts. - let Ok(scan) = crate::workspace_scan::scan_run_workspace(root, None) else { - return Vec::new(); - }; - scan.directories - .into_iter() - .flat_map(|directory| { - directory - .files - .into_iter() - .filter(|name| names.contains(&name.as_str())) - .map(move |name| directory.path.join(name)) - }) - .collect() -} - -pub(crate) fn existing_root(value: &str) -> Result { - let path = PathBuf::from(value); - if !path.is_dir() { - return Err(CoreError::new( - ErrorCode::WorkspaceNotFound, - "Project root does not exist", - )); - } - Ok(path) -} diff --git a/rust/crates/execution/src/configuration/launch.rs b/rust/crates/execution/src/configuration/launch.rs index 6e4aefa4..5cd9e9bb 100644 --- a/rust/crates/execution/src/configuration/launch.rs +++ b/rust/crates/execution/src/configuration/launch.rs @@ -26,7 +26,6 @@ pub fn provider_launch_inputs(request: ProviderLaunchInputsRequest) -> Result Result Result { @@ -101,7 +100,6 @@ pub fn create_launch_plan(request: LaunchPlanRequest) -> Result Result BTreeSet { +pub(crate) fn generated_ids(root: &Path) -> BTreeSet { generated_layer::get(root) - .map(|layer| { - layer - .document + .map(|document| { + document .configurations .iter() .map(|configuration| configuration.id.clone()) @@ -145,3 +144,32 @@ pub(crate) fn detected_ids(root: &Path) -> BTreeSet { }) .unwrap_or_default() } + +pub(crate) fn existing_root(value: &str) -> Result { + let path = PathBuf::from(value); + if !path.is_dir() { + return Err(CoreError::new( + ErrorCode::WorkspaceNotFound, + "Project root does not exist", + )); + } + Ok(path) +} + +pub(crate) fn read_local_toolchains(root: &Path) -> Result, CoreError> { + let Some(document) = read_document_value(root, "toolchains/local.json")? else { + return Ok(None); + }; + validate_sidecar_version_value(&document)?; + if document + .get("toolchains") + .and_then(Value::as_object) + .is_none() + { + return Err(CoreError::new( + ErrorCode::ParseFailed, + "Local toolchains must contain a toolchains object", + )); + } + Ok(Some(document)) +} diff --git a/rust/crates/execution/src/configuration/merge.rs b/rust/crates/execution/src/configuration/merge.rs index e16c0b93..ae298be0 100644 --- a/rust/crates/execution/src/configuration/merge.rs +++ b/rust/crates/execution/src/configuration/merge.rs @@ -1,4 +1,4 @@ -//! Merging the shared, local and detected layers of a configuration. +//! Merging the shared, local and generated layers of a configuration. use super::*; @@ -139,35 +139,10 @@ fn merge_configuration_value(existing: &mut Value, item: &Value) -> Result<(), C Ok(()) } -/// Reconciles runtime bindings from the effective command for generated v2 -/// documents written before detectors declared their consumption explicitly. -pub(crate) fn normalize_runtime_consumption(configurations: &mut [RunConfiguration]) { - for configuration in configurations { - let command = configuration - .command - .as_deref() - .unwrap_or("") - .to_ascii_lowercase(); - if matches!( - command.as_str(), - "npm" | "npm.cmd" | "pnpm" | "pnpm.cmd" | "yarn" | "yarn.cmd" - ) { - configuration - .toolchains - .entry("runtime".to_string()) - .or_insert_with(|| "project-node".to_string()); - } else if matches!(command.as_str(), "bun" | "bun.exe") - && configuration.toolchains.get("runtime").map(String::as_str) == Some("project-node") - { - configuration.toolchains.remove("runtime"); - } - } -} - /// Deep-merges the `extensions` object one namespace at a time. /// -/// A shallow insert would let a layer that touches a single `build-run` key -/// drop the whole `npm` namespace it never mentioned. +/// A shallow insert would let a layer that touches one namespace drop the +/// other namespaces it never mentioned. pub(crate) fn merge_extensions( target: &mut serde_json::Map, patch: &mut Value, diff --git a/rust/crates/execution/src/configuration/project_toolchain.rs b/rust/crates/execution/src/configuration/project_toolchain.rs index e221e6d5..ea4bd253 100644 --- a/rust/crates/execution/src/configuration/project_toolchain.rs +++ b/rust/crates/execution/src/configuration/project_toolchain.rs @@ -86,7 +86,6 @@ pub fn project_toolchain(request: ProjectToolchainRequest) -> Result, /// Host-owned local layer. When present, Core validates it instead of `.lithe/run/local.json`. #[serde(default)] pub local_document: Option, - /// Complete generic run selectors; omission preserves older callers. + /// Current provider run snapshot. When present, a generated layer from a + /// different snapshot is reported as stale. #[serde(default)] pub provider_runs: Option>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] -/// Request to regenerate detected configurations from the current project tree. +/// Request to regenerate the generated layer from the current provider runs. pub struct GenerateRequest { - /// Canonical workspace root scanned for run entries. + /// Canonical workspace root the generated layer belongs to. pub root: String, - /// Complete generic run selectors; omission preserves older callers. + /// Complete provider run snapshot; omitted generates an empty layer. #[serde(default)] pub provider_runs: Option>, - /// Application cache directory, outside the workspace. Generation records - /// its result there so the next session can list provider entries before - /// the providers answer again; omitted, only this process remembers it. - #[serde(default)] - pub cache_directory: Option, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] -/// Request to merge configuration layers and resolve host toolchains. +/// Request to merge the generated, team and local configuration layers. pub struct ResolveRequest { /// Canonical workspace root whose layers are merged. pub root: String, - /// Executables the host discovered; requirements pick among these by role. - #[serde(default)] - pub toolchain_candidates: Vec, /// Host-owned local layer. When present, Core uses it instead of `.lithe/run/local.json`. #[serde(default)] pub local_document: Option, @@ -52,23 +42,6 @@ pub struct ResolveRequest { pub team_document: Option, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Host-discovered executable that may satisfy a configuration requirement. -pub struct ToolchainCandidate { - /// Host-stable candidate identifier referenced by resolved configurations. - pub id: String, - /// Toolchain role such as `node`, not a display label. - #[serde(rename = "type")] - pub kind: String, - /// Reported version, empty when the host could not read one. - #[serde(default)] - pub version: String, - /// Distribution vendor, empty when unknown. - #[serde(default)] - pub vendor: String, -} - #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] /// Request to turn one resolved configuration into a process launch plan. @@ -101,7 +74,7 @@ pub struct ProviderLaunchInputsRequest { #[serde(rename_all = "camelCase")] /// Global machine toolchain stored at document level in the local layer. pub struct ToolchainPaths { - /// Explicit executables for generic runtime toolchain IDs such as `project-node`. + /// Explicit executables keyed by the local toolchain ID a `runtime` binding names. #[serde(default)] pub runtime_executable_paths: BTreeMap, /// Generic consumer preferences in the same machine-local document. diff --git a/rust/crates/execution/src/configuration/requirements.rs b/rust/crates/execution/src/configuration/requirements.rs deleted file mode 100644 index 09605a6c..00000000 --- a/rust/crates/execution/src/configuration/requirements.rs +++ /dev/null @@ -1,196 +0,0 @@ -//! Toolchain requirements of a project and their diagnostics. - -use super::*; - -/// Toolchain requirements of `root`: those of this session's latest -/// generation, else those derived from the project's own declarations, so a -/// runtime can be checked before the Run list has been generated. -pub fn read_requirements(root: &Path) -> Result, CoreError> { - if let Some(layer) = generated_layer::get(root) { - return Ok(Some(layer.requirements.clone())); - } - if !root.is_dir() { - return Ok(None); - } - detect_requirements(root, &[]).map(Some) -} - -pub(crate) fn read_local_toolchains(root: &Path) -> Result, CoreError> { - let Some(document) = read_document_value(root, "toolchains/local.json")? else { - return Ok(None); - }; - validate_sidecar_version_value(&document)?; - if document - .get("toolchains") - .and_then(Value::as_object) - .is_none() - { - return Err(CoreError::new( - ErrorCode::ParseFailed, - "Local toolchains must contain a toolchains object", - )); - } - Ok(Some(document)) -} - -/// Only roles a Run actually consumes become requirements; Core reads the -/// generic declarations it understands and leaves tool-specific version files to -/// the plugin that owns the toolchain. -pub(crate) fn detect_requirements( - root: &Path, - configurations: &[RunConfiguration], -) -> Result { - let mut toolchains = BTreeMap::new(); - let consumes = |toolchain: &str| { - configurations.iter().any(|configuration| { - configuration - .toolchains - .values() - .any(|candidate| candidate == toolchain) - }) - }; - if consumes("project-node") { - toolchains.insert( - "project-node".to_string(), - generic_requirement("node", declared_node_version(root)), - ); - } - Ok(ToolchainRequirementsDocument { - version: SIDECAR_VERSION, - toolchains, - }) -} - -fn generic_requirement(kind: &str, minimum_version: Option) -> ToolchainRequirement { - ToolchainRequirement { - kind: kind.to_string(), - minimum_version, - preferred_vendor: None, - version: None, - } -} - -pub(crate) fn toolchain_diagnostics( - root: &Path, - candidates: &[ToolchainCandidate], - configurations: &[RunConfiguration], -) -> Result, CoreError> { - let Some(requirements) = read_requirements(root)? else { - return Ok(Vec::new()); - }; - validate_sidecar_version(requirements.version)?; - let mut diagnostics = Vec::new(); - for (id, requirement) in requirements.toolchains { - let mut consumer_ids = configurations - .iter() - .filter(|configuration| { - configuration - .toolchains - .values() - .any(|toolchain| toolchain == &id) - }) - .map(|configuration| configuration.id.clone()) - .collect::>(); - consumer_ids.sort(); - consumer_ids.dedup(); - let Some(candidate) = candidates - .iter() - .find(|candidate| candidate.id == id && candidate.kind == requirement.kind) - else { - append_toolchain_diagnostics( - &mut diagnostics, - &consumer_ids, - json!({ - "code": "missingToolchain", - "toolchain": id, - "message": format!("No local {} toolchain is selected", requirement.kind) - }), - ); - continue; - }; - let required_version = requirement - .minimum_version - .as_deref() - .or(requirement.version.as_deref()); - if let Some(required) = required_version { - // `version` is an exact prefix match; only `minimumVersion` accepts - // newer releases. - let treat_as_minimum = requirement.minimum_version.is_some(); - if !version_satisfies(&candidate.version, required, treat_as_minimum) { - append_toolchain_diagnostics( - &mut diagnostics, - &consumer_ids, - json!({ - "code": "toolchainVersionMismatch", - "toolchain": id, - "message": format!( - "{} {} does not satisfy required version {}", - requirement.kind, candidate.version, required - ) - }), - ); - } - } - if let Some(vendor) = requirement.preferred_vendor.as_deref() { - if !candidate - .vendor - .to_lowercase() - .contains(&vendor.to_lowercase()) - { - append_toolchain_diagnostics( - &mut diagnostics, - &consumer_ids, - json!({ - "code": "toolchainVendorMismatch", - "toolchain": id, - "message": format!("Preferred {} vendor is {vendor}", requirement.kind) - }), - ); - } - } - } - Ok(diagnostics) -} - -fn append_toolchain_diagnostics( - diagnostics: &mut Vec, - consumer_ids: &[String], - diagnostic: Value, -) { - if consumer_ids.is_empty() { - return; - } - for configuration_id in consumer_ids { - let mut scoped = diagnostic.clone(); - scoped["id"] = json!(configuration_id); - diagnostics.push(scoped); - } -} - -/// Compares numeric version components. A minimum accepts any later version; -/// otherwise `required` must be a component prefix of `actual` (`20` matches -/// `20.11.1`). Tool-specific version schemes are normalized by their owner first. -pub fn version_satisfies(actual: &str, required: &str, minimum: bool) -> bool { - let actual_parts = version_parts(actual); - let required_parts = version_parts(required); - if actual_parts.is_empty() || required_parts.is_empty() { - return false; - } - if minimum { - actual_parts >= required_parts - } else { - actual_parts.starts_with(&required_parts) - } -} - -/// Splits a version into its numeric parts, ignoring separators and suffixes. -/// -/// An input with no digits yields an empty list, which callers treat as "not a -/// version" rather than as zero. -pub fn version_parts(value: &str) -> Vec { - value - .split(|character: char| !character.is_ascii_digit()) - .filter(|part| !part.is_empty()) - .filter_map(|part| part.parse().ok()) - .collect() -} diff --git a/rust/crates/execution/src/configuration/resolve.rs b/rust/crates/execution/src/configuration/resolve.rs index 3c0bd343..a860b14e 100644 --- a/rust/crates/execution/src/configuration/resolve.rs +++ b/rust/crates/execution/src/configuration/resolve.rs @@ -2,7 +2,7 @@ use super::*; -/// Merges generated, team, and local layers and selects compatible toolchains. +/// Merges generated, team, and local layers into the configurations a launch can use. pub fn resolve(request: ResolveRequest) -> Result { let root = existing_root(&request.root)?; let team = match request.team_document { @@ -15,8 +15,8 @@ pub fn resolve(request: ResolveRequest) -> Result { }; let local = local_layer_document(&root, request.local_document)?; let layer = generated_layer::get(&root); - let generated = match layer.as_ref() { - Some(layer) => serde_json::to_value(&layer.document).expect("run configurations encode"), + let generated = match layer.as_deref() { + Some(document) => serde_json::to_value(document).expect("run configurations encode"), None if has_saved_build_run(&local) || has_saved_build_run(&team) => { json!({"version": VERSION, "configurations": []}) } @@ -53,13 +53,7 @@ pub fn resolve(request: ResolveRequest) -> Result { } } } - normalize_runtime_consumption(&mut configurations); let global_toolchain = local.get("toolchain").cloned(); - diagnostics.extend(toolchain_diagnostics( - &root, - &request.toolchain_candidates, - &configurations, - )?); for configuration in &mut configurations { validate_configuration(configuration)?; if configuration.provider == "build.provider" { @@ -116,8 +110,8 @@ pub fn resolve(request: ResolveRequest) -> Result { } if default_run_configuration.is_none() { default_run_configuration = layer - .as_ref() - .and_then(|layer| detected_default(&layer.document, &configurations)); + .as_deref() + .and_then(|document| generated_default(document, &configurations)); } Ok(json!({ "version": VERSION, @@ -129,9 +123,9 @@ pub fn resolve(request: ResolveRequest) -> Result { })) } -/// Prefer a detected service when the project names no default, otherwise -/// select the first available entry. -fn detected_default( +/// Prefer a generated service when the project names no default, otherwise +/// select the first available generated entry. +fn generated_default( generated: &RunConfigurationDocument, available: &[RunConfiguration], ) -> Option { @@ -147,7 +141,7 @@ fn detected_default( by_selector.entry(selector).or_insert(configuration); } } - let detected = generated.configurations.iter().filter_map(|configuration| { + let candidates = generated.configurations.iter().filter_map(|configuration| { by_id.get(configuration.id.as_str()).copied().or_else(|| { let selector = crate::provider_runs::selector( &serde_json::to_value(configuration).expect("configuration encodes"), @@ -155,9 +149,9 @@ fn detected_default( by_selector.get(&selector).copied() }) }); - detected + candidates .clone() .find(|configuration| configuration.execution == Execution::Service) - .or_else(|| detected.clone().next()) + .or_else(|| candidates.clone().next()) .map(|configuration| configuration.id.clone()) } diff --git a/rust/crates/execution/src/detectors/cargo.rs b/rust/crates/execution/src/detectors/cargo.rs deleted file mode 100644 index d0350ac9..00000000 --- a/rust/crates/execution/src/detectors/cargo.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! Cargo binary discovery from manifests and conventional source layouts. - -use super::{Detected, DirectoryContext}; - -/// Cargo binaries come from `[[bin]]` entries, or implicitly from `src/main.rs`. -/// Workspace roots with no package of their own contribute nothing -- their -/// members are separate directories and detect independently. -pub fn detect(ctx: &DirectoryContext) -> Vec { - let Some(text) = ctx.read("Cargo.toml") else { - return Vec::new(); - }; - let Ok(document) = text.parse::() else { - return Vec::new(); - }; - let Some(package) = document.get("package") else { - return Vec::new(); - }; - let declared = document - .get("bin") - .and_then(|value| value.as_array()) - .map(|entries| { - entries - .iter() - .filter_map(|entry| entry.get("name")?.as_str()) - .map(str::to_string) - .collect::>() - }) - .unwrap_or_default(); - let names = if declared.is_empty() { - package - .get("name") - .and_then(|value| value.as_str()) - .filter(|_| has_main(ctx)) - .map(|name| vec![name.to_string()]) - .unwrap_or_default() - } else { - declared - }; - names - .into_iter() - .map(|name| { - Detected::application( - "cargo.binary", - &name, - "cargo", - vec!["run", "--bin", &name], - ctx, - "Cargo.toml", - ) - .with_extension("cargo", serde_json::json!({ "bin": name })) - }) - .collect() -} - -/// `src/main.rs` is what makes a package a binary rather than a library. It sits -/// one directory below the manifest, which the scan records separately, so this -/// is the one place a detector touches the filesystem directly. -fn has_main(ctx: &DirectoryContext) -> bool { - ctx.path.join("src").join("main.rs").is_file() -} diff --git a/rust/crates/execution/src/detectors/compose.rs b/rust/crates/execution/src/detectors/compose.rs deleted file mode 100644 index 4df9c0a8..00000000 --- a/rust/crates/execution/src/detectors/compose.rs +++ /dev/null @@ -1,71 +0,0 @@ -//! Docker Compose service discovery from the standard manifest names. -//! -//! Compose files in an application repository normally declare the databases, -//! caches, and brokers the project runs against, so these detections are -//! reported as infrastructure and hosts present them apart from the project's -//! own services. - -use super::{Detected, DirectoryContext}; - -const FILES: &[&str] = &[ - "docker-compose.yml", - "docker-compose.yaml", - "compose.yml", - "compose.yaml", -]; - -/// Returns one service configuration for each declared Compose service. -pub fn detect(ctx: &DirectoryContext) -> Vec { - let Some(file) = ctx.any_of(FILES) else { - return Vec::new(); - }; - let Some(text) = ctx.read(file) else { - return Vec::new(); - }; - let Ok(document) = serde_yaml_ng::from_str::(&text) else { - return Vec::new(); - }; - let Some(services) = document - .get("services") - .and_then(|value| value.as_mapping()) - else { - return Vec::new(); - }; - let mut detected = services - .keys() - .filter_map(|key| key.as_str()) - .map(|name| { - Detected::service( - "compose.service", - name, - "docker", - vec!["compose", "-f", file, "up", name], - ctx, - file, - ) - .with_extension( - "compose", - serde_json::json!({ "file": file, "service": name }), - ) - .into_infrastructure() - }) - .collect::>(); - // The whole stack is usually what the user wants first, so offer it as a - // single entry alongside the individual services rather than making them - // start each one by hand. - if !detected.is_empty() { - detected.push( - Detected::service( - "compose.stack", - "compose up", - "docker", - vec!["compose", "-f", file, "up"], - ctx, - file, - ) - .with_extension("compose", serde_json::json!({ "file": file })) - .into_infrastructure(), - ); - } - detected -} diff --git a/rust/crates/execution/src/detectors/go.rs b/rust/crates/execution/src/detectors/go.rs deleted file mode 100644 index e4c3645b..00000000 --- a/rust/crates/execution/src/detectors/go.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Go application discovery from module roots and conventional command layouts. - -use super::super::types::Confidence; -use super::{Detected, DirectoryContext}; - -/// A Go module is runnable when a `package main` sits next to its `go.mod`, or -/// under the conventional `cmd/` layout. There is no declaration listing -/// entry points, so both are heuristics. -pub fn detect(ctx: &DirectoryContext) -> Vec { - let mut detected = Vec::new(); - if ctx.has("go.mod") && has_main_package(ctx) { - detected.push( - Detected::application( - "go.main", - &ctx.label(), - "go", - vec!["run", "."], - ctx, - "go.mod", - ) - .with_confidence(Confidence::Heuristic), - ); - } - // `cmd/` directories carry their own main package but no manifest. - // `go run .` resolves through the module root further up the tree. - if is_command_directory(ctx) && has_main_package(ctx) { - detected.push( - Detected::application( - "go.command", - &ctx.label(), - "go", - vec!["run", "."], - ctx, - "main.go", - ) - .with_confidence(Confidence::Heuristic), - ); - } - detected -} - -fn is_command_directory(ctx: &DirectoryContext) -> bool { - ctx.relative.split('/').rev().nth(1) == Some("cmd") -} - -fn has_main_package(ctx: &DirectoryContext) -> bool { - ctx.read("main.go") - .is_some_and(|text| text.lines().any(|line| line.trim() == "package main")) -} diff --git a/rust/crates/execution/src/detectors/make.rs b/rust/crates/execution/src/detectors/make.rs deleted file mode 100644 index 70f87365..00000000 --- a/rust/crates/execution/src/detectors/make.rs +++ /dev/null @@ -1,66 +0,0 @@ -//! Runnable Make target discovery with conservative service classification. - -use super::super::types::Confidence; -use super::{Detected, DirectoryContext}; - -const FILES: &[&str] = &["Makefile", "makefile", "GNUmakefile"]; - -/// Targets whose name conventionally starts something long-running. Everything -/// else is a task, so `make clean` does not show up in the service list. -const SERVICE_TARGETS: &[&str] = &["run", "dev", "serve", "start", "up", "watch"]; - -/// Only targets the user could plausibly want to run are offered: a Makefile -/// commonly has dozens of internal rules, and listing all of them buries the -/// two that matter. -pub fn detect(ctx: &DirectoryContext) -> Vec { - let Some(file) = ctx.any_of(FILES) else { - return Vec::new(); - }; - let Some(text) = ctx.read(file) else { - return Vec::new(); - }; - targets(&text) - .into_iter() - .filter(|name| SERVICE_TARGETS.contains(&name.as_str()) || is_common(name)) - .map(|name| { - let detected = if SERVICE_TARGETS.contains(&name.as_str()) { - Detected::service("make.target", &name, "make", vec![&name], ctx, file) - } else { - Detected::task("make.target", &name, "make", vec![&name], ctx, file) - }; - detected - .with_confidence(Confidence::Declared) - .with_extension("make", serde_json::json!({ "target": name })) - }) - .collect() -} - -fn is_common(name: &str) -> bool { - matches!( - name, - "build" | "test" | "install" | "lint" | "fmt" | "check" - ) -} - -/// Recognises `target:` at the start of a line. Pattern rules, variables, and -/// `.PHONY`-style directives are excluded because they are not invocable names. -fn targets(text: &str) -> Vec { - text.lines() - .filter_map(|line| { - if line.starts_with([' ', '\t', '#']) { - return None; - } - let (name, rest) = line.split_once(':')?; - if rest.starts_with('=') { - return None; - } - let name = name.trim(); - let valid = !name.is_empty() - && !name.starts_with('.') - && name - .chars() - .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); - valid.then(|| name.to_string()) - }) - .collect() -} diff --git a/rust/crates/execution/src/detectors/mod.rs b/rust/crates/execution/src/detectors/mod.rs deleted file mode 100644 index fccbb37f..00000000 --- a/rust/crates/execution/src/detectors/mod.rs +++ /dev/null @@ -1,243 +0,0 @@ -//! Language-agnostic discovery of runnable services. -//! -//! The engine walks a project once, groups the manifest files it finds by -//! directory, and hands each directory to every detector. Detectors never walk -//! the tree themselves: a shared walk is the only way the cost stays bounded as -//! ecosystems are added. -//! -//! Ecosystems whose layout is *declared* by a build model rather than -//! discovered from manifests belong to a build provider plugin, which reports -//! its runs through `build.provider` instead of a detector here. - -mod cargo; -mod compose; -mod go; -mod make; -mod npm; -mod procfile; -mod python; -mod scan; -mod shell; - -use super::types::{Confidence, Execution, RunCategory}; -use lithe_protocol::CoreError; -use std::collections::BTreeMap; -use std::path::Path; - -pub use scan::{scan, scan_ignoring, DirectoryContext}; - -/// One runnable thing a detector found. -/// -/// Deliberately not `RunConfiguration`: detectors describe what they saw without -/// deciding ids or serialization shape. The caller owns that translation so -/// every ecosystem gets identical treatment. -#[derive(Debug, Clone)] -pub struct Detected { - /// Namespaced provider, e.g. `npm.script`. Must pass `valid_provider`. - pub provider: String, - /// Human label, unique within its directory for a given provider. - pub name: String, - pub execution: Execution, - /// Whether this runs the project or the infrastructure it depends on. - pub category: RunCategory, - pub confidence: Confidence, - /// The program to spawn. Detectors always name one; `None` is reserved for - /// launches whose executable comes from a toolchain binding. - pub command: Option, - pub args: Vec, - /// Project-relative directory the command runs in. - pub cwd: String, - pub env: BTreeMap, - /// Toolchain bindings by role, e.g. `{runtime: project-node}`. A - /// process-based detection retains `command` while declaring a runtime it - /// consumes. - pub toolchains: BTreeMap, - pub extensions: BTreeMap, - /// Which manifest produced this, for the "why is this here" affordance. - pub source: String, -} - -impl Detected { - /// Creates a short-lived or interactive application detection. - pub fn application( - provider: &str, - name: &str, - command: &str, - args: Vec<&str>, - ctx: &DirectoryContext, - source: &str, - ) -> Self { - Self::new( - provider, - name, - command, - args, - ctx, - source, - Execution::Application, - ) - } - - /// Creates a long-running service detection. - pub fn service( - provider: &str, - name: &str, - command: &str, - args: Vec<&str>, - ctx: &DirectoryContext, - source: &str, - ) -> Self { - Self::new( - provider, - name, - command, - args, - ctx, - source, - Execution::Service, - ) - } - - /// Creates a command expected to run to completion. - pub fn task( - provider: &str, - name: &str, - command: &str, - args: Vec<&str>, - ctx: &DirectoryContext, - source: &str, - ) -> Self { - Self::new(provider, name, command, args, ctx, source, Execution::Task) - } - - fn new( - provider: &str, - name: &str, - command: &str, - args: Vec<&str>, - ctx: &DirectoryContext, - source: &str, - execution: Execution, - ) -> Self { - Self { - provider: provider.to_string(), - name: name.to_string(), - execution, - category: RunCategory::Project, - confidence: Confidence::Declared, - command: Some(command.to_string()), - args: args.into_iter().map(str::to_string).collect(), - cwd: ctx.relative.clone(), - env: BTreeMap::new(), - toolchains: BTreeMap::new(), - extensions: BTreeMap::new(), - source: ctx.join_relative(source), - } - } - - /// Marks a detection as external infrastructure rather than project code. - pub fn into_infrastructure(mut self) -> Self { - self.category = RunCategory::Infrastructure; - self - } - - /// Replaces the default declared confidence with the detector's evidence level. - pub fn with_confidence(mut self, confidence: Confidence) -> Self { - self.confidence = confidence; - self - } - - /// Declares a runtime requirement while keeping the detector-owned command. - /// - /// Process-based detectors still own their command, but Core needs the - /// binding to scope compatibility diagnostics to the consumers. - pub fn requiring_toolchain(mut self, role: &str, name: &str) -> Self { - self.toolchains.insert(role.to_string(), name.to_string()); - self - } - - /// Attaches provider-specific metadata without expanding the shared schema. - pub fn with_extension(mut self, namespace: &str, value: serde_json::Value) -> Self { - self.extensions.insert(namespace.to_string(), value); - self - } - - /// Stable across runs and unique per (provider, directory, name). Ids are the - /// join key for the team and local override layers, so any change to this - /// format silently detaches every override a user has written. - pub fn id(&self) -> String { - let directory = if self.cwd == "." { - String::new() - } else { - format!("{}/", self.cwd) - }; - format!("{}:{}{}", self.provider, directory, self.name) - } - - /// Two detections describe the same service when they run in the same place - /// under the same name. Provider is excluded on purpose: a Procfile `web` - /// and a compose service `web` in one directory are one service seen twice. - fn identity(&self) -> (String, String) { - (self.cwd.clone(), self.name.to_lowercase()) - } -} - -type DetectFn = fn(&DirectoryContext) -> Vec; - -/// Every built-in detector. Adding an ecosystem means one line here and one file -/// next to it -- no changes to the engine, the merge, or the contract. -const DETECTORS: &[DetectFn] = &[ - npm::detect, - compose::detect, - procfile::detect, - python::detect, - cargo::detect, - go::detect, - make::detect, - shell::detect_just, -]; - -/// Runs every detector over the project and returns deduplicated results -/// ordered shallowest-directory-first, so the top-level service of a monorepo -/// reads before its packages. -pub fn detect_all(root: &Path) -> Result, CoreError> { - let directories = scan(root)?; - let mut found = Vec::new(); - for context in &directories { - for detector in DETECTORS { - found.extend(detector(context)); - } - } - Ok(dedupe(found)) -} - -/// Keeps the highest-confidence detection per identity. -/// -/// Ties break on provider name rather than scan order: two equally confident -/// detectors must not produce a different winner depending on which ran first, -/// or `generated.json` churns between otherwise identical runs. -fn dedupe(found: Vec) -> Vec { - let mut best: BTreeMap<(String, String), Detected> = BTreeMap::new(); - for candidate in found { - let identity = candidate.identity(); - let replace = match best.get(&identity) { - Some(existing) => { - (candidate.confidence, candidate.provider.as_str()) - > (existing.confidence, existing.provider.as_str()) - } - None => true, - }; - if replace { - best.insert(identity, candidate); - } - } - let mut results = best.into_values().collect::>(); - results.sort_by_key(|item| { - ( - item.cwd.matches('/').count(), - item.cwd.clone(), - item.name.clone(), - ) - }); - results -} diff --git a/rust/crates/execution/src/detectors/npm.rs b/rust/crates/execution/src/detectors/npm.rs deleted file mode 100644 index 057a8953..00000000 --- a/rust/crates/execution/src/detectors/npm.rs +++ /dev/null @@ -1,240 +0,0 @@ -//! JavaScript package-script discovery and framework classification. - -use super::super::types::Confidence; -use super::{Detected, DirectoryContext}; -use serde_json::Value; - -/// Frameworks in most-specific-first order, because the general framework is a -/// dependency of the specific one: Nuxt pulls in Vue, Next pulls in React, and -/// SvelteKit pulls in Svelte. Reporting `vue` for a Nuxt app would be true and -/// useless, so the first match wins. -const FRAMEWORKS: &[(&str, &str)] = &[ - ("nuxt", "nuxt"), - ("next", "next"), - ("@sveltejs/kit", "sveltekit"), - ("@remix-run/dev", "remix"), - ("@angular/core", "angular"), - ("@nestjs/core", "nest"), - ("astro", "astro"), - ("@vue/cli-service", "vue"), - ("vue", "vue"), - ("svelte", "svelte"), - ("react", "react"), -]; - -/// Programs that start a long-running server, each with the subcommands that do -/// so. An empty list means every invocation serves. -/// -/// This is read from the script *body* because the script *name* is a -/// convention, not a declaration: `serve:local` starts a dev server and `start` -/// in a library package does not. -const SERVERS: &[(&str, &[&str])] = &[ - ("vite", &["", "dev", "serve", "preview"]), - ("next", &["dev", "start"]), - ("nuxt", &["dev", "start", "preview"]), - ("nuxi", &["dev", "preview"]), - ("astro", &["dev", "preview"]), - ("remix", &["dev"]), - ("ng", &["serve"]), - ("vue-cli-service", &["serve"]), - ("react-scripts", &["start"]), - ("nest", &["start"]), - ("nodemon", &[]), - ("ts-node-dev", &[]), - ("tsx", &["watch"]), - ("webpack-dev-server", &[]), - ("webpack", &["serve"]), - ("http-server", &[]), - ("serve", &[]), -]; - -/// Programs that always run to completion. Listed so a script whose body names -/// one is classified from that evidence instead of falling back to its name: a -/// `start` script that compiles is a task, whatever it is called. -const BUILDERS: &[&str] = &[ - "tsc", - "rollup", - "esbuild", - "tsup", - "parcel", - "rimraf", - "eslint", - "prettier", - "biome", - "jest", - "vitest", - "playwright", - "cypress", - "mocha", - "tap", - "typedoc", -]; - -/// Script names that conventionally start a server. Kept as a fallback for -/// projects whose scripts shell out to something unrecognised, and reported as -/// `Heuristic` so any detector holding real evidence wins dedup. -const SERVICE_SCRIPTS: &[&str] = &["dev", "start", "serve", "server", "watch", "preview"]; - -/// Command prefixes that wrap the real program without changing what it is. -const WRAPPERS: &[&str] = &["npx", "cross-env", "env", "dotenv"]; - -/// Package managers, most specific lockfile first. The chosen manager decides -/// the command, so guessing `npm` when the repo is pnpm-only produces a run -/// entry that fails at spawn time with a confusing error. -const MANAGERS: &[(&str, &str)] = &[ - ("bun.lockb", "bun"), - ("bun.lock", "bun"), - ("pnpm-lock.yaml", "pnpm"), - ("yarn.lock", "yarn"), - ("package-lock.json", "npm"), -]; - -/// Classifies runnable package scripts using declared dependencies and commands. -pub fn detect(ctx: &DirectoryContext) -> Vec { - let Some(text) = ctx.read("package.json") else { - return Vec::new(); - }; - let Ok(manifest) = serde_json::from_str::(&text) else { - return Vec::new(); - }; - let manager = manager_for(ctx, &manifest); - let framework = framework_for(&manifest); - let Some(scripts) = manifest["scripts"].as_object() else { - return Vec::new(); - }; - scripts - .iter() - .filter(|(name, _)| !name.is_empty()) - .map(|(name, body)| { - let args = run_arguments(manager, name); - let arguments = args.iter().map(String::as_str).collect::>(); - let body = body.as_str().unwrap_or_default(); - let server = server_program(body); - let detected = match server { - Some(_) => { - Detected::service("npm.script", name, manager, arguments, ctx, "package.json") - } - None if SERVICE_SCRIPTS.contains(&name.as_str()) && !builds(body) => { - Detected::service("npm.script", name, manager, arguments, ctx, "package.json") - .with_confidence(Confidence::Heuristic) - } - None => Detected::task("npm.script", name, manager, arguments, ctx, "package.json"), - }; - let mut extension = serde_json::json!({ "script": name, "manager": manager }); - if let Some(framework) = framework { - extension["framework"] = framework.into(); - } - if let Some(server) = server { - extension["server"] = server.into(); - } - let detected = if manager == "bun" { - detected - } else { - detected.requiring_toolchain("runtime", "project-node") - }; - detected.with_extension("npm", extension) - }) - .collect() -} - -/// The framework a package is built on, from its declared dependencies. Both -/// sections are searched because a framework may be a build-time dependency in -/// one project and a runtime one in another. -fn framework_for(manifest: &Value) -> Option<&'static str> { - FRAMEWORKS - .iter() - .find(|(package, _)| { - ["dependencies", "devDependencies"] - .iter() - .any(|section| manifest[section].get(package).is_some()) - }) - .map(|(_, framework)| *framework) -} - -/// The server a script body starts, if any. -/// -/// Each `&&` segment is examined rather than only the first, because a script -/// that prepares and then serves is still a service. -fn server_program(body: &str) -> Option<&'static str> { - body.split("&&").find_map(|segment| { - let (program, subcommand) = invocation(segment)?; - SERVERS - .iter() - .find(|(name, serves)| { - *name == program && (serves.is_empty() || serves.contains(&subcommand)) - }) - .map(|(name, _)| *name) - }) -} - -/// Whether every segment of the script body runs a program known to terminate. -/// One unrecognised segment is enough to leave the question open, because it may -/// be the shell script that starts the server. -fn builds(body: &str) -> bool { - let mut segments = body.split("&&").filter_map(invocation).peekable(); - segments.peek().is_some() && segments.all(|(program, _)| BUILDERS.contains(&program)) -} - -/// Splits a command segment into its program and first subcommand, skipping -/// leading environment assignments and wrappers. The subcommand is empty when -/// the program is invoked bare or with flags only. -/// -/// Only the token immediately after the program counts: scanning further would -/// read a flag's value as the subcommand, so `vite --port 3000` would look like -/// `vite 3000` rather than the bare `vite` that serves. -fn invocation(segment: &str) -> Option<(&str, &str)> { - let mut tokens = segment - .split_whitespace() - .skip_while(|token| token.contains('=') || WRAPPERS.contains(token)); - let program = tokens.next()?; - let subcommand = tokens - .next() - .filter(|token| !token.starts_with('-')) - .unwrap_or_default(); - Some((program, subcommand)) -} - -fn manager_for(ctx: &DirectoryContext, manifest: &Value) -> &'static str { - if let Some(manager) = manifest["packageManager"] - .as_str() - .and_then(|value| value.split('@').next()) - .and_then(known_manager) - { - return manager; - } - let mut directory = Some(ctx.path.as_path()); - while let Some(path) = directory { - if let Some(manager) = MANAGERS - .iter() - .find(|(lockfile, _)| path.join(lockfile).is_file()) - .map(|(_, manager)| *manager) - { - return manager; - } - if path == ctx.root { - break; - } - directory = path.parent().filter(|parent| parent.starts_with(&ctx.root)); - } - "npm" -} - -fn known_manager(value: &str) -> Option<&'static str> { - match value { - "npm" => Some("npm"), - "pnpm" => Some("pnpm"), - "yarn" => Some("yarn"), - "bun" => Some("bun"), - _ => None, - } -} - -/// `yarn