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
@@ -0,0 +1,14 @@
|
||||
# ACP step outcome via closing hx-step block
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
The orchestrator needs step outcome, decisions and plan from every provider, including the `claude` CLI, whose tools hx does not own and so cannot hook with custom tool calls. In ACP, file tools have no permission rule, and a stuck tool can block a stop.
|
||||
|
||||
## Decision
|
||||
The model reports step outcome, decisions and plan in a closing ```hx-step JSON block of its reply, which works identically for all providers. Stops are soft: the run ends at the next turn boundary and a stuck tool gets a grace period. "Always" on a file-tool permission means all edits for the session, since file tools have no rule to store.
|
||||
|
||||
## Consequences
|
||||
Provider-independent protocol, but correctness relies on the model emitting a parseable block.
|
||||
|
||||
Code: crates/hx-cli/src/acp.rs (module doc, permission wiring around the file-tool "always" case, step run loop soft stop)
|
||||
@@ -0,0 +1,17 @@
|
||||
# Running the claude CLI under hx
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
`claude` keeps its own tools while hx supplies MCP servers through `hx mcp-serve`. Claude starts that child and hides its stderr; inside the sandbox claude needs its binary dir, config, network, and on macOS the login keychain (else "Not logged in").
|
||||
|
||||
## Decision
|
||||
- Leaving the sandbox for claude requires an explicit stored rule (`claude:unsandboxed` in `.hx/allow.json`), is never asked for and never implied by yolo: yolo is only safe because claude's tools stay confined.
|
||||
- hx's MCP servers are given to claude directly, or only through `codemode` when enabled; claude sees only `hx mcp-serve` tools. A server entry that is hx itself is skipped to avoid recursive spawning. Codemode-run tools ask hx for permission like any other.
|
||||
- Sandbox profile includes claude's resolved install dir (versions/..) and the macOS keychain.
|
||||
- mcp-serve startup failures are also written to `$TMPDIR/hx-mcp-serve.log`, since the only visible symptom is "mcp__hx__approve not found".
|
||||
|
||||
## Consequences
|
||||
Sandbox escape is auditable; failures are diagnosable via the log.
|
||||
|
||||
Code: crates/hx-cli/src/main.rs (claude unsandboxed rule, mcp_serve, claude sandbox spec, CLAUDE_CODEMODE/mcp tool config, mcp-serve log)
|
||||
@@ -0,0 +1,14 @@
|
||||
# RPC concurrency and failing loud on session storage
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
A prompt holds the agent lock for its whole run. Separately, a silent fallback for a misconfigured `sessions_dir` would put sessions outside the cloud folder.
|
||||
|
||||
## Decision
|
||||
RPC `abort` and `complete` are handled without taking the agent lock so they work while a prompt runs. An unusable sessions dir fails loudly instead of falling back.
|
||||
|
||||
## Consequences
|
||||
Abort stays responsive; misconfiguration surfaces at startup.
|
||||
|
||||
Code: crates/hx-cli/src/rpc.rs (request dispatch), crates/hx-cli/src/main.rs (sessions dir resolution)
|
||||
@@ -0,0 +1,16 @@
|
||||
# Startup latency, prompt cache stability and tool snapshots
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Startup should be fast, yet the system prompt must stay cache-stable. Slow MCP servers and model list fetches would delay it.
|
||||
|
||||
## Decision
|
||||
- Model catalog: stale-while-revalidate; any cached list starts immediately, an expired one refreshes in the background.
|
||||
- MCP servers get a short grace period so fast ones land in the (cache-stable) startup prompt; slow ones connect in the background.
|
||||
- The tool snapshot for `task` subagents and codemode is taken after every other tool (MCP, lens, task) is registered; children get the parent's tools as of then, without `task` (no recursion), and codemode is not callable inside itself.
|
||||
|
||||
## Consequences
|
||||
Late-connecting servers do not appear in the startup prompt.
|
||||
|
||||
Code: crates/hx-cli/src/main.rs (model catalog loader, run/startup MCP wait, subagent and codemode tool registration)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Agent loop ordering and failure handling invariants
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Providers require tool results to come before any images in the following user message. A model reply with no text and no tool call (for example output_tokens 0) would poison the context: every "continue" would hit the same empty reply. Transient API errors can be retried safely only before any event was emitted to the consumer. A session file can end in a torn line after a crash.
|
||||
|
||||
## Decision
|
||||
Images are appended after all tool results of a round. Empty replies are never stored; the request is retried (up to 3 retries on transient errors, only before events were emitted) and an error is returned if it stays empty. Session open skips a torn last line rather than losing the session. Subagent abort: the parent flag resets after each run, so the parent re-arms propagation once per session to reach all running children; a child waiting for a concurrency slot re-checks abort afterwards.
|
||||
|
||||
## Consequences
|
||||
Context stays valid and resumable; mid-stream failures are not retried.
|
||||
|
||||
Code: crates/hx-core/src/agent.rs:run, stream_retry; session.rs:Session::open; subagent.rs:Subs
|
||||
@@ -0,0 +1,14 @@
|
||||
# Permission bridge fails closed and delegates to the socket owner
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
The `claude` CLI provider asks permission through `hx mcp-serve`, which forwards over a Unix socket to the TUI process. hx tools run by `codemode` inside mcp-serve ask for their own permission.
|
||||
|
||||
## Decision
|
||||
Unknown `permissions` config values (typos) deny: it is a safety setting and failing open would hide the mistake. An unreachable socket denies. The socket owner stores "always" itself, so on the bridge side a yes is a plain yes. Interactive modes (`ask`, `auto`, `yolo`) leave `-p` behavior unchanged.
|
||||
|
||||
## Consequences
|
||||
Misconfiguration is visible rather than silently permissive.
|
||||
|
||||
Code: crates/hx-core/src/approve.rs
|
||||
@@ -0,0 +1,14 @@
|
||||
# Mask old tool results late and monotonically
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Old, large tool results are replaced by one-line stubs in the request; the session file keeps originals. Every change of the masked prefix rewrites the provider prompt cache from the first changed result on. A reading of real token usage and the masking boundary each describe one specific history. With a 1M window, "a third of the compaction threshold" is about 300k tokens, far beyond the point where resending old results costs more than one cache rewrite. The 60k cap came from two real sessions (contexts of 72k and 105k).
|
||||
|
||||
## Decision
|
||||
The boundary only moves forward, and only once the context passes a third of the compaction threshold (at most `MASK_FROM_MAX` = 60k tokens). While it stays put the request prefix is byte-stable. `reset` drops both the reading and the boundary whenever history is replaced or rewritten (new session, fork, clear, compaction); until the next `record` the count is a pure estimate. The boundary is stored with each assistant reply so requests can be replayed (files written before that used a stepwise rule).
|
||||
|
||||
## Consequences
|
||||
Cache is rewritten rarely, so savings beat the rewrite cost. Callers must call `reset` on any history change and `masked`/`next` once per request after compaction. The 60k constant needs tuning from `hx stats`.
|
||||
|
||||
Code: crates/hx-core/src/window.rs:ContextWindow, MASK_FROM_MAX; session.rs:append_masked
|
||||
@@ -0,0 +1,14 @@
|
||||
# Model and provider routing respects prompt-cache cost
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
A tier or provider switch makes the next request re-read the whole history uncached. Big histories make switches costly; a 1M-context session cannot move to a 200k model; Fable is the most expensive tier.
|
||||
|
||||
## Decision
|
||||
Up-tiers apply immediately; a cheaper tier only after `down_after` light prompts in a row, and the hold grows with history size. Fable is dropped at once. A tier is skipped if the history would not fit the target window. Provider choice prefers the current provider (keeps the cache), then a logged-in one with the exact tier; providers out of quota are avoided when alternatives exist; custom endpoints serve only when nothing else is logged in. Switching providers rebuilds the client even for the same provider so refreshed credentials are picked up. Auto picks and one-turn overrides are not recorded as the user's pinned choice.
|
||||
|
||||
## Consequences
|
||||
Fewer cache-busting switches at the cost of slower step-down. Routing needs the history size and window as inputs.
|
||||
|
||||
Code: crates/hx-core/src/route.rs:Router::choose, pick_provider; switch.rs:Switcher::set_provider, prepare
|
||||
@@ -0,0 +1,15 @@
|
||||
# Context shaping must keep the cached prefix stable
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Prompt caching keys on the request prefix. Any change to earlier bytes invalidates the cache from that point on.
|
||||
|
||||
## Decision
|
||||
- Observation masking is a pure function of the message list and a boundary, so the prefix is byte-stable while the boundary stays put. Moving the boundary rewrites the cache from the first changed result, so the agent moves it rarely, in steps of a fixed number of assistant turns. The session file keeps the originals.
|
||||
- The batching nudge is injected at turn end so the cached prefix is untouched.
|
||||
|
||||
## Consequences
|
||||
Masking lags behind the ideal point in exchange for cache hits.
|
||||
|
||||
Code: crates/hx-core/src/mask.rs (module, `boundary`, `apply`), crates/hx-core/src/nudge.rs
|
||||
@@ -0,0 +1,14 @@
|
||||
# Compaction cut points keep roles alternating
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
The summary must be folded into the history without breaking provider rules: roles alternate and every `tool_use` keeps its result.
|
||||
|
||||
## Decision
|
||||
Compaction cuts at the latest user prompt and folds the summary into it. Inside one long tool loop with no prompt to cut at, it cuts before an assistant message and the summary becomes its own leading user message, so the kept history still alternates and the pending `tool_use` still has its result.
|
||||
|
||||
## Consequences
|
||||
Summaries sit at a prompt boundary when possible; the fallback handles single huge tool loops.
|
||||
|
||||
Code: crates/hx-core/src/compact.rs (`plan`, `Plan`, test for the no-prompt case)
|
||||
@@ -0,0 +1,17 @@
|
||||
# Herdr state reporting is lossy, ordered and non-blocking
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
hx reports idle/working/blocked, a resume command and release to the herdr that owns the pane. Reporting must never slow the agent.
|
||||
|
||||
## Decision
|
||||
- Reports go through one worker that sends only the latest state; intermediate states are dropped and the agent never blocks.
|
||||
- The sequence number is wall-clock millis bumped within the process, so it is strictly increasing across processes.
|
||||
- The first report claims the pane; `report` marks the state changed again on every update.
|
||||
- Resume args must not contain apostrophes or control characters; herdr rejects them.
|
||||
|
||||
## Consequences
|
||||
Herdr may miss transient states, but ordering holds across restarts.
|
||||
|
||||
Code: crates/hx-core/src/herdr.rs (module, resume arg sanitising, sequence counter, worker start)
|
||||
@@ -0,0 +1,17 @@
|
||||
# Hook dispatch and extension protocol semantics
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Lens, MCP and extensions all plug into the event bus, and extensions are untrusted external processes.
|
||||
|
||||
## Decision
|
||||
- Hooks run in registration order; the first `Block` wins; a `Mutate` is visible to later hooks.
|
||||
- Bus clones share the hook list, so the permission bridge can emit on the agent's bus.
|
||||
- Extensions speak newline-delimited JSON-RPC 2.0 over stdio: `initialize {protocolVersion, cwd}` returns subscribed event types and tools; `event {event}` returns `{action: continue|block|mutate|inject, ...}`; `tool/call {name, args}` returns `{content, is_error}`.
|
||||
- A dead or slow extension never blocks the agent: errors and timeouts count as `continue`.
|
||||
|
||||
## Consequences
|
||||
Ordering matters for hook authors; failing extensions degrade silently to no-ops.
|
||||
|
||||
Code: crates/hx-core/src/hook.rs (`Bus`, dispatch), crates/hx-core/src/ext.rs (module)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Memory index is capped and write fails when full
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
The `MEMORY.md` index goes into every system prompt.
|
||||
|
||||
## Decision
|
||||
A per-scope cap on index size makes `write` fail when full, so the agent must consolidate or forget entries instead of growing the prompt.
|
||||
|
||||
## Consequences
|
||||
Upserts of existing lines still work when full.
|
||||
|
||||
Code: crates/hx-core/src/memory.rs (index cap, `write`)
|
||||
@@ -0,0 +1,17 @@
|
||||
# Command parsing and "allow always" rules are conservative
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Read-only commands run without a prompt and "allow always" persists patterns. A permissive parser or glob would let a harmless-looking prefix authorise a dangerous chain, e.g. `cargo test && rm -rf ~`.
|
||||
|
||||
## Decision
|
||||
- The auto-run read-only list deliberately omits `env`, `xargs`, `sed`, `cargo`, `curl` (they exec, write or reach the network).
|
||||
- The chain splitter accepts only `|`, `&&`, `;` and the redirects `2>&1` / `>/dev/null`. Anything else the shell would interpret (`||`, `&`, `$`, backticks, parens, `<`, `>`, newlines, open quotes) returns `None` and asks.
|
||||
- `cd` is free: it only matters for what follows, which is checked on its own.
|
||||
- "Allow always" stores one rule per non-read-only segment (first word plus subcommand, e.g. `bash:cargo test *`), joined by newlines; risky segments store their exact text; unparsable commands get no rule. A rule therefore cannot cover a chain it was not granted for. File tools get no rule; the prompt offers "allow all edits this session".
|
||||
|
||||
## Consequences
|
||||
Heredocs, `{}` groups and similar always prompt. Rules are coarse globs.
|
||||
|
||||
Code: crates/hx-core/src/permit.rs (READONLY list, `split_chain`, `cd` handling, `rule`)
|
||||
@@ -0,0 +1,16 @@
|
||||
# Permission gate ordering and auto-mode fail-safe
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Parallel tool calls may each need a prompt, and auto mode layers rules, a classifier and an LLM judge.
|
||||
|
||||
## Decision
|
||||
- Prompts are serialized behind one lock; after waiting, the stored rules are re-checked because the previous answer (e.g. "always") may already cover this call.
|
||||
- In auto mode, dangerous calls are refused without a prompt, even when a stored "always" rule matches; safe calls run; the rest goes to the judge, then the user.
|
||||
- The judge is a cheap model; any failure or unusable answer means "ask the user", never "allow".
|
||||
|
||||
## Consequences
|
||||
A stored rule never overrides a danger block. Concurrent calls queue, so prompts are one at a time.
|
||||
|
||||
Code: crates/hx-core/src/tool.rs (`gate`, `gate_result`), crates/hx-core/src/lib.rs (`ToolState` prompt lock), crates/hx-core/src/danger.rs (`Judge`)
|
||||
@@ -0,0 +1,18 @@
|
||||
# Sandbox profile ordering and git compatibility
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Both backends build a "hide $HOME, then re-allow" policy. Git is run inside the sandbox and is picky about what it can stat and read.
|
||||
|
||||
## Decision
|
||||
- Paths are canonicalised after lexical `..`/`.` removal, so a non-existent prefix cannot hide an escape from the project dir.
|
||||
- bwrap: hide `$HOME` and `/tmp` first, then mount back the allowed paths; later mounts win.
|
||||
- seatbelt: the last matching rule wins, so hide `$HOME` first and re-allow after.
|
||||
- Git resolves paths component by component and dies on EPERM, so the sandbox grants metadata-only `stat` (`literal`: the directory itself, not its contents) on `$HOME` and every directory above an allowed path.
|
||||
- Files named by `[include]`/`[includeIf]` in the global git config are made readable (followed a few levels), and the `gitdir:` directories of `includeIf` get metadata access, because git resolves them on every start and fails to start without them.
|
||||
|
||||
## Consequences
|
||||
Rule order is load-bearing and must not be reshuffled. Git config includes expand the readable surface slightly.
|
||||
|
||||
Code: crates/hx-core/src/sandbox.rs (path canonicalisation, git include scan, bwrap args, seatbelt profile)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Sandbox covers child processes only and fails closed
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Bash, LSP servers, lens runners and test runners are spawned as child processes. File tools run inside the hx process, so a process-level sandbox cannot confine them. The hx process also holds the LLM API access and OAuth tokens and must stay outside the sandbox.
|
||||
|
||||
## Decision
|
||||
Every sandboxed spawn goes through `sandbox::command`, a drop-in for `Command::new`. With the sandbox off it is a plain command. With it on, the program runs under `bwrap` (Linux) or `sandbox-exec` (macOS): filesystem read-only except the project dir and `rw`, `$HOME` hidden except `ro`/`rw`, no network unless `network`, environment filtered. File tools call `guard_read` / `guard_write` themselves. If `mode = on` and no backend works, startup errors instead of silently running unsandboxed.
|
||||
|
||||
## Consequences
|
||||
In-process tools need explicit guards. A misconfigured host refuses to start rather than giving a false sense of safety.
|
||||
|
||||
Code: crates/hx-core/src/sandbox.rs (module doc, `command`, `guard_read`, `guard_write`, init)
|
||||
@@ -0,0 +1,16 @@
|
||||
# Native build dependencies and TUI test terminal handling
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
rquickjs-sys needs a C compiler; rustls may pull aws-lc-sys, which needs cmake; the sandbox needs bubblewrap at runtime on Linux. The TUI smoke test runs under a pty with temp dirs.
|
||||
|
||||
## Decision
|
||||
- devenv provides `stdenv.cc` (gcc on Linux, clang on macOS) for rquickjs-sys (QuickJS).
|
||||
- flake.nix adds cmake and perl as native inputs because rustls may build aws-lc-sys depending on features, with cmake configure disabled; it wraps the binary with bubblewrap on PATH (Linux only).
|
||||
- tui_smoke resolves the temp dir with realpath because hx sees the real cwd (macOS /var -> /private/var) and derives the session dir slug from it. Screen text can be split by ratatui's cursor-move diffing, so the test asserts on the OSC window title, which is written whole and carries the old prompt only once the session is resumed.
|
||||
|
||||
## Consequences
|
||||
Packaging stays correct on both platforms; tests avoid flaky screen-scraping.
|
||||
|
||||
Code: devenv.nix:packages, flake.nix:hx (nativeBuildInputs, postInstall), tests/tui_smoke.py
|
||||
@@ -0,0 +1,19 @@
|
||||
# CI release pipeline constraints
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Builds run in the `cargo-zigbuild` image on Gitea act_runner, followed by a release job that commits `bin.json` consumed by `flake.nix`.
|
||||
|
||||
## Decision
|
||||
- Version: next = highest `vX.Y.Z` tag with patch bumped; minor/major bumps are done by pushing a tag by hand.
|
||||
- The image bundles rust, zig, cargo-zigbuild, both targets and a macOS SDK (SDKROOT), so no per-run toolchain setup; the runner keeps the pulled image.
|
||||
- The image has no node, which act_runner needs for JS actions, so node is installed first.
|
||||
- The release job checks out `main`, not the build sha, because `bin.json` is committed on top of it.
|
||||
- Artifacts lose the executable bit; it is restored before packaging.
|
||||
- Gitea creates the tag at `target_commitish` when it does not exist, so the release API call creates the tag.
|
||||
|
||||
## Consequences
|
||||
The workflow depends on the pinned image and node version; bin.json commits are excluded from triggers via paths-ignore.
|
||||
|
||||
Code: .gitea/workflows/build.yml (version, build, release jobs)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Attribute on-disk changes during a run to hx and re-baseline the read-guard
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
During an agent run, files can change through bash, subagents or aborted tools that already wrote. Those are the agent's own changes, not the user's. Treating them as external edits would block the agent's next edit via the read-guard. Separately, a file can change on disk while the lens is still checking it, making the findings untrustworthy.
|
||||
|
||||
## Decision
|
||||
Anything that changed on disk during the run is attributed to hx (not the user) and the read-guard is re-baselined, including after our own formatting. Only edits made while the model was thinking count as external. A freshness gate labels results when a file changed during the check instead of trusting them.
|
||||
|
||||
## Consequences
|
||||
No spurious "file changed externally" errors for the agent; genuinely external edits made between turns are still detected by the mtime watcher.
|
||||
|
||||
Code: crates/hx-lens/src/lib.rs (turn-start/end handling, report freshness gate)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Wait for rust-analyzer's on-save flycheck before trusting diagnostics
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
The lens injects diagnostics at turn end. rust-analyzer publishes plain syntax/semantic diagnostics immediately, but the cargo check results (flycheck) arrive later, after a `$/progress` `end` event, and only when the file was saved. Taking the first publish after a change gives an empty or stale result. A check still running from an earlier turn, or one that ends after our save but belongs to an earlier save, carries stale results. Under parallel cargo load, flycheck may also start late.
|
||||
|
||||
## Decision
|
||||
`Client::diagnostics_after` waits in stages: any check still running from an earlier turn or startup must finish first; checks are counted from after our own save so a check that is still ending from an earlier save is ignored; with `expect_check` it waits until a flycheck completes (checks_done grows and none active) or, if none ever starts within 15s (checkOnSave disabled, or queued under load), gives up; once the check ends it waits up to 10s for a publish that arrives after it. The test script runs the real rust-analyzer test alone, after the parallel suite, for the same reason. The test fixture also keeps the fix file's mtime clearly newer than the last check's start, since cargo's freshness check uses mtimes.
|
||||
|
||||
## Consequences
|
||||
Turn-end reports are slower (bounded by the 15s/10s limits) but not stale. Tests depending on rust-analyzer are serialized in `tests/all.sh`.
|
||||
|
||||
Code: crates/hx-lens/src/lsp.rs:Client::diagnostics_after, crates/hx-lens/src/lib.rs (rust_analyzer_turn_end test), tests/all.sh
|
||||
@@ -0,0 +1,18 @@
|
||||
# Handling of LSP server quirks and root selection
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Language servers behave inconsistently: some send `workspace/configuration` requests expecting an array of results; the rustup `rust-analyzer` proxy exits immediately when the component is not installed; servers still indexing answer requests with -32801 (ContentModified) or -32802 (ServerCancelled). Rust and TypeScript workspaces have nested markers (inner Cargo.toml / package.json), but servers must be started at the workspace root.
|
||||
|
||||
## Decision
|
||||
- Server requests: `workspace/configuration` gets an array of nulls sized to the request; all other server requests get a null result.
|
||||
- A server that exits immediately (rustup proxy without component) is treated as not installed, not as a crash.
|
||||
- Requests failing with -32801/-32802 are retried briefly, since the server is still indexing.
|
||||
- Root resolution for rust/ts keeps climbing to the outermost marker below the stop dir; the outermost Cargo.toml wins (workspace root); with no marker the workspace root is used.
|
||||
- A fake rust-analyzer test models that the first (empty) publish after a change must not be taken as the result.
|
||||
|
||||
## Consequences
|
||||
Servers are keyed by (language, outermost root), so one server serves a whole workspace. Retries add bounded latency.
|
||||
|
||||
Code: crates/hx-lens/src/lsp.rs (server request handler), crates/hx-lens/src/manager.rs (start, request, root detection, fake rust-analyzer test)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Anthropic and OAuth wire quirks
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Anthropic OAuth tokens are accepted only with Claude Code tool-name casing. Tool ids must match `[a-zA-Z0-9_-]` while Codex ids look like `call|item`. Thinking from another provider (no signature, or a Codex reasoning item) is invalid. Cache breakpoints cover tools+system via the system block. The thinking budget counts against max_tokens. The token endpoint wants JSON for Anthropic and form encoding for OpenAI. Claude's login uses the PKCE verifier as state (matching Claude Code); Codex uses a random state.
|
||||
|
||||
## Decision
|
||||
Map tool names to Claude Code casing and sanitize ids on the way out; drop foreign thinking blocks; place rolling cache breakpoints on the last message and the user message before it (where the previous request's breakpoint sat, giving a cache read); keep max_tokens above the thinking budget; encode token requests per provider; follow each provider's state convention.
|
||||
|
||||
## Consequences
|
||||
Requests are accepted and cache well; conversion code must be kept in sync with these provider rules.
|
||||
|
||||
Code: crates/hx-ai/src/anthropic.rs (tool names, id sanitizing, foreign thinking, cache breakpoints, thinking budget); crates/hx-ai/src/auth.rs (token request encoding, login state)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Claude via the official claude CLI
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Anthropic bills OAuth traffic from third-party apps as extra usage, while the official binary keeps using the subscription. In plan mode, claude's `ExitPlanMode` is rejected unless it runs with `--permission-mode plan`. On newer models print mode defaults to omitted thinking (empty thinking text).
|
||||
|
||||
## Decision
|
||||
Offer a provider that drives the real `claude -p --output-format stream-json`; claude runs its own agent loop and hx only displays the stream. When hx plan mode is on, pass `--permission-mode plan`. Pass the flag that restores thinking display.
|
||||
|
||||
## Consequences
|
||||
Subscription billing is preserved. hx depends on claude's flags and stream format.
|
||||
|
||||
Code: crates/hx-ai/src/claude_cli.rs (module, plan-mode flag, command args)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Codemode execution model
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
The model writes JS run in QuickJS; only script output reaches the model. QuickJS values are not Send. The interrupt handler only fires while JS runs, not while awaiting tools.
|
||||
|
||||
## Decision
|
||||
Inner calls go through `Registry::call` so the permission gate and shared State (read-before-edit, edit log) apply. Each script runs on its own thread with a local runtime. Waiting for a free worker counts toward the timeout; time spent awaiting tools is bounded separately. The run stops when the script settles and unawaited calls are cancelled. Store writes apply only to successful scripts. MCP tools are listed first so builtins cannot push them out of the listing budget.
|
||||
|
||||
## Consequences
|
||||
Scripts cannot bypass permissions; failed scripts leave no partial store state.
|
||||
|
||||
Code: crates/hx-tools/src/codemode.rs (module, run, tool listing, store handling)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Codex backend quirks
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Codex tool calls carry a call id and an item id. Reasoning items are encrypted and the request uses store=false. Codex models cannot switch reasoning off. The server hides models whose `minimal_client_version` exceeds the client's.
|
||||
|
||||
## Decision
|
||||
Store tool ids as `call_id|item_id` so both survive a round trip; replay the encrypted reasoning item verbatim; map Off to the lowest supported level; claim a high client version (override `HX_CODEX_CLIENT_VERSION`) so models are listed.
|
||||
|
||||
## Consequences
|
||||
Round trips are lossless; the claimed version only affects listing, the server still gates use.
|
||||
|
||||
Code: crates/hx-ai/src/codex.rs (id encoding, reasoning replay, effort mapping, client version); crates/hx-ai/src/lib.rs:Effort (start level, levels)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Lazy MCP tool registration
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Full MCP tool schemas cost many prompt tokens, but a lazy index costs an extra `mcp_describe` round trip. Startup listing must not stall a server for the full tool-call timeout.
|
||||
|
||||
## Decision
|
||||
Default to a one-line-per-tool index; the model fetches schemas with `mcp_describe` and calls via `mcp_call`. Servers whose schemas fit in `EAGER_MAX_TOKENS` (or `eager: true`) register natively, since below the threshold the saved tokens do not pay for the round trip. Startup listing uses its own shorter timeout.
|
||||
|
||||
## Consequences
|
||||
Smaller prompts for large servers; two modes to maintain.
|
||||
|
||||
Code: crates/hx-mcp/src/lib.rs (module, EAGER_MAX_TOKENS, connect)
|
||||
@@ -0,0 +1,14 @@
|
||||
# OpenAI-compatible server tolerance
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Servers (Ollama, vLLM, LM Studio, OpenRouter) vary: tool results must directly follow the assistant's tool_calls, not all accept content arrays, not all know `reasoning_effort`, some close without `[DONE]`. Custom endpoints are cheap to query and their config is edited by hand.
|
||||
|
||||
## Decision
|
||||
Emit tool results first, use plain string content, retry once without `reasoning_effort`, and still emit Done when the stream ends without `[DONE]`. Never serve the model-list cache first for custom endpoints.
|
||||
|
||||
## Consequences
|
||||
Wider server compatibility at the cost of an extra request in the retry case. Providers must always emit `Done` last with the full assembled message.
|
||||
|
||||
Code: crates/hx-ai/src/openai_compat.rs (message conversion, request retry, stream end); crates/hx-ai/src/models.rs:list_models; crates/hx-ai/src/lib.rs:StreamEvent
|
||||
@@ -0,0 +1,14 @@
|
||||
# Safe network fetch and process handling
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
web_fetch could be redirected to private hosts. bash children survive timeouts unless killed as a group. stdin reads in tokio block runtime shutdown.
|
||||
|
||||
## Decision
|
||||
Follow redirects manually and check every hop; spawn bash in its own process group so timeouts kill children; read stdin for login on a detached std thread.
|
||||
|
||||
## Consequences
|
||||
SSRF via redirects is blocked; shutdown is not delayed by pending stdin.
|
||||
|
||||
Code: crates/hx-tools/src/web.rs (GET), crates/hx-tools/src/lib.rs (bash), crates/hx-ai/src/auth.rs (stdin wait)
|
||||
@@ -0,0 +1,18 @@
|
||||
# Safety and cost guards in reload, lens polling, revert and completion
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Several UI paths touch shared state or expensive resources: `/reload` rewrites the system prompt (which invalidates the provider prompt cache); the lens poll takes the LSP manager lock, which a starting server can hold; `/diff` revert writes to user files that may have been edited by hand; `@file` completion needs a large file list; the keyboard-protocol query must precede the alternate screen.
|
||||
|
||||
## Decision
|
||||
- `/reload` leaves the agent's prompt untouched when it is unchanged, since a rewrite would drop the prompt cache.
|
||||
- The lens poll uses a 200 ms timeout on the status call because the manager lock can be held while a server starts.
|
||||
- Reverting a file refuses when its content is not what the agent left, so manual edits are never overwritten; files the agent created are deleted.
|
||||
- Command/argument completion is live, but `@file` completion waits for Tab because the file list is big; Enter on an empty or complete token passes through and submits.
|
||||
- The keyboard-enhancement support query runs before entering the alternate screen.
|
||||
|
||||
## Consequences
|
||||
Prompt cache stays warm, the UI never blocks on a slow server, and user edits are protected. Status can be stale by one poll when the lock is busy.
|
||||
|
||||
Code: crates/hx-tui/src/lib.rs (reload handler, lens_tick, completion), crates/hx-tui/src/review.rs:revert, crates/hx-tui/src/popup.rs
|
||||
@@ -0,0 +1,14 @@
|
||||
# Mouse selection in content coordinates, capped OSC 52 copy
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
The chat scrolls and streams while the user selects. Copying goes through OSC 52, and some terminals drop payloads above a size limit.
|
||||
|
||||
## Decision
|
||||
Selection coordinates are `(row, col)` in the wrapped content, not on screen, so scrolling does not move a selection. The selected text is extracted from an off-screen render of the chat. OSC 52 payloads are cut to `MAX_COPY` bytes on a char boundary.
|
||||
|
||||
## Consequences
|
||||
Selections survive scrolling and streaming. Very large copies are silently truncated.
|
||||
|
||||
Code: crates/hx-tui/src/select.rs (module, MAX_COPY, truncate)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Tolerate half-streamed markdown and pin scroll position
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Assistant text is rendered while it streams, so input is often incomplete: an unclosed code fence or an unfinished table. Users also read earlier text while new text arrives below.
|
||||
|
||||
## Decision
|
||||
The markdown renderer treats an unclosed fence as code and an unfinished table as plain text instead of failing. Scroll state is either following the bottom (`top: None`) or pinned to a line (`Some(n)`); pinned views do not move when text streams in, and reaching the bottom resumes following.
|
||||
|
||||
## Consequences
|
||||
Rendering never needs the complete message; a table pops into a grid once complete. Scroll behaviour is predictable during streaming.
|
||||
|
||||
Code: crates/hx-tui/src/markdown.rs (module), crates/hx-tui/src/scroll.rs (module)
|
||||
@@ -0,0 +1,19 @@
|
||||
# Terminal input modes, paste handling and redraw throttle
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
Shift-enter must insert a newline, but terminals disagree on how to report it. The kitty keyboard protocol reports Enter+SHIFT (ghostty, kitty, wezterm, iTerm2, foot, alacritty, zellij). tmux does not speak that protocol: it forwards shift-enter only after the app requests xterm-style modifyOtherKeys, and as `ESC[13;2u` only with `extended-keys-format csi-u`. Terminals that do not answer the keyboard-enhancement query return false. Pasted text can contain ESC and other control characters. Terminals without bracketed paste deliver a paste as a flood of key events.
|
||||
|
||||
## Decision
|
||||
- Query keyboard-enhancement support before entering the alternate screen; push the kitty flags on the alternate screen only when the terminal answered.
|
||||
- Under tmux without kitty support, send the modifyOtherKeys request instead.
|
||||
- Install a panic hook that pops the keyboard flags and disables bracketed paste, so a crash does not leave the shell in that mode.
|
||||
- Enable bracketed paste so a paste arrives as one Paste event (no redraw per char, newlines do not submit).
|
||||
- Strip ESC and similar control chars from pasted text so pasted escape sequences cannot act on the terminal.
|
||||
- Redraw at most about 60 times per second (16 ms frame), so input stays ahead of the redraw when a paste arrives as key events.
|
||||
|
||||
## Consequences
|
||||
Shift-enter works across the listed terminals and tmux when configured. Terminal state is restored after a panic. Redraws can lag up to one frame.
|
||||
|
||||
Code: crates/hx-tui/src/lib.rs:run (setup before event loop, FRAME), crates/hx-tui/src/editor.rs:insert (paste sanitising)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Theme paints no background; colour marks status only
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
The UI uses Catppuccin Mocha but must work on arbitrary terminal themes, NO_COLOR, ASCII-only and non-truecolor terminals.
|
||||
|
||||
## Decision
|
||||
The background is never painted so the terminal's own ground shows through. Colour marks status only; `NO_COLOR` drops colours but keeps modifiers; `HX_ASCII=1` swaps in ASCII symbols; without `COLORTERM=truecolor|24bit` colours map to the nearest xterm-256 entry.
|
||||
|
||||
## Consequences
|
||||
Works on light and dark terminals; diff backgrounds are mixed from the base colour rather than painted across the screen.
|
||||
|
||||
Code: crates/hx-tui/src/theme.rs (module, nearest xterm-256 mapping)
|
||||
Reference in new issue
Block a user