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:
1 parent
0545702fe0
commit
a94632ea3d
131 files changed
+1051
-1746
No files matched your search
@@ -18,7 +18,6 @@ use std::sync::Arc;
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "hx",
|
||||
// CI sets HX_VERSION to the release version; local builds use Cargo's
|
||||
version = option_env!("HX_VERSION").unwrap_or(env!("CARGO_PKG_VERSION")),
|
||||
about = "Minimal coding agent"
|
||||
)]
|
||||
@@ -127,7 +126,6 @@ enum ConfigAction {
|
||||
},
|
||||
}
|
||||
|
||||
/// Every key commented out; `sample_config_parses` keeps it in sync with `Config`.
|
||||
const SAMPLE_CONFIG: &str = include_str!("config.sample.toml");
|
||||
|
||||
#[derive(Subcommand)]
|
||||
@@ -138,7 +136,6 @@ enum McpAction {
|
||||
Logout { server: String },
|
||||
}
|
||||
|
||||
/// `~/.hx/config.toml`, overridden by `.hx/config.toml` in the project.
|
||||
#[derive(Clone, serde::Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum CliCfg {
|
||||
@@ -152,41 +149,24 @@ struct Config {
|
||||
provider: Option<Kind>,
|
||||
model: Option<String>,
|
||||
claude_model: Option<String>,
|
||||
/// Run Claude through the official `claude` CLI (subscription billing). Default: on when `claude` is in PATH.
|
||||
/// `false` = own OAuth calls (billed as extra usage); `true` / `[]` = on; a list = on with extra `claude` args.
|
||||
claude_cli: Option<CliCfg>,
|
||||
/// OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter, ...), provider "custom".
|
||||
openai_compat: Option<hx_ai::openai_compat::Config>,
|
||||
codex_model: Option<String>,
|
||||
/// Auto-compact threshold in estimated tokens.
|
||||
compact_at: Option<usize>,
|
||||
max_tokens: Option<u32>,
|
||||
/// Model for read-only `task` subagents; default: the provider's cheapest tier (Haiku / Luna).
|
||||
explore_model: Option<String>,
|
||||
/// Register the `task` subagent tool (default true; each call still asks the user). `--no-subagents` = off.
|
||||
subagents: Option<bool>,
|
||||
/// Add the `codemode` tool: JS scripts that call the other tools (default false).
|
||||
codemode: Option<bool>,
|
||||
/// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift).
|
||||
mouse: Option<bool>,
|
||||
/// Where sessions live (default `~/.hx/sessions`); `~` expands. Point at a synced/mounted cloud folder. `HX_SESSIONS_DIR` wins.
|
||||
sessions_dir: Option<String>,
|
||||
/// Prefix session folders with the host name, so machines sharing `sessions_dir` stay apart (default false).
|
||||
sessions_host: Option<bool>,
|
||||
/// Reuse the last model chosen with /model or /provider (default true).
|
||||
remember_model: Option<bool>,
|
||||
/// `/model auto`: tier pins (`fast`, `balanced`, `deep` = model ids) and `down_after`.
|
||||
auto: Option<hx_core::route::Cfg>,
|
||||
/// "ask" (default), "auto" or "yolo": whether bash/write/edit prompt in the TUI.
|
||||
permissions: Option<String>,
|
||||
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
|
||||
system_prompt: Option<String>,
|
||||
/// confine child processes: mode = "on", backend, network, rw, ro, env_allow
|
||||
sandbox: Option<hx_core::sandbox::Cfg>,
|
||||
lsp: Option<LspCfg>,
|
||||
/// web_search backend: search = "brave" (default, key in $BRAVE_API_KEY) | "searxng", searxng_url
|
||||
web: Option<WebCfg>,
|
||||
/// subprocess extensions (JSON-RPC over stdio); global and project lists are concatenated
|
||||
extensions: Vec<hx_core::ext::ExtCfg>,
|
||||
}
|
||||
|
||||
@@ -209,17 +189,11 @@ fn web_search(cfg: &Config) -> Option<hx_tools::web::Search> {
|
||||
#[derive(Default, Clone, serde::Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
struct LspCfg {
|
||||
/// turn_end (default) | agent_end | off
|
||||
mode: Option<hx_lens::Mode>,
|
||||
/// extra or overriding servers (same `id` replaces a built-in)
|
||||
servers: Vec<hx_lens::manager::ServerCfg>,
|
||||
/// built-in server ids to disable
|
||||
disable: Vec<String>,
|
||||
/// runner ids to enable in addition to defaults (e.g. "clippy")
|
||||
enable_runners: Vec<String>,
|
||||
/// runner ids to disable (e.g. "rustfmt", "biome-format")
|
||||
disable_runners: Vec<String>,
|
||||
/// affected tests: turn_end (default) | agent_end | off
|
||||
tests: Option<hx_lens::testrun::TestMode>,
|
||||
}
|
||||
|
||||
@@ -264,12 +238,9 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tool context of the agent, for the stored "run claude outside the sandbox" rule.
|
||||
static CLAUDE_CX: std::sync::OnceLock<ToolCtx> = std::sync::OnceLock::new();
|
||||
const OUTSIDE_RULE: &str = "claude:unsandboxed";
|
||||
|
||||
/// Leave the sandbox only on an explicit, stored rule (`claude:unsandboxed` in `.hx/allow.json`). Never
|
||||
/// asked and never implied by yolo: yolo is only safe because claude's tools stay confined.
|
||||
fn claude_outside() -> bool {
|
||||
CLAUDE_CX.get().is_some_and(|cx| {
|
||||
cx.state
|
||||
@@ -280,7 +251,6 @@ fn claude_outside() -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// `hx mcp-serve`: lens/LSP, hx's MCP servers and (with a permission socket) `approve` for claude.
|
||||
async fn mcp_serve() -> Result<()> {
|
||||
let cwd = std::env::current_dir()?;
|
||||
let mgr = Arc::new(hx_lens::manager::Manager::new(
|
||||
@@ -296,17 +266,14 @@ async fn mcp_serve() -> Result<()> {
|
||||
let sock = std::env::var_os(hx_core::approve::ENV);
|
||||
if let Some(p) = &sock {
|
||||
reg.add(hx_core::approve::Approve(p.into()));
|
||||
// tools run by codemode ask hx for permission like any other
|
||||
let _ = cx
|
||||
.state
|
||||
.permit
|
||||
.set(hx_core::approve::remote_permit(p.into()));
|
||||
}
|
||||
// claude keeps its own tools; hx's MCP servers are added directly, or only through `codemode`
|
||||
let cfg = Config::load(&cwd)?;
|
||||
let mut servers =
|
||||
hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?;
|
||||
// a server entry that is hx itself would spawn mcp-serve recursively
|
||||
servers.retain(|_, s| !s.args.iter().any(|a| a == "mcp-serve"));
|
||||
let hub = Arc::new(hx_mcp::Hub::start(servers).await);
|
||||
if std::env::var_os("HX_CODEMODE").is_some() {
|
||||
@@ -329,7 +296,6 @@ async fn mcp_serve() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Appends a line to `$TMPDIR/hx-mcp-serve.log` (writable inside the sandbox too); best effort.
|
||||
fn mcp_serve_log(line: &str) {
|
||||
use std::io::Write;
|
||||
let p = std::env::temp_dir().join("hx-mcp-serve.log");
|
||||
@@ -351,8 +317,6 @@ fn mcp_serve_log(line: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// What `claude` (and its `hx mcp-serve` child) need inside the sandbox: its binary and config,
|
||||
/// the network, hx itself and the permission socket.
|
||||
fn claude_extra(bin: &str) -> hx_core::sandbox::Extra {
|
||||
let home = std::path::PathBuf::from(std::env::var_os("HOME").unwrap_or_default());
|
||||
let mut ro = vec![];
|
||||
@@ -373,14 +337,12 @@ fn claude_extra(bin: &str) -> hx_core::sandbox::Extra {
|
||||
{
|
||||
ro.extend(f.parent().map(Into::into));
|
||||
}
|
||||
// claude's install dir (versions/..) sits next to the resolved symlink target
|
||||
hx_core::sandbox::Extra {
|
||||
ro,
|
||||
rw: vec![
|
||||
home.join(".claude"),
|
||||
home.join(".claude.json"),
|
||||
home.join(".config/claude"),
|
||||
// macOS keeps claude's login in the login keychain; without it claude says "Not logged in"
|
||||
home.join("Library/Keychains"),
|
||||
hx_core::approve::sock_path(),
|
||||
],
|
||||
@@ -401,7 +363,6 @@ fn claude_extra(bin: &str) -> hx_core::sandbox::Extra {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `claude` command: sandboxed when the sandbox is on, unless claude's sandbox is off or a rule lets it out.
|
||||
async fn claude_command(bin: String) -> tokio::process::Command {
|
||||
if hx_core::sandbox::active().is_none()
|
||||
|| !hx_core::sandbox::claude_sandboxed()
|
||||
@@ -412,8 +373,6 @@ async fn claude_command(bin: String) -> tokio::process::Command {
|
||||
hx_core::sandbox::command_with(&bin, &claude_extra(&bin))
|
||||
}
|
||||
|
||||
/// Builtins, MCP prompts (`/server:prompt`), then skills (builtins win name clashes).
|
||||
/// `models` feeds `/model` completion (any other id still works); `kinds` = logged-in providers.
|
||||
fn command_specs(
|
||||
mcp: &hx_mcp::Hub,
|
||||
cwd: &std::path::Path,
|
||||
@@ -437,7 +396,6 @@ fn command_specs(
|
||||
Source::Builtin,
|
||||
ArgKind::None,
|
||||
));
|
||||
// servers still connecting have no prompts yet; `/mcp` shows them, typed `/server:prompt` still resolves
|
||||
v.extend(mcp.prompts().iter().map(|(n, p)| {
|
||||
CmdSpec::new(
|
||||
&format!("{n}:{}", p["name"].as_str().unwrap_or_default()),
|
||||
@@ -451,7 +409,6 @@ fn command_specs(
|
||||
v
|
||||
}
|
||||
|
||||
/// Providers with stored or importable credentials.
|
||||
fn logged_in() -> Vec<Kind> {
|
||||
[Kind::Claude, Kind::Codex, Kind::Custom]
|
||||
.into_iter()
|
||||
@@ -463,13 +420,11 @@ fn logged_in() -> Vec<Kind> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Model catalog of every logged-in provider (live list cached a day, else the built-in list).
|
||||
async fn catalog(kinds: &[Kind]) -> Vec<ModelInfo> {
|
||||
let one = |k: Kind| async move {
|
||||
let Ok(p) = provider(k) else {
|
||||
return hx_ai::models::fallback(k);
|
||||
};
|
||||
// stale-while-revalidate: any cached list starts us now; an expired one refreshes in the background
|
||||
if k != Kind::Custom
|
||||
&& let Some((m, fresh)) = hx_ai::models::cached(k)
|
||||
{
|
||||
@@ -498,7 +453,6 @@ async fn catalog(kinds: &[Kind]) -> Vec<ModelInfo> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `HX_TRACE_STARTUP=1`: print time since process start at each phase.
|
||||
fn trace(phase: &str) {
|
||||
static T0: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
let t0 = T0.get_or_init(std::time::Instant::now);
|
||||
@@ -507,7 +461,6 @@ fn trace(phase: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// `hx models`: what each provider's `/models` returns, and where the list came from.
|
||||
async fn print_models(refresh: bool) {
|
||||
for k in logged_in() {
|
||||
let Ok(p) = provider(k) else { continue };
|
||||
@@ -519,7 +472,6 @@ async fn print_models(refresh: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// USD per million tokens. ponytail: subscription usage isn't billed per token; this is an API-equivalent estimate.
|
||||
fn pricing(model: &str) -> Option<hx_ai::Pricing> {
|
||||
let p = |input, output, cache_read, cache_write| hx_ai::Pricing {
|
||||
input,
|
||||
@@ -527,7 +479,6 @@ fn pricing(model: &str) -> Option<hx_ai::Pricing> {
|
||||
cache_read,
|
||||
cache_write,
|
||||
};
|
||||
// 5.x generation prices first; older ids keep their own
|
||||
Some(match model {
|
||||
m if m.contains("fable") => p(10.0, 50.0, 1.0, 12.5),
|
||||
m if m.contains("opus-5") => p(4.0, 20.0, 0.4, 5.0),
|
||||
@@ -544,11 +495,8 @@ fn pricing(model: &str) -> Option<hx_ai::Pricing> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `[openai_compat]` from config, set once at startup.
|
||||
static COMPAT: std::sync::OnceLock<hx_ai::openai_compat::Config> = std::sync::OnceLock::new();
|
||||
/// `codemode` from config: also offer the codemode tool to claude.
|
||||
static CODEMODE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
/// claude_cli sees only the `hx mcp-serve` tools: MCP is script-only with codemode, else `mcp__hx__*`.
|
||||
fn via() -> hx_mcp::Via {
|
||||
match (
|
||||
CLAUDE_CLI.get().is_some(),
|
||||
@@ -559,7 +507,6 @@ fn via() -> hx_mcp::Via {
|
||||
_ => hx_mcp::Via::Direct,
|
||||
}
|
||||
}
|
||||
/// `claude_cli` from config: extra args for the `claude` binary.
|
||||
static CLAUDE_CLI: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
|
||||
|
||||
fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
|
||||
@@ -608,7 +555,6 @@ fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Streams text to stdout and tool activity to stderr.
|
||||
struct Printer;
|
||||
#[async_trait::async_trait]
|
||||
impl Hook for Printer {
|
||||
@@ -637,7 +583,6 @@ impl Hook for Printer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets an `Arc`-shared hook sit on the bus while tools hold the same instance.
|
||||
struct ArcHook<H>(Arc<H>);
|
||||
#[async_trait::async_trait]
|
||||
impl<H: Hook> Hook for ArcHook<H> {
|
||||
@@ -669,7 +614,6 @@ fn session_dir(cwd: &std::path::Path, cfg: &Config) -> Result<std::path::PathBuf
|
||||
.map_or("host".into(), |h| h.trim().to_string())
|
||||
});
|
||||
let dir = hx_core::session::dir(&root, cwd, host.as_deref());
|
||||
// fail loud: a silent fallback would leave sessions off the cloud folder
|
||||
std::fs::create_dir_all(&dir)
|
||||
.map_err(|e| anyhow::anyhow!("sessions dir {}: {e}", dir.display()))?;
|
||||
Ok(dir)
|
||||
@@ -683,7 +627,6 @@ async fn main() -> Result<()> {
|
||||
match cli.cmd {
|
||||
Some(Cmd::Serve { acp, cwd, session }) => {
|
||||
anyhow::ensure!(acp, "hx serve: --acp is required");
|
||||
// file-name safe, so the id maps to one session file
|
||||
let id: String = session
|
||||
.chars()
|
||||
.map(|c| {
|
||||
@@ -864,8 +807,6 @@ async fn main() -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
Some(Cmd::McpServe) => {
|
||||
// claude starts this and hides its stderr: a failed start shows up only as
|
||||
// "mcp__hx__approve not found", so the reason goes to a log file as well
|
||||
let r = mcp_serve().await;
|
||||
if let Err(e) = &r {
|
||||
mcp_serve_log(&format!("mcp-serve failed: {e:#}"));
|
||||
@@ -894,7 +835,6 @@ async fn main() -> Result<()> {
|
||||
if let Some(oc) = cfg.openai_compat.clone() {
|
||||
let _ = COMPAT.set(oc);
|
||||
}
|
||||
// auto-detect, except against a test server (HX_BASE_URL)
|
||||
let cli_args = match cfg.claude_cli.clone() {
|
||||
Some(CliCfg::Args(a)) => Some(a),
|
||||
Some(CliCfg::Switch(on)) => on.then(Vec::new),
|
||||
@@ -906,18 +846,15 @@ async fn main() -> Result<()> {
|
||||
if let Some(a) = cli_args {
|
||||
let _ = CLAUDE_CLI.set(a);
|
||||
}
|
||||
// MCP servers connect while the model catalog loads
|
||||
let mcp_cfg = hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?;
|
||||
let mcp = hx_mcp::Hub::spawn(mcp_cfg);
|
||||
let kinds = logged_in();
|
||||
let last_path = context::hx_home().join("last.json");
|
||||
let remember = cfg.remember_model != Some(false);
|
||||
// last /model choice, only while its provider is still logged in
|
||||
let last = remember
|
||||
.then(|| hx_core::switch::Last::load(&last_path))
|
||||
.flatten()
|
||||
.filter(|l| kinds.contains(&l.provider));
|
||||
// default provider: flag, config, last choice, else the first one logged in
|
||||
let kind = cli
|
||||
.provider
|
||||
.or(cfg.provider)
|
||||
@@ -926,16 +863,13 @@ async fn main() -> Result<()> {
|
||||
.unwrap_or(Kind::Claude);
|
||||
let models = catalog(&kinds).await;
|
||||
trace("catalog");
|
||||
// an explicit model picks its provider unless --provider says otherwise
|
||||
let kind = match (&cli.provider, cli.model.as_deref().or(cfg.model.as_deref())) {
|
||||
(None, Some(m)) => hx_ai::models::kind_of(&models, m).unwrap_or(kind),
|
||||
_ => kind,
|
||||
};
|
||||
// the remembered model applies only to the provider it was chosen on
|
||||
let last_fable = last.as_ref().and_then(|l| l.fable);
|
||||
let last = last.filter(|l| l.provider == kind);
|
||||
let last_effort = last.as_ref().and_then(|l| l.effort);
|
||||
// auto mode: `--model auto` / `model = "auto"`, else whatever was on last time
|
||||
let want_auto = match cli.model.as_deref().or(cfg.model.as_deref()) {
|
||||
Some(m) => m == "auto",
|
||||
None => last.as_ref().is_some_and(|l| l.auto),
|
||||
@@ -1014,7 +948,6 @@ async fn main() -> Result<()> {
|
||||
.unwrap_or(context::DEFAULT_PROMPT)
|
||||
));
|
||||
trace("prompt");
|
||||
// short grace so fast servers land in the (cache-stable) startup prompt; slow ones connect in the background
|
||||
mcp.wait_all(std::time::Duration::from_secs(1)).await;
|
||||
trace("mcp");
|
||||
mcp.register(&mut agent.tools);
|
||||
@@ -1079,7 +1012,6 @@ async fn main() -> Result<()> {
|
||||
let _ = tl.state.set(agent.cx.state.clone());
|
||||
agent.bus.add(tl);
|
||||
}
|
||||
// rust-analyzer & co are slow to index: start servers for languages present at the top level now
|
||||
let probe: Vec<_> = std::fs::read_dir(&cwd)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
@@ -1103,7 +1035,6 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
trace("lens");
|
||||
if !cli.no_subagents && cfg.subagents != Some(false) {
|
||||
// children get the parent's tools as of now (no `task`, so no recursion)
|
||||
let mut general = agent.tools.clone();
|
||||
general.retain(|n| n != "ask_user" && n != "exit_plan");
|
||||
let mut explore = agent.tools.clone();
|
||||
@@ -1140,7 +1071,6 @@ async fn main() -> Result<()> {
|
||||
hx_ai::models::cheap_for(kind, &models).or_else(|| Some(agent.model().to_string())),
|
||||
)
|
||||
{
|
||||
// auto permissions: a cheap model judges the commands the rules cannot classify
|
||||
let _ = agent
|
||||
.cx
|
||||
.state
|
||||
@@ -1148,7 +1078,6 @@ async fn main() -> Result<()> {
|
||||
.set(hx_core::danger::Judge { provider: p, model });
|
||||
}
|
||||
if cfg.codemode.unwrap_or(false) {
|
||||
// snapshot after every other tool (MCP, lens, task); codemode itself is not callable inside
|
||||
let cm = hx_tools::codemode::Codemode::new(&agent.tools);
|
||||
agent.tools.add(cm);
|
||||
agent.append_system(
|
||||
@@ -1183,19 +1112,15 @@ async fn main() -> Result<()> {
|
||||
anyhow::bail!("--mode json needs -p <prompt>");
|
||||
}
|
||||
if CLAUDE_CLI.get().is_some() {
|
||||
// claude asks here (via `hx mcp-serve`) before running its tools
|
||||
let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone());
|
||||
let _ = CLAUDE_CX.set(cx.clone());
|
||||
let bus = agent.bus.clone();
|
||||
// only -p has no prompt; `permissions = "deny" | "extensions-only"` closes it
|
||||
let mode = hx_core::approve::Unanswered::from_config(cfg.permissions.as_deref());
|
||||
tokio::spawn(async move {
|
||||
let _ = hx_core::approve::serve(&p, cx, bus, mode).await;
|
||||
});
|
||||
}
|
||||
if let Some(id) = acp_id {
|
||||
// no TUI, no prompts: every permission question goes to the orchestrator, except what
|
||||
// --yolo / --auto (or `permissions` in config.toml) settle here, the same as in the TUI
|
||||
{
|
||||
let yolo = cli.yolo || cfg.permissions.as_deref() == Some("yolo");
|
||||
let auto = cli.auto || cfg.permissions.as_deref() == Some("auto");
|
||||
|
||||
Reference in new issue
Block a user