diff --git a/Cargo.lock b/Cargo.lock index 183065b77d..d77f7166d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2931,6 +2931,7 @@ dependencies = [ "tokio-test", "tokio-tungstenite 0.28.0", "toml 0.8.23", + "tool-working-set", "tower", "tower-http", "tracing", @@ -3249,6 +3250,7 @@ dependencies = [ "tokio", "tokio-stream", "toml 0.8.23", + "tool-working-set", "tracing", "ts-rs 12.0.1", "uuid", diff --git a/core/continuum-core/Cargo.toml b/core/continuum-core/Cargo.toml index 0f211b931c..3cc5e19ecf 100644 --- a/core/continuum-core/Cargo.toml +++ b/core/continuum-core/Cargo.toml @@ -46,6 +46,7 @@ name = "forge-custodian" path = "src/bin/forge_custodian.rs" [dependencies] +tool-working-set = { path = "../tool-working-set" } # one relevance seam: commands/help ranks a query the way the learned tool head reads relevance continuum-tool-protocol = { path = "../continuum-tool-protocol" } tokio.workspace = true expert-pager-policy = { path = "../expert-pager-policy" } diff --git a/core/continuum-core/src/commands/ai/generate.rs b/core/continuum-core/src/commands/ai/generate.rs index 9365b0b793..6384ba1ed4 100644 --- a/core/continuum-core/src/commands/ai/generate.rs +++ b/core/continuum-core/src/commands/ai/generate.rs @@ -126,6 +126,7 @@ fn parse_request(params: &Value) -> Result { .json_opt("stop_sequences") .or_else(|| p.json_opt("stopSequences")), tools: p.json_opt("tools"), + tail_tools: None, tool_choice: p.json_opt("tool_choice"), response_format: None, active_adapters: p.json_opt("activeAdapters"), diff --git a/core/continuum-core/src/commands/help.rs b/core/continuum-core/src/commands/help.rs index b45dff779c..4e98ebbdee 100644 --- a/core/continuum-core/src/commands/help.rs +++ b/core/continuum-core/src/commands/help.rs @@ -37,6 +37,10 @@ pub struct CommandsHelpParams { #[serde(default)] #[ts(optional)] pub name: Option, + /// What you want to do, when you do not know the command's name: the best matches, ranked. + #[serde(default)] + #[ts(optional)] + pub query: Option, } #[derive(Debug, Clone, Serialize, TS)] @@ -65,8 +69,8 @@ impl ActionCommand for CommandsHelp { const NATIVE: bool = true; // discovery pair — the on-demand "how do I call this?" tool const ACCESS: AccessLevel = AccessLevel::AiSafe; const DESCRIPTION: &'static str = - "Show how to CALL a command: the exact tool-call format to emit + its arguments. \ - Pass the command name (e.g. code/read). Use it when unsure how to invoke a tool."; + "Show how to CALL a command: its exact tool-call format + arguments. Pass `name` \ + (e.g. code/read), or `query` (what you want to do) to find one."; type Params = CommandsHelpParams; type Output = CommandsHelpResult; @@ -83,6 +87,11 @@ impl ActionCommand for CommandsHelp { .filter(|d| is_command_authorized(d.name, trust)) .collect(); + // A query → the commands that best match what she wants to do, ranked, one line each. + if let Some(query) = p.query.as_deref().filter(|q| !q.trim().is_empty()).filter(|_| p.name.is_none()) { + return Ok(ranked_matches(query, &authorized)); + } + // No name → the INDEX: every command you can call, one line each. This is the // orientation an agent needs FIRST; erroring here (the old "missing field name") // dead-ends the very first discovery move. @@ -132,11 +141,65 @@ impl ActionCommand for CommandsHelp { crate::register_stateless_command!(CommandsHelp); +/// The authorized commands whose name and description best match `query`, through the same +/// relevance seam the learned tool head reads (`tool_working_set::relevance`). +fn ranked_matches(query: &str, authorized: &[crate::sdk_codegen::CommandDescriptor]) -> CommandsHelpResult { + use tool_working_set::relevance::{Lexical, Relevance}; + use tool_working_set::vocab::{ToolSchema, Vocabulary}; + let schemas: Vec = authorized + .iter() + .map(|d| ToolSchema { name: d.name.to_string(), description: d.description.to_string(), tokens: 0 }) + .collect(); + let lines = match Vocabulary::new(schemas) { + Ok(vocab) => { + let relevance = Lexical::new(&vocab).relevance(query); + let mut ranked: Vec<(f32, tool_working_set::ToolId)> = + vocab.ids().map(|tool| (relevance[tool.index()], tool)).filter(|(score, _)| *score > 0.0).collect(); + ranked.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1))); + ranked + .into_iter() + .take(crate::sdk_codegen::ai_help::SUGGESTION_WINDOW) + .map(|(_, tool)| format!("- {} — {}", vocab.name(tool), vocab.schema(tool).description)) + .collect::>() + } + Err(refused) => vec![format!("(the registry could not be ranked: {refused})")], + }; + let manual = if lines.is_empty() { + format!("No command matches \"{query}\". Call `commands/help` with no arguments for the full index.") + } else { + format!( + "The commands that best match \"{query}\". Call `commands/help` with the `name` you choose for its exact call; \ + it is then callable on your next act.\n\n{}", + lines.join("\n") + ) + }; + CommandsHelpResult { + name: String::new(), + description: format!("commands matching \"{query}\""), + access_level: "ai-safe".to_string(), + manual, + } +} + #[cfg(test)] mod tests { use super::*; use serde_json::{json, Value}; + // what this catches: a mind that does not know a verb's name having no way to find it + // once her head no longer lists every verb: a query in her words must reach the verb + // over the LIVE registry, ranked first, within the shared window. + #[test] + fn a_query_in_her_words_ranks_the_verb_she_means_over_the_live_registry() { + let registry = command_registry_live(); + let result = ranked_matches("open a pull request on github", ®istry); + let names: Vec<&str> = result.manual.lines().filter_map(|l| l.strip_prefix("- ")).map(|l| l.split(" — ").next().unwrap_or(l)).collect(); // unwrap_or: a line without a description is all name + assert!(names.first().is_some_and(|n| n.contains("pr-create")), "{}", result.manual); + assert!(names.len() <= crate::sdk_codegen::ai_help::SUGGESTION_WINDOW); + let none = ranked_matches("zzqx", ®istry); + assert!(none.manual.starts_with("No command matches"), "{}", none.manual); + } + // what this catches: an underscored bare guess getting NO suggestion at all, which // is what let a citizen re-issue `list_cards` 31 times (2026-09-05). Neither // `commands/list` nor `work/list` shares the category prefix `list_cards` or a whole diff --git a/core/continuum-core/src/commands/models/try_.rs b/core/continuum-core/src/commands/models/try_.rs index 23093a05e1..046b912285 100644 --- a/core/continuum-core/src/commands/models/try_.rs +++ b/core/continuum-core/src/commands/models/try_.rs @@ -133,6 +133,7 @@ async fn run_text_probe(registry: &AdapterRegistry, model_id: &str) -> (bool, Op repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, @@ -207,6 +208,7 @@ async fn run_vision_probe(registry: &AdapterRegistry, model_id: &str) -> (bool, repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-core/src/http/mod.rs b/core/continuum-core/src/http/mod.rs index 4902c6cced..de4423b4bc 100644 --- a/core/continuum-core/src/http/mod.rs +++ b/core/continuum-core/src/http/mod.rs @@ -234,6 +234,7 @@ async fn messages_handler( repeat_last_n: None, stop_sequences: req.stop_sequences.clone(), tools: None, // Tool calls handled by Claude Code, not the local model + tail_tools: None, tool_choice: None, response_format: None, active_adapters, diff --git a/core/continuum-core/src/modules/agent.rs b/core/continuum-core/src/modules/agent.rs index fe9aab795d..d5d65c7fa3 100644 --- a/core/continuum-core/src/modules/agent.rs +++ b/core/continuum-core/src/modules/agent.rs @@ -757,6 +757,7 @@ async fn call_llm( repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, request_id: None, user_id: None, diff --git a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs index 905131c611..b3d37966e2 100644 --- a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs +++ b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs @@ -731,7 +731,11 @@ fn tool_surface_is_a_category_index_plus_discovery_pair() { // 17238 -> 17298 (PR #5112, 2026-10-16): work/list gains `limit` (default 40, // claimable first) so a board of 776 cards is never one 198k-char line again; // one optional field and its one-line doc, measured locally at 17298. - const AGENTIC_SURFACE_CEILING: u32 = 17298; + // 17298 -> 17335 (goal 10 slice 2, card ecd5dff3, 2026-10-24): commands/help gains + // `query`, the way a mind finds a verb by what she wants to do once her learned head no + // longer lists every verb. Its text was cut to one line (it measured 17427 first); the + // 37 left are the param itself, the feature. Measured locally at 17335. + const AGENTIC_SURFACE_CEILING: u32 = 17335; let surface = faculty.describe_tool_tokens() as u32 + faculty.framing_floor_tokens(); println!("agentic surface: {surface} guard tokens; ceiling {AGENTIC_SURFACE_CEILING}"); assert!( diff --git a/core/continuum-engine/src/ai/adapter/global_registry/tests.rs b/core/continuum-engine/src/ai/adapter/global_registry/tests.rs index 13ce9864f2..80187e16b3 100644 --- a/core/continuum-engine/src/ai/adapter/global_registry/tests.rs +++ b/core/continuum-engine/src/ai/adapter/global_registry/tests.rs @@ -62,6 +62,7 @@ single_resident_model: false, dynamic_model_catalog: false, llamacpp_sampling_extensions: false, + tail_tools: false, }); let catalog_default = gateway.default_model().to_string(); assert_eq!(gateway.served_model_ids(), vec![catalog_default.clone()]); diff --git a/core/continuum-engine/src/ai/adapter/inference_device.rs b/core/continuum-engine/src/ai/adapter/inference_device.rs index 15f3d5bc89..bbcc2594c6 100644 --- a/core/continuum-engine/src/ai/adapter/inference_device.rs +++ b/core/continuum-engine/src/ai/adapter/inference_device.rs @@ -415,6 +415,12 @@ pub trait AIProviderAdapter: Send + Sync { AdapterCapabilities::text_only() } + /// Whether this adapter's server accepts `tail_tools` (callable verbs outside the rendered + /// head). Default `false`: only a server that declares it gets a learned tool head. + fn accepts_tail_tools(&self) -> bool { + false + } + /// Get API style. /// /// Default: `Local` (in-process inference). Cloud adapters override diff --git a/core/continuum-engine/src/ai/heuristic_adapter.rs b/core/continuum-engine/src/ai/heuristic_adapter.rs index 89cc2970a5..10f06e433a 100644 --- a/core/continuum-engine/src/ai/heuristic_adapter.rs +++ b/core/continuum-engine/src/ai/heuristic_adapter.rs @@ -579,6 +579,7 @@ mod tests { repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-engine/src/ai/openai_adapter.rs b/core/continuum-engine/src/ai/openai_adapter.rs index 876cdfc05e..4b1ce33825 100644 --- a/core/continuum-engine/src/ai/openai_adapter.rs +++ b/core/continuum-engine/src/ai/openai_adapter.rs @@ -111,6 +111,8 @@ pub struct OpenAICompatibleConfig { /// `Provider.capabilities.llamacpp_sampling_extensions` (#55) — replaces /// the `id == "docker-model-runner"` `repeat_penalty` branch. pub llamacpp_sampling_extensions: bool, + /// The server accepts `tail_tools`. From `Provider.capabilities.tail_tools`. + pub tail_tools: bool, } /// What the serving backend told us when we asked it `GET /lora-adapters`. diff --git a/core/continuum-engine/src/ai/openai_adapter/provider.rs b/core/continuum-engine/src/ai/openai_adapter/provider.rs index 1369d3b5f6..b0e6b0d9fb 100644 --- a/core/continuum-engine/src/ai/openai_adapter/provider.rs +++ b/core/continuum-engine/src/ai/openai_adapter/provider.rs @@ -13,6 +13,10 @@ impl AIProviderAdapter for OpenAICompatibleAdapter { &self.config.provider_id } + fn accepts_tail_tools(&self) -> bool { + self.config.tail_tools + } + /// The live set the daemon's reconcile / `/v1/models` refresh verified /// (`runtime_models`), sorted for stable output; the catalog default only /// when nothing has been verified yet. `config.default_model` is a diff --git a/core/continuum-engine/src/ai/openai_adapter/registry.rs b/core/continuum-engine/src/ai/openai_adapter/registry.rs index 6be828c7a2..b9c96a1379 100644 --- a/core/continuum-engine/src/ai/openai_adapter/registry.rs +++ b/core/continuum-engine/src/ai/openai_adapter/registry.rs @@ -116,6 +116,7 @@ impl OpenAICompatibleAdapter { single_resident_model: provider.capabilities.single_resident_model, dynamic_model_catalog: provider.capabilities.dynamic_model_catalog, llamacpp_sampling_extensions: provider.capabilities.llamacpp_sampling_extensions, + tail_tools: provider.capabilities.tail_tools, }) } diff --git a/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs b/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs index bb8a0f9ca9..aed7da28f5 100644 --- a/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs +++ b/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs @@ -37,5 +37,6 @@ fn test_adapter() -> OpenAICompatibleAdapter { single_resident_model: false, dynamic_model_catalog: false, llamacpp_sampling_extensions: false, + tail_tools: false, }) } diff --git a/core/continuum-engine/src/ai/types.rs b/core/continuum-engine/src/ai/types.rs index a191d1d123..ff458fd413 100644 --- a/core/continuum-engine/src/ai/types.rs +++ b/core/continuum-engine/src/ai/types.rs @@ -256,6 +256,13 @@ pub struct TextGenerationRequest { #[serde(skip_serializing_if = "Option::is_none")] #[ts(optional)] pub tools: Option>, + /// Verbs she loaded into the TAIL this epoch: callable natively (the engine's parser and + /// grammar accept them) but never rendered in the head, so the cached prefix is unchanged + /// (goal 10, card ecd5dff3). Their schemas ride the conversation, after the cache point. + /// Sent only to a llama.cpp-family server; one that predates the field ignores it. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub tail_tools: Option>, #[serde(skip_serializing_if = "Option::is_none")] #[ts(optional)] pub tool_choice: Option, diff --git a/core/continuum-engine/src/inference/airc_remote/adapter/tests.rs b/core/continuum-engine/src/inference/airc_remote/adapter/tests.rs index 646e407730..0ac5069ae3 100644 --- a/core/continuum-engine/src/inference/airc_remote/adapter/tests.rs +++ b/core/continuum-engine/src/inference/airc_remote/adapter/tests.rs @@ -31,6 +31,7 @@ fn req(text: &str) -> TextGenerationRequest { repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-engine/src/inference/airc_remote/protocol.rs b/core/continuum-engine/src/inference/airc_remote/protocol.rs index 32bfb96d7a..1e3c632ae4 100644 --- a/core/continuum-engine/src/inference/airc_remote/protocol.rs +++ b/core/continuum-engine/src/inference/airc_remote/protocol.rs @@ -183,6 +183,7 @@ mod tests { repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-engine/src/inference/airc_remote/transport/tests.rs b/core/continuum-engine/src/inference/airc_remote/transport/tests.rs index 36f8847a08..88e391c32f 100644 --- a/core/continuum-engine/src/inference/airc_remote/transport/tests.rs +++ b/core/continuum-engine/src/inference/airc_remote/transport/tests.rs @@ -240,6 +240,7 @@ fn req(text: &str) -> RemoteInferenceRequest { repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-engine/src/inference/handle_module/tests.rs b/core/continuum-engine/src/inference/handle_module/tests.rs index 62f5a0357f..b4cb095e1f 100644 --- a/core/continuum-engine/src/inference/handle_module/tests.rs +++ b/core/continuum-engine/src/inference/handle_module/tests.rs @@ -27,6 +27,7 @@ fn empty_request() -> TextGenerationRequest { repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-engine/src/inference/handle_store.rs b/core/continuum-engine/src/inference/handle_store.rs index 5532f72cb3..dbbc09bd5a 100644 --- a/core/continuum-engine/src/inference/handle_store.rs +++ b/core/continuum-engine/src/inference/handle_store.rs @@ -433,6 +433,7 @@ mod tests { repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-engine/src/inference/llamacpp_adapter.rs b/core/continuum-engine/src/inference/llamacpp_adapter.rs index fccfb59b35..a5c3f83cf0 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter.rs @@ -289,6 +289,7 @@ impl AIProviderAdapter for LlamaCppAdapter { repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-engine/src/inference/llamacpp_adapter/tests.rs b/core/continuum-engine/src/inference/llamacpp_adapter/tests.rs index eca8568ff7..2d43aaecb3 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter/tests.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter/tests.rs @@ -55,6 +55,7 @@ fn text_request(response_format: Option) -> TextGenerationReques repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format, active_adapters: None, @@ -285,6 +286,7 @@ async fn owned_gene_page_in_changes_output() { repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: Some(ResponseFormat::Text), active_adapters: adapters, diff --git a/core/continuum-engine/src/inference/llm_module_service.rs b/core/continuum-engine/src/inference/llm_module_service.rs index 59772cc911..445a141960 100644 --- a/core/continuum-engine/src/inference/llm_module_service.rs +++ b/core/continuum-engine/src/inference/llm_module_service.rs @@ -398,6 +398,7 @@ pub(super) async fn run_adapter_inference( Some(request.stop_sequences.clone()) }, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-engine/src/inference/request_body.rs b/core/continuum-engine/src/inference/request_body.rs index 3e2a2289f4..620a244a1d 100644 --- a/core/continuum-engine/src/inference/request_body.rs +++ b/core/continuum-engine/src/inference/request_body.rs @@ -188,6 +188,13 @@ pub(crate) fn finish_body( == crate::model_registry::ToolProtocol::NativeFunctionCalling { body["tools"] = json!(openai_tools(tools)); + if let Some(tail) = request.tail_tools.as_deref().filter(|tail| !tail.is_empty()) { + // Our fork's field: only a server that declares it gets it (a cloud provider + // would reject an unknown field, a stock llama-server would ignore it). + if cfg.tail_tools { + body["tail_tools"] = json!(openai_tools(tail)); + } + } // Add tool_choice if specified if let Some(choice) = &request.tool_choice { @@ -215,6 +222,7 @@ pub(crate) fn finish_body( class = "ai.request.tool_surface", model = %model, tools_n = body.get("tools").and_then(|t| t.as_array()).map_or(0, |a| a.len()), + tail_tools_n = body.get("tail_tools").and_then(|t| t.as_array()).map_or(0, |a| a.len()), tool_choice = body.get("tool_choice").is_some(), stops_n = body.get("stop").and_then(|s| s.as_array()).map_or(0, |a| a.len()), msgs_n = body.get("messages").and_then(|m| m.as_array()).map_or(0, |a| a.len()), @@ -681,4 +689,50 @@ mod tests { let mut none = json!({ "model": "m" }); assert_eq!(apply_reasoning_budget(None, &mut none), None); } + + // what this catches: a tail-loaded verb not reaching a llama.cpp-family server (she could + // read its schema and never call it), or the non-standard field going to a cloud provider + // that rejects unknown fields. + #[test] + fn tail_tools_reach_only_a_llamacpp_family_server_and_never_join_the_head() { + let spec = |name: &str| crate::ai::types::NativeToolSpec { + name: name.to_owned(), + description: format!("{name} does one thing"), + input_schema: crate::ai::types::ToolInputSchema { + schema_type: "object".to_owned(), + properties: json!({}), + required: None, + definitions: None, + }, + }; + let request = TextGenerationRequest { + tools: Some(vec![spec("commands_help")]), + tail_tools: Some(vec![spec("code_git_apply")]), + ..Default::default() + }; + let cfg = |llamacpp: bool| OpenAICompatibleConfig { + provider_id: "test-gateway".into(), + name: "Test Gateway".into(), + base_url: "http://127.0.0.1:0".into(), + api_key_env: None, + default_model: "test-model".into(), + capabilities: [Capability::ToolUse].into_iter().collect(), + models: Vec::new(), + model_prefixes: Vec::new(), + requires_auth: false, + tool_protocol: crate::model_registry::ToolProtocol::NativeFunctionCalling, + thinking: ThinkingMode::Default, + single_resident_model: false, + dynamic_model_catalog: false, + llamacpp_sampling_extensions: llamacpp, + tail_tools: llamacpp, + }; + let mut served = json!({ "model": "m" }); + finish_body(&cfg(true), &request, "m", &mut served); + assert_eq!(served["tools"].as_array().map(Vec::len), Some(1), "the head holds only its own verbs"); + assert_eq!(served["tail_tools"][0]["function"]["name"], "code_git_apply"); + let mut cloud = json!({ "model": "m" }); + finish_body(&cfg(false), &request, "m", &mut cloud); + assert!(cloud.get("tail_tools").is_none(), "{cloud}"); + } } diff --git a/core/continuum-engine/src/model_registry/catalog/providers.rs b/core/continuum-engine/src/model_registry/catalog/providers.rs index 0f278df94f..ba015fba93 100644 --- a/core/continuum-engine/src/model_registry/catalog/providers.rs +++ b/core/continuum-engine/src/model_registry/catalog/providers.rs @@ -230,6 +230,9 @@ pub fn providers() -> Vec { // 4B doesn't loop its `` block to the token budget // (same failure DMR hit; the in-process path defaults 1.1). llamacpp_sampling_extensions: true, + // `tail_tools` arrives with the fork pin that carries CambrianTech/llama.cpp#71; + // until then a mind's head stays her activity's static surface. + tail_tools: false, // Its served model ids match the registry rows (the forged // model now lives under this provider), so NO dynamic-catalog // name resolution — `dynamic_model_catalog` stays false and diff --git a/core/continuum-engine/src/model_registry/types.rs b/core/continuum-engine/src/model_registry/types.rs index de268a5d6a..14fc858c7e 100644 --- a/core/continuum-engine/src/model_registry/types.rs +++ b/core/continuum-engine/src/model_registry/types.rs @@ -259,6 +259,12 @@ pub struct ProviderCapabilities { /// `false`. #[serde(default)] pub llamacpp_sampling_extensions: bool, + /// The server accepts `tail_tools` (CambrianTech/llama.cpp#71): verbs callable through its + /// tool-call parser and grammar without rendering them in the head. A mind's learned tool + /// head (goal 10) is offered only where this holds, since a verb outside the head must stay + /// callable. Default: `false`. + #[serde(default)] + pub tail_tools: bool, } /// How prompt_assembly should shape multi-party chat history when diff --git a/core/continuum-genome/src/genome/teach.rs b/core/continuum-genome/src/genome/teach.rs index 808046b636..98364c8755 100644 --- a/core/continuum-genome/src/genome/teach.rs +++ b/core/continuum-genome/src/genome/teach.rs @@ -138,6 +138,7 @@ pub async fn teacher_generate( repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-kernel/src/sdk_codegen/ai_help.rs b/core/continuum-kernel/src/sdk_codegen/ai_help.rs index 9508e8f2fd..c175526cf1 100644 --- a/core/continuum-kernel/src/sdk_codegen/ai_help.rs +++ b/core/continuum-kernel/src/sdk_codegen/ai_help.rs @@ -7,6 +7,11 @@ use std::collections::HashSet; use serde_json::{json, Value}; +/// How many commands a lookup names at once: the nearest names to a miss, and the matches a +/// `commands/help` query returns. Wide enough that the route survives the eight-way tie +/// `list_cards` produced (2026-09-05, see `did_you_mean`), narrow enough to read at a glance. +pub const SUGGESTION_WINDOW: usize = 6; + /// Closest authorized command names to a miss — same category prefix (before `/`), /// or sharing a path segment. Cheap, dependency-free, and enough to unstick an agent /// that guessed a plausible-but-wrong name (e.g. `commands/describe` → `commands/help`). @@ -77,7 +82,7 @@ pub fn did_you_mean<'a>(query: &str, authorized: &[&'a str]) -> Vec<&'a str> { .then(depth(a.1).cmp(&depth(b.1))) .then(a.1.cmp(b.1)) }); - scored.into_iter().take(6).map(|(_, n)| n).collect() + scored.into_iter().take(SUGGESTION_WINDOW).map(|(_, n)| n).collect() } /// Path segments in a command name — `work/list` is 2, `ai/providers/list` is 3. diff --git a/core/continuum-mind/Cargo.toml b/core/continuum-mind/Cargo.toml index 2b18e6ae99..5922aa7c58 100644 --- a/core/continuum-mind/Cargo.toml +++ b/core/continuum-mind/Cargo.toml @@ -24,6 +24,7 @@ serde_json.workspace = true uuid.workspace = true continuum-base = { path = "../continuum-base" } continuum-context = { path = "../continuum-context" } +tool-working-set = { path = "../tool-working-set" } # the learned tool head: pure policy, no core dependency schemars = { version = "0.8", features = ["uuid1"] } continuum-airc-protocol = { path = "../continuum-airc-protocol" } continuum-positron = { path = "../continuum-positron" } diff --git a/core/continuum-mind/src/cognition/check_redundancy.rs b/core/continuum-mind/src/cognition/check_redundancy.rs index d92a9775d6..ab05a4f5b4 100644 --- a/core/continuum-mind/src/cognition/check_redundancy.rs +++ b/core/continuum-mind/src/cognition/check_redundancy.rs @@ -203,6 +203,7 @@ fn build_redundancy_generation_request( repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: Some(ResponseFormat::JsonObject), active_adapters: None, diff --git a/core/continuum-mind/src/cognition/dream_consolidation/distiller.rs b/core/continuum-mind/src/cognition/dream_consolidation/distiller.rs index 037532995e..efb7a9ca8b 100644 --- a/core/continuum-mind/src/cognition/dream_consolidation/distiller.rs +++ b/core/continuum-mind/src/cognition/dream_consolidation/distiller.rs @@ -356,6 +356,7 @@ impl SemanticDistiller { repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-mind/src/cognition/generate_recipe/orchestrator.rs b/core/continuum-mind/src/cognition/generate_recipe/orchestrator.rs index c72eac76b9..beb53a2791 100644 --- a/core/continuum-mind/src/cognition/generate_recipe/orchestrator.rs +++ b/core/continuum-mind/src/cognition/generate_recipe/orchestrator.rs @@ -133,6 +133,7 @@ pub async fn generate_recipe_with_ai( repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-mind/src/cognition/generate_response.rs b/core/continuum-mind/src/cognition/generate_response.rs index 02ab026912..5c49cb7c66 100644 --- a/core/continuum-mind/src/cognition/generate_response.rs +++ b/core/continuum-mind/src/cognition/generate_response.rs @@ -424,6 +424,7 @@ pub fn build_response_generation_request( repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, // Local Qwen takes plain text; no JSON-mode constraint here. response_format: Some(ResponseFormat::Text), diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty.rs b/core/continuum-mind/src/cognition/llm_deliberation_faculty.rs index 34b0a08068..31512f283a 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-mind/src/cognition/llm_deliberation_faculty.rs @@ -321,6 +321,7 @@ impl LlmDeliberationFaculty { memory: Arc, ) -> Self { self.working_memory = Some(memory); + self.share_vocabulary(); self } diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/epoch.rs b/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/epoch.rs index 1e76648804..53dc63d9fa 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/epoch.rs +++ b/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/epoch.rs @@ -181,7 +181,10 @@ impl LlmDeliberationFaculty { } else { let whole = |claims: &[Claim]| claims.iter().map(|claim| claim.full_chars).collect(); match View::start(Vec::new(), &sources, whole) { - Ok((view, _)) => *held = Some(view), + Ok((view, _)) => { + *held = Some(view); + self.tool_head_turned_over(); + } Err(mismatch) => continuum_base::probe!( class = "delib.view.refused", persona = %self.persona_name, @@ -222,15 +225,18 @@ impl LlmDeliberationFaculty { } }; match started { - Ok(start) => continuum_base::probe!( - class = "delib.view.turnover", - persona = %self.persona_name, - epoch = start.epoch, - start_chars = start.chars, - collapsed_items = start.collapsed, - "her view started a new epoch: the one re-prefill an epoch costs, collapsed \ - by the flexbox at its start" - ), + Ok(start) => { + continuum_base::probe!( + class = "delib.view.turnover", + persona = %self.persona_name, + epoch = start.epoch, + start_chars = start.chars, + collapsed_items = start.collapsed, + "her view started a new epoch: the one re-prefill an epoch costs, collapsed \ + by the flexbox at its start" + ); + self.tool_head_turned_over(); + } Err(mismatch) => continuum_base::probe!( class = "delib.view.refused", persona = %self.persona_name, diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/request.rs b/core/continuum-mind/src/cognition/llm_deliberation_faculty/request.rs index f86a61dec1..c0c0a003c8 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty/request.rs +++ b/core/continuum-mind/src/cognition/llm_deliberation_faculty/request.rs @@ -387,6 +387,7 @@ impl LlmDeliberationFaculty { // her turn ends, never continuing the transcript as a teammate. stop_sequences, tools, + tail_tools: None, tool_choice: None, response_format: None, // Page in the persona's current genome (wait-free read). Empty → None, diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tool_surface.rs b/core/continuum-mind/src/cognition/llm_deliberation_faculty/tool_surface.rs index 8ec0919de5..156c40b039 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tool_surface.rs +++ b/core/continuum-mind/src/cognition/llm_deliberation_faculty/tool_surface.rs @@ -18,6 +18,73 @@ impl LlmDeliberationFaculty { self.surface = ToolSurface::build(persona_tools::native_tool_specs(), |spec| { crate::ai::tool_dialect::to_wire_spec_with(spec, style) }); + self.share_vocabulary(); + } + + /// Hand her tool head the verbs it chooses from, priced as this surface sends them. + pub(super) fn share_vocabulary(&self) { + let Some(memory) = self.working_memory.as_deref() else { + return; + }; + match self.surface.vocabulary() { + Ok(vocab) => memory.tool_head().set_vocabulary(vocab), + Err(error) => continuum_base::probe!( + class = "delib.tool_head.vocabulary_refused", + persona = %self.persona_name, + error = %error, + "her tool surface could not become the head's vocabulary; her head stays static" + ), + } + } + + /// One act's price, measured: the engine's prefill and decode rates for her model and the + /// tokens her acts decode (`working_set::need_of`, p90 with headroom, so a miss is priced + /// high and the head errs toward holding a verb). The request overhead is not measured + /// here and is left out. `None` while any of them is unmeasured: then her head stays the + /// activity's static surface. + fn act_cost(&self) -> Option { + let binding = self.binding.load(); + let model = binding.requested_model(); + let prefill = crate::inference::prefill_rate::measured_rate_for(model).tps?; + let decode = crate::inference::decode_knee::rate_for(model).tps?; + let need = self.working_set.as_ref()?.need_of(self.persona_id)?; + (prefill > 0.0 && decode > 0.0).then(|| tool_working_set::CostModel { + prefill_tokens_per_s: prefill, + decode_tokens_per_s: decode, + act_decode_tokens: f64::from(need.reasoning.saturating_add(need.answer)), + act_overhead_ms: 0.0, + samples: need.turns as usize, + }) + } + + /// Her learned head over `selected` (the activity's surface). It always computes and + /// reserves the head the next epoch would hold, so a turnover can adopt it and the shadow + /// receipt (`delib.tool_head.epoch`) measures it. It changes what is SENT only on a server + /// that takes `tail_tools`, where a verb outside the head stays callable. + fn with_learned_head<'a>(&'a self, selected: SelectedSurface<'a>, ws: &Workspace) -> SelectedSurface<'a> { + let Some(memory) = self.working_memory.as_deref() else { + return selected; + }; + let Some(cost) = self.act_cost() else { + return selected; + }; + let binding = self.binding.load(); + let budget = super::super::context_budget::ContextBudget::from_window_unbounded(binding.context_window).tool_surface_tokens(); + let head = memory.tool_head(); + let next = head.next( + ws.now_ms.map_or_else(continuum_base::time::EpochMs::now, continuum_base::time::EpochMs::from_millis), // map_or_else: a workspace that carries no clock reading decides at now + Some(ws.room_id), + u32::try_from(budget).unwrap_or(u32::MAX), // unwrap_or: a share past u32 bounds nothing a schema set can reach + &cost, + ); + if !binding.adapter.accepts_tail_tools() { + return selected; + } + let reserve = next.as_ref().map_or(0, |next| next.tokens() as usize); // map_or: no next head reserves nothing beyond this one + match head.held() { + Some(held) => self.surface.learned(&held, &head.loaded(), reserve), + None => selected.reserving(reserve), + } } /// Her native tool surfaces, as built for her tool set and model. @@ -47,7 +114,32 @@ impl LlmDeliberationFaculty { the rule binds nothing here; offering her hands instead" ); } - selected + self.with_learned_head(selected, ws) + } + + /// Her view started a new epoch, the one moment her head may change: her tool head learns + /// from the epoch that ended and holds the head this act reserved. The receipt is the + /// miss/waste read of the head that epoch held (`sent`: whether it was on the wire, or a + /// shadow head measured while her server cannot take `tail_tools`). + pub(super) fn tool_head_turned_over(&self) { + let Some(memory) = self.working_memory.as_deref() else { + return; + }; + let Some(cost) = memory.tool_head().turn_over_reserved(continuum_base::time::EpochMs::now()) else { + return; + }; + continuum_base::probe!( + class = "delib.tool_head.epoch", + persona = %self.persona_name, + sent = self.binding.load().adapter.accepts_tail_tools(), + learned = cost.learned, + calls = cost.calls, + misses = cost.misses, + waste_tokens = cost.waste_tokens, + head_tokens = cost.head_tokens, + "an epoch ended: the verbs she called that her head did not hold (one find each) and \ + the head schema she never called" + ); } /// A citizen served below [`Self::min_window_for_agentic_surface`] provably cannot hold diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-mind/src/cognition/llm_deliberation_faculty/verdict/contribute.rs index 6f9b3765d4..c6985640af 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty/verdict/contribute.rs +++ b/core/continuum-mind/src/cognition/llm_deliberation_faculty/verdict/contribute.rs @@ -207,7 +207,9 @@ impl LlmDeliberationFaculty { // [`Self::select_tool_surface`] so the budget in `prompt_view_within` reaches the // SAME answer (card dec1a7ff). if request_template.is_none() { - let selected = self.select_tool_surface(ws); + let mut selected = self.select_tool_surface(ws); + // Verbs she loaded into the tail ride beside the head, callable natively. + let tail = std::mem::take(&mut selected.tail); if selected.reason == SurfaceReason::CoreHandsForWindow { // The one truncating arm: the served window cannot hold her extended // hands. Whoever later asks "why did she never call X" needs this row. @@ -250,6 +252,7 @@ impl LlmDeliberationFaculty { ); let mut template = request; + template.tail_tools = (!tail.is_empty()).then_some(tail); template.messages.clear(); request_template = Some(template); } diff --git a/core/continuum-mind/src/cognition/mod.rs b/core/continuum-mind/src/cognition/mod.rs index be9c99d009..1c0d79a4bc 100644 --- a/core/continuum-mind/src/cognition/mod.rs +++ b/core/continuum-mind/src/cognition/mod.rs @@ -77,6 +77,7 @@ pub mod learning_policy; pub mod llm_deliberation_faculty; pub(crate) mod context_streams; pub mod tool_surface; +pub mod tool_head; pub mod model_binding; pub mod model_resolver; /// Paging cursors over large data she is working through, kept in working memory. diff --git a/core/continuum-mind/src/cognition/persona_workspace/root_acting_workspace.rs b/core/continuum-mind/src/cognition/persona_workspace/root_acting_workspace.rs index 0936672b6f..49b13e3fb5 100644 --- a/core/continuum-mind/src/cognition/persona_workspace/root_acting_workspace.rs +++ b/core/continuum-mind/src/cognition/persona_workspace/root_acting_workspace.rs @@ -289,6 +289,12 @@ impl PersonaWorkspaceRegistry { // Assembly restores disk state; do it outside the lookup lock. let restored = load_volatile(persona_id)?; let (cycle, working_memory) = assemble_workspace_cycle(cfg, restored, Capture::Recorded); + // A resident keeps her learned tool head in her own store; a fork never does. + if let Some(store) = template.admission.tool_heads() { + working_memory + .tool_head() + .attach(crate::cognition::tool_head::entity::ToolHeadStore::new(Arc::clone(store), persona_id)); + } let cycle = Arc::new(cycle); // cycles THEN templates (the one canonical lock order). let mut cycles = self.cycles.lock(); @@ -319,6 +325,12 @@ impl PersonaWorkspaceRegistry { let template = cfg.clone(); let restored = load_volatile(persona_id)?; let (cycle, working_memory) = assemble_workspace_cycle(cfg, restored, Capture::Recorded); + // A resident keeps her learned tool head in her own store; a fork never does. + if let Some(store) = template.admission.tool_heads() { + working_memory + .tool_head() + .attach(crate::cognition::tool_head::entity::ToolHeadStore::new(Arc::clone(store), persona_id)); + } let cycle = Arc::new(cycle); // cycles THEN templates (the one canonical lock order). let mut cycles = self.cycles.lock(); diff --git a/core/continuum-mind/src/cognition/rate_proposals/orchestrator.rs b/core/continuum-mind/src/cognition/rate_proposals/orchestrator.rs index 1aecbedd4d..c669a034b2 100644 --- a/core/continuum-mind/src/cognition/rate_proposals/orchestrator.rs +++ b/core/continuum-mind/src/cognition/rate_proposals/orchestrator.rs @@ -108,6 +108,7 @@ pub async fn rate_proposals_with_ai( repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/continuum-mind/src/cognition/shared_analysis/mod.rs b/core/continuum-mind/src/cognition/shared_analysis/mod.rs index 5fd68a4d3d..694808e045 100644 --- a/core/continuum-mind/src/cognition/shared_analysis/mod.rs +++ b/core/continuum-mind/src/cognition/shared_analysis/mod.rs @@ -273,6 +273,7 @@ async fn run_analysis( repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, // FORCE JSON OUTPUT. llama.cpp / DMR constrain the sampler so the // model can only emit valid JSON. Eliminates qwen3.5's thinking-mode diff --git a/core/continuum-mind/src/cognition/should_respond.rs b/core/continuum-mind/src/cognition/should_respond.rs index 0c0c9cd601..3ae4002a29 100644 --- a/core/continuum-mind/src/cognition/should_respond.rs +++ b/core/continuum-mind/src/cognition/should_respond.rs @@ -213,6 +213,7 @@ pub async fn evaluate_gating( repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: Some(ResponseFormat::JsonObject), active_adapters: None, diff --git a/core/continuum-mind/src/cognition/tool_head/entity.rs b/core/continuum-mind/src/cognition/tool_head/entity.rs new file mode 100644 index 0000000000..33d05ebad3 --- /dev/null +++ b/core/continuum-mind/src/cognition/tool_head/entity.rs @@ -0,0 +1,65 @@ +//! Her tool head's state as an ORM entity: one row per mind, keyed by her persona id, in her +//! own store (`engrams.sqlite`), written once per epoch at turnover and read at boot. + +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::orm::{BaseEntity, Entity, OrmStore, OrmStoreError}; + +use super::ToolHeadState; + +/// One mind's learned tool head: her calls, her epochs, what this epoch holds and has loaded, +/// and the learned weights. +#[derive(Debug, Clone, Serialize, Deserialize, Entity)] +#[serde(rename_all = "camelCase")] +#[entity(collection = "tool_heads")] +pub struct ToolHeadRecord { + #[serde(flatten)] + pub base: BaseEntity, + + /// Whose head this is; also the row id, so there is one row per mind. + #[entity(unique, indexed)] + pub persona_id: Uuid, + + #[entity(json)] + pub state: ToolHeadState, +} + +/// Her head's persistence: the row keyed by her persona id. +#[derive(Clone)] +pub struct ToolHeadStore { + store: Arc>, + persona_id: Uuid, +} + +impl std::fmt::Debug for ToolHeadStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ToolHeadStore").field("persona_id", &self.persona_id).finish() + } +} + +impl ToolHeadStore { + pub fn new(store: Arc>, persona_id: Uuid) -> Self { + Self { store, persona_id } + } + + /// Her saved head, if a previous life kept one. + pub async fn load(&self) -> Result, OrmStoreError> { + Ok(self.store.find_by_id(self.persona_id).await?.map(|record| record.state)) + } + + /// Keep `state` as her head's row: insert the first time, update after. + pub async fn keep(&self, state: ToolHeadState) -> Result<(), OrmStoreError> { + let exists = self.store.find_by_id(self.persona_id).await?.is_some(); + let mut base = BaseEntity::for_new_record(); + base.id = self.persona_id.to_string(); + let record = ToolHeadRecord { base, persona_id: self.persona_id, state }; + if exists { + self.store.update(self.persona_id, &record).await + } else { + self.store.save(self.persona_id, &record).await + } + } +} diff --git a/core/continuum-mind/src/cognition/tool_head/mod.rs b/core/continuum-mind/src/cognition/tool_head/mod.rs new file mode 100644 index 0000000000..db6752f05f --- /dev/null +++ b/core/continuum-mind/src/cognition/tool_head/mod.rs @@ -0,0 +1,350 @@ +//! Her learned tool head (plan goal 10, card ecd5dff3): which tool schemas the head of her +//! prompt carries for an epoch, learned online from her own calls, and which verbs she has +//! loaded into the tail since it turned over. +//! +//! # The rules it keeps +//! +//! - The head changes ONLY when her view starts a new epoch: the schemas render right after +//! the system prompt, so any other change would re-prefill everything after them. Each act +//! computes the head the NEXT epoch would hold ([`ToolHead::next`]), the budget reserves +//! the larger of the two, and [`ToolHead::turn_over`] adopts it at the turnover. +//! - Every verb stays reachable. One she does not hold, she finds with `commands/help`; its +//! schema is in that result (the tail) and the verb rides the request's `tail_tools`, which +//! the engine's parser and grammar accept without rendering it in the head. It stays loaded +//! until the epoch ends. +//! - The policy is the replay-tested one (`tool-working-set`, slice 1): an online logistic +//! blend of her recent and standing habits, the activity's, her call-to-call chain and the +//! relevance of her latest acts, deciding each verb by `p · miss > schema · (1 − p)`. It +//! learns at every turnover from the epoch that just ended. +//! +//! Its state ([`ToolHeadState`]) is hers and survives a restart (see `entity`). + +pub mod entity; +#[cfg(test)] +mod tests; + +use continuum_base::time::EpochMs; +use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; +use tool_working_set::features::{Signals, LONG_HALF_LIFE_MS}; +use tool_working_set::head::{choose, HeadSet}; +use tool_working_set::logistic::Logistic; +use tool_working_set::policy::blend::examples; +use tool_working_set::relevance::Lexical; +use tool_working_set::{ActivityId, Call, CostModel, Epoch, History, ToolId, Vocabulary}; +use uuid::Uuid; + +/// The verb that finds the others: always held, so every verb is one call away. +pub const FINDER: &str = "commands/help"; + +/// The online learner's step size: the rate the slice-1 replay ran (`--online-rate 0.05`, the +/// best held-out cost of every policy there). +const ONLINE_RATE: f64 = 0.05; + +/// One call she made. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct UseRecord { + pub at_ms: u64, + /// Canonical command name (`code/read`). + pub verb: String, + pub room: Option, + /// Her act as recorded (the call line), the text relevance reads. + pub text: String, + /// The epoch it fell in. + pub epoch: u64, +} + +/// Where one of her epochs began. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct EpochStart { + pub epoch: u64, + pub start_ms: u64, +} + +/// Everything the head knows: what she called, when her epochs turned over, what this epoch +/// holds and has loaded, and the learned weights. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct ToolHeadState { + pub uses: Vec, + /// Her epochs, oldest first; the last is the current one. + pub epochs: Vec, + /// The verbs the current epoch's head holds; `None` until the first learned head is adopted + /// (until then her surface is the activity's static one). + pub held: Option>, + /// Verbs loaded into the tail this epoch. + pub loaded: Vec, + pub model: Logistic, +} + +/// What one ended epoch cost, the miss/waste receipt. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct EpochCost { + pub calls: u64, + /// Distinct verbs she called that the head did not hold: each cost one find. + pub misses: u64, + /// Head schema tokens of verbs she did not call. + pub waste_tokens: u64, + pub head_tokens: u64, + /// Whether a learned head was held (before the first adoption her surface was static). + pub learned: bool, +} + +/// The vocabulary the head is chosen from and the relevance model built over it, rebuilt +/// whenever her tool set or model changes. +#[derive(Debug)] +struct Live { + vocab: Vocabulary, + lexical: Lexical, +} + +/// Her tool head. Interior-mutable, one per mind, shared by the act path (which notes her +/// calls) and the deliberation faculty (which reads and adopts the head). +#[derive(Debug, Default)] +pub struct ToolHead { + state: Mutex, + live: Mutex>, + /// The head the budget reserved this act: what a turnover in this act adopts. + reserved: Mutex>, + /// Her row in her own store, attached for a resident mind (never a measurement fork). + store: Mutex>, +} + +impl ToolHead { + /// The verbs the head may hold, with each schema's price. + pub fn set_vocabulary(&self, vocab: Vocabulary) { + let lexical = Lexical::new(&vocab); + *self.live.lock() = Some(Live { vocab, lexical }); + } + + /// Her calls of one act. A `commands/help` call naming a verb loads that verb into the + /// tail; so do the verbs a help query returned (`found`). + pub fn note(&self, at: EpochMs, room: Option, verbs: &[String], found: &[String], text: &str) { + let mut state = self.state.lock(); + let epoch = state.epochs.last().map_or(0, |start| start.epoch); // map_or: calls before any turnover fall in epoch 0 + if state.epochs.is_empty() { + state.epochs.push(EpochStart { epoch, start_ms: at.millis() }); + } + for verb in verbs { + state.uses.push(UseRecord { at_ms: at.millis(), verb: verb.clone(), room, text: text.to_owned(), epoch }); + } + for verb in found { + let held = state.held.as_ref().is_some_and(|held| held.contains(verb)); + if !held && !state.loaded.contains(verb) { + state.loaded.push(verb.clone()); + } + } + } + + /// The head the next epoch would hold, were it to turn over now (her current epoch counted + /// as ended), reserved for a turnover in this act to adopt. `None` when there is no + /// vocabulary or no call to learn from yet. + pub fn next(&self, at: EpochMs, activity: Option, budget_tokens: u32, cost: &CostModel) -> Option { + let live = self.live.lock(); + let live = live.as_ref()?; + let state = self.state.lock(); + let (calls, epochs) = replayable(&state, &live.vocab, None); + if calls.is_empty() { + return None; + } + let history = History { + vocab: &live.vocab, + calls: &calls, + epochs: &epochs, + at, + activity: activity.map(ActivityId), + population: None, + }; + let head = head_from(&history, &live.lexical, &state.model, cost, budget_tokens); + *self.reserved.lock() = Some(head.clone()); + Some(head) + } + + /// Her view started a new epoch at `at`: learn from the epoch that ended, report what it + /// cost, hold the head the budget reserved this act, and keep the state in her store. + pub fn turn_over_reserved(&self, at: EpochMs) -> Option { + let reserved = self.reserved.lock().take(); + let receipt = self.turn_over(at, reserved.as_ref()); + self.keep(); + receipt + } + + /// [`Self::turn_over_reserved`] with an explicit head. Epochs are numbered here, + /// monotonically across restarts (the view's own counter restarts). + pub fn turn_over(&self, at: EpochMs, next: Option<&HeadSet>) -> Option { + let live = self.live.lock(); + let mut state = self.state.lock(); + let receipt = live.as_ref().and_then(|live| learn_from_ended(&mut state, live)); + if let Some(live) = live.as_ref() { + if let Some(next) = next { + state.held = Some(next.tools().iter().map(|tool| live.vocab.name(*tool).to_owned()).collect()); + } + } + state.loaded.clear(); + let epoch = state.epochs.last().map_or(0, |start| start.epoch + 1); // map_or: the first turnover opens epoch 0 + state.epochs.push(EpochStart { epoch, start_ms: at.millis() }); + prune(&mut state, at); + receipt + } + + /// The verbs the current epoch's head holds, once a learned head has been adopted. + pub fn held(&self) -> Option> { + self.state.lock().held.clone() + } + + /// The verbs loaded into the tail this epoch. + pub fn loaded(&self) -> Vec { + self.state.lock().loaded.clone() + } + + /// Attach her store and bring back what a previous life kept. A load that lands after she + /// has already acted this life keeps the live state (the newer evidence) and says so. + pub fn attach(self: &std::sync::Arc, store: entity::ToolHeadStore) { + *self.store.lock() = Some(store.clone()); + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + continuum_base::probe!(class = "delib.tool_head.unpersisted", "no runtime to read her saved tool head on"); + return; + }; + let head = std::sync::Arc::clone(self); + runtime.spawn(async move { + match store.load().await { + Ok(Some(saved)) => { + let mut state = head.state.lock(); + if state.uses.is_empty() { + *state = saved; + } else { + continuum_base::probe!( + class = "delib.tool_head.restore_late", + live_uses = state.uses.len() as u64, + saved_uses = saved.uses.len() as u64, + "her saved tool head arrived after she acted; the live state stays" + ); + } + } + Ok(None) => {} + Err(error) => continuum_base::probe!(class = "delib.tool_head.load_failed", error = %error, "her saved tool head could not be read"), + } + }); + } + + /// Write her state to her store, off the act path. + fn keep(&self) { + let Some(store) = self.store.lock().clone() else { + return; + }; + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + return; + }; + let state = self.snapshot(); + runtime.spawn(async move { + if let Err(error) = store.keep(state).await { + continuum_base::probe!(class = "delib.tool_head.save_failed", error = %error, "her tool head could not be saved"); + } + }); + } + + pub fn snapshot(&self) -> ToolHeadState { + self.state.lock().clone() + } + + pub fn restore(&self, state: ToolHeadState) { + *self.state.lock() = state; + } +} + +/// The verbs a batch of calls found with the finder: `commands/help(name=X)` loads `X`, by its +/// canonical name whichever dialect she asked in (`read_file` loads `code/read`). +pub fn found_by_finder<'a>(calls: impl Iterator) -> Vec { + calls + .filter(|call| call.name == FINDER) + .filter_map(|call| call.input.get("name").and_then(serde_json::Value::as_str)) + .map(|name| crate::ai::tool_dialect::resolve_wire_name(name).to_string()) + .collect() +} + +/// Her calls as the policy reads them, and her epochs before `before` (an epoch seq; `None`: +/// every epoch, the current one counted as ended). Calls of verbs the vocabulary lacks are +/// left out (a verb her tool set no longer has cannot be held). +fn replayable(state: &ToolHeadState, vocab: &Vocabulary, before: Option) -> (Vec, Vec) { + let mut calls = Vec::new(); + let mut epochs: Vec = Vec::new(); + for start in &state.epochs { + if before.is_some_and(|before| start.epoch >= before) { + break; + } + let first = calls.len(); + for record in state.uses.iter().filter(|record| record.epoch == start.epoch) { + if let Some(tool) = vocab.id(&record.verb) { + calls.push(Call { + at: EpochMs::from_millis(record.at_ms), + tool, + activity: record.room.map(ActivityId), + text: record.text.clone(), + }); + } + } + if calls.len() > first { + epochs.push(Epoch { start: EpochMs::from_millis(start.start_ms), calls: first..calls.len() }); + } + } + (calls, epochs) +} + +/// The head the blend chooses for `history`, the finder always held. +fn head_from(history: &History<'_>, lexical: &Lexical, model: &Logistic, cost: &CostModel, budget_tokens: u32) -> HeadSet { + let signals = Signals::of(history, lexical); + let chance: Vec = (0..history.vocab.len()) + .map(|tool| if signals.any(tool) { model.chance(&signals.row(tool)) } else { 0.0 }) + .collect(); + let pinned: Vec = history.vocab.id(FINDER).into_iter().collect(); + choose(history.vocab, &chance, cost, budget_tokens, &pinned) +} + +/// Teach the model the epoch that just ended (the last one), and what it cost against the +/// head it held. `None` when no epoch has ended with a call in it. +fn learn_from_ended(state: &mut ToolHeadState, live: &Live) -> Option { + let ended = *state.epochs.last()?; + let mut used: Vec = + state.uses.iter().filter(|record| record.epoch == ended.epoch).filter_map(|record| live.vocab.id(&record.verb)).collect(); + let calls = used.len() as u64; + if used.is_empty() { + return None; + } + used.sort_unstable(); + used.dedup(); + let (prior_calls, prior_epochs) = replayable(state, &live.vocab, Some(ended.epoch)); + let history = History { + vocab: &live.vocab, + calls: &prior_calls, + epochs: &prior_epochs, + at: EpochMs::from_millis(ended.start_ms), + activity: state + .uses + .iter() + .find(|record| record.epoch == ended.epoch) + .and_then(|record| record.room) + .map(ActivityId), + population: None, + }; + let signals = Signals::of(&history, &live.lexical); + state.model.learn(&examples(&signals, &used), ONLINE_RATE); + let held: Vec = + state.held.iter().flatten().filter_map(|verb| live.vocab.id(verb)).collect(); + let held_set = HeadSet::of(&live.vocab, held); + Some(EpochCost { + calls, + misses: used.iter().filter(|tool| !held_set.contains(**tool)).count() as u64, + waste_tokens: held_set.tools().iter().filter(|tool| used.binary_search(tool).is_err()).map(|tool| u64::from(live.vocab.tokens(*tool))).sum(), + head_tokens: held_set.tokens(), + learned: state.held.is_some(), + }) +} + +/// Drop calls older than four of the longest half-lives the policy reads (they weigh under a +/// sixteenth) and the epochs left with none, so her state stays bounded by her own pace. +fn prune(state: &mut ToolHeadState, at: EpochMs) { + let horizon = at.millis().saturating_sub(4 * LONG_HALF_LIFE_MS); + state.uses.retain(|record| record.at_ms >= horizon); + let current = state.epochs.last().map(|start| start.epoch); + let uses = &state.uses; + state.epochs.retain(|start| Some(start.epoch) == current || uses.iter().any(|record| record.epoch == start.epoch)); +} diff --git a/core/continuum-mind/src/cognition/tool_head/tests.rs b/core/continuum-mind/src/cognition/tool_head/tests.rs new file mode 100644 index 0000000000..8d8745bb00 --- /dev/null +++ b/core/continuum-mind/src/cognition/tool_head/tests.rs @@ -0,0 +1,116 @@ +#![cfg(test)] + +use std::sync::Arc; + +use super::entity::{ToolHeadRecord, ToolHeadStore}; +use super::*; +use tool_working_set::vocab::ToolSchema; + +fn vocab() -> Vocabulary { + let schema = |name: &str, tokens| ToolSchema { name: name.into(), description: format!("{name} does one thing"), tokens }; + Vocabulary::new(vec![ + schema("commands/help", 100), + schema("code/read", 100), + schema("code/edit", 300), + schema("web/fetch", 200), + ]) + .expect("small vocabulary") +} + +fn cost() -> CostModel { + // one extra act costs 2,000 prompt-token equivalents: decode 200 tokens at a 10x rate ratio + CostModel { prefill_tokens_per_s: 100.0, decode_tokens_per_s: 10.0, act_decode_tokens: 200.0, act_overhead_ms: 0.0, samples: 1 } +} + +fn verbs(names: &[&str]) -> Vec { + names.iter().map(|name| (*name).to_owned()).collect() +} + +fn at(minutes: u64) -> EpochMs { + EpochMs::from_millis(1_800_000_000_000 + minutes * 60_000) +} + +fn names(head: &HeadSet, vocab: &Vocabulary) -> Vec { + head.tools().iter().map(|tool| vocab.name(*tool).to_owned()).collect() +} + +// what this catches: the head moving mid-epoch (a re-prefill of everything after the system +// prompt), or a turnover adopting something other than the head the budget reserved for. +#[test] +fn the_head_changes_only_at_a_turnover_and_to_the_head_that_was_reserved() { + let head = ToolHead::default(); + head.set_vocabulary(vocab()); + let room = Some(Uuid::from_u128(7)); + for minute in 0..6 { + head.note(at(minute), room, &verbs(&["code/read"]), &[], "code/read(file_path=a.rs)"); + } + let next = head.next(at(6), room, 10_000, &cost()).expect("a call to learn from"); + assert!(names(&next, &vocab()).contains(&FINDER.to_owned()), "the finder is always held"); + assert_eq!(head.held(), None, "nothing is adopted before a turnover"); + head.note(at(7), room, &verbs(&["code/read"]), &[], "code/read(file_path=b.rs)"); + assert_eq!(head.held(), None, "an act inside the epoch never moves the head"); + head.turn_over(at(8), Some(&next)); + assert_eq!(head.held(), Some(names(&next, &vocab()))); +} + +// what this catches: a verb found with commands/help not becoming callable for the rest of the +// epoch, a held verb counted as loaded, or the tail surviving into the next epoch's head. +#[test] +fn a_found_verb_is_loaded_until_the_epoch_ends() { + let head = ToolHead::default(); + head.set_vocabulary(vocab()); + let vocab = vocab(); + let held = HeadSet::of(&vocab, vec![vocab.id("commands/help").expect("listed"), vocab.id("code/read").expect("listed")]); + head.turn_over(at(0), Some(&held)); + head.note(at(1), None, &verbs(&["commands/help"]), &verbs(&["web/fetch", "code/read"]), "commands/help(name=web/fetch)"); + assert_eq!(head.loaded(), verbs(&["web/fetch"])); + head.turn_over(at(2), Some(&held)); + assert!(head.loaded().is_empty()); +} + +// what this catches: the miss/waste receipt counting a verb she called twice as two finds, or +// charging waste for a held verb she did use. +#[test] +fn an_ended_epoch_reports_its_misses_and_waste_against_the_head_it_held() { + let head = ToolHead::default(); + head.set_vocabulary(vocab()); + let vocab = vocab(); + let held = HeadSet::of(&vocab, vec![vocab.id("commands/help").expect("listed"), vocab.id("code/edit").expect("listed")]); + head.turn_over(at(0), Some(&held)); + for minute in 1..4 { + head.note(at(minute), None, &verbs(&["code/read"]), &[], "code/read(file_path=a.rs)"); + } + let cost = head.turn_over(at(5), Some(&held)).expect("an epoch with calls ended"); + assert_eq!((cost.calls, cost.misses, cost.waste_tokens, cost.head_tokens, cost.learned), (3, 1, 400, 400, true)); +} + +// what this catches: her learned head not surviving a restart, or a second save inserting a +// second row for the same mind. +#[tokio::test] +async fn her_head_survives_a_restart_through_her_store() { + let (adapter, _dir) = crate::orm::store::fresh_adapter().await; + let store = Arc::new(crate::orm::OrmStore::::new(adapter).await.expect("schema")); + let persona = Uuid::from_u128(42); + let kept = ToolHeadStore::new(Arc::clone(&store), persona); + assert_eq!(kept.load().await.expect("read"), None); + let head = ToolHead::default(); + head.set_vocabulary(vocab()); + head.note(at(1), None, &verbs(&["code/read"]), &[], "code/read(file_path=a.rs)"); + kept.keep(head.snapshot()).await.expect("first save"); + head.note(at(2), None, &verbs(&["code/edit"]), &[], "code/edit(file_path=a.rs)"); + kept.keep(head.snapshot()).await.expect("second save updates"); + assert_eq!(store.find_all().await.expect("rows").len(), 1); + let restored = ToolHead::default(); + restored.restore(kept.load().await.expect("read").expect("kept")); + assert_eq!(restored.snapshot(), head.snapshot()); +} + +// what this catches: a verb found through the finder not loading, or another verb's `name` +// argument loading something. (Its wire aliases resolve through `tool_dialect::resolve_wire_name`, +// whose index the command registrations fill; core's `tool_aliases` tests pin that mapping.) +#[test] +fn only_the_finder_loads_the_verb_it_names() { + let call = |name: &str, verb: &str| crate::ai::types::ToolCall { id: "t".into(), name: verb.into(), input: serde_json::json!({ "name": name }) }; + assert_eq!(found_by_finder([call("code/read", FINDER)].iter()), verbs(&["code/read"])); + assert!(found_by_finder([call("x", "code/read")].iter()).is_empty(), "only the finder loads"); +} diff --git a/core/continuum-mind/src/cognition/tool_surface.rs b/core/continuum-mind/src/cognition/tool_surface.rs index 37d73bca4a..d33a6b2e70 100644 --- a/core/continuum-mind/src/cognition/tool_surface.rs +++ b/core/continuum-mind/src/cognition/tool_surface.rs @@ -55,6 +55,9 @@ pub enum SurfaceReason { /// the discovery pair and her focus verbs beside them. Not a truncation: the recipe is /// the rule. RoomAffordances, + /// Her learned head for this epoch ([`crate::cognition::tool_head`]), on a server that takes + /// `tail_tools`: every other verb is one `commands/help` away and callable from the tail. + LearnedHead, } /// One working set as it goes on the wire, priced once when it is built. @@ -139,6 +142,7 @@ impl ToolSurface { tokens, reason: SurfaceReason::RoomAffordances, demand: tokens, + tail: Vec::new(), }; } // The SERVED window, never the prefill-affordable one: the schemas sit in the cached @@ -152,6 +156,45 @@ impl ToolSurface { } } + /// Every native verb as the learned head chooses from it: its canonical name, its + /// description, and what its schema costs on the wire. + pub fn vocabulary(&self) -> Result { + let schemas = self + .names + .iter() + .zip(self.registry.specs.iter()) + .map(|(name, spec)| { + let tokens = u32::try_from(tool_surface_tokens_of(std::slice::from_ref(spec))) + .map_err(|e| format!("{name}: schema size: {e}"))?; + Ok(tool_working_set::vocab::ToolSchema { name: name.clone(), description: spec.description.clone(), tokens }) + }) + .collect::, String>>()?; + tool_working_set::Vocabulary::new(schemas) + } + + /// Her learned head: the `held` verbs in canonical order, the `loaded` ones riding the + /// tail, the budget charged `reserve_tokens` when that exceeds the head (the larger of + /// this epoch's head and the next one, so a turnover in this act fits what it adopts). + pub fn learned(&self, held: &[String], loaded: &[String], reserve_tokens: usize) -> SelectedSurface<'_> { + let pick = |wanted: &[String]| -> Vec { + self.names + .iter() + .zip(self.registry.specs.iter()) + .filter(|(name, _)| wanted.contains(name)) + .map(|(_, spec)| spec.clone()) + .collect() + }; + let specs = pick(held); + let tokens = tool_surface_tokens_of(&specs); + SelectedSurface { + specs: Some(Cow::Owned(specs)), + tokens: tokens.max(reserve_tokens), + reason: SurfaceReason::LearnedHead, + demand: tokens, + tail: pick(loaded), + } + } + /// The verbs an activity declares (a command name, or a subtree `code/**`), with the /// discovery pair and her own mind's verbs beside them: a room's recipe is the rule of /// that room, never of her mind (Kimi, 2026-10-05: "help works; nothing to invoke @@ -196,11 +239,13 @@ pub struct SelectedSurface<'a> { pub tokens: usize, pub reason: SurfaceReason, demand: usize, + /// Verbs loaded into the tail: callable through the request's `tail_tools`, never in the head. + pub tail: Vec, } impl<'a> SelectedSurface<'a> { fn borrowed(specs: &'a [NativeToolSpec], tokens: usize, reason: SurfaceReason, demand: usize) -> Self { - Self { specs: (reason != SurfaceReason::NoTools).then_some(Cow::Borrowed(specs)), tokens, reason, demand } + Self { specs: (reason != SurfaceReason::NoTools).then_some(Cow::Borrowed(specs)), tokens, reason, demand, tail: Vec::new() } } /// What an UNTRUNCATED demand measurement prices for this turn. @@ -212,6 +257,13 @@ impl<'a> SelectedSurface<'a> { pub fn demand_tokens(&self) -> usize { self.demand } + + /// Charge the budget at least `reserve_tokens` for this surface: the next epoch's head, + /// which a turnover in this act would adopt, is larger than this one. + pub fn reserving(mut self, reserve_tokens: usize) -> Self { + self.tokens = self.tokens.max(reserve_tokens); + self + } } /// The verbs a capable citizen's hands add over the core working set: the web, her rooms @@ -382,4 +434,25 @@ mod tests { assert!(names.contains(&"commands/list") && !names.contains(&"web/fetch"), "{names:?}"); assert_eq!(surface.select(&[], 0).reason, SurfaceReason::Hands, "an unknown window is never an invented one"); } + + // what this catches: the learned head sending verbs out of canonical order (two acts in one + // epoch would differ), a loaded verb landing in the head instead of the tail, or the budget + // charged less than the next epoch's head a turnover in this act would adopt. + #[test] + fn a_learned_head_holds_its_verbs_in_order_loads_the_rest_in_the_tail_and_reserves_the_next() { + let surface = built(REGISTRY.iter().copied()); + let held = vec!["commands/help".to_string(), "code/edit".to_string()]; + let loaded = vec!["web/fetch".to_string()]; + let head = surface.learned(&held, &loaded, 0); + let names: Vec<&str> = head.specs.as_deref().into_iter().flatten().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["code/edit", "commands/help"]); + assert_eq!(head.tail.iter().map(|s| s.name.as_str()).collect::>(), ["web/fetch"]); + assert_eq!(head.reason, SurfaceReason::LearnedHead); + let reserved = surface.learned(&held, &loaded, 100_000); + assert_eq!((reserved.tokens, reserved.demand_tokens()), (100_000, head.tokens)); + let vocab = surface.vocabulary().expect("vocabulary"); + assert_eq!(vocab.len(), REGISTRY.len()); + let edit = vocab.id("code/edit").expect("canonical names key the vocabulary"); + assert_eq!(vocab.tokens(edit) as usize, tool_surface_tokens_of(&[spec("code/edit")])); + } } diff --git a/core/continuum-mind/src/cognition/validate_response.rs b/core/continuum-mind/src/cognition/validate_response.rs index fd448b753d..b4f9ae19ac 100644 --- a/core/continuum-mind/src/cognition/validate_response.rs +++ b/core/continuum-mind/src/cognition/validate_response.rs @@ -240,6 +240,7 @@ fn build_validate_generation_request( repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: Some(ResponseFormat::Text), active_adapters: None, diff --git a/core/continuum-mind/src/cognition/working_memory.rs b/core/continuum-mind/src/cognition/working_memory.rs index b17126e28a..205fa4a953 100644 --- a/core/continuum-mind/src/cognition/working_memory.rs +++ b/core/continuum-mind/src/cognition/working_memory.rs @@ -330,6 +330,9 @@ pub struct WorkingMemory { /// has read: her cursors, kept here because the history that carried each page is the /// first thing a tight window's fit drops ([`super::open_views`]). open_views: Mutex, + /// Her learned tool head: every call she makes is noted here, and the deliberation faculty + /// reads and adopts the head at each epoch turnover ([`super::tool_head`]). + tool_head: Arc, } /// The PROVENANCE of one working-memory entry — the type that makes receipts, diff --git a/core/continuum-mind/src/cognition/working_memory/ledger.rs b/core/continuum-mind/src/cognition/working_memory/ledger.rs index 9bbd6aec3a..1fb42de272 100644 --- a/core/continuum-mind/src/cognition/working_memory/ledger.rs +++ b/core/continuum-mind/src/cognition/working_memory/ledger.rs @@ -68,9 +68,15 @@ impl WorkingMemory { receipt_children: Mutex::new(BTreeMap::new()), active_from_seq: AtomicU64::new(0), open_views: Mutex::new(Default::default()), + tool_head: Default::default(), } } + /// Her learned tool head. + pub fn tool_head(&self) -> &Arc { + &self.tool_head + } + /// Keep the existing measured truncation peak across intermediate Act replies. /// Switching activity/root does not transfer this evidence to another concern. pub fn retain_truncated_emission(&self, room: Uuid, peak_tokens: u32) { @@ -347,6 +353,10 @@ impl WorkingMemory { // trail's KV-cache prefix byte-stable across a settle-act. let head: String = a.chars().take(self.budget().trail_head_chars()).collect(); let text = format!("[action #{seq}] {head}"); + // Her tool head learns from every call, and a verb she found is loaded into the tail. + let verbs: Vec = acts.iter().map(|act| act.call.name.clone()).collect(); + let found = super::super::tool_head::found_by_finder(acts.iter().map(|act| &act.call)); + self.tool_head.note(continuum_base::time::EpochMs::now(), room, &verbs, &found, &text); let mut e = self.entries.lock(); // Transfer provenance before bounded entry eviction. Match this scope, // activity. Consume it once; mismatched IDs remain an explicit protocol diff --git a/core/continuum-mind/src/persona/admission_state/admission_state.rs b/core/continuum-mind/src/persona/admission_state/admission_state.rs index d6866a2540..6fb63954ee 100644 --- a/core/continuum-mind/src/persona/admission_state/admission_state.rs +++ b/core/continuum-mind/src/persona/admission_state/admission_state.rs @@ -36,6 +36,7 @@ impl AdmissionState { persistence: RwLock::new(persistence), owner_id: RwLock::new(None), graph: crate::persona::engram_graph::EngramGraph::new(), + tool_heads: None, } } @@ -84,9 +85,15 @@ impl AdmissionState { // empty graph and re-accumulates from live acts. Sidecar // persistence is the next slice (CAUSAL-MEMORY-GRAPH.md §4). graph: crate::persona::engram_graph::EngramGraph::new(), + tool_heads: None, } } + /// Her tool head's row store, when this state has a disk. + pub fn tool_heads(&self) -> Option<&Arc>> { + self.tool_heads.as_ref() + } + /// Borrow the shared recall metadata registry. Recall + decay tick /// subsystems clone this Arc for their own reads/writes — they /// observe the same DashMap admission writes into. @@ -231,13 +238,19 @@ impl AdmissionState { let (engrams, metadata, row_id_pairs) = loader.load_with_row_ids().await?; sink_concrete.prime_cache(row_id_pairs); - Ok(Self::new_rehydrated( + // Her tool head's row lives in the same database (one home, one store). + let tool_heads = Arc::new( + OrmStore::::new(Arc::clone(&adapter)).await?, + ); + let mut state = Self::new_rehydrated( recall_metadata, sink_concrete as Arc, engrams, metadata, - )) + ); + state.tool_heads = Some(tool_heads); + Ok(state) } /// Run the admission pipeline on one inbox message, recording all diff --git a/core/continuum-mind/src/persona/admission_state/in_memory_seen_content.rs b/core/continuum-mind/src/persona/admission_state/in_memory_seen_content.rs index 8432355674..d7bc5895e7 100644 --- a/core/continuum-mind/src/persona/admission_state/in_memory_seen_content.rs +++ b/core/continuum-mind/src/persona/admission_state/in_memory_seen_content.rs @@ -115,6 +115,9 @@ pub struct AdmissionState { /// retrieval surfaces walk it, cognition judges. In-memory (DashMap); /// sidecar durability is a follow-on slice. pub(super) graph: crate::persona::engram_graph::EngramGraph, + /// Her learned tool head's row store, in this same per-persona database; `None` for a + /// state with no disk (tests, replay, a measurement fork). + pub(super) tool_heads: Option>>, /// The persona this store BELONGS to (its own user id). Set once at spawn via /// [`set_owner_id`](Self::set_owner_id); `None` for bare/test states. Used to /// recognize the persona's OWN authored chat engrams (`Chat` origin whose diff --git a/core/continuum-mind/src/persona/rag_inspect.rs b/core/continuum-mind/src/persona/rag_inspect.rs index b8c6b90410..e27ecd2b5c 100644 --- a/core/continuum-mind/src/persona/rag_inspect.rs +++ b/core/continuum-mind/src/persona/rag_inspect.rs @@ -549,6 +549,7 @@ async fn run_inference_probe( repeat_last_n: None, stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, // The substrate's cognition contract: JSON-grammar-constrained // output. LlamaCpp wires this to GBNF grammar so the sampler diff --git a/core/continuum-mind/src/persona/response.rs b/core/continuum-mind/src/persona/response.rs index 45e49039b7..9d49eb900f 100644 --- a/core/continuum-mind/src/persona/response.rs +++ b/core/continuum-mind/src/persona/response.rs @@ -691,6 +691,7 @@ async fn run_render( repeat_last_n: Some(sampling.repeat_last_n), stop_sequences: None, tools: None, + tail_tools: None, tool_choice: None, response_format: None, active_adapters: None, diff --git a/core/tool-working-set/src/logistic.rs b/core/tool-working-set/src/logistic.rs index 762573e9bf..13fcbe1dde 100644 --- a/core/tool-working-set/src/logistic.rs +++ b/core/tool-working-set/src/logistic.rs @@ -8,7 +8,9 @@ use crate::features::FEATURES; /// One training example: a tool's input row at a turnover, and whether she called it. pub type Example = ([f32; FEATURES], bool); -#[derive(Debug, Clone, PartialEq)] +/// Serializable so a mind's learned weights and running scale survive a restart (the core +/// keeps them as an ORM entity). +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Logistic { weights: [f64; FEATURES], count: f64, diff --git a/protocol/typescript/ai/TextGenerationRequest.ts b/protocol/typescript/ai/TextGenerationRequest.ts index 018cc5dddb..fceaac3ee8 100644 --- a/protocol/typescript/ai/TextGenerationRequest.ts +++ b/protocol/typescript/ai/TextGenerationRequest.ts @@ -24,7 +24,14 @@ frequencyPenalty?: number, * by the substrate sampling defaults to catch loops whose span * exceeds 64 tokens (#181). Ignored by cloud OpenAI-compat providers. */ -repeatLastN?: number, stopSequences?: Array, tools?: Array, toolChoice?: ToolChoice, +repeatLastN?: number, stopSequences?: Array, tools?: Array, +/** + * Verbs she loaded into the TAIL this epoch: callable natively (the engine's parser and + * grammar accept them) but never rendered in the head, so the cached prefix is unchanged + * (goal 10, card ecd5dff3). Their schemas ride the conversation, after the cache point. + * Sent only to a llama.cpp-family server; one that predates the field ignores it. + */ +tailTools?: Array, toolChoice?: ToolChoice, /** * Force the model to output a specific format (e.g. JSON object). * OpenAI-compatible: serializes as `{"type": "json_object"}` etc. The diff --git a/protocol/typescript/help/CommandsHelpParams.ts b/protocol/typescript/help/CommandsHelpParams.ts index aea1188995..7de1b45dbf 100644 --- a/protocol/typescript/help/CommandsHelpParams.ts +++ b/protocol/typescript/help/CommandsHelpParams.ts @@ -6,4 +6,8 @@ export type CommandsHelpParams = { * command you can call (name + one-line description) — your starting point when * you don't yet know which tool to use. */ -name?: string, }; +name?: string, +/** + * What you want to do, when you do not know the command's name: the best matches, ranked. + */ +query?: string, };