chore: delete code comments, add ratchet lint and ADRs

Classify every comment as tautology, stale, excuse or decision record.
Tautology/stale/excuse comments are deleted (excuses filed as issues
#196-#236), decisions moved to docs/adr/0001-0034.

- scripts/lint-comments.sh + .comment-baseline: per-file comment count
  may only go down; wired into tests/all.sh
- .claude/skills/delete-comment: repeatable audit workflow
- cargo fmt applied to touched crates

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
johannesandClaude Sonnet 5.5 committed 2026-11-21 13:37:32 +01:00
1 parent 0545702fe0
commit a94632ea3d
131 files changed
+1051 -1746

No files matched your search

+53 -65
View File
@@ -1,10 +1,3 @@
//! `codemode`: the model writes a JavaScript async-function body that calls the other tools
//! inside a QuickJS sandbox; only the script's output reaches the model (pi's codemode, minus
//! `models`). Inner calls go through `Registry::call`, so the permission gate and the shared
//! `State` (read-before-edit, edit log) apply as for direct calls. Inner calls are reported
//! live through `State::nested` (the agent shows them as notices); images shown with `image()`
//! travel as `ToolResult::images`.
use super::{head_tail, spec};
use async_trait::async_trait;
use base64::Engine;
@@ -19,12 +12,9 @@ use std::time::{Duration, Instant};
use tokio::sync::{Notify, Semaphore};
const MEM: usize = 256 << 20;
/// ~10k tokens of output; the rest goes to a temp file.
const MAX_OUT: usize = 40_000;
/// Tool listing budget in the description (~3k tokens).
const LIST_BUDGET: usize = 12_000;
const DEFAULT_TIMEOUT_S: u64 = 300;
/// Scripts running at once in this process; others wait (see `HX_CODEMODE_MAX_WORKERS`).
const DEFAULT_WORKERS: usize = 2;
const WORKER_WAIT: Duration = Duration::from_secs(60);
@@ -102,21 +92,15 @@ globalThis.store = (k, v) => {
globalThis.__store_out = () => JSON.stringify({ set: __sets, del: __dels });
"#;
/// A callable tool as the discovery globals see it.
struct Doc {
/// JS identifier
id: String,
/// MCP server for `mcp__server__tool`, else empty
ns: String,
/// `tools.id({sig}): first sentence`
line: String,
/// lowercase name + description, for ranking
hay: String,
}
pub struct Codemode {
reg: Arc<Registry>,
/// JS identifier -> real tool name
names: Arc<BTreeMap<String, String>>,
docs: Arc<Vec<Doc>>,
desc: String,
@@ -134,7 +118,6 @@ fn ident(n: &str) -> String {
.collect()
}
/// `{path: string, limit?: integer}` from a JSON schema.
fn sig(schema: &Value) -> String {
let req: Vec<&str> = schema["required"]
.as_array()
@@ -155,7 +138,6 @@ fn sig(schema: &Value) -> String {
format!("{{{}}}", args.join(", "))
}
/// MCP server of `mcp__server__tool`.
fn namespace(name: &str) -> String {
name.strip_prefix("mcp__")
.and_then(|r| r.split("__").next())
@@ -163,7 +145,6 @@ fn namespace(name: &str) -> String {
.unwrap_or_default()
}
/// Tools matching `query`, best first: name hits weigh more than description hits.
fn search(docs: &[Doc], query: &str, limit: usize, ns: &str) -> Value {
let terms: Vec<String> = query
.to_lowercase()
@@ -180,7 +161,8 @@ fn search(docs: &[Doc], query: &str, limit: usize, ns: &str) -> Value {
let score: usize = terms
.iter()
.map(|t| {
let in_id = id.split('_').any(|p| p == t) as usize * 2 + id.contains(t) as usize * 2;
let in_id =
id.split('_').any(|p| p == t) as usize * 2 + id.contains(t) as usize * 2;
in_id + d.hay.contains(t.as_str()) as usize
})
.sum();
@@ -195,13 +177,11 @@ fn search(docs: &[Doc], query: &str, limit: usize, ns: &str) -> Value {
}
impl Codemode {
/// Snapshot of `reg` at construction: tools added later (and codemode itself) are not callable.
pub fn new(reg: &Registry) -> Self {
let mut names = BTreeMap::new();
let mut docs = vec![];
let mut list = String::new();
let mut hidden = 0;
// MCP tools first so builtins cannot push them out of the listing budget
let mut specs = reg.specs();
specs.sort_by_key(|s| !(s.name.contains("__") || s.name.starts_with("mcp_")));
for s in specs {
@@ -252,7 +232,6 @@ fn workers() -> &'static Semaphore {
})
}
/// Everything one script run needs.
struct Job {
script: String,
secs: u64,
@@ -283,10 +262,9 @@ impl Tool for Codemode {
.as_u64()
.unwrap_or(DEFAULT_TIMEOUT_S)
.clamp(1, 3600);
let max_out = a["max_output_tokens"]
.as_u64()
.map_or(MAX_OUT, |t| (t as usize).saturating_mul(4).clamp(400, 400_000));
// The wait for a free worker counts toward the timeout.
let max_out = a["max_output_tokens"].as_u64().map_or(MAX_OUT, |t| {
(t as usize).saturating_mul(4).clamp(400, 400_000)
});
let t0 = Instant::now();
let permit = match tokio::time::timeout(
WORKER_WAIT.min(Duration::from_secs(secs)),
@@ -302,7 +280,6 @@ impl Tool for Codemode {
}
};
let secs = secs.saturating_sub(t0.elapsed().as_secs()).max(1);
// Dropping this future (agent abort) interrupts the script.
struct Stop(Arc<AtomicBool>);
impl Drop for Stop {
fn drop(&mut self) {
@@ -321,7 +298,6 @@ impl Tool for Codemode {
cx: cx.clone(),
stop: stop.0.clone(),
};
// QuickJS values are !Send: run the script on its own thread with a local runtime.
std::thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
@@ -338,12 +314,11 @@ impl Tool for Codemode {
}
}
/// (settled ok?/error, store writes as JSON, text items, console lines, images)
type Outcome = (
Option<(bool, String, Option<String>)>,
Vec<String>,
Vec<String>,
Vec<String>, // `mime|base64`
Vec<String>,
);
fn preview(s: &str) -> String {
@@ -376,7 +351,6 @@ async fn run(job: Job) -> ToolResult {
stop,
} = job;
let t0 = Instant::now();
// (tool, "running" | "ok" | "error" | "cancelled") in call order
let log: Arc<Mutex<Vec<(String, &'static str)>>> = Arc::default();
let fail = |e: String| ToolResult::err(format!("Script failed\n\nScript error: {e}"));
let rt = match AsyncRuntime::new() {
@@ -519,14 +493,12 @@ async fn run(job: Job) -> ToolResult {
}
return fail(e);
}
// The interrupt handler only fires while JS runs; also bound time spent awaiting tools.
let stop2 = stop.clone();
let watch = async move {
while !stop2.load(Ordering::Relaxed) && Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(100)).await;
}
};
// Stop as soon as the script settles: unawaited tool calls are dropped (cancelled), not waited for.
tokio::select! {
_ = finished.notified() => {}
_ = rt.idle() => {}
@@ -552,7 +524,6 @@ async fn run(job: Job) -> ToolResult {
Ok(x) => x,
Err(e) => return fail(e.to_string()),
};
// Calls still running were cut off by the end of the script, a timeout or an abort.
let calls = {
let mut l = log.lock().unwrap_or_else(|e| e.into_inner());
for c in l.iter_mut().filter(|c| c.1 == "running") {
@@ -560,36 +531,45 @@ async fn run(job: Job) -> ToolResult {
}
l.clone()
};
// Save images next to the output so the model has their paths; `image()` left markers.
let mut sent = vec![];
let mut labels: Vec<String> = vec![];
for (i, (mime, data)) in imgs
.iter()
.filter_map(|s| s.split_once('|'))
.enumerate()
{
labels.push(match base64::engine::general_purpose::STANDARD.decode(data) {
Ok(bytes) => {
let f = std::env::temp_dir().join(format!(
"hx-codemode-{}-{}-{i}.{}",
std::process::id(),
t0.elapsed().as_nanos(),
ext(mime)
));
sent.push((mime.to_string(), data.to_string()));
match std::fs::write(&f, &bytes) {
Ok(()) => format!("[Image saved to {} ({mime}, {} bytes)]", f.display(), bytes.len()),
Err(e) => format!("[Image ({mime}, {} bytes) could not be saved: {e}]", bytes.len()),
for (i, (mime, data)) in imgs.iter().filter_map(|s| s.split_once('|')).enumerate() {
labels.push(
match base64::engine::general_purpose::STANDARD.decode(data) {
Ok(bytes) => {
let f = std::env::temp_dir().join(format!(
"hx-codemode-{}-{}-{i}.{}",
std::process::id(),
t0.elapsed().as_nanos(),
ext(mime)
));
sent.push((mime.to_string(), data.to_string()));
match std::fs::write(&f, &bytes) {
Ok(()) => format!(
"[Image saved to {} ({mime}, {} bytes)]",
f.display(),
bytes.len()
),
Err(e) => format!(
"[Image ({mime}, {} bytes) could not be saved: {e}]",
bytes.len()
),
}
}
}
Err(e) => format!("[Image {i} is not valid base64: {e}]"),
});
Err(e) => format!("[Image {i} is not valid base64: {e}]"),
},
);
}
let out: Vec<String> = out
.into_iter()
.map(|t| match t.strip_prefix("\u{1}img").and_then(|i| i.parse::<usize>().ok()) {
Some(i) => labels.get(i).cloned().unwrap_or_default(),
None => t,
.map(|t| {
match t
.strip_prefix("\u{1}img")
.and_then(|i| i.parse::<usize>().ok())
{
Some(i) => labels.get(i).cloned().unwrap_or_default(),
None => t,
}
})
.collect();
let mut body = String::new();
@@ -616,7 +596,6 @@ async fn run(job: Job) -> ToolResult {
.into(),
),
};
// Store writes count only for a script that succeeded.
if err.is_none()
&& let Some((_, _, Some(w))) = &done
&& let Ok(w) = serde_json::from_str::<Value>(w)
@@ -626,7 +605,12 @@ async fn run(job: Job) -> ToolResult {
.codemode_store
.lock()
.unwrap_or_else(|e| e.into_inner());
for k in w["del"].as_array().into_iter().flatten().filter_map(Value::as_str) {
for k in w["del"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
{
s.remove(k);
}
for (k, v) in w["set"].as_object().into_iter().flatten() {
@@ -737,7 +721,6 @@ mod tests {
"{}",
r.content
);
// what ran before the failure is listed
assert!(r.content.contains("bash (error)"), "{}", r.content);
let r = go("await tools.nope({});").await;
assert!(r.content.contains("unknown tool `nope`"), "{}", r.content);
@@ -803,7 +786,11 @@ mod tests {
"#)
.await;
assert!(!r.is_error, "{}", r.content);
assert!(r.content.contains("true,\n \"edit\",\n true"), "{}", r.content);
assert!(
r.content.contains("true,\n \"edit\",\n true"),
"{}",
r.content
);
}
#[tokio::test]
@@ -825,12 +812,13 @@ mod tests {
#[tokio::test]
async fn images_flow_from_read_to_the_result() {
let d = tempfile::tempdir().unwrap();
// 1x1 transparent png
let png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==";
use base64::Engine;
std::fs::write(
d.path().join("p.png"),
base64::engine::general_purpose::STANDARD.decode(png).unwrap(),
base64::engine::general_purpose::STANDARD
.decode(png)
.unwrap(),
)
.unwrap();
let cm = Codemode::new(&crate::registry());
-13
View File
@@ -1,5 +1,3 @@
//! Built-in tools: read, write, edit, bash.
pub mod codemode;
pub mod skill;
pub mod web;
@@ -13,7 +11,6 @@ use std::time::Duration;
const MAX_LINES: usize = 600;
const MAX_BYTES: usize = 20_000;
/// bash keeps this much of the start (command echo, first errors) and the rest from the end.
const HEAD_BYTES: usize = 4_000;
pub(crate) fn spec(name: &str, desc: &str, schema: Value) -> ToolSpec {
@@ -33,8 +30,6 @@ fn resolve(cx: &ToolCtx, p: &str) -> PathBuf {
}
}
/// Keep the tail of `s` within `max` bytes on a char boundary.
/// First `head` bytes + last `max - head` bytes, char-boundary safe. Returns (text, cut bytes).
fn head_tail(s: &str, max: usize, head: usize) -> (String, usize) {
if s.len() <= max {
return (s.to_string(), 0);
@@ -234,7 +229,6 @@ impl Tool for Edit {
Ok(s) => s,
Err(e) => return ToolResult::err(format!("{}: {e}", p.display())),
};
// Models send LF; preserve CRLF files.
let crlf = src.contains("\r\n");
let fix = |s: &str| {
if crlf {
@@ -326,7 +320,6 @@ impl Tool for AskUser {
}
}
/// Plan mode's end: the TUI shows the plan in full, the user approves or sends feedback.
pub struct ExitPlan;
#[async_trait]
impl Tool for ExitPlan {
@@ -366,13 +359,11 @@ impl Tool for ExitPlan {
v.join(", ")
))
}
// no frontend (print mode) or dismissed: stay in plan mode
_ => ToolResult::ok("plan not approved; keep planning and ask what to change"),
}
}
}
/// Bytes of running bash output kept for the live view.
const LIVE_TAIL: usize = 2048;
pub struct Bash;
@@ -398,7 +389,6 @@ impl Tool for Bash {
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.kill_on_drop(true);
// own process group so timeouts kill children too
#[cfg(unix)]
c.process_group(0);
let mut child = match c.spawn() {
@@ -406,7 +396,6 @@ impl Tool for Bash {
Err(e) => return ToolResult::err(format!("spawn: {e}")),
};
let pid = child.id();
// read output as it comes so the UI can show the last lines live (state.live)
let mut so = child.stdout.take().expect("piped");
let live = &cx.state.live;
let run = async {
@@ -638,7 +627,6 @@ mod tests {
.await
.is_error
);
// blind overwrite of an existing unread file is refused
std::fs::write(d.path().join("other.rs"), "keep").unwrap();
assert!(
Write
@@ -680,7 +668,6 @@ mod tests {
std::fs::read_to_string(&p).unwrap(),
"fn a() {}\r\nfn c() {}\r\nfn b() {}\r\n"
);
// external change invalidates
std::thread::sleep(Duration::from_millis(20));
std::fs::write(&p, "changed\n").unwrap();
assert!(
-2
View File
@@ -1,5 +1,3 @@
//! `skill` tool: the model loads a skill body by name (no paths, so no traversal).
use crate::spec;
use async_trait::async_trait;
use hx_ai::ToolSpec;
+3 -17
View File
@@ -1,5 +1,3 @@
//! `web_fetch` (URL -> text) and `web_search` (Brave or SearXNG). Both return untrusted text.
use crate::spec;
use async_trait::async_trait;
use hx_ai::ToolSpec;
@@ -16,15 +14,11 @@ const MAX_REDIRECTS: usize = 5;
#[derive(Clone)]
pub enum Search {
/// API key.
Brave(String),
/// Base URL of the instance (needs `json` in its `search.formats`).
Searx(String),
}
impl Search {
/// `kind` = config `web.search` ("brave" default | "searxng"). Brave without key falls back to
/// SearXNG when a URL is set; None = no `web_search` tool.
pub fn pick(
kind: Option<&str>,
brave_key: Option<String>,
@@ -42,7 +36,6 @@ impl Search {
struct Web {
http: reqwest::Client,
/// tests only: allow loopback/private targets
private_ok: bool,
}
@@ -74,7 +67,7 @@ fn private(ip: IpAddr) -> bool {
|| v.is_unspecified()
|| v.is_broadcast()
|| v.octets()[0] == 0
|| (v.octets()[0] == 100 && v.octets()[1] & 0xc0 == 64) // CGNAT
|| (v.octets()[0] == 100 && v.octets()[1] & 0xc0 == 64)
}
IpAddr::V6(v) => {
if let Some(m) = v.to_ipv4_mapped() {
@@ -82,15 +75,12 @@ fn private(ip: IpAddr) -> bool {
}
v.is_loopback()
|| v.is_unspecified()
|| v.segments()[0] & 0xfe00 == 0xfc00 // unique local
|| v.segments()[0] & 0xffc0 == 0xfe80 // link local
|| v.segments()[0] & 0xfe00 == 0xfc00
|| v.segments()[0] & 0xffc0 == 0xfe80
}
}
}
/// Reject non-http(s) and hosts resolving to private ranges.
// ponytail: resolve-then-connect leaves a DNS-rebinding gap; pin the resolved IP via
// `ClientBuilder::resolve` if that matters.
async fn check(w: &Web, u: &Url) -> Result<(), String> {
if !matches!(u.scheme(), "http" | "https") {
return Err(format!(
@@ -117,7 +107,6 @@ async fn check(w: &Web, u: &Url) -> Result<(), String> {
Ok(())
}
/// GET with manual redirects (each hop checked) and a body cap.
async fn get(
w: &Web,
url: &str,
@@ -337,7 +326,6 @@ mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
/// Serves `routes` (path -> (status line, headers, body)); returns base URL.
async fn serve(routes: Vec<(&'static str, String)>) -> String {
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = l.local_addr().unwrap().port();
@@ -402,7 +390,6 @@ mod tests {
)
.await;
assert!(r.content.contains("truncated"));
// guard on: loopback and bad scheme refused
let g = Fetch(Arc::new(Web::new(false)));
let r = g.call(json!({"url": format!("{base}/page")}), &cx()).await;
assert!(r.is_error && r.content.contains("private"), "{}", r.content);
@@ -414,7 +401,6 @@ mod tests {
#[tokio::test]
async fn redirect_to_private_blocked() {
// public-looking first hop is impossible offline, so test `private()` directly
for ip in [
"127.0.0.1",
"10.1.2.3",