Author SHA1 Message Date
hermes 45d296d911 Memory: /memory list+forget, /remember, memory counts in hx stats 2026-11-30 12:56:25 +00:00
hermes 8705b128ea Memory: byte-budgeted index, memory_search (BM25), auto extraction on compaction/exit 2026-11-30 12:46:16 +00:00
gitea-actions 59bf45f41d ci: bin.json v0.2.9 2026-11-29 10:29:43 +00:00
johannes 2866eeee28 feat: add consultant feature for asking a configured model mid-session
build / version (push) Successful in 17s
build / build (aarch64-apple-darwin) (push) Successful in 4m52s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m7s
build / release (push) Successful in 37s
Adds a new 'consult' tool that makes single tool-less calls to a configured
consultant model. The feature includes:
- Consult backend (consult.rs) with permission checks
- Call limit (default 5 per session) tracked in State
- Three nudge triggers: before exit_plan, after edits, after 3 failed tools
- Side-panel card showing consultant status and call count
- Config keys: consultant = "<model>" to enable; consultant_max_calls for limit
- All nudges are always on; disable by unsetting the consultant config

The consultant model sees the question and context (passed by itself since the
tool has no context visibility). Token usage counts toward subagent quotas.
2026-11-29 11:23:39 +01:00
gitea-actions 45f399ed6c ci: bin.json v0.2.8 2026-11-28 13:55:11 +00:00
johannesandClaude Sonnet 5.5 dfec176f43 feat: add --schema, --max-turns and rpc --ask
build / version (push) Successful in 16s
build / build (aarch64-apple-darwin) (push) Successful in 10m46s
build / build (x86_64-unknown-linux-musl) (push) Successful in 10m45s
build / release (push) Successful in 31s
- hx -p --schema <file> validates the final answer against a JSON schema,
  with one retry that includes the validation errors
- max_turns config key and --max-turns cap the main agent's model calls
- hx --mode rpc --ask sends permission requests to the client instead of
  auto-allowing bash/write/edit calls

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 14:15:03 +01:00
johannesandClaude Sonnet 5.5 13d914c8c0 style: fix clippy errors and formatting drift
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 14:15:03 +01:00
28 changed files with 1507 additions and 89 deletions

No files matched your search

