From 024258235c8f36e49544fb9981570ee9722d4006 Mon Sep 17 00:00:00 2001 From: Dionisio Chiuratto Agourakis Date: Wed, 28 Oct 2026 02:24:05 -0300 Subject: [PATCH] chore(release): regenerate from the source tree (leio-code-plugin-v2.6.7) --- .agents/skills/run-leio-bench/SKILL.md | 2 +- .agents/skills/run-leio-code/SKILL.md | 2 +- .chatgpt-plugin/plugin.json | 2 +- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .github/workflows/binary-release.yml | 42 +- CHANGELOG.md | 6 + Cargo.lock | 6 +- Cargo.toml | 10 +- README.md | 6 +- apps-sdk/package-lock.json | 4 +- apps-sdk/package.json | 2 +- crates/leio-harness/Cargo.toml | 2 +- crates/leio-harness/src/acp.rs | 15 +- crates/leio-harness/src/bus.rs | 105 +++-- crates/leio-harness/src/bus_client.rs | 46 +- crates/leio-harness/src/delivery.rs | 3 + crates/leio-harness/src/lease.rs | 3 + crates/leio-harness/src/managed_bus.rs | 56 ++- crates/leio-harness/src/process.rs | 98 +++- crates/leio-harness/src/shm.rs | 442 +++++++++++++------ crates/leio-harness/src/task.rs | 133 ++++-- crates/leio-harness/src/workflow.rs | 1 + crates/leio-knowledge-core/Cargo.toml | 2 +- docs/BENCHMARKS.md | 2 +- docs/RELEASE-CHECKLIST.md | 7 +- docs/install-stdio.md | 2 +- gemini-extension.json | 2 +- manifest.json | 2 +- mcp/install-binary.mjs | 1 + mcp/package-lock.json | 4 +- mcp/package.json | 2 +- mcp/resolve-binary.test.js | 7 + packaging/npm/README.md | 2 +- packaging/npm/bin/leio-code.js | 3 +- packaging/npm/bin/leio-harness.js | 3 +- packaging/npm/bin/leio-mcp.js | 7 +- packaging/npm/install.js | 12 +- packaging/npm/package.json | 2 +- packaging/python/README.md | 2 +- packaging/python/pyproject.toml | 4 +- packaging/python/src/leio_code/__init__.py | 2 +- packaging/python/src/leio_code/_exec.py | 14 +- packaging/python/src/leio_code/mcp.py | 3 + packaging/register-mcp.js | 3 + packaging/register-mcp.test.js | 12 + schema/leio-code-mcp-service-descriptor.json | 8 +- scripts/build_packages.py | 34 +- skills/leio-bench/SKILL.md | 2 +- skills/leio-code-apps-sdk/SKILL.md | 2 +- skills/leio-code/SKILL.md | 2 +- skills/leio-day/SKILL.md | 2 +- skills/leio-trio/SKILL.md | 2 +- src/doctors/env_contract.rs | 5 +- src/doctors/local_packs.rs | 33 +- src/doctors/native.rs | 97 ++-- tools/leio-self-doctors/Cargo.lock | 5 +- 58 files changed, 915 insertions(+), 369 deletions(-) diff --git a/.agents/skills/run-leio-bench/SKILL.md b/.agents/skills/run-leio-bench/SKILL.md index 4b83424..43bd24a 100644 --- a/.agents/skills/run-leio-bench/SKILL.md +++ b/.agents/skills/run-leio-bench/SKILL.md @@ -5,7 +5,7 @@ license: MIT OR Apache-2.0 compatibility: Requires python3, leio-harness, and a clean git checkout. metadata: author: leio-code - version: "2.6.6" + version: "2.6.7" --- # run-leio-bench (repo-local) diff --git a/.agents/skills/run-leio-code/SKILL.md b/.agents/skills/run-leio-code/SKILL.md index 70e06a3..730ad5c 100644 --- a/.agents/skills/run-leio-code/SKILL.md +++ b/.agents/skills/run-leio-code/SKILL.md @@ -5,7 +5,7 @@ license: MIT OR Apache-2.0 compatibility: Requires cargo, python3, and a local git checkout. metadata: author: leio-code - version: "2.6.6" + version: "2.6.7" --- diff --git a/.chatgpt-plugin/plugin.json b/.chatgpt-plugin/plugin.json index a5ad1cc..edfdfc6 100644 --- a/.chatgpt-plugin/plugin.json +++ b/.chatgpt-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "leio-code", - "version": "2.6.6", + "version": "2.6.7", "description": "LEIO Code ChatGPT App — capability-aware repository intelligence over MCP Apps (https://leio-code.getjai.com/mcp). Local wiki, SPARQL explain, lattice nav.", "mcp": { "url": "https://leio-code.getjai.com/mcp", diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 7ee294b..be6a3e4 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ { "name": "leio-code", "description": "Indexed lookup, graph, doctors, local wiki, SPARQL-gated explain, formal graph, lattice nav, and JSON-LD provenance via CLI/MCP.", - "version": "2.6.6", + "version": "2.6.7", "author": { "name": "LEIO Code contributors", "url": "https://github.com/josaum/leio-code" diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index b6cd8f5..81be362 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "leio-code", - "version": "2.6.6", + "version": "2.6.7", "description": "Agent-first code intelligence. CLI/MCP for index, find, graph, doctors, local Arrow wiki, SPARQL-gated knowledge explain, formal.nq, lattice/heading nav, and JSON-LD provenance events. Concurrent-agent safe.", "author": { "name": "LEIO Code contributors", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index f4b95bf..6b018d1 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "leio-code", - "version": "2.6.6", + "version": "2.6.7", "description": "Agent-first code intelligence. Local Arrow wiki first, SPARQL-gated knowledge explain, formal.nq, lattice/heading nav, JSON-LD provenance. Fully local.", "author": { "name": "LEIO Code contributors", diff --git a/.github/workflows/binary-release.yml b/.github/workflows/binary-release.yml index f6b86d4..dfeebe6 100644 --- a/.github/workflows/binary-release.yml +++ b/.github/workflows/binary-release.yml @@ -45,12 +45,19 @@ jobs: - os: ubuntu-latest target: x86_64-unknown-linux-gnu asset_name: leio-code-linux-amd64 + ext: "" - os: macos-15 target: aarch64-apple-darwin asset_name: leio-code-darwin-arm64 + ext: "" - os: macos-15-intel target: x86_64-apple-darwin asset_name: leio-code-darwin-amd64 + ext: "" + - os: windows-latest + target: x86_64-pc-windows-msvc + asset_name: leio-code-windows-amd64 + ext: ".exe" runs-on: ${{ matrix.os }} timeout-minutes: 60 permissions: @@ -64,27 +71,37 @@ jobs: with: shared-key: leio-code-binary-${{ matrix.target }} - name: Build release binary + shell: bash env: RUSTC_WRAPPER: "" CARGO_TARGET_DIR: target run: | cargo build --locked --release --target ${{ matrix.target }} -p leio-code -p leio-harness - BINARY=$(find target -name leio-code -type f ! -path "*/deps/*" ! -path "*/build/*" | grep release | head -1) - HARNESS=$(find target -name leio-harness -type f ! -path "*/deps/*" ! -path "*/build/*" | grep release | head -1) - cp "$BINARY" ${{ matrix.asset_name }} - cp "$HARNESS" ${{ matrix.asset_name }}-harness + cp "target/${{ matrix.target }}/release/leio-code${{ matrix.ext }}" "${{ matrix.asset_name }}${{ matrix.ext }}" + cp "target/${{ matrix.target }}/release/leio-harness${{ matrix.ext }}" "${{ matrix.asset_name }}-harness${{ matrix.ext }}" - name: Strip binary + shell: bash run: | - command -v strip >/dev/null && strip ${{ matrix.asset_name }} ${{ matrix.asset_name }}-harness || true + if [ -z "${{ matrix.ext }}" ] && command -v strip >/dev/null; then + strip "${{ matrix.asset_name }}${{ matrix.ext }}" "${{ matrix.asset_name }}-harness${{ matrix.ext }}" || true + fi - name: Smoke release binaries + shell: bash run: | - ./${{ matrix.asset_name }} --version - ./${{ matrix.asset_name }}-harness --version + "./${{ matrix.asset_name }}${{ matrix.ext }}" --version + "./${{ matrix.asset_name }}-harness${{ matrix.ext }}" --version - name: Checksum + shell: bash run: | - shasum -a 256 ${{ matrix.asset_name }} > ${{ matrix.asset_name }}.sha256 - shasum -a 256 ${{ matrix.asset_name }}-harness > ${{ matrix.asset_name }}-harness.sha256 + if command -v shasum >/dev/null 2>&1; then + shasum -a 256 "${{ matrix.asset_name }}${{ matrix.ext }}" > "${{ matrix.asset_name }}${{ matrix.ext }}.sha256" + shasum -a 256 "${{ matrix.asset_name }}-harness${{ matrix.ext }}" > "${{ matrix.asset_name }}-harness${{ matrix.ext }}.sha256" + else + sha256sum "${{ matrix.asset_name }}${{ matrix.ext }}" > "${{ matrix.asset_name }}${{ matrix.ext }}.sha256" + sha256sum "${{ matrix.asset_name }}-harness${{ matrix.ext }}" > "${{ matrix.asset_name }}-harness${{ matrix.ext }}.sha256" + fi - name: Ensure release + shell: bash env: GH_TOKEN: ${{ github.token }} run: | @@ -93,7 +110,8 @@ jobs: gh release create "$TAG" --target "$GITHUB_SHA" \ --title "LEIO Code v${{ needs.resolve-tag.outputs.version }}" \ --notes "Binary release for leio-code v${{ needs.resolve-tag.outputs.version }}" \ - --draft + --draft || true fi - gh release upload "$TAG" "${{ matrix.asset_name }}" "${{ matrix.asset_name }}.sha256" \ - "${{ matrix.asset_name }}-harness" "${{ matrix.asset_name }}-harness.sha256" --clobber + gh release upload "$TAG" \ + "${{ matrix.asset_name }}${{ matrix.ext }}" "${{ matrix.asset_name }}${{ matrix.ext }}.sha256" \ + "${{ matrix.asset_name }}-harness${{ matrix.ext }}" "${{ matrix.asset_name }}-harness${{ matrix.ext }}.sha256" --clobber diff --git a/CHANGELOG.md b/CHANGELOG.md index 28d60a7..0a2379e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to LEIO Code. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow the crate version in `Cargo.toml`. +## [2.6.7] — 2026-10-28 + +### Added +- Windows x64 (`x86_64-pc-windows-msvc` / `win32-x64`) release support across `leio-code` and `leio-harness`, GitHub Release assets (`leio-code-windows-amd64.exe` and `leio-code-windows-amd64-harness.exe`), `cargo-binstall` metadata, `@leio/leio-code-mcp` binary installer, `leio-code` npm package, and `leio_code` `win_amd64` Python wheel. +- Cross-platform `leio-harness` process supervision, local TCP managed bus fallback, file-backed shared-memory ring and loopback UDP signaling plane, and native/local doctor pack execution on Windows. + ## [2.6.5] — 2026-09-23 - Move product-specific doctors, baselines and regression tests into their owning diff --git a/Cargo.lock b/Cargo.lock index b65248e..ccab3fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1324,7 +1324,7 @@ dependencies = [ [[package]] name = "leio-code" -version = "2.6.6" +version = "2.6.7" dependencies = [ "aho-corasick", "anyhow", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "leio-harness" -version = "2.6.6" +version = "2.6.7" dependencies = [ "anyhow", "arrow-array", @@ -1404,7 +1404,7 @@ dependencies = [ [[package]] name = "leio-knowledge-core" -version = "2.6.6" +version = "2.6.7" dependencies = [ "anyhow", "oxigraph", diff --git a/Cargo.toml b/Cargo.toml index 4c739ed..a39685d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ exclude = ["tools/leio-self-doctors"] [package] name = "leio-code" -version = "2.6.6" +version = "2.6.7" edition = "2024" description = "Agent-first code intelligence for one repository at a time" license = "MIT OR Apache-2.0" @@ -26,11 +26,17 @@ pkg-url = "https://github.com/josaum/leio-code/releases/download/leio-code-plugi [package.metadata.binstall.overrides.x86_64-unknown-linux-gnu] pkg-url = "https://github.com/josaum/leio-code/releases/download/leio-code-plugin-v{ version }/leio-code-linux-amd64" +[package.metadata.binstall.overrides.x86_64-pc-windows-msvc] +pkg-url = "https://github.com/josaum/leio-code/releases/download/leio-code-plugin-v{ version }/leio-code-windows-amd64.exe" + +[package.metadata.binstall.overrides.x86_64-pc-windows-gnu] +pkg-url = "https://github.com/josaum/leio-code/releases/download/leio-code-plugin-v{ version }/leio-code-windows-amd64.exe" + [dependencies] # Formal store + anchored-or-refuse SPARQL envelope, split out so runtimes # that ship an ontology without a repo (container images, brain substrates) # share one mechanism instead of re-implementing it. -leio-knowledge-core = { path = "crates/leio-knowledge-core", version = "2.6.6" } +leio-knowledge-core = { path = "crates/leio-knowledge-core", version = "2.6.7" } anyhow = "1" aho-corasick = "=1.1.4" tempfile = "3" diff --git a/README.md b/README.md index 9f72c5f..adaccc9 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ and confirm the session cursor is still there. **15 of 15 scripted runs passed**, including cursor restoration after provider restart. Measured on this repository's **420 indexed files**, Apple M1, -release 2.6.2. The current release is 2.6.6; these timings were not re-run. +release 2.6.2. The current release is 2.6.7; these timings were not re-run. Five runs per scenario; warm index/graph. Timings include the 11 calls, checks and reconnect; setup is excluded. @@ -71,9 +71,9 @@ npm install -g leio-code cargo binstall leio-code ``` -The Python wheel and the Node package install `leio-code`, `leio-harness`, and the stdio server `leio-mcp`. They register that server with harnesses already on the machine. Any other MCP host launches `leio-mcp`. `cargo binstall leio-code` installs Code. The release covers macOS arm64, macOS x64, and Linux x64. Pass an absolute `--repo` or `repo_root` for each codebase. Do not set `LEIO_CODE_REPO_ROOT`. +The Python wheel and the Node package install `leio-code`, `leio-harness`, and the stdio server `leio-mcp`. They register that server with harnesses already on the machine. Any other MCP host launches `leio-mcp`. `cargo binstall leio-code` installs Code. The release covers macOS arm64, macOS x64, Linux x64, and Windows x64. Pass an absolute `--repo` or `repo_root` for each codebase. Do not set `LEIO_CODE_REPO_ROOT`. -[Release 2.6.6](https://github.com/josaum/leio-code/releases/tag/leio-code-plugin-v2.6.6) +[Release 2.6.7](https://github.com/josaum/leio-code/releases/tag/leio-code-plugin-v2.6.7) ## Your first useful query diff --git a/apps-sdk/package-lock.json b/apps-sdk/package-lock.json index 1514ec6..5dba30b 100644 --- a/apps-sdk/package-lock.json +++ b/apps-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@leio/leio-code-apps-sdk", - "version": "2.6.6", + "version": "2.6.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@leio/leio-code-apps-sdk", - "version": "2.6.6", + "version": "2.6.7", "dependencies": { "@modelcontextprotocol/sdk": "^1.29.0", "jose": "^6.1.3", diff --git a/apps-sdk/package.json b/apps-sdk/package.json index 5fc0b8d..d0fd0f9 100644 --- a/apps-sdk/package.json +++ b/apps-sdk/package.json @@ -1,6 +1,6 @@ { "name": "@leio/leio-code-apps-sdk", - "version": "2.6.6", + "version": "2.6.7", "private": true, "type": "module", "description": "OpenAI Apps SDK / ChatGPT MCP app for LEIO Code (self-host production-capable; private package)", diff --git a/crates/leio-harness/Cargo.toml b/crates/leio-harness/Cargo.toml index 8b9c349..6b872d9 100644 --- a/crates/leio-harness/Cargo.toml +++ b/crates/leio-harness/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "leio-harness" -version = "2.6.6" +version = "2.6.7" edition = "2024" license = "MIT OR Apache-2.0" description = "LEIO-Harness — agent execution runtime for LEIO Code" diff --git a/crates/leio-harness/src/acp.rs b/crates/leio-harness/src/acp.rs index 67050f1..c0bc788 100644 --- a/crates/leio-harness/src/acp.rs +++ b/crates/leio-harness/src/acp.rs @@ -12,7 +12,9 @@ use crate::arrow_events::{EventStreamWriter, StreamEvent}; use crate::model::{AgentSessionResult, AgentSessionSpec, RunStatus}; use crate::process::inherited_value; use anyhow::{Context, Result, bail}; +#[cfg(unix)] use nix::sys::signal::{Signal, killpg}; +#[cfg(unix)] use nix::unistd::Pid; use std::collections::BTreeSet; use std::fs::File; @@ -406,8 +408,18 @@ fn terminate_group(pid: u32, grace_ms: u64) -> Result<()> { } #[cfg(not(unix))] { - let _ = pid; thread::sleep(Duration::from_millis(grace_ms)); + #[cfg(windows)] + { + let _ = Command::new("taskkill") + .args(["/PID", &pid.to_string(), "/T", "/F"]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + #[cfg(not(windows))] + let _ = pid; } Ok(()) } @@ -419,6 +431,7 @@ fn write_json_atomic(path: &Path, value: &impl serde::Serialize) -> Result<()> { file.write_all(b"\n")?; file.sync_all()?; std::fs::rename(temporary, path)?; + #[cfg(unix)] if let Some(parent) = path.parent() { File::open(parent)?.sync_all()?; } diff --git a/crates/leio-harness/src/bus.rs b/crates/leio-harness/src/bus.rs index 791dc5a..8369ac0 100644 --- a/crates/leio-harness/src/bus.rs +++ b/crates/leio-harness/src/bus.rs @@ -523,51 +523,60 @@ pub async fn serve_persistent(bind: SocketAddr, persist_path: Option) - } pub async fn serve_uds(path: PathBuf, persist_path: Option) -> AnyResult<()> { - use tokio::net::UnixListener; - use tokio_stream::wrappers::UnixListenerStream; - - use std::os::unix::fs::{FileTypeExt, PermissionsExt}; - let _socket_lock = { + #[cfg(unix)] + { + use std::os::unix::fs::{FileTypeExt, PermissionsExt}; + use tokio::net::UnixListener; + use tokio_stream::wrappers::UnixListenerStream; + let _socket_lock = { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let lock = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(path.with_extension("socket.lock"))?; + fs2::FileExt::try_lock_exclusive(&lock).context("bus socket already owned")?; + lock + }; + if let Ok(meta) = std::fs::symlink_metadata(&path) { + anyhow::ensure!( + meta.file_type().is_socket(), + "refusing to replace a non-socket path" + ); + match std::os::unix::net::UnixStream::connect(&path) { + Ok(_) => bail!("bus socket already serving"), + Err(error) if error.kind() == std::io::ErrorKind::ConnectionRefused => { + std::fs::remove_file(&path)? + } + Err(error) => return Err(error.into()), + } + } if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } - let lock = std::fs::OpenOptions::new() - .create(true) - .truncate(false) - .read(true) - .write(true) - .open(path.with_extension("socket.lock"))?; - fs2::FileExt::try_lock_exclusive(&lock).context("bus socket already owned")?; - lock - }; - if let Ok(meta) = std::fs::symlink_metadata(&path) { - anyhow::ensure!( - meta.file_type().is_socket(), - "refusing to replace a non-socket path" - ); - match std::os::unix::net::UnixStream::connect(&path) { - Ok(_) => bail!("bus socket already serving"), - Err(error) if error.kind() == std::io::ErrorKind::ConnectionRefused => { - std::fs::remove_file(&path)? - } - Err(error) => return Err(error.into()), - } - } - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } - let listener = UnixListener::bind(&path) - .with_context(|| format!("failed to bind UDS flight bus to {}", path.display()))?; - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; - let stream = UnixListenerStream::new(listener); + let listener = UnixListener::bind(&path) + .with_context(|| format!("failed to bind UDS flight bus to {}", path.display()))?; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; + let stream = UnixListenerStream::new(listener); - let bus = Arc::new(SemanticBus::load_or_default(persist_path)?); - Server::builder() - .add_service(FlightServiceServer::from_arc(bus)) - .serve_with_incoming(stream) - .await - .context("flight bus serve over uds") + let bus = Arc::new(SemanticBus::load_or_default(persist_path)?); + Server::builder() + .add_service(FlightServiceServer::from_arc(bus)) + .serve_with_incoming(stream) + .await + .context("flight bus serve over uds") + } + #[cfg(not(unix))] + { + let _ = (path, persist_path); + bail!( + "Unix domain socket bus is not supported on Windows; use a TCP bind address such as 127.0.0.1:8815" + ) + } } pub async fn serve_auto(bind: &str, persist_path: Option) -> AnyResult<()> { @@ -779,6 +788,7 @@ fn handle_exchange_match( )?) } +#[allow(dead_code)] #[derive(Debug)] struct RenamedSnapshotError(std::io::Error); impl std::fmt::Display for RenamedSnapshotError { @@ -794,7 +804,6 @@ impl std::error::Error for RenamedSnapshotError {} pub(crate) fn save_bus_snapshot(path: &Path, rows: &[EmbeddingRow]) -> AnyResult<()> { use arrow_ipc::writer::FileWriter; - use std::os::unix::fs::OpenOptionsExt; static TEMP_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let parent = path .parent() @@ -808,16 +817,20 @@ pub(crate) fn save_bus_snapshot(path: &Path, rows: &[EmbeddingRow]) -> AnyResult .as_nanos(); let temporary = path.with_extension(format!("{}.{nanos}.{id}.tmp", std::process::id())); let result = (|| -> AnyResult<()> { - let file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(&temporary)?; + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let file = options.open(&temporary)?; let mut writer = FileWriter::try_new(file, &embedding_schema())?; writer.write(&batch)?; writer.finish()?; writer.get_ref().sync_all()?; std::fs::rename(&temporary, path)?; + #[cfg(unix)] std::fs::File::open(parent) .and_then(|f| f.sync_all()) .map_err(RenamedSnapshotError)?; diff --git a/crates/leio-harness/src/bus_client.rs b/crates/leio-harness/src/bus_client.rs index ce4c039..40e0c1e 100644 --- a/crates/leio-harness/src/bus_client.rs +++ b/crates/leio-harness/src/bus_client.rs @@ -76,25 +76,33 @@ impl BusClient { } async fn connect_uds(path: PathBuf) -> Result { - use hyper_util::rt::TokioIo; - use tower::service_fn; - let endpoint = Endpoint::try_from("http://[::]:50051")? - .timeout(Duration::from_secs(30)) - .connect_timeout(Duration::from_secs(2)); - let socket_path = path.clone(); - let channel = endpoint - .connect_with_connector(service_fn(move |_: tonic::transport::Uri| { - let p = socket_path.clone(); - async move { - let stream = tokio::net::UnixStream::connect(p).await?; - Ok::<_, std::io::Error>(TokioIo::new(stream)) - } - })) - .await - .with_context(|| { - format!("failed to connect to UDS flight bus at {}", path.display()) - })?; - Ok(channel) + #[cfg(unix)] + { + use hyper_util::rt::TokioIo; + use tower::service_fn; + let endpoint = Endpoint::try_from("http://[::]:50051")? + .timeout(Duration::from_secs(30)) + .connect_timeout(Duration::from_secs(2)); + let socket_path = path.clone(); + let channel = endpoint + .connect_with_connector(service_fn(move |_: tonic::transport::Uri| { + let p = socket_path.clone(); + async move { + let stream = tokio::net::UnixStream::connect(p).await?; + Ok::<_, std::io::Error>(TokioIo::new(stream)) + } + })) + .await + .with_context(|| { + format!("failed to connect to UDS flight bus at {}", path.display()) + })?; + Ok(channel) + } + #[cfg(not(unix))] + { + let _ = path; + bail!("Unix domain socket bus is not supported on Windows; use a TCP endpoint") + } } pub async fn connect_with_retry(addr: &str, attempts: usize, delay: Duration) -> Result { diff --git a/crates/leio-harness/src/delivery.rs b/crates/leio-harness/src/delivery.rs index 1b4c046..33f2b73 100644 --- a/crates/leio-harness/src/delivery.rs +++ b/crates/leio-harness/src/delivery.rs @@ -118,6 +118,7 @@ fn atomic_json(path: &Path, value: &Value) -> Result<()> { file.write_all(&serde_json::to_vec_pretty(value)?)?; file.sync_all()?; fs::rename(tmp, path)?; + #[cfg(unix)] File::open(path.parent().unwrap())?.sync_all()?; Ok(()) } @@ -129,6 +130,7 @@ fn sync_directories(dir: &Path) -> Result<()> { sync_directories(&path)?; } } + #[cfg(unix)] File::open(dir)?.sync_all()?; Ok(()) } @@ -335,6 +337,7 @@ pub fn prepare(source: &Path, target: &Path) -> Result { )?; sync_directories(&staging)?; fs::rename(&staging, &destination)?; + #[cfg(unix)] File::open(target.join("releases"))?.sync_all()?; } Ok( diff --git a/crates/leio-harness/src/lease.rs b/crates/leio-harness/src/lease.rs index 583c70c..595a152 100644 --- a/crates/leio-harness/src/lease.rs +++ b/crates/leio-harness/src/lease.rs @@ -176,9 +176,12 @@ impl LeaseStore { } fn sync_parent(path: &Path) -> Result<()> { + #[cfg(unix)] if let Some(parent) = path.parent() { File::open(parent)?.sync_all()?; } + #[cfg(not(unix))] + let _ = path; Ok(()) } diff --git a/crates/leio-harness/src/managed_bus.rs b/crates/leio-harness/src/managed_bus.rs index 91fc6aa..8d50d35 100644 --- a/crates/leio-harness/src/managed_bus.rs +++ b/crates/leio-harness/src/managed_bus.rs @@ -17,10 +17,10 @@ pub fn directory() -> Result { if let Some(path) = std::env::var_os("LEIO_HARNESS_BUS_DIR") { return Ok(PathBuf::from(path)); } - Ok( - PathBuf::from(std::env::var_os("HOME").context("HOME missing; set LEIO_HARNESS_BUS_DIR")?) - .join(".local/share/leio-harness/bus"), - ) + let home = std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .context("HOME missing; set LEIO_HARNESS_BUS_DIR")?; + Ok(PathBuf::from(home).join(".local/share/leio-harness/bus")) } pub async fn ensure(explicit: Option, disabled: bool) -> Result> { @@ -42,7 +42,8 @@ pub async fn ensure(explicit: Option, disabled: bool) -> Result, disabled: bool) -> Result, disabled: bool) -> Result>) -> Re // Descendants can retain stdout/stderr after the leader exits. Terminate // the owned process group before joining pipe readers, or a successful // shell can hang this supervisor forever. + #[cfg(unix)] let _ = killpg(Pid::from_raw(child.id() as i32), Signal::SIGKILL); + #[cfg(windows)] + let _ = Command::new("taskkill") + .args(["/PID", &child.id().to_string(), "/T", "/F"]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); finished.store(true, Ordering::Release); stdout_reader .join() @@ -242,7 +253,10 @@ impl std::ops::DerefMut for OwnedChild { } impl Drop for OwnedChild { fn drop(&mut self) { + #[cfg(unix)] let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL); + #[cfg(not(unix))] + let _ = self.0.kill(); let _ = self.0.wait(); } } @@ -254,6 +268,7 @@ struct StreamFlags { observer: Option>, } +#[cfg(unix)] fn read_stream( mut reader: R, stream: &'static str, @@ -342,6 +357,75 @@ fn read_stream( }) } +#[cfg(not(unix))] +fn read_stream( + mut reader: R, + stream: &'static str, + max_bytes: usize, + mut log: File, + tx: SyncSender, + seq: Arc, + flags: StreamFlags, +) -> StreamReaderHandle { + thread::spawn(move || { + let StreamFlags { + truncated: truncated_flag, + finished, + observer, + } = flags; + let mut captured = 0_usize; + let mut drain_chunks = 0; + loop { + if finished.load(Ordering::Acquire) { + drain_chunks += 1; + if drain_chunks > 32 { + break; + } + } + let mut buffer = vec![0_u8; 64 * 1024]; + let read = match reader.read(&mut buffer) { + Ok(count) => count, + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error.into()), + }; + if read == 0 { + break; + } + buffer.truncate(read); + let remaining = max_bytes.saturating_sub(captured); + if remaining > 0 { + let kept = buffer.len().min(remaining); + log.write_all(&buffer[..kept])?; + captured += kept; + if let Some(observer) = &observer { + observer.output(stream, kept)?; + } + } + if read > remaining { + truncated_flag.store(true, Ordering::Relaxed); + } + buffer.truncate(read.min(remaining)); + if buffer.is_empty() { + continue; + } + if tx + .send(StreamEvent { + seq: seq.fetch_add(1, Ordering::Relaxed), + timestamp_ms: now_ms() as i64, + kind: "process_output".to_owned(), + stream: stream.to_owned(), + payload: buffer, + }) + .is_err() + { + break; + } + } + log.sync_all()?; + Ok(()) + }) +} + fn arrow_writer(path: &Path, rx: Receiver) -> Result<()> { let mut writer = EventStreamWriter::create(path)?; for event in rx { @@ -382,8 +466,18 @@ fn terminate_group(pid: u32, grace_ms: u64) -> Result<()> { } #[cfg(not(unix))] { - let _ = pid; thread::sleep(Duration::from_millis(grace_ms)); + #[cfg(windows)] + { + let _ = Command::new("taskkill") + .args(["/PID", &pid.to_string(), "/T", "/F"]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + #[cfg(not(windows))] + let _ = pid; } Ok(()) } @@ -395,6 +489,7 @@ pub(crate) fn write_json_atomic(path: &Path, value: &impl serde::Serialize) -> R file.write_all(b"\n")?; file.sync_all()?; std::fs::rename(temporary, path)?; + #[cfg(unix)] if let Some(parent) = path.parent() { File::open(parent)?.sync_all()?; } @@ -427,6 +522,7 @@ pub(crate) fn harness_env_path() -> Option { .map(std::path::PathBuf::from) .or_else(|| { std::env::var("HOME") + .or_else(|_| std::env::var("USERPROFILE")) .ok() .map(|home| std::path::Path::new(&home).join(".config/leio-harness/env")) }) diff --git a/crates/leio-harness/src/shm.rs b/crates/leio-harness/src/shm.rs index 9cffb1d..62b16a6 100644 --- a/crates/leio-harness/src/shm.rs +++ b/crates/leio-harness/src/shm.rs @@ -8,10 +8,14 @@ //! and dual-plane Unix Domain datagram signaling to prevent CPU busy-spinning. use anyhow::{Context, Result, bail}; +#[cfg(unix)] use nix::libc; +#[cfg(unix)] use std::ffi::CString; +#[cfg(unix)] use std::os::unix::net::UnixDatagram; use std::path::PathBuf; +#[cfg(unix)] use std::ptr::NonNull; use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; @@ -172,7 +176,8 @@ pub struct ShmRingHeader { pub tail: CachePaddedAtomicU64, } -/// Cross-platform POSIX / memfd shared memory mapping. +/// Cross-platform POSIX / memfd / file-backed shared memory mapping. +#[cfg(unix)] pub struct ShmSegment { name: String, size: usize, @@ -180,6 +185,15 @@ pub struct ShmSegment { is_owner: bool, } +#[cfg(not(unix))] +pub struct ShmSegment { + name: String, + size: usize, + mmap: memmap2::MmapMut, + backing_path: PathBuf, + is_owner: bool, +} + unsafe impl Send for ShmSegment {} unsafe impl Sync for ShmSegment {} @@ -203,89 +217,138 @@ impl ShmSegment { .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-'), "shm name must contain at most 29 ASCII letters, digits, underscores or hyphens" ); - let c_name = CString::new(final_name.clone())?; - let flags = libc::O_RDWR - | if owner { - libc::O_CREAT | libc::O_EXCL - } else { - 0 - }; - // SAFETY: NUL-terminated name and valid flags. Owners exclusively create; - // attaching never creates or truncates an existing mapping. - let fd = unsafe { libc::shm_open(c_name.as_ptr(), flags, 0o600) }; - if fd < 0 { - bail!("shm_open {final_name}: {}", std::io::Error::last_os_error()); - } - let checked = (|| -> Result<()> { - if owner { - if unsafe { libc::ftruncate(fd, size as libc::off_t) } != 0 { - return Err(std::io::Error::last_os_error().into()); + #[cfg(unix)] + { + let c_name = CString::new(final_name.clone())?; + let flags = libc::O_RDWR + | if owner { + libc::O_CREAT | libc::O_EXCL + } else { + 0 + }; + // SAFETY: NUL-terminated name and valid flags. Owners exclusively create; + // attaching never creates or truncates an existing mapping. + let fd = unsafe { libc::shm_open(c_name.as_ptr(), flags, 0o600) }; + if fd < 0 { + bail!("shm_open {final_name}: {}", std::io::Error::last_os_error()); + } + let checked = (|| -> Result<()> { + if owner { + if unsafe { libc::ftruncate(fd, size as libc::off_t) } != 0 { + return Err(std::io::Error::last_os_error().into()); + } + } else { + let mut stat = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::fstat(fd, stat.as_mut_ptr()) } != 0 { + return Err(std::io::Error::last_os_error().into()); + } + let stat = unsafe { stat.assume_init() }; + anyhow::ensure!( + stat.st_size >= 0 && { + // Darwin reports page-rounded POSIX shm sizes; Linux + // reports the ftruncate length. Validate either form, + // then validate the exact logical capacity in the ABI. + let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + page > 0 + && (stat.st_size as usize == size + || stat.st_size as usize + == size.div_ceil(page as usize) * page as usize) + }, + "shm mapping size mismatch (requested {size}, found {}); refusing to resize existing segment", + stat.st_size + ); } - } else { - let mut stat = std::mem::MaybeUninit::::uninit(); - if unsafe { libc::fstat(fd, stat.as_mut_ptr()) } != 0 { - return Err(std::io::Error::last_os_error().into()); + Ok(()) + })(); + if let Err(error) = checked { + unsafe { + libc::close(fd); + if owner { + libc::shm_unlink(c_name.as_ptr()); + } } - let stat = unsafe { stat.assume_init() }; - anyhow::ensure!( - stat.st_size >= 0 && { - // Darwin reports page-rounded POSIX shm sizes; Linux - // reports the ftruncate length. Validate either form, - // then validate the exact logical capacity in the ABI. - let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; - page > 0 - && (stat.st_size as usize == size - || stat.st_size as usize - == size.div_ceil(page as usize) * page as usize) - }, - "shm mapping size mismatch (requested {size}, found {}); refusing to resize existing segment", - stat.st_size - ); + return Err(error); } - Ok(()) - })(); - if let Err(error) = checked { - unsafe { - libc::close(fd); + + let ptr = unsafe { + libc::mmap( + std::ptr::null_mut(), + size, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED, + fd, + 0, + ) + }; + unsafe { libc::close(fd) }; + + if ptr == libc::MAP_FAILED { if owner { - libc::shm_unlink(c_name.as_ptr()); + unsafe { + libc::shm_unlink(c_name.as_ptr()); + } } + bail!( + "mmap failed for {}: {}", + final_name, + std::io::Error::last_os_error() + ); } - return Err(error); - } - let ptr = unsafe { - libc::mmap( - std::ptr::null_mut(), + let non_null = NonNull::new(ptr as *mut u8).context("mmap returned null")?; + Ok(Self { + name: final_name, size, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_SHARED, - fd, - 0, - ) - }; - unsafe { libc::close(fd) }; - - if ptr == libc::MAP_FAILED { - if owner { - unsafe { - libc::shm_unlink(c_name.as_ptr()); + ptr: non_null, + is_owner: owner, + }) + } + #[cfg(not(unix))] + { + let backing_path = + std::env::temp_dir().join(format!("leio-shm-{}.bin", &final_name[1..])); + let file = if owner { + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(&backing_path) + .with_context(|| format!("shm_open {final_name}"))?; + if let Err(error) = file.set_len(size as u64) { + let _ = std::fs::remove_file(&backing_path); + return Err(error.into()); } - } - bail!( - "mmap failed for {}: {}", - final_name, - std::io::Error::last_os_error() - ); + file + } else { + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(&backing_path) + .with_context(|| format!("shm_open {final_name}"))?; + let actual = file.metadata()?.len() as usize; + anyhow::ensure!( + actual == size, + "shm mapping size mismatch (requested {size}, found {actual}); refusing to resize existing segment" + ); + file + }; + let mmap = match unsafe { memmap2::MmapMut::map_mut(&file) } { + Ok(mmap) => mmap, + Err(error) => { + if owner { + let _ = std::fs::remove_file(&backing_path); + } + return Err(error).with_context(|| format!("mmap failed for {final_name}")); + } + }; + Ok(Self { + name: final_name, + size, + mmap, + backing_path, + is_owner: owner, + }) } - - let non_null = NonNull::new(ptr as *mut u8).context("mmap returned null")?; - Ok(Self { - name: final_name, - size, - ptr: non_null, - is_owner: owner, - }) } pub fn name(&self) -> &str { @@ -297,12 +360,20 @@ impl ShmSegment { #[inline] pub fn as_ptr(&self) -> *mut u8 { - self.ptr.as_ptr() + #[cfg(unix)] + { + self.ptr.as_ptr() + } + #[cfg(not(unix))] + { + self.mmap.as_ptr() as *mut u8 + } } } impl Drop for ShmSegment { fn drop(&mut self) { + #[cfg(unix)] unsafe { libc::munmap(self.ptr.as_ptr() as *mut libc::c_void, self.size); if self.is_owner @@ -311,16 +382,29 @@ impl Drop for ShmSegment { libc::shm_unlink(c_name.as_ptr()); } } + #[cfg(not(unix))] + if self.is_owner { + let _ = std::fs::remove_file(&self.backing_path); + } } } -/// Lightweight Unix Domain Datagram notification plane to avoid 100% CPU busy-spinning. +/// Lightweight datagram notification plane to avoid 100% CPU busy-spinning. +#[cfg(unix)] pub struct ShmSignal { socket: UnixDatagram, peer_path: Option, bind_path: Option, } +#[cfg(not(unix))] +pub struct ShmSignal { + socket: std::net::UdpSocket, + peer_addr: Option, + peer_path: Option, + bind_path: Option, +} + impl ShmSignal { /// Create a listener signal bound to a filesystem path. pub fn bind(ring_name: &str) -> Result { @@ -329,46 +413,101 @@ impl ShmSignal { !path.exists(), "signal socket already exists; refusing to unlink another listener" ); - let socket = UnixDatagram::bind(&path) - .with_context(|| format!("failed to bind shm signal socket: {}", path.display()))?; - socket.set_nonblocking(true)?; - Ok(Self { - socket, - peer_path: None, - bind_path: Some(path), - }) + #[cfg(unix)] + { + let socket = UnixDatagram::bind(&path) + .with_context(|| format!("failed to bind shm signal socket: {}", path.display()))?; + socket.set_nonblocking(true)?; + Ok(Self { + socket, + peer_path: None, + bind_path: Some(path), + }) + } + #[cfg(not(unix))] + { + let socket = std::net::UdpSocket::bind("127.0.0.1:0")?; + let addr = socket.local_addr()?; + std::fs::write(&path, addr.to_string())?; + Ok(Self { + socket, + peer_addr: None, + peer_path: None, + bind_path: Some(path), + }) + } } /// Create an unbound sender signal targeting a ring listener. pub fn connect(ring_name: &str) -> Result { let peer_path = Self::socket_path(ring_name); - let socket = - UnixDatagram::unbound().context("failed to create unbound unix datagram socket")?; - socket.set_nonblocking(true)?; - Ok(Self { - socket, - peer_path: Some(peer_path), - bind_path: None, - }) + #[cfg(unix)] + { + let socket = + UnixDatagram::unbound().context("failed to create unbound unix datagram socket")?; + socket.set_nonblocking(true)?; + Ok(Self { + socket, + peer_path: Some(peer_path), + bind_path: None, + }) + } + #[cfg(not(unix))] + { + let socket = std::net::UdpSocket::bind("127.0.0.1:0")?; + socket.set_nonblocking(true)?; + Ok(Self { + socket, + peer_addr: None, + peer_path: Some(peer_path), + bind_path: None, + }) + } } /// Anonymous pair for intra-process or fork-exec child signaling. pub fn pair() -> Result<(Self, Self)> { - let (s1, s2) = UnixDatagram::pair().context("UnixDatagram::pair failed")?; - s1.set_nonblocking(true)?; - s2.set_nonblocking(true)?; - Ok(( - Self { - socket: s1, - peer_path: None, - bind_path: None, - }, - Self { - socket: s2, - peer_path: None, - bind_path: None, - }, - )) + #[cfg(unix)] + { + let (s1, s2) = UnixDatagram::pair().context("UnixDatagram::pair failed")?; + s1.set_nonblocking(true)?; + s2.set_nonblocking(true)?; + Ok(( + Self { + socket: s1, + peer_path: None, + bind_path: None, + }, + Self { + socket: s2, + peer_path: None, + bind_path: None, + }, + )) + } + #[cfg(not(unix))] + { + let s1 = std::net::UdpSocket::bind("127.0.0.1:0")?; + let s2 = std::net::UdpSocket::bind("127.0.0.1:0")?; + let a1 = s1.local_addr()?; + let a2 = s2.local_addr()?; + s1.connect(a2)?; + s2.connect(a1)?; + Ok(( + Self { + socket: s1, + peer_addr: Some(a2), + peer_path: None, + bind_path: None, + }, + Self { + socket: s2, + peer_addr: Some(a1), + peer_path: None, + bind_path: None, + }, + )) + } } fn socket_path(ring_name: &str) -> PathBuf { @@ -380,11 +519,22 @@ impl ShmSignal { /// Send notification that a slot was updated. Non-blocking. pub fn notify(&self, slot_index: usize) -> Result<()> { let payload = (slot_index as u32).to_le_bytes(); + #[cfg(unix)] let sent = if let Some(ref peer) = self.peer_path { self.socket.send_to(&payload, peer) } else { self.socket.send(&payload) }; + #[cfg(not(unix))] + let sent = if self.peer_addr.is_some() { + self.socket.send(&payload) + } else if let Some(ref peer) = self.peer_path { + let text = std::fs::read_to_string(peer)?; + let addr: std::net::SocketAddr = text.trim().parse()?; + self.socket.send_to(&payload, addr) + } else { + self.socket.send(&payload) + }; match sent { Ok(4) => Ok(()), // Datagram wakeups are hints; a full queue already contains wakeups. @@ -397,36 +547,60 @@ impl ShmSignal { /// Wait without changing shared descriptor flags. Always recheck ring state /// after waiting: wakeups are hints, not the data/ownership protocol. pub fn wait_timeout(&self, timeout: std::time::Duration) -> Result> { - use std::os::fd::AsRawFd; - let mut descriptor = libc::pollfd { - fd: self.socket.as_raw_fd(), - events: libc::POLLIN, - revents: 0, - }; - // SAFETY: one initialized pollfd is writable for the duration of poll. - let result = unsafe { - libc::poll( - &mut descriptor, - 1, - timeout.as_millis().min(i32::MAX as u128) as i32, - ) - }; - if result < 0 { - let error = std::io::Error::last_os_error(); - if error.kind() == std::io::ErrorKind::Interrupted { + #[cfg(unix)] + { + use std::os::fd::AsRawFd; + let mut descriptor = libc::pollfd { + fd: self.socket.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + // SAFETY: one initialized pollfd is writable for the duration of poll. + let result = unsafe { + libc::poll( + &mut descriptor, + 1, + timeout.as_millis().min(i32::MAX as u128) as i32, + ) + }; + if result < 0 { + let error = std::io::Error::last_os_error(); + if error.kind() == std::io::ErrorKind::Interrupted { + return Ok(None); + } + return Err(error.into()); + } + if result == 0 { return Ok(None); } - return Err(error.into()); - } - if result == 0 { - return Ok(None); + let mut buf = [0u8; 4]; + match self.socket.recv(&mut buf) { + Ok(4) => Ok(Some(u32::from_le_bytes(buf) as usize)), + Ok(_) => Ok(None), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => Ok(None), + Err(e) => Err(e.into()), + } } - let mut buf = [0u8; 4]; - match self.socket.recv(&mut buf) { - Ok(4) => Ok(Some(u32::from_le_bytes(buf) as usize)), - Ok(_) => Ok(None), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => Ok(None), - Err(e) => Err(e.into()), + #[cfg(not(unix))] + { + self.socket + .set_read_timeout(Some(timeout.max(std::time::Duration::from_millis(1))))?; + let mut buf = [0u8; 4]; + match self.socket.recv(&mut buf) { + Ok(4) => Ok(Some(u32::from_le_bytes(buf) as usize)), + Ok(_) => Ok(None), + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::WouldBlock + | std::io::ErrorKind::TimedOut + | std::io::ErrorKind::Interrupted + ) => + { + Ok(None) + } + Err(e) => Err(e.into()), + } } } } diff --git a/crates/leio-harness/src/task.rs b/crates/leio-harness/src/task.rs index a68abfb..f88b2ba 100644 --- a/crates/leio-harness/src/task.rs +++ b/crates/leio-harness/src/task.rs @@ -7,6 +7,7 @@ use anyhow::{Context, Result, ensure}; use fs2::FileExt; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +#[cfg(unix)] use std::os::unix::{ ffi::OsStrExt, fs::{DirBuilderExt, OpenOptionsExt}, @@ -25,6 +26,7 @@ use std::{ }; static INTERRUPTED: AtomicBool = AtomicBool::new(false); +#[cfg(unix)] extern "C" fn interrupt(_: i32) { INTERRUPTED.store(true, Ordering::SeqCst); } @@ -105,14 +107,19 @@ fn directory(repo: &Path, id: &str) -> Result { Ok(dir) } fn lock(path: &Path) -> Result { - Ok(OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .mode(0o600) - .custom_flags(nix::libc::O_NOFOLLOW) - .open(path)?) + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + options.mode(0o600).custom_flags(nix::libc::O_NOFOLLOW); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); + } + Ok(options.open(path)?) } fn locked(path: &Path) -> Result { let file = lock(path)?; @@ -123,10 +130,11 @@ fn locked(path: &Path) -> Result { } } fn private_directory(path: &Path) -> Result<()> { - std::fs::DirBuilder::new() - .recursive(true) - .mode(0o700) - .create(path)?; + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + builder.mode(0o700); + builder.create(path)?; ensure!( std::fs::symlink_metadata(path)?.file_type().is_dir(), "sidecar directory must not be a symlink" @@ -159,11 +167,11 @@ impl Tracker { s.last_activity_at_ms = now(); s.last_activity = detail.to_owned(); let event = json!({"seq":s.sequence,"timestampMs":s.last_activity_at_ms,"kind":kind,"phase":s.phase,"state":s.state,"workerPid":s.worker_pid,"detail":detail}); - let mut file = OpenOptions::new() - .create(true) - .append(true) - .mode(0o600) - .open(self.dir.join("events.ndjson"))?; + let mut options = OpenOptions::new(); + options.create(true).append(true); + #[cfg(unix)] + options.mode(0o600); + let mut file = options.open(self.dir.join("events.ndjson"))?; serde_json::to_writer(&mut file, &event)?; file.write_all(b"\n")?; file.sync_all()?; @@ -241,8 +249,13 @@ pub fn submit( .output() .context("resolve Git checkout root")?; ensure!(top.status.success(), "task requires a Git repository"); - let top_bytes = top.stdout.strip_suffix(b"\n").unwrap_or(&top.stdout); - let checkout = Path::new(std::ffi::OsStr::from_bytes(top_bytes)).canonicalize()?; + #[cfg(unix)] + let checkout = { + let top_bytes = top.stdout.strip_suffix(b"\n").unwrap_or(&top.stdout); + Path::new(std::ffi::OsStr::from_bytes(top_bytes)).canonicalize()? + }; + #[cfg(not(unix))] + let checkout = Path::new(std::str::from_utf8(&top.stdout)?.trim()).canonicalize()?; ensure!( repo == checkout, "task repo must be the Git checkout root ({}); constrain module scope in the task instead of submitting a subdirectory", @@ -271,7 +284,10 @@ pub fn submit( private_directory(&runs(&repo))?; let id = process::unique_id(); let dir = runs(&repo).join(&id); + #[cfg(unix)] std::fs::DirBuilder::new().mode(0o700).create(&dir)?; + #[cfg(not(unix))] + std::fs::DirBuilder::new().create(&dir)?; let spec = TaskSpec { run_id: id.clone(), repo_root: repo.display().to_string(), @@ -316,11 +332,11 @@ pub fn submit( }), }; tracker.record("submitted", "explicit task submitted", |_| {})?; - let log = OpenOptions::new() - .create_new(true) - .write(true) - .mode(0o600) - .open(dir.join("supervisor.log"))?; + let mut log_options = OpenOptions::new(); + log_options.create_new(true).write(true); + #[cfg(unix)] + log_options.mode(0o600); + let log = log_options.open(dir.join("supervisor.log"))?; let mut command = Command::new(std::env::current_exe()?); command .args(["task", "execute", "--repo"]) @@ -331,12 +347,20 @@ pub fn submit( .stderr(log); // Detach from the calling coding host's process group. Only the task // supervisor owns worker cancellation, never the MCP request lifetime. + #[cfg(unix)] unsafe { command.pre_exec(|| { nix::unistd::setsid().map_err(std::io::Error::from)?; Ok(()) }); } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW); + } match command.spawn() { Ok(mut child) => { std::thread::spawn(move || { @@ -429,14 +453,17 @@ pub fn execute(repo: &Path, id: &str) -> Result<()> { state: Mutex::new(s), }); INTERRUPTED.store(false, Ordering::SeqCst); - let signal = nix::sys::signal::SigAction::new( - nix::sys::signal::SigHandler::Handler(interrupt), - nix::sys::signal::SaFlags::empty(), - nix::sys::signal::SigSet::empty(), - ); - unsafe { - nix::sys::signal::sigaction(nix::sys::signal::Signal::SIGTERM, &signal)?; - nix::sys::signal::sigaction(nix::sys::signal::Signal::SIGINT, &signal)?; + #[cfg(unix)] + { + let signal = nix::sys::signal::SigAction::new( + nix::sys::signal::SigHandler::Handler(interrupt), + nix::sys::signal::SaFlags::empty(), + nix::sys::signal::SigSet::empty(), + ); + unsafe { + nix::sys::signal::sigaction(nix::sys::signal::Signal::SIGTERM, &signal)?; + nix::sys::signal::sigaction(nix::sys::signal::Signal::SIGINT, &signal)?; + } } if tracker.canceled() { return tracker.finish("cancelled", Some("cancelled before dispatch".to_owned())); @@ -621,16 +648,24 @@ fn collect(spec: &TaskSpec, dir: &Path, tracker: &Tracker) -> Result<()> { } let target = dir.join("untracked").join(relative); private_directory(target.parent().context("untracked parent missing")?)?; - let mut input = OpenOptions::new() - .read(true) - .custom_flags(nix::libc::O_NOFOLLOW) + let mut input_options = OpenOptions::new(); + input_options.read(true); + #[cfg(unix)] + input_options.custom_flags(nix::libc::O_NOFOLLOW); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + input_options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut input = input_options .open(source)? .take(budget.min(4 * 1024 * 1024)); - let mut output = OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(&target)?; + let mut output_options = OpenOptions::new(); + output_options.write(true).create_new(true); + #[cfg(unix)] + output_options.mode(0o600); + let mut output = output_options.open(&target)?; let size = std::io::copy(&mut input, &mut output)?; output.sync_all()?; budget -= size; @@ -747,13 +782,17 @@ pub fn cancel(repo: &Path, id: &str) -> Result { let dir = directory(&repo, id)?; let current = inspect(&repo, id)?; if !terminal(current["state"].as_str().unwrap_or("")) { - let mut file = OpenOptions::new() - .create(true) - .write(true) - .truncate(true) - .mode(0o600) - .custom_flags(nix::libc::O_NOFOLLOW) - .open(dir.join("cancel.request"))?; + let mut options = OpenOptions::new(); + options.create(true).write(true).truncate(true); + #[cfg(unix)] + options.mode(0o600).custom_flags(nix::libc::O_NOFOLLOW); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut file = options.open(dir.join("cancel.request"))?; writeln!(file, "{}", now())?; file.sync_all()?; } diff --git a/crates/leio-harness/src/workflow.rs b/crates/leio-harness/src/workflow.rs index 88891fb..61ea134 100644 --- a/crates/leio-harness/src/workflow.rs +++ b/crates/leio-harness/src/workflow.rs @@ -94,6 +94,7 @@ fn save(dir: &Path, state: &Workflow) -> Result<()> { file.write_all(&serde_json::to_vec_pretty(state)?)?; file.sync_all()?; fs::rename(dir.join("state.jsonld.tmp"), dir.join("state.jsonld"))?; + #[cfg(unix)] fs::File::open(dir)?.sync_all()?; Ok(()) } diff --git a/crates/leio-knowledge-core/Cargo.toml b/crates/leio-knowledge-core/Cargo.toml index 3533298..d9d9f5b 100644 --- a/crates/leio-knowledge-core/Cargo.toml +++ b/crates/leio-knowledge-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "leio-knowledge-core" -version = "2.6.6" +version = "2.6.7" edition = "2024" license = "MIT OR Apache-2.0" description = "In-memory formal knowledge store: Oxigraph SPARQL with anchored-or-refuse envelopes" diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md index 58573bc..81768ba 100644 --- a/docs/BENCHMARKS.md +++ b/docs/BENCHMARKS.md @@ -8,7 +8,7 @@ Measured **9 September 2026**, Apple M1, macOS 26.5.2, release binary `2.6.2 (377ee12faf61, clean)`, against source revision [`377ee12`](https://github.com/josaum/leio-code/tree/377ee12faf616acb9f84688de867097579c74df2). [Machine-readable results](../benchmarks/public-results.json). -The current crate is 2.6.6. This page is the 2.6.2 receipt; it was not re-run +The current crate is 2.6.7. This page is the 2.6.2 receipt; it was not re-run for that release. ## Multi-step investigations through stdio MCP diff --git a/docs/RELEASE-CHECKLIST.md b/docs/RELEASE-CHECKLIST.md index 2357bf6..362771e 100644 --- a/docs/RELEASE-CHECKLIST.md +++ b/docs/RELEASE-CHECKLIST.md @@ -20,9 +20,10 @@ leio-code --version ## GitHub Release binaries `.github/workflows/binary-release.yml` builds `leio-code-linux-amd64`, -`leio-code-darwin-arm64`, and `leio-code-darwin-amd64`, plus the matching -harness binaries, on tag `leio-code-plugin-v*`. Current release: -[`leio-code-plugin-v2.6.6`](https://github.com/josaum/leio-code/releases/tag/leio-code-plugin-v2.6.6). +`leio-code-darwin-arm64`, `leio-code-darwin-amd64`, and +`leio-code-windows-amd64.exe`, plus the matching harness binaries, on tag +`leio-code-plugin-v*`. Current release: +[`leio-code-plugin-v2.6.7`](https://github.com/josaum/leio-code/releases/tag/leio-code-plugin-v2.6.7). ## Homebrew diff --git a/docs/install-stdio.md b/docs/install-stdio.md index 52a5f0f..aa7f5f9 100644 --- a/docs/install-stdio.md +++ b/docs/install-stdio.md @@ -12,7 +12,7 @@ The Python wheel and the Node package install `leio-code`, `leio-harness`, and the stdio server `leio-mcp`. They register that server with harnesses already on the machine. Any other MCP host launches `leio-mcp`. `cargo binstall leio-code` installs Code. Release binaries cover macOS arm64, -macOS x64, and Linux x64. `scripts/build_packages.py` builds the wheel and the +macOS x64, Linux x64, and Windows x64. `scripts/build_packages.py` builds the wheel and the npm package from the GitHub release assets. The steps below are for changing Leio itself. A browser-only chat cannot diff --git a/gemini-extension.json b/gemini-extension.json index 5e5018b..b3267f5 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "leio-code", - "version": "2.6.6", + "version": "2.6.7", "description": "Agent-first code intelligence for the workspace. Index, find, graph, doctors, local wiki, SPARQL-gated explain, lattice nav, JSON-LD provenance.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/manifest.json b/manifest.json index dfc4b34..144bd4b 100644 --- a/manifest.json +++ b/manifest.json @@ -2,7 +2,7 @@ "manifest_version": "0.3", "name": "leio-code", "display_name": "LEIO Code", - "version": "2.6.6", + "version": "2.6.7", "description": "Agent-first code intelligence. Index, find, graph, doctors, SPARQL knowledge, lattice nav over one repo_root.", "author": { "name": "LEIO Code contributors", diff --git a/mcp/install-binary.mjs b/mcp/install-binary.mjs index 9fb7c73..c6b0192 100644 --- a/mcp/install-binary.mjs +++ b/mcp/install-binary.mjs @@ -28,6 +28,7 @@ const ASSETS = { "linux-x64": "leio-code-linux-amd64", "darwin-arm64": "leio-code-darwin-arm64", "darwin-x64": "leio-code-darwin-amd64", + "win32-x64": "leio-code-windows-amd64.exe", }; function hint(message) { diff --git a/mcp/package-lock.json b/mcp/package-lock.json index 8f5580c..e49eb09 100644 --- a/mcp/package-lock.json +++ b/mcp/package-lock.json @@ -1,12 +1,12 @@ { "name": "@leio/leio-code-mcp", - "version": "2.6.6", + "version": "2.6.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@leio/leio-code-mcp", - "version": "2.6.6", + "version": "2.6.7", "hasInstallScript": true, "license": "MIT OR Apache-2.0", "dependencies": { diff --git a/mcp/package.json b/mcp/package.json index d9fda22..ac7c411 100644 --- a/mcp/package.json +++ b/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@leio/leio-code-mcp", - "version": "2.6.6", + "version": "2.6.7", "private": true, "type": "module", "description": "Evidence-first MCP wrapper for the LEIO Code CLI", diff --git a/mcp/resolve-binary.test.js b/mcp/resolve-binary.test.js index 1acf2a4..2bef559 100644 --- a/mcp/resolve-binary.test.js +++ b/mcp/resolve-binary.test.js @@ -283,6 +283,13 @@ test("isTrustedEnvBinary rejects directories and wrong basenames", () => { }), true, ); + assert.equal( + isTrustedEnvBinary("/opt/explicit/leio-code.exe", { + exists: () => true, + stat: () => ({ isFile: () => true, isDirectory: () => false }), + }), + true, + ); assert.equal( isTrustedEnvBinary("/opt/explicit/leio-code", { exists: () => true, diff --git a/packaging/npm/README.md b/packaging/npm/README.md index 1b4d17b..bb7e7bb 100644 --- a/packaging/npm/README.md +++ b/packaging/npm/README.md @@ -8,4 +8,4 @@ leio-code --repo /absolute/path/to/repo context "fix the payment validation" leio-harness workflow --repo /absolute/path/to/repo --dir /tmp/my-run --action show ``` -Release binaries cover macOS arm64, macOS x64, and Linux x64. +Release binaries cover macOS arm64, macOS x64, Linux x64, and Windows x64. diff --git a/packaging/npm/bin/leio-code.js b/packaging/npm/bin/leio-code.js index 40a1be4..77a84b5 100644 --- a/packaging/npm/bin/leio-code.js +++ b/packaging/npm/bin/leio-code.js @@ -3,7 +3,8 @@ import { execFileSync } from "node:child_process"; import path from "node:path"; import { fileURLToPath } from "node:url"; -const binary = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "vendor", "leio-code"); +const ext = process.platform === "win32" ? ".exe" : ""; +const binary = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "vendor", `leio-code${ext}`); try { execFileSync(binary, process.argv.slice(2), { stdio: "inherit" }); } catch (error) { diff --git a/packaging/npm/bin/leio-harness.js b/packaging/npm/bin/leio-harness.js index 4035c05..4165e2e 100644 --- a/packaging/npm/bin/leio-harness.js +++ b/packaging/npm/bin/leio-harness.js @@ -3,7 +3,8 @@ import { execFileSync } from "node:child_process"; import path from "node:path"; import { fileURLToPath } from "node:url"; -const binary = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "vendor", "leio-harness"); +const ext = process.platform === "win32" ? ".exe" : ""; +const binary = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "vendor", `leio-harness${ext}`); try { execFileSync(binary, process.argv.slice(2), { stdio: "inherit" }); } catch (error) { diff --git a/packaging/npm/bin/leio-mcp.js b/packaging/npm/bin/leio-mcp.js index 671162f..cbcf45a 100644 --- a/packaging/npm/bin/leio-mcp.js +++ b/packaging/npm/bin/leio-mcp.js @@ -16,14 +16,19 @@ const server = firstExisting([ path.join(root, "mcp", "index.js"), path.join(here, "index.js"), ]); +const ext = process.platform === "win32" ? ".exe" : ""; const codeBin = firstExisting([ process.env.LEIO_CODE_BIN, + path.join(root, "vendor", `leio-code${ext}`), path.join(root, "vendor", "leio-code"), + path.join(root, "bin", `leio-code${ext}`), path.join(root, "bin", "leio-code"), ].filter(Boolean)); const harnessBin = firstExisting([ process.env.LEIO_HARNESS_BIN, + path.join(root, "vendor", `leio-harness${ext}`), path.join(root, "vendor", "leio-harness"), + path.join(root, "bin", `leio-harness${ext}`), path.join(root, "bin", "leio-harness"), ].filter(Boolean)); @@ -41,6 +46,6 @@ const child = spawn(process.execPath, [server], { }, }); child.on("exit", (code, signal) => { - if (signal) process.kill(process.pid, signal); + if (signal && process.platform !== "win32") process.kill(process.pid, signal); process.exit(code ?? 1); }); diff --git a/packaging/npm/install.js b/packaging/npm/install.js index dd380e1..2e8ffff 100644 --- a/packaging/npm/install.js +++ b/packaging/npm/install.js @@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url"; import { applyRegistration } from "../register-mcp.js"; const root = path.dirname(fileURLToPath(import.meta.url)); -const version = "2.6.6"; +const version = "2.6.7"; const tag = `leio-code-plugin-v${version}`; const repo = "josaum/leio-code"; @@ -13,6 +13,7 @@ const assets = { "darwin-arm64": ["leio-code-darwin-arm64", "leio-code-darwin-arm64-harness"], "darwin-x64": ["leio-code-darwin-amd64", "leio-code-darwin-amd64-harness"], "linux-x64": ["leio-code-linux-amd64", "leio-code-linux-amd64-harness"], + "win32-x64": ["leio-code-windows-amd64.exe", "leio-code-windows-amd64-harness.exe"], }; const key = `${process.platform}-${process.arch}`; @@ -24,10 +25,11 @@ if (!pair) { const vendor = path.join(root, "vendor"); mkdirSync(vendor, { recursive: true }); +const ext = process.platform === "win32" ? ".exe" : ""; for (const [asset, name] of [ - [pair[0], "leio-code"], - [pair[1], "leio-harness"], + [pair[0], `leio-code${ext}`], + [pair[1], `leio-harness${ext}`], ]) { const url = `https://github.com/${repo}/releases/download/${tag}/${asset}`; const response = await fetch(url, { redirect: "follow" }); @@ -37,7 +39,9 @@ for (const [asset, name] of [ } const dest = path.join(vendor, name); writeFileSync(dest, Buffer.from(await response.arrayBuffer())); - chmodSync(dest, 0o755); + if (process.platform !== "win32") { + chmodSync(dest, 0o755); + } } if (process.env.LEIO_MCP_SKIP_REGISTER !== "1") { diff --git a/packaging/npm/package.json b/packaging/npm/package.json index ffeab73..6ffe5b2 100644 --- a/packaging/npm/package.json +++ b/packaging/npm/package.json @@ -1,6 +1,6 @@ { "name": "leio-code", - "version": "2.6.6", + "version": "2.6.7", "description": "Prebuilt Leio Code and Leio Harness", "license": "MIT OR Apache-2.0", "repository": { diff --git a/packaging/python/README.md b/packaging/python/README.md index 33efe70..6a39a67 100644 --- a/packaging/python/README.md +++ b/packaging/python/README.md @@ -10,4 +10,4 @@ leio-harness workflow --repo /absolute/path/to/repo --dir /tmp/my-run --action s Each command reads one repository. Pass `--repo` or, for the MCP server, `repo_root`. -Release binaries cover macOS arm64, macOS x64, and Linux x64. +Release binaries cover macOS arm64, macOS x64, Linux x64, and Windows x64. diff --git a/packaging/python/pyproject.toml b/packaging/python/pyproject.toml index a63be18..24ef1ce 100644 --- a/packaging/python/pyproject.toml +++ b/packaging/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "leio-code" -version = "2.6.6" +version = "2.6.7" description = "Prebuilt Leio Code and Leio Harness" readme = "README.md" requires-python = ">=3.9" @@ -20,7 +20,7 @@ classifiers = [ [project.urls] Homepage = "https://github.com/josaum/leio-code" Repository = "https://github.com/josaum/leio-code" -Changelog = "https://github.com/josaum/leio-code/releases/tag/leio-code-plugin-v2.6.6" +Changelog = "https://github.com/josaum/leio-code/releases/tag/leio-code-plugin-v2.6.7" [project.scripts] leio-code = "leio_code._exec:code" diff --git a/packaging/python/src/leio_code/__init__.py b/packaging/python/src/leio_code/__init__.py index 609b3eb..30c7294 100644 --- a/packaging/python/src/leio_code/__init__.py +++ b/packaging/python/src/leio_code/__init__.py @@ -1,3 +1,3 @@ """Prebuilt Leio Code and Leio Harness.""" -__version__ = "2.6.6" +__version__ = "2.6.7" diff --git a/packaging/python/src/leio_code/_exec.py b/packaging/python/src/leio_code/_exec.py index e92e081..ca7806e 100644 --- a/packaging/python/src/leio_code/_exec.py +++ b/packaging/python/src/leio_code/_exec.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +import subprocess import sys from pathlib import Path @@ -24,8 +25,15 @@ def _register() -> None: def _exec(name: str) -> None: - binary = Path(__file__).resolve().parent / "bin" / name + bindir = Path(__file__).resolve().parent / "bin" + binary = bindir / (f"{name}.exe" if sys.platform == "win32" else name) if not binary.is_file(): - sys.stderr.write(f"leio-code package is missing {binary}\n") - raise SystemExit(1) + fallback = bindir / name + if fallback.is_file(): + binary = fallback + else: + sys.stderr.write(f"leio-code package is missing {binary}\n") + raise SystemExit(1) + if sys.platform == "win32": + raise SystemExit(subprocess.run([str(binary), *sys.argv[1:]]).returncode) os.execv(binary, [str(binary), *sys.argv[1:]]) diff --git a/packaging/python/src/leio_code/mcp.py b/packaging/python/src/leio_code/mcp.py index a0d2e12..84bf54d 100644 --- a/packaging/python/src/leio_code/mcp.py +++ b/packaging/python/src/leio_code/mcp.py @@ -4,6 +4,7 @@ import os import shutil +import subprocess import sys from pathlib import Path @@ -19,4 +20,6 @@ def main() -> None: ensure() if "--register" in sys.argv[1:]: return + if sys.platform == "win32": + raise SystemExit(subprocess.run([node, str(launcher)]).returncode) os.execv(node, [node, str(launcher)]) diff --git a/packaging/register-mcp.js b/packaging/register-mcp.js index e9b1807..9ac369d 100644 --- a/packaging/register-mcp.js +++ b/packaging/register-mcp.js @@ -27,6 +27,9 @@ const HOSTS = [ { dir: "Library/Application Support/Claude", file: "claude_desktop_config.json", kind: "mcpServers" }, { dir: "Library/Application Support/Code/User", file: "mcp.json", kind: "servers" }, { dir: "Library/Application Support/Cursor/User", file: "mcp.json", kind: "mcpServers" }, + { dir: "AppData/Roaming/Claude", file: "claude_desktop_config.json", kind: "mcpServers" }, + { dir: "AppData/Roaming/Code/User", file: "mcp.json", kind: "servers" }, + { dir: "AppData/Roaming/Cursor/User", file: "mcp.json", kind: "mcpServers" }, { dir: ".config/Code/User", file: "mcp.json", kind: "servers" }, ]; diff --git a/packaging/register-mcp.test.js b/packaging/register-mcp.test.js index 9f349c4..ba05f00 100644 --- a/packaging/register-mcp.test.js +++ b/packaging/register-mcp.test.js @@ -38,6 +38,11 @@ test("registration updates every detected harness and keeps other servers", () = path.join(home, "Library/Application Support/Code/User/mcp.json"), JSON.stringify({ servers: { editor: { command: "editor" } } }), ); + fs.mkdirSync(path.join(home, "AppData/Roaming/Code/User"), { recursive: true }); + fs.writeFileSync( + path.join(home, "AppData/Roaming/Code/User/mcp.json"), + JSON.stringify({ servers: { winEditor: { command: "win-editor" } } }), + ); fs.mkdirSync(path.join(home, ".vscode")); fs.mkdirSync(path.join(home, ".gemini/antigravity"), { recursive: true }); fs.writeFileSync( @@ -75,6 +80,13 @@ test("registration updates every detected harness and keeps other servers", () = assert.equal(code.servers["leio-code"].type, "stdio"); assert.equal(code.servers["leio-code"].command, spec.command); + const winCode = JSON.parse( + fs.readFileSync(path.join(home, "AppData/Roaming/Code/User/mcp.json"), "utf8"), + ); + assert.equal(winCode.servers.winEditor.command, "win-editor"); + assert.equal(winCode.servers["leio-code"].type, "stdio"); + assert.equal(winCode.servers["leio-code"].command, spec.command); + const gemini = JSON.parse(fs.readFileSync(path.join(home, ".gemini/settings.json"), "utf8")); assert.deepEqual(gemini.mcpServers["leio-code"], spec); const antigravity = JSON.parse( diff --git a/schema/leio-code-mcp-service-descriptor.json b/schema/leio-code-mcp-service-descriptor.json index 97765d7..d130a76 100644 --- a/schema/leio-code-mcp-service-descriptor.json +++ b/schema/leio-code-mcp-service-descriptor.json @@ -8,7 +8,7 @@ "serverInfo": { "name": "leio-code", "title": "LEIO Code", - "version": "2.6.6", + "version": "2.6.7", "description": "Evidence-first repository intelligence over stdio: status, capabilities, context, find, explain, graph, doctors, formal SPARQL, and lattice navigation. One absolute repo_root per call.", "websiteUrl": "https://github.com/josaum/leio-code", "icons": [ @@ -3374,6 +3374,7 @@ "type": "string", "enum": [ "symbol", + "text", "env-var", "redis-key", "deploy-target", @@ -3806,6 +3807,7 @@ "kind": { "type": "string", "enum": [ + "symbol", "deploy-target", "env-var", "redis-key", @@ -12693,6 +12695,7 @@ "type": "string", "enum": [ "symbol", + "text", "env-var", "redis-key", "deploy-target", @@ -12769,6 +12772,7 @@ "type": "string", "enum": [ "symbol", + "text", "env-var", "redis-key", "deploy-target", @@ -13206,6 +13210,7 @@ "name": "kind", "type": "string", "enum": [ + "symbol", "deploy-target", "env-var", "redis-key", @@ -13269,6 +13274,7 @@ "kind": { "type": "string", "enum": [ + "symbol", "deploy-target", "env-var", "redis-key", diff --git a/scripts/build_packages.py b/scripts/build_packages.py index ec39e27..795460f 100644 --- a/scripts/build_packages.py +++ b/scripts/build_packages.py @@ -26,6 +26,8 @@ "envelope.js", "guide.js", "workflow.js", + "harness-tasks.js", + "harness-review.js", "mcp-spec-2025-11-25.js", "output-schemas.js", "install-root.js", @@ -45,7 +47,7 @@ def server_modules() -> Path: shutil.rmtree(cached) cached.mkdir(parents=True) (cached / "package.json").write_text( - '{"name":"leio-code-server","private":true,"version":"2.6.6"}\n', + '{"name":"leio-code-server","private":true,"version":"2.6.7"}\n', encoding="utf-8", ) subprocess.run( @@ -63,13 +65,13 @@ def stage_server(dest: Path, *, with_modules: bool = False) -> None: for name in SERVER_FILES: shutil.copy2(ROOT / "mcp" / name, dest / name) (dest / "package.json").write_text( - '{"name":"leio-code-server","private":true,"type":"module","version":"2.6.6"}\n', + '{"name":"leio-code-server","private":true,"type":"module","version":"2.6.7"}\n', encoding="utf-8", ) shutil.copy2(ROOT / "packaging" / "npm" / "bin" / "leio-mcp.js", dest / "leio-mcp.js") if with_modules: shutil.copytree(server_modules(), dest / "node_modules") -VERSION = "2.6.6" +VERSION = "2.6.7" TAG = f"leio-code-plugin-v{VERSION}" REPO = "josaum/leio-code" @@ -89,6 +91,11 @@ def stage_server(dest: Path, *, with_modules: bool = False) -> None: "harness": "leio-code-linux-amd64-harness", "tag": "py3-none-manylinux_2_34_x86_64", }, + { + "code": "leio-code-windows-amd64.exe", + "harness": "leio-code-windows-amd64-harness.exe", + "tag": "py3-none-win_amd64", + }, ) @@ -133,8 +140,14 @@ def retag_wheel(source: Path, tag: str) -> Path: wheel_text = re.sub(r"^Tag: .*$", f"Tag: {tag}", wheel_text, flags=re.M) wheel_text = wheel_text.replace("Root-Is-Purelib: true", "Root-Is-Purelib: false") files[wheel_name] = wheel_text.encode() - for name in ("leio_code/bin/leio-code", "leio_code/bin/leio-harness"): - modes[name] = 0o100755 + for name in ( + "leio_code/bin/leio-code", + "leio_code/bin/leio-harness", + "leio_code/bin/leio-code.exe", + "leio_code/bin/leio-harness.exe", + ): + if name in files: + modes[name] = 0o100755 files["leio_register.pth"] = ( b"import leio_code.register; leio_code.register.ensure()\n" ) @@ -170,10 +183,13 @@ def build_wheel(platform: dict[str, str]) -> Path: ) bindir = stage / "src" / "leio_code" / "bin" bindir.mkdir(parents=True) - shutil.copy2(code, bindir / "leio-code") - shutil.copy2(harness, bindir / "leio-harness") - (bindir / "leio-code").chmod(0o755) - (bindir / "leio-harness").chmod(0o755) + ext = ".exe" if platform["code"].endswith(".exe") else "" + code_dest = bindir / f"leio-code{ext}" + harness_dest = bindir / f"leio-harness{ext}" + shutil.copy2(code, code_dest) + shutil.copy2(harness, harness_dest) + code_dest.chmod(0o755) + harness_dest.chmod(0o755) mcp_dir = stage / "src" / "leio_code" / "mcp" stage_server(mcp_dir, with_modules=True) shutil.copy2(ROOT / "packaging" / "register-mcp.js", stage / "src" / "leio_code" / "register-mcp.js") diff --git a/skills/leio-bench/SKILL.md b/skills/leio-bench/SKILL.md index 6f79091..0026b20 100644 --- a/skills/leio-bench/SKILL.md +++ b/skills/leio-bench/SKILL.md @@ -5,7 +5,7 @@ license: MIT OR Apache-2.0 compatibility: Requires python3, leio-harness, and a clean git checkout. metadata: author: leio-code - version: "2.6.6" + version: "2.6.7" --- # LEIO Bench — model-swept golden tasks diff --git a/skills/leio-code-apps-sdk/SKILL.md b/skills/leio-code-apps-sdk/SKILL.md index f2a74de..b40e03a 100644 --- a/skills/leio-code-apps-sdk/SKILL.md +++ b/skills/leio-code-apps-sdk/SKILL.md @@ -5,7 +5,7 @@ license: MIT OR Apache-2.0 compatibility: Requires ChatGPT Developer Mode or remote HTTP MCP connection to the LEIO Code Apps SDK server. metadata: author: leio-code - version: "2.6.6" + version: "2.6.7" --- # LEIO Code — Apps SDK (ChatGPT) diff --git a/skills/leio-code/SKILL.md b/skills/leio-code/SKILL.md index 30d8a08..be5787a 100644 --- a/skills/leio-code/SKILL.md +++ b/skills/leio-code/SKILL.md @@ -5,7 +5,7 @@ license: MIT OR Apache-2.0 compatibility: Requires leio-code CLI or leio-code stdio MCP server with local repository filesystem access. metadata: author: leio-code - version: "2.6.6" + version: "2.6.7" --- # LEIO Code diff --git a/skills/leio-day/SKILL.md b/skills/leio-day/SKILL.md index 9f925e0..f161544 100644 --- a/skills/leio-day/SKILL.md +++ b/skills/leio-day/SKILL.md @@ -5,7 +5,7 @@ license: MIT OR Apache-2.0 compatibility: Requires leio-code, leio-harness, and a clean git repository. metadata: author: leio-code - version: "2.6.6" + version: "2.6.7" --- # LEIO Day — multi-model orchestration diff --git a/skills/leio-trio/SKILL.md b/skills/leio-trio/SKILL.md index 7e55753..47d29ec 100644 --- a/skills/leio-trio/SKILL.md +++ b/skills/leio-trio/SKILL.md @@ -5,7 +5,7 @@ license: MIT OR Apache-2.0 compatibility: Requires python3, leio-code, and leio-harness. metadata: author: leio-code - version: "2.6.6" + version: "2.6.7" --- # LEIO Trio — three sovereignties, one evidence chain diff --git a/src/doctors/env_contract.rs b/src/doctors/env_contract.rs index 40c0aba..c201b49 100644 --- a/src/doctors/env_contract.rs +++ b/src/doctors/env_contract.rs @@ -58,8 +58,11 @@ impl Doctor for EnvContractDoctor { /// declaration is normal, so they are never flagged. The list is intentionally /// small; repo-specific exemptions belong in `[doctors.env_contract] allow`. const PLATFORM_VARS: &[&str] = &[ - // POSIX session basics. + // POSIX / Windows session basics. "HOME", + "USERPROFILE", + "APPDATA", + "LOCALAPPDATA", "PATH", "PWD", "USER", diff --git a/src/doctors/local_packs.rs b/src/doctors/local_packs.rs index 411e189..6d6490e 100644 --- a/src/doctors/local_packs.rs +++ b/src/doctors/local_packs.rs @@ -2636,8 +2636,8 @@ fn read_regular_file_no_follow( } #[cfg(not(unix))] { - let _ = (root, relative, max_bytes); - Err(NoFollowError::Unreadable) + let file = open_regular_file_handle_no_follow(root, relative)?; + read_bounded_utf8(file, max_bytes) } } @@ -2652,11 +2652,36 @@ fn read_regular_file_bytes_no_follow( } #[cfg(not(unix))] { - let _ = (root, relative, max_bytes); - Err(NoFollowError::Unreadable) + let file = open_regular_file_handle_no_follow(root, relative)?; + read_bounded_bytes(file, max_bytes) } } +#[cfg(not(unix))] +fn open_regular_file_handle_no_follow(root: &Path, relative: &Path) -> Result { + let metadata = open_existing_no_follow(root, relative)?.ok_or(NoFollowError::Missing)?; + if !metadata.is_file() { + return Err(NoFollowError::Unreadable); + } + let full_path = root.join(relative); + let mut options = fs::OpenOptions::new(); + options.read(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); + } + let file = options + .open(&full_path) + .map_err(|_| NoFollowError::Unreadable)?; + let opened_meta = file.metadata().map_err(|_| NoFollowError::Unreadable)?; + if !opened_meta.is_file() || opened_meta.file_type().is_symlink() { + return Err(NoFollowError::Unreadable); + } + Ok(file) +} + #[cfg(unix)] fn open_regular_file_no_follow( root: &Path, diff --git a/src/doctors/native.rs b/src/doctors/native.rs index 9f29989..a1c278e 100644 --- a/src/doctors/native.rs +++ b/src/doctors/native.rs @@ -151,7 +151,9 @@ fn state_dir() -> Result { if let Some(path) = std::env::var_os("LEIO_DOCTOR_TRUST_DIR") { return Ok(PathBuf::from(path)); } - let home = std::env::var_os("HOME").context("HOME unavailable for local doctor trust")?; + let home = std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .context("HOME unavailable for local doctor trust")?; Ok(PathBuf::from(home).join(".local/share/leio-code/doctor-packs")) } fn trust_path(root: &Path) -> Result { @@ -404,7 +406,7 @@ fn invoke( .context("native doctor stdout unavailable")?; let mut guard = Guard(child); #[cfg(unix)] - { + let (bytes, exit) = { use std::os::fd::AsRawFd; let fd = stdout.as_raw_fd(); let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; @@ -412,43 +414,76 @@ fn invoke( flags >= 0 && unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } >= 0, "could not bound native doctor output" ); - } - #[cfg(not(unix))] - { - anyhow::bail!("native doctors currently require a Unix host"); - } - let deadline = Instant::now() + Duration::from_secs(60); - let mut bytes = Vec::new(); - let mut block = [0u8; 16384]; - let mut exit = None; - loop { - ensure!(Instant::now() < deadline, "native doctor deadline exceeded"); - match stdout.read(&mut block) { - Ok(0) => { - if exit.is_some() { - break; + let deadline = Instant::now() + Duration::from_secs(60); + let mut bytes = Vec::new(); + let mut block = [0u8; 16384]; + let mut exit = None; + loop { + ensure!(Instant::now() < deadline, "native doctor deadline exceeded"); + match stdout.read(&mut block) { + Ok(0) => { + if exit.is_some() { + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + Ok(n) => { + ensure!( + bytes.len() + n <= MAX_OUTPUT, + "native doctor output limit exceeded" + ); + bytes.extend_from_slice(&block[..n]); } - std::thread::sleep(Duration::from_millis(5)); + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + if exit.is_some() { + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + Err(e) => return Err(e.into()), + } + if exit.is_none() { + exit = guard.0.try_wait()?; } - Ok(n) => { + } + (bytes, exit) + }; + #[cfg(not(unix))] + let (bytes, exit) = { + let (tx, rx) = std::sync::mpsc::sync_channel(1); + std::thread::spawn(move || { + let mut buf = Vec::new(); + let res = (&mut stdout) + .take((MAX_OUTPUT as u64).saturating_add(1)) + .read_to_end(&mut buf) + .map(|_| buf); + let _ = tx.send(res); + }); + let deadline = Instant::now() + Duration::from_secs(60); + let mut exit = None; + let mut bytes = None; + loop { + ensure!(Instant::now() < deadline, "native doctor deadline exceeded"); + if bytes.is_none() + && let Ok(res) = rx.try_recv() + { + let buf = res?; ensure!( - bytes.len() + n <= MAX_OUTPUT, + buf.len() <= MAX_OUTPUT, "native doctor output limit exceeded" ); - bytes.extend_from_slice(&block[..n]); + bytes = Some(buf); } - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { - if exit.is_some() { - break; - } - std::thread::sleep(Duration::from_millis(5)); + if exit.is_none() { + exit = guard.0.try_wait()?; } - Err(e) => return Err(e.into()), - } - if exit.is_none() { - exit = guard.0.try_wait()?; + if exit.is_some() && bytes.is_some() { + break; + } + std::thread::sleep(Duration::from_millis(5)); } - } + (bytes.unwrap_or_default(), exit) + }; ensure!( exit.is_some_and(|status| status.success()), "native doctor process failed" diff --git a/tools/leio-self-doctors/Cargo.lock b/tools/leio-self-doctors/Cargo.lock index 9991933..872cd68 100644 --- a/tools/leio-self-doctors/Cargo.lock +++ b/tools/leio-self-doctors/Cargo.lock @@ -898,8 +898,9 @@ dependencies = [ [[package]] name = "leio-code" -version = "2.6.5" +version = "2.6.7" dependencies = [ + "aho-corasick", "anyhow", "arrow-array", "arrow-buffer", @@ -946,7 +947,7 @@ dependencies = [ [[package]] name = "leio-knowledge-core" -version = "2.6.5" +version = "2.6.7" dependencies = [ "anyhow", "oxigraph",