Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
3 changes: 3 additions & 0 deletions agentcore/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ proto = { path = "../proto" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
ureq = "3"

[lints]
workspace = true
2 changes: 2 additions & 0 deletions agentcore/src/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down
3 changes: 3 additions & 0 deletions agentcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -128,6 +129,8 @@ fn main() {
// Another engine in the same program: an installed agent in place of our own turns.
let args: Vec<String> = 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())));
Expand Down
3 changes: 3 additions & 0 deletions appd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,6 @@ ureq = "3"

[dev-dependencies]
rusqlite = { version = "0.37", features = ["bundled"] }

[lints]
workspace = true
4 changes: 4 additions & 0 deletions appd/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1079,6 +1079,8 @@ impl Core {
for id in self.servers.keys().cloned().collect::<Vec<_>>() {
self.stop_server(&id);
}
// Top-level service shutdown after stopping child servers.
#[allow(clippy::disallowed_methods)]
std::process::exit(0);
}
Msg::Browsed {
Expand Down Expand Up @@ -5095,6 +5097,8 @@ impl Core {
for id in self.servers.keys().cloned().collect::<Vec<_>>() {
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) => {
Expand Down
134 changes: 134 additions & 0 deletions appd/tests/architecture.rs
Original file line number Diff line number Diff line change
@@ -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<String> {
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}"
);
}
6 changes: 6 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
@@ -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" },
]
3 changes: 3 additions & 0 deletions helper/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
32 changes: 20 additions & 12 deletions helper/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,33 @@ 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;

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(),
Expand Down Expand Up @@ -66,9 +72,9 @@ fn main() {
loop {
let request = match read_frame::<Request>(&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 {
Expand Down Expand Up @@ -120,6 +126,8 @@ fn frame((accessibility, screen_recording, full_disk_access): (bool, bool, bool)
fn send(out: &Mutex<UnixStream>, 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);
}
}
Expand Down
3 changes: 3 additions & 0 deletions native/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ objc2-user-notifications = { version = "0.3", optional = true }
name = "native"
path = "src/main.rs"
required-features = ["gui"]

[lints]
workspace = true
7 changes: 5 additions & 2 deletions native/src/main.rs
Original file line number Diff line number Diff line change
@@ -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
}
3 changes: 3 additions & 0 deletions proto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 2 additions & 0 deletions proto/tests/engine_host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions window/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,6 @@ objc2-user-notifications = "0.3"

[build-dependencies]
tauri-build = { version = "2", features = [] }

[lints]
workspace = true
5 changes: 4 additions & 1 deletion window/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions window/ui/standin/standin.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
);
});
Loading