Generated
+315 -10
View File
@@ -2,6 +2,20 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "ahash"
version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519"
dependencies = [
"cfg-if",
"getrandom 0.4.3",
"once_cell",
"serde",
"version_check",
"zerocopy",
]
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -166,7 +180,16 @@ version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"
dependencies = [
"bit-vec",
"bit-vec 0.6.3",
]
[[package]]
name = "bit-set"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
"bit-vec 0.8.0",
]
[[package]]
@@ -175,6 +198,12 @@ version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
[[package]]
name = "bit-vec"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -205,6 +234,12 @@ dependencies = [
"hybrid-array",
]
[[package]]
name = "borrow-or-share"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c"
[[package]]
name = "bstr"
version = "1.13.1"
@@ -227,6 +262,12 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"
[[package]]
name = "bytecount"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e"
[[package]]
name = "bytemuck"
version = "1.25.2"
@@ -542,6 +583,12 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "deltae"
version = "0.3.2"
@@ -629,6 +676,15 @@ version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
[[package]]
name = "email_address"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ab6bbd053d3cdc62ba3de82aae11530a97bbd5b3a572fbdbcd0f0e545e3ff21"
dependencies = [
"serde",
]
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -690,10 +746,21 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b95f7c0680e4142284cf8b22c14a476e87d61b004a3a0861872b32ef7ead40a2"
dependencies = [
"bit-set",
"bit-set 0.5.3",
"regex",
]
[[package]]
name = "fancy-regex"
version = "0.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a2e16b9a584b602f1e0e5e22c30ca0906786088c27500653e432d086def8b53"
dependencies = [
"bit-set 0.8.0",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "fastrand"
version = "2.5.0"
@@ -729,6 +796,17 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "fluent-uri"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e"
dependencies = [
"borrow-or-share",
"ref-cast",
"serde",
]
[[package]]
name = "fnv"
version = "1.0.7"
@@ -750,6 +828,16 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "fraction"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e246562084dde8ebbcc943b261c406ce4f68e5032ec28029a251a47d6a295500"
dependencies = [
"num",
"num-bigint",
]
[[package]]
name = "fs_extra"
version = "1.3.0"
@@ -874,9 +962,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 5.3.0",
"wasip2",
"wasm-bindgen",
]
[[package]]
@@ -1052,6 +1142,7 @@ dependencies = [
"hx-mcp",
"hx-tools",
"hx-tui",
"jsonschema",
"serde",
"serde_json",
"similar",
@@ -1464,6 +1555,60 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "jsonschema"
version = "0.63.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0802aebc749a4ef12e76aee083622b100249be0dc6d2103d84bbb2f7936a1ae"
dependencies = [
"ahash",
"bytecount",
"data-encoding",
"email_address",
"fancy-regex 0.20.2",
"fraction",
"getrandom 0.3.4",
"itoa",
"jsonschema-regex",
"jsonschema-value",
"num-cmp",
"num-traits",
"percent-encoding",
"referencing",
"regex",
"serde",
"serde_json",
"strum",
"unicode-general-category",
"uuid-simd",
]
[[package]]
name = "jsonschema-regex"
version = "0.63.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba1527289dfcb1400df61b5c591218e8e30031376671f611faecb5b9a1ff4987"
dependencies = [
"regex-syntax",
]
[[package]]
name = "jsonschema-value"
version = "0.63.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a95285ab129d630f01cf2f1345c28662116340fac1a35eb0795e5dbbf0ef990d"
dependencies = [
"ahash",
"bytecount",
"fraction",
"getrandom 0.3.4",
"memchr",
"num-cmp",
"num-traits",
"serde_json",
"zmij",
]
[[package]]
name = "kasuari"
version = "0.4.12"
@@ -1598,6 +1743,12 @@ dependencies = [
"autocfg",
]
[[package]]
name = "micromap"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -1645,6 +1796,45 @@ dependencies = [
"minimal-lexical",
]
[[package]]
name = "num"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
dependencies = [
"num-bigint",
"num-complex",
"num-integer",
"num-iter",
"num-rational",
"num-traits",
]
[[package]]
name = "num-bigint"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-cmp"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa"
[[package]]
name = "num-complex"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
]
[[package]]
name = "num-conv"
version = "0.2.2"
@@ -1662,6 +1852,36 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -1707,6 +1927,12 @@ dependencies = [
"num-traits",
]
[[package]]
name = "outref"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
[[package]]
name = "palette"
version = "0.7.7"
@@ -2200,10 +2426,47 @@ dependencies = [
]
[[package]]
name = "regex"
version = "1.13.1"
name = "ref-cast"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
dependencies = [
"ref-cast-impl",
]
[[package]]
name = "ref-cast-impl"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "referencing"
version = "0.63.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "858eb92e3a3c1d120695a04d5c6e8861915ee4394b8f77c90adbf686d6ddbf6e"
dependencies = [
"ahash",
"fluent-uri",
"getrandom 0.3.4",
"hashbrown 0.17.1",
"itoa",
"micromap",
"parking_lot",
"percent-encoding",
"serde_json",
]
[[package]]
name = "regex"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
dependencies = [
"aho-corasick",
"memchr",
@@ -2213,9 +2476,9 @@ dependencies = [
[[package]]
name = "regex-automata"
version = "0.4.18"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
@@ -2224,9 +2487,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
version = "0.8.11"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "relative-path"
@@ -2883,7 +3146,7 @@ dependencies = [
"anyhow",
"base64 0.22.1",
"bitflags 2.13.2",
"fancy-regex",
"fancy-regex 0.11.0",
"filedescriptor",
"finl_unicode",
"fixedbitset",
@@ -3183,6 +3446,12 @@ version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
[[package]]
name = "unicode-general-category"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f"
[[package]]
name = "unicode-ident"
version = "1.0.26"
@@ -3260,12 +3529,28 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "uuid-simd"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8"
dependencies = [
"outref",
"vsimd",
]
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "vsimd"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
[[package]]
name = "vtparse"
version = "0.6.2"
@@ -3654,6 +3939,26 @@ dependencies = [
"synstructure",
]
[[package]]
name = "zerocopy"
version = "0.8.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zerofrom"
version = "0.1.8"
+15 -4
View File
@@ -142,10 +142,13 @@ Builtin commands win when names collide.
## Memory
The agent keeps notes across sessions with `memory_write` / `memory_forget`. `MEMORY.md` (one hook line per
topic, max 50) is in the system prompt; the full text lives in `topics/<slug>.md` and is read on demand.
Global: `~/.hx/memory/`, project: `.hx/memory/` (add it to `.gitignore`). The index is read at session
start, so new entries show up next session. `hx prefix` shows its size.
The agent keeps notes across sessions with `memory_write` / `memory_forget` / `memory_search`. Default scope is
project (`.hx/memory/`, add it to `.gitignore`); global is `~/.hx/memory/`. `MEMORY.md` holds one hook line per
topic, the full text lives in `topics/<slug>.md`. No entry cap: the system prompt shows the most recently
used/written hooks up to 2 KB per scope plus "+N more"; `memory_search` (BM25 over all topics) finds the rest and
refreshes recency. `/memory` lists entries (`/memory forget <scope/slug>` deletes), `/remember <text>` saves a note (`global:` prefix for global scope), `hx stats` shows memory writes, auto-extractions and searches. The prompt tells the agent to save decisions, conventions and corrections immediately. On
compaction and on exit, one extra model call extracts up to 5 durable facts from the transcript and saves them
automatically. The index is read at session start. `hx prefix` shows its size.
## Lens
@@ -231,6 +234,12 @@ the pane on quit. Outside herdr nothing happens.
## Machine interfaces
### Structured output (`hx -p "..." --schema schema.json`)
The final answer must be JSON matching the schema file. hx adds the schema to the system prompt, validates the answer (a ```json fence is stripped) and, on a mismatch, asks once more with the validation errors. Success prints only the JSON on stdout (`--mode json`: it is `output` in the `done` event); a second mismatch exits non-zero. Streamed text is not printed in text mode, since a rejected first answer must not reach stdout.
`--max-turns N` (or `max_turns` in config) caps the model calls per prompt (default 200).
### Event stream (`hx -p "..." --mode json`)
One JSON object per line on stdout. `type` is one of:
@@ -257,6 +266,8 @@ offset defaulting to the end). One prompt at a time; other methods are rejected
`abort` and `complete`). Sessions: `sessions {scope?: "project"|"all"}` (path, title, messages, model,
branches, project, modified), `new`, `resume {path}`; `state` includes `title`. Example client: `examples/rpc_client.py`.
With `hx --mode rpc --ask`, a bash/write/edit call that would prompt in the TUI instead sends the client a request `{"id": N, "method": "permission", "params": {tool, detail, rule}}` and waits. Answer with `{"id": N, "result": {"decision": "once" | "always" | "deny"}}` (`always` on write/edit allows edits for the session). Any other reply, or an `abort`, denies. Without `--ask` everything is allowed, as before. Sample: `tests/rpc_ask_client.py`.
### Extensions
```toml
+3 -3
View File
@@ -1,7 +1,7 @@
{
"version": "0.2.7",
"version": "0.2.9",
"sha256": {
"aarch64-apple-darwin": "41e4c6c207ecce76e30517286b29d98685a13b89dcd2a5a02327af5af2947499",
"x86_64-unknown-linux-musl": "f4a6306496c959c7b577b3b341ebf43e42c9a2349789ae1c2131d24c52beb41f"
"aarch64-apple-darwin": "5718f60493a45c6b6d81540df1c9a3048c6b21445e133c13feec7cf8dbe77ede",
"x86_64-unknown-linux-musl": "d5708ccf61308145fb0b4b528294e7f72b572b88228dc3fa2c060d0d0b08a8f8"
}
}
+4 -1
View File
@@ -484,6 +484,9 @@ mod tests {
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
panic!("child {pid} survived: {:?}", std::fs::read_to_string(format!("/proc/{pid}/stat")));
panic!(
"child {pid} survived: {:?}",
std::fs::read_to_string(format!("/proc/{pid}/stat"))
);
}
}
+1
View File
@@ -24,6 +24,7 @@ similar = "3.2.0"
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal", "io-std", "io-util", "sync", "time"] }
serde_json = "1.0.151"
toml = "1.1.6"
jsonschema = { version = "0.63", default-features = false }
[lints]
workspace = true
+5 -2
View File
@@ -5,13 +5,16 @@
# model = "claude-sonnet-5-5" # model for the chosen provider; "auto" = pick per prompt (see [auto])
# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet
# codex_model = "gpt-5.6-sol" # default: Codex's top-listed model
# subagents = false # do not offer the `task` tool (default true; every call asks first)
# max_turns = 200 # model calls per prompt before the run stops (CLI: --max-turns)
# subagents = false # do not offer the `task` tool (default true; every call asks first)
# explore_model = "claude-haiku-4-5" # read-only `task` subagents; default: cheapest tier of the provider
# subagent_parallel = 3 # subagents running at once
# subagent_max_turns = 40 # turn limit per subagent (an agent file's max_turns wins)
# subagent_max_tokens = 500000 # stop a subagent that spends more tokens than this; default: no limit
# subagent_timeout_secs = 600 # stop a subagent run after this long; default: no limit
# remember_model = true # reuse the last model picked with /model or /provider
# consultant = "claude-fable-5-2" # stronger model behind the `consult` tool (off when unset; each call asks first)
# consultant_max_calls = 5 # calls allowed per session (resets on /new)
# remember_model = true # reuse the last model picked with /model or /provider
# compact_at = 900000 # auto-compact at this many tokens; default: 90% of the context window
# max_tokens = 16384
# permissions = "ask" # ask | auto (refuse dangerous calls, run safe ones) | yolo (nothing asks)
+96 -3
View File
@@ -13,6 +13,7 @@ use std::io::Write;
mod acp;
mod rpc;
mod schema;
use std::sync::Arc;
#[derive(Parser)]
@@ -63,6 +64,22 @@ struct Cli {
/// Output mode: text (default for -p), json (NDJSON events on stdout; needs -p), rpc (JSON-RPC on stdio).
#[arg(long, value_enum, default_value_t = Mode::Text)]
mode: Mode,
#[arg(
long,
help = "rpc mode: send a `permission` request to the client for bash/write/edit calls"
)]
ask: bool,
#[arg(
long,
help = "Model calls per prompt before the run stops (default 200)"
)]
max_turns: Option<u32>,
#[arg(
long,
requires = "print",
help = "JSON schema file: the final answer must match it (one retry); prints only the JSON"
)]
schema: Option<std::path::PathBuf>,
}
#[derive(Clone, Copy, PartialEq, clap::ValueEnum)]
@@ -154,12 +171,15 @@ struct Config {
codex_model: Option<String>,
compact_at: Option<usize>,
max_tokens: Option<u32>,
max_turns: Option<u32>,
explore_model: Option<String>,
subagents: Option<bool>,
subagent_parallel: Option<usize>,
subagent_max_turns: Option<u32>,
subagent_max_tokens: Option<u64>,
subagent_timeout_secs: Option<u64>,
consultant: Option<String>,
consultant_max_calls: Option<u32>,
codemode: Option<bool>,
mouse: Option<bool>,
sessions_dir: Option<String>,
@@ -222,12 +242,15 @@ impl Config {
codex_model: o.codex_model.or(c.codex_model),
compact_at: o.compact_at.or(c.compact_at),
max_tokens: o.max_tokens.or(c.max_tokens),
max_turns: o.max_turns.or(c.max_turns),
explore_model: o.explore_model.or(c.explore_model),
subagents: o.subagents.or(c.subagents),
subagent_parallel: o.subagent_parallel.or(c.subagent_parallel),
subagent_max_turns: o.subagent_max_turns.or(c.subagent_max_turns),
subagent_max_tokens: o.subagent_max_tokens.or(c.subagent_max_tokens),
subagent_timeout_secs: o.subagent_timeout_secs.or(c.subagent_timeout_secs),
consultant: o.consultant.or(c.consultant),
consultant_max_calls: o.consultant_max_calls.or(c.consultant_max_calls),
codemode: o.codemode.or(c.codemode),
mouse: o.mouse.or(c.mouse),
sessions_dir: o.sessions_dir.or(c.sessions_dir),
@@ -666,6 +689,10 @@ async fn main() -> Result<()> {
hx_core::stats::model_report(&Session::open(&session)?)
);
print!("{}", hx_core::stats::task_report(&Session::open(&session)?));
print!(
"{}",
hx_core::stats::memory_report(&Session::open(&session)?)
);
print!("{}", hx_core::stats::route_report(&session));
print!("{}", hx_core::stats::claude_report(&session));
print!("{}", hx_core::stats::sub_report(&session));
@@ -1125,6 +1152,27 @@ async fn main() -> Result<()> {
.bus
.add(hx_core::subagent::Notify(agent.cx.state.clone()));
}
if let Some(model) = cfg.consultant.clone()
&& let Ok(p) = provider(kind)
{
let stats = hx_core::consult::Stats::new(
model,
cfg.consultant_max_calls
.unwrap_or(hx_core::consult::DEFAULT_MAX),
&[
hx_core::consult::PLAN,
hx_core::consult::DONE,
hx_core::consult::STUCK_NAME,
],
);
agent
.tools
.add(hx_core::consult::Consult::new(p, stats.clone()));
agent
.bus
.add(hx_core::consult::ConsultNudge::new(stats.clone()));
let _ = agent.cx.state.consult.set(stats);
}
if CLAUDE_CLI.get().is_none()
&& let (Ok(p), Some(model)) = (
provider(kind),
@@ -1137,6 +1185,9 @@ async fn main() -> Result<()> {
.judge
.set(hx_core::danger::Judge { provider: p, model });
}
if let Some(n) = cli.max_turns.or(cfg.max_turns) {
agent.set_max_turns(n);
}
if cfg.codemode.unwrap_or(false) {
let cm = hx_tools::codemode::Codemode::new(&agent.tools);
agent.tools.add(cm);
@@ -1161,6 +1212,7 @@ async fn main() -> Result<()> {
.auto_cfg(auto_cfg.clone())
.remember_in(last_path.clone(), start.clone())
.auto_on(want_auto),
ask: cli.ask,
},
)
.await;
@@ -1321,9 +1373,17 @@ async fn main() -> Result<()> {
mgr.shutdown().await;
return Ok(());
};
let schema = cli
.schema
.as_deref()
.map(schema::Schema::load)
.transpose()?;
if let Some(s) = &schema {
agent.append_system(&format!("{}{}", schema::INSTRUCTION, s.text));
}
if cli.mode == Mode::Json {
agent.bus.add(rpc::Ndjson);
} else {
} else if schema.is_none() {
agent.bus.add(Printer);
}
tokio::spawn(async move {
@@ -1331,10 +1391,40 @@ async fn main() -> Result<()> {
abort.abort();
}
});
let r = agent.run(prompt).await;
let mut r = agent.run(prompt).await;
let mut output = None;
let mut schema_err = None;
if let Some(s) = &schema {
for attempt in 0..2 {
let Ok(m) = &r else { break };
match s.check(&m.text()) {
Ok(v) => {
schema_err = None;
output = Some(v);
break;
}
Err(p) => {
schema_err = Some(p.clone());
if attempt == 0 {
r = agent.run(schema::retry_prompt(&p)).await;
}
}
}
}
if let Some(v) = &output
&& cli.mode != Mode::Json
{
println!("{v}");
}
}
let error = r
.as_ref()
.err()
.map(|e| e.to_string())
.or(schema_err.map(|e| format!("answer does not match the schema: {e}")));
if cli.mode == Mode::Json {
rpc::emit(
&serde_json::json!({"type": "done", "error": r.as_ref().err().map(|e| e.to_string()),
&serde_json::json!({"type": "done", "error": error, "output": output,
"usage": agent.usage(), "session": path}),
);
}
@@ -1359,6 +1449,9 @@ async fn main() -> Result<()> {
hx_core::herdr::release().await;
mgr.shutdown().await;
r?;
if let Some(e) = error {
anyhow::bail!(e);
}
Ok(())
}
+61
View File
@@ -1,9 +1,11 @@
use anyhow::Result;
use hx_core::agent::{AbortHandle, Agent};
use hx_core::hook::{Event, Hook, HookAction};
use hx_core::permit::Decision;
use serde_json::{Value, json};
use std::io::Write;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering::SeqCst};
use tokio::io::AsyncBufReadExt;
use tokio::sync::Mutex;
@@ -38,11 +40,56 @@ fn reply(id: &Value, r: Result<Value, String>) {
});
}
type Pending =
Arc<std::sync::Mutex<std::collections::HashMap<u64, tokio::sync::oneshot::Sender<Value>>>>;
fn install_permit(agent: &Agent, pending: &Pending) {
let state = &agent.cx.state;
let abort = state.abort.get().cloned();
let next = Arc::new(AtomicU64::new(1));
let pending = pending.clone();
let _ = state.permit.set(Arc::new(move |r| {
let (pending, abort) = (pending.clone(), abort.clone());
let n = next.fetch_add(1, SeqCst);
Box::pin(async move {
let (tx, rx) = tokio::sync::oneshot::channel();
pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(n, tx);
emit(&json!({"jsonrpc": "2.0", "id": n, "method": "permission",
"params": {"tool": r.tool, "detail": r.detail, "rule": r.rule}}));
let mut abort = abort;
let reply = tokio::select! {
v = rx => v.ok(),
_ = async {
match abort.as_mut() {
Some(a) => { let _ = a.wait_for(|x| *x).await; }
None => std::future::pending::<()>().await,
}
} => None,
};
pending.lock().unwrap_or_else(|e| e.into_inner()).remove(&n);
let edit = matches!(r.tool.as_str(), "write" | "edit");
match reply
.as_ref()
.and_then(|v| v["result"]["decision"].as_str())
{
Some("once") => Decision::Once,
Some("always") if edit => Decision::Edits,
Some("always") => Decision::Always,
_ => Decision::Deny,
}
})
}));
}
pub struct Ctx {
pub specs: Vec<hx_core::command::CmdSpec>,
pub files: Vec<String>,
pub session_dir: std::path::PathBuf,
pub switcher: hx_core::switch::Switcher,
pub ask: bool,
}
pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()> {
@@ -51,7 +98,12 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()>
files,
session_dir,
mut switcher,
ask,
} = cx;
let pending = Pending::default();
if ask {
install_permit(&agent, &pending);
}
agent.bus.add(Notify);
let agent = Arc::new(Mutex::new(agent));
let busy = Arc::new(std::sync::atomic::AtomicBool::new(false));
@@ -66,6 +118,15 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()>
}
};
let id = m["id"].clone();
if m.get("method").is_none() && id.is_u64() {
let tx = id
.as_u64()
.and_then(|n| pending.lock().unwrap_or_else(|e| e.into_inner()).remove(&n));
if let Some(tx) = tx {
let _ = tx.send(m);
}
continue;
}
let p = &m["params"];
let method = m["method"].as_str().unwrap_or_default();
if method == "complete" {
+83
View File
@@ -0,0 +1,83 @@
use serde_json::Value;
pub const INSTRUCTION: &str = "\n\nYour final answer must be a single JSON value that matches this JSON schema. Reply with the JSON only, no prose and no code fence:\n";
pub struct Schema {
validator: jsonschema::Validator,
pub text: String,
}
impl Schema {
pub fn load(path: &std::path::Path) -> anyhow::Result<Self> {
let text = std::fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("--schema {}: {e}", path.display()))?;
let v: Value = serde_json::from_str(&text)
.map_err(|e| anyhow::anyhow!("--schema {}: {e}", path.display()))?;
let validator = jsonschema::validator_for(&v)
.map_err(|e| anyhow::anyhow!("--schema {}: {e}", path.display()))?;
Ok(Self { validator, text })
}
pub fn check(&self, answer: &str) -> Result<Value, String> {
let v = extract(answer).ok_or("the answer is not valid JSON")?;
let errs: Vec<String> = self
.validator
.iter_errors(&v)
.map(|e| format!("{} (at {})", e, e.instance_path()))
.collect();
if errs.is_empty() {
Ok(v)
} else {
Err(errs.join("\n"))
}
}
}
pub fn retry_prompt(problem: &str) -> String {
format!(
"Your last answer does not match the schema:\n{problem}\nReply again with only the corrected JSON."
)
}
fn extract(s: &str) -> Option<Value> {
let s = s.trim();
let body = match s.strip_prefix("```") {
Some(rest) => {
let rest = rest.split_once('\n').map_or(rest, |(_, b)| b);
rest.rsplit_once("```").map_or(rest, |(b, _)| b)
}
None => s,
};
serde_json::from_str(body.trim()).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn schema() -> Schema {
let v: Value = serde_json::json!({
"type": "object",
"required": ["name"],
"properties": {"name": {"type": "string"}}
});
Schema {
validator: jsonschema::validator_for(&v).unwrap(),
text: v.to_string(),
}
}
#[test]
fn accepts_plain_and_fenced() {
let s = schema();
assert!(s.check(r#"{"name":"a"}"#).is_ok());
assert!(s.check("```json\n{\"name\":\"a\"}\n```").is_ok());
}
#[test]
fn rejects_wrong_shape_and_prose() {
let s = schema();
assert!(s.check(r#"{"name":1}"#).unwrap_err().contains("name"));
assert!(s.check("here you go").is_err());
}
}
+46 -2
View File
@@ -271,6 +271,9 @@ impl Agent {
crate::herdr::set_session(session.path());
self.session = session;
self.window.reset();
if let Some(c) = self.cx.state.consult.get() {
c.reset();
}
self.publish();
}
@@ -310,6 +313,35 @@ impl Agent {
self.compact(KEEP_MESSAGES).await
}
pub async fn extract_memory(&mut self, transcript: &str) -> Vec<String> {
let home = crate::context::hx_home();
let req = crate::memory::extract_request(&self.model, transcript, &home, &self.cx.cwd);
let Ok(mut s) = self.provider.stream(req).await else {
return vec![];
};
let mut reply = String::new();
while let Some(Ok(ev)) = s.next().await {
if let StreamEvent::Done { message, usage, .. } = ev {
self.usage.add(&usage);
reply = message.text();
}
}
let saved = crate::memory::apply_extracted(&reply, &home, &self.cx.cwd);
if !saved.is_empty() {
crate::stats::log_memory_saved(self.session.path(), saved.len());
}
saved
}
pub async fn extract_memory_now(&mut self) -> Vec<String> {
let msgs = self.session.messages();
if msgs.len() < 4 {
return vec![];
}
self.extract_memory(&crate::compact::transcript(&msgs))
.await
}
pub async fn compact(&mut self, keep: usize) -> Result<bool, Error> {
let Some(plan) = compact::plan(&self.session.messages(), keep) else {
return Ok(false);
@@ -323,6 +355,11 @@ impl Agent {
}
}
let summary = summary.ok_or(Error::Truncated)?;
let saved = self.extract_memory(plan.transcript()).await;
if !saved.is_empty() {
self.emit(Event::Info(format!("memory saved: {}", saved.join(", "))))
.await;
}
self.session.rebase(plan.apply(&summary))?;
self.window.reset();
self.publish();
@@ -1260,6 +1297,7 @@ mod tests {
asst(vec![tu("2", "b")]),
text("fin"),
text("SUMMARY"),
text("[]"),
text("next"),
]),
Mutex::new(vec![]),
@@ -1355,7 +1393,13 @@ mod tests {
async fn compaction() {
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
let script = Arc::new(Script(
Mutex::new(vec![text("r1"), text("r2"), text("SUMMARY"), text("r3")]),
Mutex::new(vec![
text("r1"),
text("r2"),
text("SUMMARY"),
text("[]"),
text("r3"),
]),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
@@ -1390,7 +1434,7 @@ mod tests {
async fn replacing_the_session_drops_stale_context_usage() {
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
let script = Arc::new(Script(
Mutex::new(vec![text("r1"), text("SUMMARY"), text("r2")]),
Mutex::new(vec![text("r1"), text("SUMMARY"), text("[]"), text("r2")]),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
+11 -1
View File
@@ -106,6 +106,16 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
None,
),
b("btw", "side question; no tools, not saved", Free),
b(
"memory",
"list memory; `/memory forget <scope/slug>` deletes",
Free,
),
b(
"remember",
"save a note to project memory (`global:` prefix for global)",
Free,
),
b("skills", "list skills and where they load from", None),
b(
"reload",
@@ -422,7 +432,7 @@ mod tests {
let c = |l: &str| complete(l, l.len(), &specs, &files);
assert_eq!(c("/").items.len(), MAX_ITEMS);
assert_eq!(labels(&c("/mo")), ["/model"]);
assert_eq!(labels(&c("/mod")), ["/model"]);
assert_eq!(labels(&c("/co")), ["/copy", "/compact"]);
let r = c("/rev");
assert_eq!(labels(&r), ["/review"]);
+5 -1
View File
@@ -22,6 +22,10 @@ pub fn plan(msgs: &[Message], keep: usize) -> Option<Plan> {
}
impl Plan {
pub fn transcript(&self) -> &str {
&self.transcript
}
pub fn request(&self, model: &str) -> Request {
Request {
model: model.into(),
@@ -53,7 +57,7 @@ fn is_prompt(m: &Message) -> bool {
.any(|b| matches!(b, ContentBlock::ToolResult { .. }))
}
fn transcript(msgs: &[Message]) -> String {
pub fn transcript(msgs: &[Message]) -> String {
let cut = |s: &str| -> String {
if s.len() > 800 {
format!("{}…", s.chars().take(800).collect::<String>())
+371
View File
@@ -0,0 +1,371 @@
use crate::hook::{Event, Hook, HookAction};
use crate::tool::{Tool, ToolCtx, ToolResult};
use async_trait::async_trait;
use futures::StreamExt;
use hx_ai::{Effort, Message, Provider, Request, StreamEvent, ToolSpec};
use serde_json::{Value, json};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
pub const DEFAULT_MAX: u32 = 5;
const STUCK: u32 = 3;
const MAX_TOKENS: u32 = 4096;
const TIMEOUT: Duration = Duration::from_secs(180);
const SYSTEM: &str = "You are a senior consultant to a coding agent. You cannot run tools and see only what the caller wrote. Give a direct answer: the recommended approach, the risks it missed, and what to check. Short, no preamble.";
pub const PLAN: &str = "before a plan";
pub const DONE: &str = "before done";
pub const STUCK_NAME: &str = "when stuck";
struct Inner {
advising: bool,
count: u32,
last: Option<(Instant, Duration)>,
triggers: Vec<(&'static str, bool)>,
}
pub struct Stats {
pub model: String,
pub max: u32,
inner: Mutex<Inner>,
}
pub struct Snapshot {
pub model: String,
pub max: u32,
pub advising: bool,
pub count: u32,
pub last: Option<(Duration, Duration)>,
pub triggers: Vec<(String, bool)>,
}
impl Stats {
pub fn new(model: String, max: u32, triggers: &[&'static str]) -> Arc<Self> {
Arc::new(Self {
model,
max,
inner: Mutex::new(Inner {
advising: false,
count: 0,
last: None,
triggers: triggers.iter().map(|t| (*t, false)).collect(),
}),
})
}
fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
self.inner.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn reset(&self) {
let mut i = self.lock();
i.advising = false;
i.count = 0;
i.last = None;
i.triggers.iter_mut().for_each(|t| t.1 = false);
}
pub fn left(&self) -> u32 {
self.max.saturating_sub(self.lock().count)
}
fn enabled(&self, name: &str) -> bool {
self.lock().triggers.iter().any(|t| t.0 == name)
}
fn mark(&self, name: &str, on: bool) {
for t in self.lock().triggers.iter_mut().filter(|t| t.0 == name) {
t.1 = on;
}
}
fn begin(&self) -> Result<(), String> {
let mut i = self.lock();
if i.count >= self.max {
return Err(format!(
"consultant limit reached ({}/{}) for this session; decide yourself or ask the user",
i.count, self.max
));
}
i.count += 1;
i.advising = true;
i.triggers.iter_mut().for_each(|t| t.1 = false);
Ok(())
}
fn end(&self, took: Duration) {
let mut i = self.lock();
i.advising = false;
i.last = Some((Instant::now(), took));
}
pub fn snapshot(&self) -> Snapshot {
let i = self.lock();
Snapshot {
model: self.model.clone(),
max: self.max,
advising: i.advising,
count: i.count,
last: i.last.map(|(at, took)| (at.elapsed(), took)),
triggers: i.triggers.iter().map(|t| (t.0.to_string(), t.1)).collect(),
}
}
}
pub fn spec() -> ToolSpec {
ToolSpec {
name: "consult".into(),
description: "Ask a stronger consultant model for advice. It sees only `question` and `context`, no tools, no conversation. Use it before committing to a plan, when stuck after repeated failures, and before declaring a hard task done. The number of calls per session is limited; the user is asked to approve each call. Make the question specific and put the relevant code, errors and constraints in `context`.".into(),
input_schema: json!({"type":"object","properties":{
"question":{"type":"string"},
"context":{"type":"string","description":"relevant facts, code, error output, what you already tried"}},
"required":["question"]}),
}
}
pub struct Consult {
provider: Arc<dyn Provider>,
stats: Arc<Stats>,
}
impl Consult {
pub fn new(provider: Arc<dyn Provider>, stats: Arc<Stats>) -> Self {
Self { provider, stats }
}
async fn ask(&self, prompt: String) -> Result<(String, hx_ai::Usage), String> {
let req = Request {
model: self.stats.model.clone(),
system: SYSTEM.into(),
messages: vec![Message::user(prompt)],
tools: vec![],
max_tokens: MAX_TOKENS,
effort: Effort::Off,
};
let run = async {
let mut s = self.provider.stream(req).await.map_err(|e| e.to_string())?;
while let Some(ev) = s.next().await {
if let StreamEvent::Done { message, usage, .. } = ev.map_err(|e| e.to_string())? {
return Ok((message.text(), usage));
}
}
Err("stream ended without an answer".to_string())
};
let (text, usage) = tokio::time::timeout(TIMEOUT, run)
.await
.map_err(|_| "timed out".to_string())??;
Ok((text, usage))
}
}
#[async_trait]
impl Tool for Consult {
fn spec(&self) -> ToolSpec {
spec()
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let q = a["question"].as_str().unwrap_or_default().trim();
if q.is_empty() {
return ToolResult::err("question is required");
}
if cx.state.abort.get().is_some_and(|r| *r.borrow()) {
return ToolResult::err("aborted");
}
if let Err(e) = self.stats.begin() {
return ToolResult::err(e);
}
let ctx = a["context"].as_str().unwrap_or_default();
let prompt = format!("<context>\n{ctx}\n</context>\n\n{q}");
let t0 = Instant::now();
let r = self.ask(prompt).await;
self.stats.end(t0.elapsed());
match r {
Ok((text, usage)) => {
cx.state
.sub_usage
.lock()
.unwrap_or_else(|e| e.into_inner())
.add(&usage);
ToolResult::ok(format!(
"{}\n[consult · {} · {}/{} calls · {}s]",
text.trim(),
self.stats.model,
self.stats.snapshot().count,
self.stats.max,
t0.elapsed().as_secs()
))
}
Err(e) => ToolResult::err(format!("consultant failed: {e}")),
}
}
}
#[derive(Default)]
struct Seen {
edited: bool,
errors: u32,
done_nudged: bool,
stuck_nudged: bool,
}
pub struct ConsultNudge {
stats: Arc<Stats>,
s: Mutex<Seen>,
}
impl ConsultNudge {
pub fn new(stats: Arc<Stats>) -> Self {
Self {
stats,
s: Mutex::default(),
}
}
fn hint(&self, name: &str, text: &str) -> HookAction {
if self.stats.left() == 0 || !self.stats.enabled(name) {
return HookAction::Continue;
}
self.stats.mark(name, true);
HookAction::Inject(format!(
"hint: {text} Consider the `consult` tool ({} calls left).",
self.stats.left()
))
}
}
#[async_trait]
impl Hook for ConsultNudge {
async fn on(&self, ev: &Event) -> HookAction {
let mut s = self.s.lock().unwrap_or_else(|e| e.into_inner());
match ev {
Event::ToolCall { name, .. } => match name.as_str() {
"exit_plan" => return self.hint(PLAN, "You are about to submit a plan."),
"edit" | "write" => s.edited = true,
"consult" => *s = Seen::default(),
_ => {}
},
Event::ToolResult { is_error, name, .. } if name != "consult" => {
s.errors = if *is_error { s.errors + 1 } else { 0 };
if s.errors >= STUCK && !s.stuck_nudged {
s.stuck_nudged = true;
return self.hint(STUCK_NAME, "Several tool calls in a row failed.");
}
if !*is_error {
s.stuck_nudged = false;
}
}
Event::AgentEnd if s.edited && !s.done_nudged => {
s.done_nudged = true;
return self.hint(DONE, "You made edits and are about to finish.");
}
Event::AgentEnd => s.done_nudged = false,
_ => {}
}
HookAction::Continue
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::stream::BoxStream;
use hx_ai::{StopReason, Usage};
use std::sync::atomic::{AtomicUsize, Ordering};
struct Fake(AtomicUsize);
#[async_trait]
impl Provider for Fake {
async fn stream(
&self,
_req: Request,
) -> hx_ai::Result<BoxStream<'static, hx_ai::Result<StreamEvent>>> {
self.0.fetch_add(1, Ordering::Relaxed);
let done = StreamEvent::Done {
message: Message {
role: hx_ai::Role::Assistant,
content: vec![hx_ai::ContentBlock::Text {
text: "use a trait".into(),
}],
},
stop: StopReason::EndTurn,
usage: Usage {
input_tokens: 10,
..Default::default()
},
};
Ok(futures::stream::iter(vec![Ok(done)]).boxed())
}
}
fn cx() -> ToolCtx {
ToolCtx {
cwd: ".".into(),
state: Arc::new(crate::State::default()),
}
}
fn all() -> Arc<Stats> {
Stats::new("m".into(), 2, &[PLAN, DONE, STUCK_NAME])
}
#[tokio::test]
async fn caps_calls_without_invoking_the_provider() {
let p = Arc::new(Fake(AtomicUsize::new(0)));
let st = all();
let t = Consult::new(p.clone(), st.clone());
let cx = cx();
for _ in 0..2 {
let r = t.call(json!({"question": "q"}), &cx).await;
assert!(
!r.is_error && r.content.contains("use a trait"),
"{}",
r.content
);
}
let r = t.call(json!({"question": "q"}), &cx).await;
assert!(r.is_error && r.content.contains("limit reached (2/2)"));
assert_eq!(p.0.load(Ordering::Relaxed), 2);
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 20);
let snap = st.snapshot();
assert_eq!(
(snap.count, snap.advising, snap.last.is_some()),
(2, false, true)
);
st.reset();
assert_eq!(st.snapshot().count, 0);
}
#[tokio::test]
async fn nudges_on_triggers_and_stops_at_cap() {
let st = all();
let h = ConsultNudge::new(st.clone());
let call = |n: &str| Event::ToolCall {
id: "i".into(),
name: n.into(),
args: json!({}),
};
let res = |e: bool| Event::ToolResult {
id: "i".into(),
name: "bash".into(),
args: json!({}),
content: String::new(),
is_error: e,
};
assert_eq!(h.on(&call("edit")).await, HookAction::Continue);
assert!(
matches!(h.on(&Event::AgentEnd).await, HookAction::Inject(m) if m.contains("2 calls"))
);
assert!(st.snapshot().triggers.iter().any(|t| t.0 == DONE && t.1));
assert_eq!(h.on(&Event::AgentEnd).await, HookAction::Continue);
h.on(&res(true)).await;
h.on(&res(true)).await;
assert!(matches!(h.on(&res(true)).await, HookAction::Inject(_)));
assert!(matches!(
h.on(&call("exit_plan")).await,
HookAction::Inject(_)
));
st.begin().unwrap();
st.begin().unwrap();
assert_eq!(h.on(&call("exit_plan")).await, HookAction::Continue);
}
}
+2
View File
@@ -2,6 +2,7 @@ pub mod agent;
pub mod approve;
pub mod command;
pub mod compact;
pub mod consult;
pub mod context;
pub mod danger;
pub mod ext;
@@ -62,6 +63,7 @@ pub struct State {
pub abort: std::sync::OnceLock<tokio::sync::watch::Receiver<bool>>,
pub sub_usage: Mutex<hx_ai::Usage>,
pub subs: subagent::Subs,
pub consult: std::sync::OnceLock<std::sync::Arc<consult::Stats>>,
pub live: Mutex<HashMap<String, String>>,
pub claude_seen: Mutex<std::collections::HashSet<String>>,
pub lens: Mutex<LensView>,
+217 -14
View File
@@ -1,6 +1,6 @@
use std::path::{Path, PathBuf};
pub const MAX_LINES: usize = 50;
pub const INDEX_BYTES: usize = 2000;
const HOOK_CHARS: usize = 100;
pub fn dir(project: bool, home: &Path, cwd: &Path) -> PathBuf {
@@ -53,11 +53,6 @@ pub fn write(dir: &Path, slug: &str, hook: &str, body: &str) -> Result<(), Strin
let line = format!("- [{slug}](topics/{slug}.md) – {hook}");
match l.iter().position(|x| x.starts_with(&prefix(slug))) {
Some(i) => l[i] = line,
None if l.len() >= MAX_LINES => {
return Err(format!(
"memory index full ({MAX_LINES} entries): merge related topics or memory_forget stale ones first"
));
}
None => l.push(line),
}
std::fs::create_dir_all(dir.join("topics")).map_err(|e| e.to_string())?;
@@ -79,26 +74,207 @@ pub fn forget(dir: &Path, slug: &str) -> Result<(), String> {
save(dir, &l)
}
fn mtime(dir: &Path, slug: &str) -> std::time::SystemTime {
std::fs::metadata(dir.join(format!("topics/{slug}.md")))
.and_then(|m| m.modified())
.unwrap_or(std::time::UNIX_EPOCH)
}
fn slug_of(line: &str) -> Option<&str> {
line.strip_prefix("- [")?.split_once("](").map(|x| x.0)
}
fn touch(dir: &Path, slug: &str) {
if let Ok(f) = std::fs::File::options()
.write(true)
.open(dir.join(format!("topics/{slug}.md")))
{
let _ = f.set_modified(std::time::SystemTime::now());
}
}
fn index(dir: &Path) -> (Vec<String>, usize) {
let mut l = lines(dir);
l.sort_by_key(|x| std::cmp::Reverse(slug_of(x).map(|s| mtime(dir, s))));
let (mut used, mut keep) = (0, 0);
for x in &l {
used += x.len() + 1;
if used > INDEX_BYTES && keep > 0 {
break;
}
keep += 1;
}
let hidden = l.len() - keep;
l.truncate(keep);
(l, hidden)
}
pub fn list(dir: &Path) -> Vec<(String, String)> {
lines(dir)
.iter()
.filter_map(|l| Some((slug_of(l)?.to_string(), l.split_once(") – ")?.1.to_string())))
.collect()
}
pub fn remember(dir: &Path, text: &str) -> Result<String, String> {
let words: Vec<String> = tokens(text).into_iter().take(4).collect();
let slug = words.join("-").chars().take(48).collect::<String>();
if slug.is_empty() {
return Err("nothing to remember".into());
}
write(dir, &slug, text, text).map(|_| slug)
}
pub struct Hit {
pub slug: String,
pub hook: String,
pub snippet: String,
pub score: f64,
}
fn tokens(s: &str) -> Vec<String> {
s.split(|c: char| !c.is_alphanumeric())
.filter(|w| !w.is_empty())
.map(str::to_lowercase)
.collect()
}
pub fn search(dir: &Path, query: &str, k: usize) -> Vec<Hit> {
let q = tokens(query);
let docs: Vec<(String, String, String, Vec<String>)> = lines(dir)
.iter()
.filter_map(|l| {
let slug = slug_of(l)?.to_string();
let hook = l.split_once(") – ").map_or("", |x| x.1).to_string();
let body =
std::fs::read_to_string(dir.join(format!("topics/{slug}.md"))).unwrap_or_default();
let t = tokens(&format!("{slug} {hook} {hook} {body}"));
Some((slug, hook, body, t))
})
.collect();
if q.is_empty() || docs.is_empty() {
return vec![];
}
let n = docs.len() as f64;
let avg = docs.iter().map(|d| d.3.len()).sum::<usize>() as f64 / n;
let mut hits: Vec<Hit> = docs
.iter()
.filter_map(|(slug, hook, body, t)| {
let mut score = 0.0;
for w in &q {
let tf = t.iter().filter(|x| *x == w).count() as f64;
if tf == 0.0 {
continue;
}
let df = docs.iter().filter(|d| d.3.contains(w)).count() as f64;
let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
score += idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * t.len() as f64 / avg));
}
(score > 0.0).then(|| Hit {
slug: slug.clone(),
hook: hook.clone(),
snippet: snippet(body, &q),
score,
})
})
.collect();
hits.sort_by(|a, b| b.score.total_cmp(&a.score));
hits.truncate(k);
for h in &hits {
touch(dir, &h.slug);
}
hits
}
fn snippet(body: &str, q: &[String]) -> String {
let line = body
.lines()
.find(|l| tokens(l).iter().any(|w| q.contains(w)))
.or_else(|| body.lines().next())
.unwrap_or_default();
match line.char_indices().nth(200) {
Some((i, _)) => format!("{}…", &line[..i]),
None => line.to_string(),
}
}
pub fn prompt_section(home: &Path, cwd: &Path) -> String {
let mut s = String::from(
"\n\n# Memory\nPersistent notes across sessions. `memory_write` only durable facts (user preferences, \
corrections, project conventions, environment quirks), never task progress. Entries below are \
one-line hooks; `read` the topic file when relevant. This index is fixed per session.\n",
"\n\n# Memory\nPersistent notes across sessions (project scope is the default; the other scope is only for facts about the user or machine). \
Call `memory_write` IMMEDIATELY, without asking, when: the user states a convention or decision, the user corrects you, \
you learn a non-obvious build/test/environment quirk, or a design choice is settled after discussion. \
Never save task progress. Keep one topic per subject and update the slug instead of adding duplicates. \
Before asking the user about conventions or assuming one, call `memory_search`; the index below is only the most recently used part. \
`read` a topic file when a hook is relevant. This index is fixed per session.\n",
);
for (name, project) in [("global", false), ("project", true)] {
let d = dir(project, home, cwd);
let l = lines(&d);
let (l, hidden) = index(&d);
if !l.is_empty() {
s.push_str(&format!(
"{name} memory ({}):\n{}\n",
d.display(),
l.join("\n")
));
if hidden > 0 {
s.push_str(&format!("(+{hidden} more, use `memory_search`)\n"));
}
}
}
s
}
const EXTRACT_PROMPT: &str = "You maintain long-term memory for a coding agent. From the conversation, extract at most 5 DURABLE facts worth remembering in future sessions: \
project decisions and their reasons, conventions, user corrections/preferences, non-obvious build/test/environment quirks. Skip task progress, anything derivable from the code, and anything already in the existing index (reuse its slug to update an entry). \
Output ONLY a JSON array (possibly empty) of {\"scope\":\"project\"|\"global\",\"slug\":\"a-z0-9-_\",\"hook\":\"one line <=100 chars\",\"body\":\"full text\"}. Scope is project unless the fact is about the user or machine.";
pub const EXTRACT_MAX: usize = 5;
pub fn extract_request(model: &str, transcript: &str, home: &Path, cwd: &Path) -> hx_ai::Request {
let mut idx = String::new();
for (name, project) in [("global", false), ("project", true)] {
for l in lines(&dir(project, home, cwd)) {
idx.push_str(&format!("[{name}] {l}\n"));
}
}
let tail: String = {
let n = transcript.chars().count();
transcript.chars().skip(n.saturating_sub(60_000)).collect()
};
hx_ai::Request {
model: model.into(),
system: EXTRACT_PROMPT.into(),
messages: vec![hx_ai::Message::user(format!(
"Existing index:\n{idx}\nConversation:\n{tail}"
))],
tools: vec![],
max_tokens: 4096,
effort: hx_ai::Effort::Off,
}
}
pub fn apply_extracted(reply: &str, home: &Path, cwd: &Path) -> Vec<String> {
let (Some(a), Some(b)) = (reply.find('['), reply.rfind(']')) else {
return vec![];
};
let Ok(v) = serde_json::from_str::<Vec<serde_json::Value>>(&reply[a..=b]) else {
return vec![];
};
let mut saved = vec![];
for e in v.iter().take(EXTRACT_MAX) {
let g = |k: &str| e[k].as_str().unwrap_or_default();
let project = g("scope") != "global";
if write(&dir(project, home, cwd), g("slug"), g("hook"), g("body")).is_ok() {
saved.push(format!(
"{}/{}",
if project { "project" } else { "global" },
g("slug")
));
}
}
saved
}
#[cfg(test)]
mod tests {
use super::*;
@@ -123,10 +299,37 @@ mod tests {
forget(&d, "a").unwrap();
assert!(forget(&d, "a").is_err());
assert!(!d.join("topics/a.md").exists() && lines(&d).is_empty());
for i in 0..MAX_LINES {
write(&d, &format!("t{i}"), "h", "b").unwrap();
for i in 0..200 {
write(
&d,
&format!("t{i}"),
"filler hook for padding the index out",
"b",
)
.unwrap();
}
assert!(write(&d, "over", "h", "b").unwrap_err().contains("full"));
write(&d, "t0", "updated", "b").unwrap();
write(
&d,
"db",
"database",
"Use sqlite WAL mode; migrations in db/migrate.sql",
)
.unwrap();
let p = prompt_section(&home, &cwd);
assert!(p.contains("more, use `memory_search`") && p.len() < INDEX_BYTES + 2000);
assert!(p.contains("[db]"), "newest topic stays in prompt");
let h = search(&d, "how do migrations work", 3);
assert_eq!(h[0].slug, "db");
assert!(h[0].snippet.contains("migrate.sql"));
assert!(search(&d, "zzzz", 3).is_empty());
let r = r#"sure: [{"scope":"project","slug":"ex","hook":"h","body":"b"},{"slug":"../bad","hook":"h","body":"b"}]"#;
assert_eq!(apply_extracted(r, &home, &cwd), ["project/ex"]);
assert_eq!(
remember(&d, "Use tabs, not spaces!").unwrap(),
"use-tabs-not-spaces"
);
assert!(remember(&d, "!!!").is_err());
assert!(list(&d).iter().any(|(s, h)| s == "ex" && h == "h"));
assert!(apply_extracted("no json", &home, &cwd).is_empty());
}
}
+8 -1
View File
@@ -184,7 +184,7 @@ pub fn needs_permit(tool: &str, args: &serde_json::Value) -> bool {
"task" => {
!(args["wait"].is_array() && args["prompt"].is_null() && args["prompts"].is_null())
}
"web_fetch" => true,
"web_fetch" | "consult" => true,
_ => gated(tool),
}
}
@@ -235,6 +235,13 @@ pub fn request(tool: &str, args: &serde_json::Value) -> Request {
rule: format!("web:{host}"),
};
}
if tool == "consult" {
return Request {
tool: tool.into(),
detail: s("question").chars().take(200).collect(),
rule: "consult".into(),
};
}
if tool == "task" {
let kind = args["kind"].as_str().unwrap_or("explore");
let ps: Vec<&str> = match args["prompts"].as_array() {
+35
View File
@@ -41,6 +41,41 @@ pub fn task_report(s: &Session) -> String {
)
}
pub fn log_memory_saved(session: &std::path::Path, n: usize) {
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(session.with_extension("mem"))
{
let _ = writeln!(f, "{n}");
}
}
pub fn memory_report(s: &Session) -> String {
let (mut w, mut r) = (0, 0);
for m in s.messages() {
for b in &m.content {
if let ContentBlock::ToolUse { name, .. } = b {
match name.as_str() {
"memory_write" => w += 1,
"memory_search" => r += 1,
_ => {}
}
}
}
}
let auto: usize = std::fs::read_to_string(s.path().with_extension("mem"))
.unwrap_or_default()
.lines()
.filter_map(|l| l.parse::<usize>().ok())
.sum();
if w + r + auto == 0 {
return String::new();
}
format!("memory: {w} agent writes, {auto} auto-extracted, {r} searches\n")
}
pub fn log_claude_tool(
session: &std::path::Path,
name: &str,
+10 -9
View File
@@ -517,15 +517,16 @@ impl Tool for Task {
spec_for(&self.kinds())
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
if a["prompt"].is_null() && a["prompts"].is_null() {
if let Some(w) = a["wait"].as_array() {
let ids: Vec<usize> = w
.iter()
.filter_map(|v| v.as_u64())
.map(|n| n as usize)
.collect();
return self.wait(&ids, cx).await;
}
if a["prompt"].is_null()
&& a["prompts"].is_null()
&& let Some(w) = a["wait"].as_array()
{
let ids: Vec<usize> = w
.iter()
.filter_map(|v| v.as_u64())
.map(|n| n as usize)
.collect();
return self.wait(&ids, cx).await;
}
if a["background"].as_bool() == Some(true) {
let ps: Vec<&str> = match a["prompts"].as_array() {
+46 -4
View File
@@ -64,6 +64,7 @@ pub fn registry() -> Registry {
.add(ExitPlan)
.add(MemoryWrite)
.add(MemoryForget)
.add(MemorySearch)
.add(skill::Skill);
r
}
@@ -483,7 +484,7 @@ impl Tool for Bash {
fn memory_dir(a: &Value, cx: &ToolCtx) -> PathBuf {
hx_core::memory::dir(
a["scope"].as_str() == Some("project"),
a["scope"].as_str() != Some("global"),
&hx_core::context::hx_home(),
&cx.cwd,
)
@@ -495,13 +496,13 @@ impl Tool for MemoryWrite {
fn spec(&self) -> ToolSpec {
spec(
"memory_write",
"Save or replace a persistent memory topic (durable facts only, not task progress). `hook` is the one-line index entry shown in every future session; `body` is the full text, read on demand. Appears in the prompt from the next session.",
"Save or replace a persistent memory topic (durable facts only, not task progress). Default scope is project. `hook` is the one-line index entry; `body` is the full text, found via memory_search or read on demand. Appears in the prompt index from the next session, searchable immediately.",
json!({"type":"object","properties":{
"scope":{"type":"string","enum":["global","project"],"description":"global: about the user/environment; project: this repo"},
"slug":{"type":"string","description":"a-z 0-9 - _"},
"hook":{"type":"string","description":"one line, max 100 chars"},
"body":{"type":"string"}},
"required":["scope","slug","hook","body"]}),
"required":["slug","hook","body"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
@@ -518,6 +519,47 @@ impl Tool for MemoryWrite {
}
}
pub struct MemorySearch;
#[async_trait]
impl Tool for MemorySearch {
fn spec(&self) -> ToolSpec {
spec(
"memory_search",
"Search persistent memory (all topics, not just those in the prompt index). Use before asking the user about conventions/decisions or assuming them. Searches both scopes unless `scope` is given.",
json!({"type":"object","properties":{
"query":{"type":"string"},
"scope":{"type":"string","enum":["global","project"]}},
"required":["query"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let q = a["query"].as_str().unwrap_or_default();
let home = hx_core::context::hx_home();
let mut out = String::new();
for (name, project) in [("project", true), ("global", false)] {
if a["scope"].as_str().is_some_and(|s| s != name) {
continue;
}
let d = hx_core::memory::dir(project, &home, &cx.cwd);
for h in hx_core::memory::search(&d, q, 5) {
out.push_str(&format!(
"[{name}] {} – {}\n {}\n file: {}/topics/{}.md\n",
h.slug,
h.hook,
h.snippet,
d.display(),
h.slug
));
}
}
if out.is_empty() {
ToolResult::ok("no matching memory")
} else {
ToolResult::ok(out)
}
}
}
pub struct MemoryForget;
#[async_trait]
impl Tool for MemoryForget {
@@ -528,7 +570,7 @@ impl Tool for MemoryForget {
json!({"type":"object","properties":{
"scope":{"type":"string","enum":["global","project"]},
"slug":{"type":"string"}},
"required":["scope","slug"]}),
"required":["slug"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
+57 -6
View File
@@ -110,6 +110,12 @@ impl Hook for Forward {
}
}
type DocPrompt = (
doc_view::DocView,
hx_core::Question,
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
);
struct App {
t: Transcript,
ed: Editor,
@@ -143,11 +149,7 @@ struct App {
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
)>,
review: Option<review::Review>,
doc: Option<(
doc_view::DocView,
hx_core::Question,
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
)>,
doc: Option<DocPrompt>,
probe: bool,
kbd: bool,
stats: Option<(hx_core::stats::Summary, String)>,
@@ -710,6 +712,11 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
);
}
ratatui::restore();
eprintln!("[saving memory…]");
let saved = agent.lock().await.extract_memory_now().await;
if !saved.is_empty() {
eprintln!("[memory saved: {}]", saved.join(", "));
}
let a = agent.lock().await;
let cost = pricing(a.model())
.map(|p| format!(" ${:.4}", app.st.usage.cost(&p)))
@@ -967,7 +974,7 @@ fn chat_buf(app: &App) -> (Buffer, Vec<bool>) {
.line_count(w)
.max(1);
cont.push(false);
cont.extend(std::iter::repeat(true).take(n - 1));
cont.extend(std::iter::repeat_n(true, n - 1));
}
let para = Paragraph::new(lines).wrap(Wrap { trim: false });
let r = Rect::new(0, 0, w, para.line_count(w) as u16);
@@ -1473,6 +1480,39 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
)));
}
},
"memory" => {
let home = hx_core::context::hx_home();
let dir = |p: &str| hx_core::memory::dir(p == "project", &home, cwd);
if let Some(t) = arg.strip_prefix("forget ") {
let (sc, slug) = t.trim().split_once('/').unwrap_or(("project", t.trim()));
app.t.push(match hx_core::memory::forget(&dir(sc), slug) {
Ok(()) => Item::Info(format!("forgot {sc}/{slug}")),
Err(e) => Item::Error(e),
});
} else {
let mut l = String::new();
for sc in ["project", "global"] {
for (slug, hook) in hx_core::memory::list(&dir(sc)) {
l.push_str(&format!("{sc}/{slug} – {hook}\n"));
}
}
if l.is_empty() {
l = "no memory yet".into();
}
show(app, "memory", l);
}
}
"remember" => {
let (sc, text) = match arg.strip_prefix("global:") {
Some(t) => ("global", t.trim()),
None => ("project", arg),
};
let d = hx_core::memory::dir(sc == "project", &hx_core::context::hx_home(), cwd);
app.t.push(match hx_core::memory::remember(&d, text) {
Ok(slug) => Item::Info(format!("memory saved: {sc}/{slug}")),
Err(e) => Item::Error(e),
});
}
"skills" => {
let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd);
let mut l = skills_list(&app.specs, &dirs);
@@ -1902,6 +1942,17 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
.unwrap_or_else(|e| e.into_inner())
.clone();
let subs = app.state.subs.list();
app.consult = app.state.consult.get().map(|c| {
let s = c.snapshot();
side::Consult {
model: s.model,
advising: s.advising,
consults: s.count,
max: s.max,
last: s.last,
triggers: s.triggers,
}
});
ls.extend(side::lines(&side::View {
st: &app.st,
mode: app.mode,
-3
View File
@@ -234,9 +234,6 @@ impl W {
self.text(" ", st);
} else {
self.flush();
if self.lists.is_empty() {
return;
}
}
}
Event::Rule => {
+40 -11
View File
@@ -36,6 +36,7 @@ pub struct Consult {
pub model: String,
pub advising: bool,
pub consults: u32,
pub max: u32,
pub last: Option<(Duration, Duration)>,
pub triggers: Vec<(String, bool)>,
}
@@ -289,7 +290,7 @@ fn consult_card(c: &View) -> Option<Vec<Line<'static>>> {
};
Some(card(
"CONSULTANT",
&format!("{state} {} {}", th.sym.info, k.consults),
&format!("{state} {} {}/{}", th.sym.info, k.consults, k.max),
border,
b,
c.w,
@@ -365,9 +366,13 @@ fn lsp_card(c: &View) -> Vec<Line<'static>> {
if b.is_empty() {
b.push(Line::styled("no servers started", th.dim()));
}
let (errs, warns) = c.lens.diags.iter().fold((0, 0), |(e, w), d| {
if d.error { (e + 1, w) } else { (e, w + 1) }
});
let (errs, warns) =
c.lens.diags.iter().fold(
(0, 0),
|(e, w), d| {
if d.error { (e + 1, w) } else { (e, w + 1) }
},
);
if errs + warns > 0 {
let mut ds = c.lens.diags.clone();
ds.sort_by_key(|d| (!d.error, d.file.clone(), d.line));
@@ -393,7 +398,10 @@ fn lsp_card(c: &View) -> Vec<Line<'static>> {
}
let mut right = format!("{up}/{} ready", c.lens_lines.len());
if errs + warns > 0 {
right += &format!(" {} {}{errs} {}{warns}", th.sym.info, th.sym.err, th.sym.warn);
right += &format!(
" {} {}{errs} {}{warns}",
th.sym.info, th.sym.err, th.sym.warn
);
}
let border = if bad || errs > 0 {
th.err()
@@ -544,7 +552,12 @@ mod tests {
fn text(ls: &[Line]) -> String {
ls.iter()
.map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>())
.map(|l| {
l.spans
.iter()
.map(|s| s.content.as_ref())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
@@ -625,7 +638,10 @@ mod tests {
let s = text(&lines(&view(&st, &lens, &mcp, &log, 80)));
assert!(s.contains("MCP") && s.contains("1/3 up"), "{s}");
assert!(s.contains("git") && s.contains("12 tools"), "{s}");
assert!(s.contains("connection refused") && s.contains("connecting"), "{s}");
assert!(
s.contains("connection refused") && s.contains("connecting"),
"{s}"
);
}
#[test]
@@ -650,13 +666,23 @@ mod tests {
model: "claude-fable-5-2".into(),
advising: true,
consults: 2,
max: 5,
last: Some((Duration::from_secs(7), Duration::from_secs(27))),
triggers: vec![("before a plan".into(), false), ("before done".into(), true)],
triggers: vec![
("before a plan".into(), false),
("before done".into(), true),
],
};
v.consult = Some(&k);
let s = text(&lines(&v));
assert!(s.contains("CONSULTANT") && s.contains("advising"), "{s}");
assert!(s.contains("● before done") && s.contains("○ before a plan"), "{s}");
assert!(
s.contains("CONSULTANT") && s.contains("advising") && s.contains("2/5"),
"{s}"
);
assert!(
s.contains("● before done") && s.contains("○ before a plan"),
"{s}"
);
}
#[test]
@@ -667,6 +693,9 @@ mod tests {
let tall = text(&lines(&view(&st, &lens, &[], &log, 80)));
assert!(tall.contains("SESSION LOG"), "{tall}");
let short = text(&lines(&view(&st, &lens, &[], &log, 12)));
assert!(short.contains("MODEL") && !short.contains("SESSION LOG"), "{short}");
assert!(
short.contains("MODEL") && !short.contains("SESSION LOG"),
"{short}"
);
}
}
-14
View File
@@ -1,14 +0,0 @@
# 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,14 @@
# Memory: byte-budgeted index, BM25 search, automatic extraction
Status: accepted (supersedes 0013)
## Context
The 50-entry cap made `write` fail instead of letting memory grow, and the agent rarely wrote memory at all, so project decisions were lost between sessions.
## Decision
No entry cap. The prompt index shows the most recently used hooks up to 2 KB per scope; `memory_search` (BM25 over slug, hook and body, no dependency) reaches the rest and bumps recency (topic file mtime). The prompt lists concrete write triggers and defaults to project scope. Compaction and session exit run one extraction call (max 5 entries, written without asking).
## Consequences
Prompt cost stays flat as memory grows. Search scans all topic files per query. Embeddings can replace the ranking later without changing the tools.
Code: crates/hx-core/src/memory.rs
+2
View File
@@ -11,6 +11,8 @@ cargo test -q -p hx-lens rust_analyzer_turn_end >>"$log" 2>&1 || { grep -E 'FAIL
grep -oE 'ok. [0-9]+ passed' "$log" | awk '{s+=$2} END {print s" unit tests ok"}'
cargo build -q
sh tests/e2e.sh
sh tests/schema_e2e.sh
sh tests/rpc_ask_e2e.sh
python3 tests/tui_smoke.py | grep -q FAIL && { echo "tui smoke FAIL"; exit 1; } || echo "tui smoke ok"
sh tests/lens_e2e.sh
sh tests/m4_e2e.sh
+27
View File
@@ -0,0 +1,27 @@
"""RPC client for `hx --mode rpc --ask`: allows write, denies everything else.
Usage: python3 tests/rpc_ask_client.py HX_BINARY
"""
import json, subprocess, sys
p = subprocess.Popen([sys.argv[1], "--mode", "rpc", "--ask"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
def send(m):
p.stdin.write(json.dumps({"jsonrpc": "2.0", **m}) + "\n")
p.stdin.flush()
send({"id": 1000, "method": "prompt", "params": {"text": "make hello.txt"}})
asked = []
while True:
m = json.loads(p.stdout.readline())
if m.get("method") == "permission":
asked.append(m["params"]["tool"])
send({"id": m["id"], "result": {"decision": "once" if m["params"]["tool"] == "write" else "deny"}})
elif m.get("id") == 1000:
assert "error" not in m, m
break
p.stdin.close()
p.wait(timeout=30)
assert asked and asked[0] == "write", asked
print("asked", asked)
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
tmp=$(mktemp -d)
trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT
port=$((20000 + ($$ + 13) % 20000))
python3 "$root/tests/fake_anthropic.py" $port & srv=$!
mkdir -p "$tmp/home/.hx" "$tmp/repo"
echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json"
sleep 0.5
cd "$tmp/repo"
export HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port"
python3 "$root/tests/rpc_ask_client.py" "$root/target/debug/hx" > "$tmp/out" || { echo "FAIL: rpc ask"; cat "$tmp/out"; exit 1; }
[ "$(cat hello.txt)" = "hi from hx" ] || { echo "FAIL: allowed write did not run"; exit 1; }
echo "rpc ask e2e ok"
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
tmp=$(mktemp -d)
trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT
port=$((20000 + ($$ + 7) % 20000))
echo '[[["text","no json here"]],[["text","```json\n{\"name\":\"Ann\"}\n```"]]]' > "$tmp/turns.json"
python3 "$root/tests/fake_anthropic.py" $port "$tmp/turns.json" & srv=$!
mkdir -p "$tmp/home/.hx" "$tmp/repo"
echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json"
echo '{"type":"object","required":["name"],"properties":{"name":{"type":"string"}}}' > "$tmp/schema.json"
sleep 0.5
cd "$tmp/repo"
export HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port"
out=$("$root/target/debug/hx" -p "who" --schema "$tmp/schema.json" 2> "$tmp/err")
[ "$out" = '{"name":"Ann"}' ] || { echo "FAIL: schema output: $out"; cat "$tmp/err"; exit 1; }
curl -s "http://127.0.0.1:$port/" | grep -q 'does not match the schema' || { echo "FAIL: no retry prompt"; exit 1; }
echo "schema e2e ok"