diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fced6290..332c7d3d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,9 @@ on: tags: ["v*", "wp-*"] pull_request: +permissions: + contents: read + jobs: check: runs-on: macos-latest # the service is macOS-only (launchd); the toolchain comes from rust-toolchain.toml diff --git a/Cargo.toml b/Cargo.toml index b4e497ee..a11e8cfa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,3 +5,6 @@ members = ["proto", "appd", "agentcore", "window", "helper", "native"] [workspace.package] edition = "2024" version = "0.1.0" + +[workspace.lints.clippy] +disallowed_methods = "deny" diff --git a/agentcore/Cargo.toml b/agentcore/Cargo.toml index 2c3b7160..7dd892bd 100644 --- a/agentcore/Cargo.toml +++ b/agentcore/Cargo.toml @@ -9,3 +9,6 @@ proto = { path = "../proto" } serde = { version = "1", features = ["derive"] } serde_json = "1" ureq = "3" + +[lints] +workspace = true diff --git a/agentcore/src/acp.rs b/agentcore/src/acp.rs index bf999020..a5fb1441 100644 --- a/agentcore/src/acp.rs +++ b/agentcore/src/acp.rs @@ -89,6 +89,8 @@ fn out(event: &Event) { // SAFETY: a plain signal to our own child. unsafe { libc::kill(pid, libc::SIGKILL) }; } + // The service stdout pipe is gone; abort immediately after killing the child agent. + #[allow(clippy::disallowed_methods)] std::process::exit(1); } } diff --git a/agentcore/src/main.rs b/agentcore/src/main.rs index b0c46b33..80f24d24 100644 --- a/agentcore/src/main.rs +++ b/agentcore/src/main.rs @@ -29,6 +29,7 @@ impl Out { if let Err(e) = proto::write_frame(&mut *lock(&self.0), event, MAX_EVENT_FRAME) { // The service reads our output; without it there is nothing left to do. eprintln!("cannot send an event: {e}"); + #[allow(clippy::disallowed_methods)] std::process::exit(1); } } @@ -128,6 +129,8 @@ fn main() { // Another engine in the same program: an installed agent in place of our own turns. let args: Vec = std::env::args().skip(1).collect(); if args.first().is_some_and(|arg| arg == "acp") { + // Top-level dispatch to the ACP engine mode; forward its exact process exit code. + #[allow(clippy::disallowed_methods)] std::process::exit(acp::run(&args[1..])); } let out = Out(Arc::new(Mutex::new(io::stdout()))); diff --git a/appd/Cargo.toml b/appd/Cargo.toml index 336ede01..532155bb 100644 --- a/appd/Cargo.toml +++ b/appd/Cargo.toml @@ -21,3 +21,6 @@ ureq = "3" [dev-dependencies] rusqlite = { version = "0.37", features = ["bundled"] } + +[lints] +workspace = true diff --git a/appd/src/core.rs b/appd/src/core.rs index dab739f7..4c7d48c4 100644 --- a/appd/src/core.rs +++ b/appd/src/core.rs @@ -1079,6 +1079,8 @@ impl Core { for id in self.servers.keys().cloned().collect::>() { self.stop_server(&id); } + // Top-level service shutdown after stopping child servers. + #[allow(clippy::disallowed_methods)] std::process::exit(0); } Msg::Browsed { @@ -5095,6 +5097,8 @@ impl Core { for id in self.servers.keys().cloned().collect::>() { self.stop_server(&id); } + // Exit with the update-install status code (0 for bundle relaunch, 75 for launchd). + #[allow(clippy::disallowed_methods)] std::process::exit(code); } Err(e) => { diff --git a/appd/tests/architecture.rs b/appd/tests/architecture.rs new file mode 100644 index 00000000..6cca9c74 --- /dev/null +++ b/appd/tests/architecture.rs @@ -0,0 +1,134 @@ +//! Mechanical architecture invariants from `docs/agents/contract.md`. +//! +//! Each test guards one standing rule so regressions fail `cargo test` automatically instead of +//! relying on prose review. + +use std::fs; +use std::path::{Path, PathBuf}; + +fn repo_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("appd sits directly under the workspace root") + .to_path_buf() +} + +/// Names of dependencies declared under any `[dependencies]`, `[dev-dependencies]`, +/// `[build-dependencies]`, or target-scoped dependency table in a `Cargo.toml`. +fn cargo_dependency_names(manifest: &str) -> Vec { + let mut deps = Vec::new(); + let mut in_deps = false; + for raw in manifest.lines() { + let line = raw.split('#').next().unwrap_or("").trim(); + if line.is_empty() { + continue; + } + if line.starts_with('[') && line.ends_with(']') { + let header = &line[1..line.len() - 1]; + in_deps = header == "dependencies" + || header == "dev-dependencies" + || header == "build-dependencies" + || header.ends_with(".dependencies") + || header.ends_with(".dev-dependencies") + || header.ends_with(".build-dependencies"); + continue; + } + if in_deps && let Some((key, _)) = line.split_once('=') { + let name = key.trim().trim_matches('"'); + if !name.is_empty() { + deps.push(name.to_owned()); + } + } + } + deps +} + +#[test] +fn core_crates_never_depend_on_an_async_runtime() { + let root = repo_root(); + let forbidden = ["tokio", "async-std", "smol"]; + for crate_name in ["proto", "appd", "agentcore", "helper"] { + let path = root.join(crate_name).join("Cargo.toml"); + let manifest = fs::read_to_string(&path) + .unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display())); + let deps = cargo_dependency_names(&manifest); + for banned in forbidden { + assert!( + !deps.iter().any(|d| d == banned), + "{crate_name}/Cargo.toml must not depend on `{banned}` (the service and engine stay synchronous; see docs/agents/contract.md)" + ); + } + } +} + +#[test] +fn every_workspace_member_inherits_workspace_lints() { + let root = repo_root(); + let root_toml = fs::read_to_string(root.join("Cargo.toml")).unwrap(); + let mut in_members = false; + let mut members = Vec::new(); + for line in root_toml.lines() { + let trimmed = line.trim(); + if trimmed.starts_with("members = [") { + in_members = true; + } + if in_members { + for part in trimmed.split('"').skip(1).step_by(2) { + members.push(part.to_owned()); + } + if trimmed.contains(']') { + break; + } + } + } + assert!( + members.len() >= 6, + "expected all workspace crates in Cargo.toml, found {members:?}" + ); + for member in members { + let path = root.join(&member).join("Cargo.toml"); + let manifest = fs::read_to_string(&path) + .unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display())); + let has_lints_section = manifest.lines().any(|l| l.trim() == "[lints]"); + let inherits_workspace = manifest.lines().any(|l| l.trim() == "workspace = true"); + assert!( + has_lints_section && inherits_workspace, + "{member}/Cargo.toml must include `[lints]\\nworkspace = true` so clippy.toml rules apply across the workspace" + ); + } +} + +#[test] +fn agents_md_stays_compact_and_every_referenced_doc_exists() { + let root = repo_root(); + let agents_path = root.join("AGENTS.md"); + let text = fs::read_to_string(&agents_path).expect("AGENTS.md must exist at the repo root"); + + assert!( + text.len() <= 4096, + "AGENTS.md is {} bytes (limit 4096): keep it a compact map and put details in docs/agents/", + text.len() + ); + let lines = text.lines().count(); + assert!( + lines <= 80, + "AGENTS.md is {lines} lines (limit 80): keep it short and link to docs/agents/" + ); + + let mut checked = 0usize; + for chunk in text.split('`').skip(1).step_by(2) { + if chunk.ends_with(".md") || chunk.ends_with('/') { + let target = root.join(chunk); + assert!( + target.exists(), + "AGENTS.md references `{chunk}`, which does not exist at {}", + target.display() + ); + checked += 1; + } + } + assert!( + checked >= 4, + "expected AGENTS.md to reference docs/agents/*.md and GLOSSARY.md, found only {checked}" + ); +} diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 00000000..fda3db71 --- /dev/null +++ b/clippy.toml @@ -0,0 +1,6 @@ +# Workspace-wide banned APIs enforced by `cargo clippy` (`[workspace.lints.clippy]`). +# See `docs/agents/contract.md` ("When a review finds the same thing twice"). +disallowed-methods = [ + { path = "std::env::set_current_dir", reason = "process-global working directory breaks parallel threads and tests; pass explicit paths or Command::current_dir instead" }, + { path = "std::process::exit", reason = "exiting skips destructors and locks; return ExitCode/Result from main, or explicitly #[allow(clippy::disallowed_methods)] at documented top-level exit points" }, +] diff --git a/helper/Cargo.toml b/helper/Cargo.toml index 81cbca21..1240ca60 100644 --- a/helper/Cargo.toml +++ b/helper/Cargo.toml @@ -8,3 +8,6 @@ core-foundation = "0.10" core-foundation-sys = "0.8" proto = { path = "../proto" } rusqlite = { version = "0.37", features = ["bundled"] } + +[lints] +workspace = true diff --git a/helper/src/main.rs b/helper/src/main.rs index c8ed55a7..03c3ab68 100644 --- a/helper/src/main.rs +++ b/helper/src/main.rs @@ -11,7 +11,7 @@ use proto::{read_frame, write_frame}; use std::io::{self, BufReader}; use std::os::unix::net::UnixStream; use std::path::{Path, PathBuf}; -use std::process::exit; +use std::process::{ExitCode, exit}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; @@ -19,19 +19,25 @@ use std::time::Duration; const NO_ACCESSIBILITY: &str = "Bate Helper is not allowed to control apps. The user must allow it in System Settings > Privacy & Security > Accessibility."; const NO_SCREEN: &str = "Bate Helper is not allowed to record the screen. The user must allow it in System Settings > Privacy & Security > Screen Recording."; -fn main() { +fn main() -> ExitCode { // The service passes its socket when it starts the helper. let socket = std::env::args_os() .nth(1) .map_or_else(proto::paths::helper_socket, PathBuf::from); - let stream = connect(&socket).unwrap_or_else(|e| { - eprintln!("bate-helper: cannot use {}: {e}", socket.display()); - exit(1) - }); - let out = Arc::new(Mutex::new(stream.try_clone().unwrap_or_else(|e| { - eprintln!("bate-helper: {e}"); - exit(1) - }))); + let stream = match connect(&socket) { + Ok(stream) => stream, + Err(e) => { + eprintln!("bate-helper: cannot use {}: {e}", socket.display()); + return ExitCode::FAILURE; + } + }; + let out = match stream.try_clone() { + Ok(cloned) => Arc::new(Mutex::new(cloned)), + Err(e) => { + eprintln!("bate-helper: {e}"); + return ExitCode::FAILURE; + } + }; let status = || { ( ax::trusted(), @@ -66,9 +72,9 @@ fn main() { loop { let request = match read_frame::(&mut input, MAX_FRAME, &mut buf) { Ok(Some(request)) => request, - Ok(None) => exit(0), + Ok(None) => return ExitCode::SUCCESS, Err(e) if e.kind() == io::ErrorKind::InvalidData => continue, - Err(_) => exit(0), + Err(_) => return ExitCode::SUCCESS, }; let reply = match run(request.call, &mut tree) { Ok((output, png)) => Frame::Reply { @@ -120,6 +126,8 @@ fn frame((accessibility, screen_recording, full_disk_access): (bool, bool, bool) fn send(out: &Mutex, frame: &Frame) { let mut out = out.lock().unwrap_or_else(|e| e.into_inner()); if write_frame(&mut *out, frame, MAX_FRAME).is_err() { + // Called from the permission-watcher thread as well as main; exit the process at once. + #[allow(clippy::disallowed_methods)] exit(0); } } diff --git a/native/Cargo.toml b/native/Cargo.toml index 9fd2f054..d957e2eb 100644 --- a/native/Cargo.toml +++ b/native/Cargo.toml @@ -35,3 +35,6 @@ objc2-user-notifications = { version = "0.3", optional = true } name = "native" path = "src/main.rs" required-features = ["gui"] + +[lints] +workspace = true diff --git a/native/src/main.rs b/native/src/main.rs index 27ffac02..63116026 100644 --- a/native/src/main.rs +++ b/native/src/main.rs @@ -1,6 +1,9 @@ -fn main() { +use std::process::ExitCode; + +fn main() -> ExitCode { if let Err(e) = native::window::main(std::env::args().skip(1)) { eprintln!("native: {e}"); - std::process::exit(1); + return ExitCode::FAILURE; } + ExitCode::SUCCESS } diff --git a/proto/Cargo.toml b/proto/Cargo.toml index e4ba3768..4a45807a 100644 --- a/proto/Cargo.toml +++ b/proto/Cargo.toml @@ -13,3 +13,6 @@ serde_json = "1" [target.'cfg(target_os = "macos")'.dependencies] core-foundation = "0.10" security-framework = "3.7.0" + +[lints] +workspace = true diff --git a/proto/tests/engine_host.rs b/proto/tests/engine_host.rs index 3e0cfa47..438063b9 100644 --- a/proto/tests/engine_host.rs +++ b/proto/tests/engine_host.rs @@ -21,6 +21,8 @@ fn the_service_runs_the_engine_named_by_appd_engine_over_stdio() { std::thread::spawn(|| { std::thread::sleep(std::time::Duration::from_secs(10)); eprintln!("engine test timed out"); + // Watchdog thread: force-exit a wedged test binary so `cargo test` cannot hang. + #[allow(clippy::disallowed_methods)] std::process::exit(1); }); // The script sits under the workspace target folder and is named by a path diff --git a/window/Cargo.toml b/window/Cargo.toml index 39163ad7..8bb52b1e 100644 --- a/window/Cargo.toml +++ b/window/Cargo.toml @@ -27,3 +27,6 @@ objc2-user-notifications = "0.3" [build-dependencies] tauri-build = { version = "2", features = [] } + +[lints] +workspace = true diff --git a/window/src/main.rs b/window/src/main.rs index bcc2144a..1b132c23 100644 --- a/window/src/main.rs +++ b/window/src/main.rs @@ -333,6 +333,9 @@ fn open_outside(url: &Url) { } fn main() { + // `tauri::generate_context!()` expands to `std::process::exit` on internal asset errors. + #[allow(clippy::disallowed_methods)] + let context = tauri::generate_context!(); let app = tauri::Builder::default() .manage(Bridges::default()) .manage(Note::default()) @@ -381,7 +384,7 @@ fn main() { open_window(handle)?; Ok(()) }) - .build(tauri::generate_context!()) + .build(context) .expect("the window could not start"); app.run(|app, event| match event { // The last window closed: Bate stays in the menu bar. Quit ends it. diff --git a/window/ui/standin/standin.test.mjs b/window/ui/standin/standin.test.mjs index 3c675738..7b8d75b7 100644 --- a/window/ui/standin/standin.test.mjs +++ b/window/ui/standin/standin.test.mjs @@ -56,3 +56,29 @@ test("every selector the screen list names is in the page's code", () => { } } }); + +test("window/ui/src has no unsafe type escapes or focused tests", () => { + const all = readdirSync(src) + .filter((f) => /\.tsx?$/.test(f)) + .map((f) => ({ name: f, text: readFileSync(new URL(f, src), "utf8") })); + const patterns = [ + { name: "`as any`", re: /\bas\s+any\b/ }, + { name: "`@ts-ignore`", re: /@ts-ignore\b/ }, + { name: "`@ts-nocheck`", re: /@ts-nocheck\b/ }, + { name: "focused `.only(` test", re: /\b(?:test|it|describe)\.only\s*\(/ }, + ]; + const findings = []; + for (const { name, text } of all) { + const lines = text.split("\n"); + for (let i = 0; i < lines.length; i++) { + for (const p of patterns) { + if (p.re.test(lines[i])) findings.push(`${name}:${i + 1}: ${p.name}`); + } + } + } + assert.deepEqual( + findings, + [], + "remove type-check escapes and focused tests from window/ui/src", + ); +});