Skip to main content

vtcode_core/subagents/
model.rs

1use anyhow::{Context, Result};
2use vtcode_config::SubagentSpec;
3use vtcode_config::core::{CustomProviderConfig, ProviderOverrideConfig};
4
5use std::collections::BTreeMap;
6use std::path::{Path, PathBuf};
7use std::sync::OnceLock;
8
9use crate::config::VTCodeConfig;
10use crate::config::constants::models;
11use crate::config::models::{ModelId, Provider};
12use crate::core::agent::types::AgentType;
13use crate::llm::auto_lightweight_model;
14use crate::llm::factory::{infer_provider, infer_provider_from_model};
15use crate::prompts::resource_cache::{ResourceCache, canonical_cache_path, fingerprint_files};
16use vtcode_commons::VtCodePaths;
17
18// ─── Model Resolution ───────────────────────────────────────────────────────
19
20/// Resolves the model for a subagent given an optional request override.
21///
22/// When `requested` is `None`, `"inherit"`, or empty, the parent model is inherited.
23/// Special aliases like `"small"`, `"haiku"`, `"sonnet"`, and `"opus"` are mapped
24/// to concrete model identifiers based on the active provider.
25pub fn resolve_subagent_model(
26    vt_cfg: &VTCodeConfig,
27    parent_model: &str,
28    parent_provider: &str,
29    requested: Option<&str>,
30    agent_name: &str,
31) -> Result<ModelId> {
32    let requested = requested.unwrap_or("inherit").trim();
33    if requested.eq_ignore_ascii_case("inherit") || requested.is_empty() {
34        return resolve_inherit_model(vt_cfg, parent_model, parent_provider, agent_name);
35    }
36    resolve_explicit_model(vt_cfg, parent_provider, parent_model, requested, agent_name)
37}
38
39fn resolve_inherit_model(
40    vt_cfg: &VTCodeConfig,
41    parent_model: &str,
42    parent_provider: &str,
43    agent_name: &str,
44) -> Result<ModelId> {
45    let sources = RuntimeModelSources::from_config(vt_cfg);
46    // Use the same identity rule as the CLI's ModelId::from_config so a parent
47    // and its inheriting subagent cannot disagree about the active route.
48    if let Ok(model) =
49        ModelId::from_config(parent_model, parent_provider, sources.provider_overrides, sources.custom_providers)
50    {
51        return Ok(model);
52    }
53    if parent_provider.eq_ignore_ascii_case("copilot") {
54        let fallback = ModelId::default_orchestrator_for_provider(Provider::Copilot);
55        tracing::warn!(
56            agent_name,
57            parent_model = parent_model.trim(),
58            parent_provider = parent_provider.trim(),
59            fallback_model = &*fallback.as_str(),
60            "Falling back to the default Copilot subagent model because the inherited parent model identifier is not supported internally"
61        );
62        return Ok(fallback);
63    }
64
65    finalize_subagent_model(&sources, parent_model, parent_provider, agent_name)
66}
67
68/// Narrow, read-only view of the config-defined runtime model sources that are
69/// not part of the built-in [`ModelId`] catalog.
70///
71/// Isolating these two fields (instead of passing the whole [`VTCodeConfig`])
72/// keeps the custom-model fallback policy independently testable and prevents
73/// the resolution logic from coupling to unrelated config surface.
74struct RuntimeModelSources<'a> {
75    provider_overrides: &'a BTreeMap<String, ProviderOverrideConfig>,
76    custom_providers: &'a [CustomProviderConfig],
77}
78
79impl<'a> RuntimeModelSources<'a> {
80    fn from_config(vt_cfg: &'a VTCodeConfig) -> Self {
81        Self {
82            provider_overrides: &vt_cfg.provider_overrides,
83            custom_providers: &vt_cfg.custom_providers,
84        }
85    }
86}
87
88/// Normalizes `raw_model` and resolves it into a [`ModelId`], attaching a
89/// consistent subagent context message on failure.
90///
91/// Shared by the inherit and explicit resolution paths so both apply the same
92/// alias normalization, custom-model fallback, and error wording.
93fn finalize_subagent_model(
94    sources: &RuntimeModelSources<'_>,
95    raw_model: &str,
96    provider_hint: &str,
97    agent_name: &str,
98) -> Result<ModelId> {
99    let normalized = normalize_subagent_model_alias(raw_model);
100    parse_model_or_custom(sources, normalized, provider_hint)
101        .with_context(|| format!("Failed to resolve model '{normalized}' for subagent {agent_name}"))
102}
103
104/// Parses `model` into a [`ModelId`], falling back to a runtime [`ModelId::Custom`]
105/// variant for user-defined providers and local providers.
106///
107/// Local providers (Ollama, LM Studio, llama.cpp), `[providers.<name>]`
108/// overrides, and `[[custom_providers]]` endpoints expose arbitrary model
109/// identifiers that are not part of the built-in catalog, so a strict
110/// `parse::<ModelId>()` would incorrectly reject valid runtime models. This
111/// helper honors those identifiers instead of failing subagent resolution.
112///
113/// Config-defined models are only honored when they belong to the active
114/// provider (`provider_hint`); this preserves the invalid-override fallback for
115/// unrelated providers and avoids mis-routing a model to the wrong endpoint.
116fn parse_model_or_custom(sources: &RuntimeModelSources<'_>, model: &str, provider_hint: &str) -> Result<ModelId> {
117    let trimmed = model.trim();
118    let provider_hint = provider_hint.trim();
119    let hinted_provider = provider_hint.parse::<Provider>().ok();
120    let declared = declared_custom_model(sources, trimmed, provider_hint, hinted_provider);
121    let catalog = trimmed.parse::<ModelId>().ok();
122
123    // An explicit declaration by the active provider wins when the catalog
124    // would attribute the slug to a different provider, matching both
125    // ModelId::from_config and the lightweight-routing rule.
126    if let Some(declared) = &declared
127        && catalog.as_ref().is_none_or(|parsed| Some(parsed.provider()) != hinted_provider)
128    {
129        return Ok(declared.clone());
130    }
131    if let Some(parsed) = catalog {
132        return Ok(parsed);
133    }
134    if let Some(declared) = declared {
135        return Ok(declared);
136    }
137
138    // Local providers expose arbitrary runtime model identifiers that cannot be
139    // validated against the built-in catalog; honor them as custom models.
140    if let Some(provider) = hinted_provider.filter(|provider| provider.is_local()) {
141        return Ok(ModelId::Custom(provider.to_string(), trimmed.to_string()));
142    }
143
144    Ok(trimmed.parse::<ModelId>()?)
145}
146
147/// Find a model explicitly declared by the active provider, using the same
148/// scoped matching rules as `ModelId::from_config`.
149fn declared_custom_model(
150    sources: &RuntimeModelSources<'_>,
151    trimmed: &str,
152    provider_hint: &str,
153    hinted_provider: Option<Provider>,
154) -> Option<ModelId> {
155    // Built-in provider overrides (`[providers.<name>]`), scoped to the active provider.
156    for (provider_key, override_cfg) in sources.provider_overrides {
157        let matches_hint = match hinted_provider {
158            Some(active) => provider_key.parse::<Provider>().ok() == Some(active),
159            None => provider_key.eq_ignore_ascii_case(provider_hint),
160        };
161        if matches_hint && override_cfg.models.iter().any(|m| m.trim() == trimmed) {
162            return Some(ModelId::Custom(provider_key.clone(), trimmed.to_string()));
163        }
164    }
165
166    // Custom OpenAI-compatible providers (`[[custom_providers]]`), matched by key.
167    for custom in sources.custom_providers {
168        if custom.name.eq_ignore_ascii_case(provider_hint) && custom.effective_models().iter().any(|m| m == trimmed) {
169            return Some(ModelId::Custom(custom.name.to_lowercase(), trimmed.to_string()));
170        }
171    }
172    None
173}
174
175fn resolve_explicit_model(
176    vt_cfg: &VTCodeConfig,
177    parent_provider: &str,
178    parent_model: &str,
179    requested: &str,
180    agent_name: &str,
181) -> Result<ModelId> {
182    let resolved = if requested.eq_ignore_ascii_case("small") {
183        resolve_lightweight_model(vt_cfg, parent_provider, parent_model, agent_name)
184    } else if matches!(requested.to_ascii_lowercase().as_str(), "haiku" | "sonnet" | "opus") {
185        alias_model_for_provider(parent_provider, requested, parent_model)
186    } else {
187        requested.to_string()
188    };
189
190    finalize_subagent_model(&RuntimeModelSources::from_config(vt_cfg), resolved.as_str(), parent_provider, agent_name)
191}
192
193fn resolve_lightweight_model(
194    vt_cfg: &VTCodeConfig,
195    parent_provider: &str,
196    parent_model: &str,
197    agent_name: &str,
198) -> String {
199    if vt_cfg.agent.small_model.model.trim().is_empty() {
200        return auto_lightweight_model(parent_provider, parent_model);
201    }
202
203    let configured = vt_cfg.agent.small_model.model.trim();
204    let active_provider = infer_provider(Some(parent_provider), parent_model);
205    let configured_provider = infer_provider_from_model(configured).or_else(|| infer_provider(None, configured));
206
207    // A custom endpoint may deliberately serve a model whose slug looks like a
208    // built-in provider's (e.g. a gateway exposing `gpt-5.6-luna`). Its explicit
209    // declaration is authoritative — the same rule `route_for_candidate` uses
210    // for every other lightweight route — so provider inference must not reject it.
211    let is_declared_custom_model = vt_cfg
212        .custom_provider(parent_provider)
213        .is_some_and(|provider| provider.effective_models().iter().any(|model| model == configured));
214
215    if configured_provider.is_some() && configured_provider != active_provider && !is_declared_custom_model {
216        tracing::warn!(
217            agent_name,
218            configured_model = configured,
219            active_provider = active_provider
220                .map(|provider| provider.to_string())
221                .unwrap_or_else(|| parent_provider.to_string()),
222            "Ignoring cross-provider lightweight subagent model; using same-provider automatic route"
223        );
224        auto_lightweight_model(parent_provider, parent_model)
225    } else {
226        configured.to_string()
227    }
228}
229
230/// Resolves the effective subagent model, preferring the explicit override, then the spec model,
231/// then falling back to the parent model.
232pub fn resolve_effective_subagent_model(
233    vt_cfg: &VTCodeConfig,
234    parent_model: &str,
235    parent_provider: &str,
236    model_override: Option<&str>,
237    spec_model: Option<&str>,
238    agent_name: &str,
239) -> Result<ModelId> {
240    if let Some(requested) = model_override {
241        match resolve_subagent_model(vt_cfg, parent_model, parent_provider, Some(requested), agent_name) {
242            Ok(model) => return Ok(model),
243            Err(err) => {
244                return handle_model_override_failure(
245                    vt_cfg,
246                    parent_model,
247                    parent_provider,
248                    requested,
249                    spec_model,
250                    agent_name,
251                    err,
252                );
253            }
254        }
255    }
256
257    match resolve_subagent_model(vt_cfg, parent_model, parent_provider, spec_model, agent_name) {
258        Ok(model) => Ok(model),
259        Err(err) if spec_model.map(str::trim).is_some_and(|v| v.eq_ignore_ascii_case("small")) => {
260            tracing::warn!(
261                agent_name,
262                error = %err,
263                "Failed to resolve lightweight subagent model from spec; falling back to parent model"
264            );
265            resolve_subagent_model(vt_cfg, parent_model, parent_provider, Some("inherit"), agent_name)
266        }
267        Err(err) => Err(err),
268    }
269}
270
271fn handle_model_override_failure(
272    vt_cfg: &VTCodeConfig,
273    parent_model: &str,
274    parent_provider: &str,
275    requested: &str,
276    spec_model: Option<&str>,
277    agent_name: &str,
278    err: anyhow::Error,
279) -> Result<ModelId> {
280    if requested.trim().eq_ignore_ascii_case("small") {
281        tracing::warn!(
282            agent_name,
283            requested_model = requested.trim(),
284            error = %err,
285            "Failed to bootstrap lightweight subagent model; falling back to parent model"
286        );
287        return resolve_subagent_model(vt_cfg, parent_model, parent_provider, Some("inherit"), agent_name);
288    }
289    let fallback = spec_model.map(str::trim).filter(|v| !v.is_empty()).unwrap_or("inherit");
290    tracing::warn!(
291        agent_name,
292        requested_model = requested.trim(),
293        fallback_model = fallback,
294        error = %err,
295        "Failed to resolve subagent model override; falling back"
296    );
297    let model = resolve_subagent_model(vt_cfg, parent_model, parent_provider, spec_model, agent_name)
298        .or_else(|_| resolve_subagent_model(vt_cfg, parent_model, parent_provider, Some("inherit"), agent_name))?;
299    Ok(model)
300}
301
302fn normalize_subagent_model_alias(model: &str) -> &str {
303    match model.trim() {
304        "claude-haiku-4.5" => models::anthropic::CLAUDE_SONNET_5,
305        "claude-sonnet-4.6" => models::anthropic::CLAUDE_SONNET_5,
306        "claude-opus-4.8" => models::anthropic::CLAUDE_OPUS_5,
307        other => other,
308    }
309}
310
311fn alias_model_for_provider(parent_provider: &str, alias: &str, parent_model: &str) -> String {
312    match infer_provider(Some(parent_provider), parent_model) {
313        Some(Provider::Anthropic) => match alias.to_ascii_lowercase().as_str() {
314            "haiku" => models::anthropic::CLAUDE_SONNET_5.to_string(),
315            "opus" => models::anthropic::CLAUDE_OPUS_5.to_string(),
316            _ => models::anthropic::CLAUDE_SONNET_5.to_string(),
317        },
318        Some(Provider::OpenAI) => match alias.to_ascii_lowercase().as_str() {
319            "haiku" => models::openai::GPT_5_6_LUNA.to_string(),
320            "opus" => models::openai::GPT_5_6_SOL.to_string(),
321            _ => models::openai::GPT_5_6_SOL.to_string(),
322        },
323        Some(Provider::Gemini) => match alias.to_ascii_lowercase().as_str() {
324            "haiku" => models::google::GEMINI_3_FLASH_PREVIEW.to_string(),
325            _ => models::google::GEMINI_3_7_FLASH.to_string(),
326        },
327        _ => parent_model.to_string(),
328    }
329}
330
331/// Maps a subagent spec name to its corresponding [`AgentType`] variant.
332pub fn agent_type_for_spec(spec: &SubagentSpec) -> AgentType {
333    match spec.name.as_str() {
334        "explorer" | "explore" => AgentType::Explore,
335        "plan" => AgentType::Plan,
336        "worker" | "general" | "general-purpose" | "default" => AgentType::General,
337        _ => AgentType::Custom(spec.name.clone()),
338    }
339}
340
341// ─── Memory Appendix ────────────────────────────────────────────────────────
342
343use super::constants::{SUBAGENT_MEMORY_BYTES_LIMIT, SUBAGENT_MEMORY_HIGHLIGHT_LIMIT, SUBAGENT_MEMORY_LINE_LIMIT};
344use crate::persistent_memory::extract_memory_highlights;
345use vtcode_config::SubagentMemoryScope;
346
347/// Loads the persistent memory appendix for a subagent, including key-point highlights.
348///
349/// Returns `None` when no memory scope is configured. Creates the memory directory
350/// if it does not exist, and returns a guidance prompt when the memory file is absent.
351pub fn load_memory_appendix(
352    workspace_root: &Path,
353    agent_name: &str,
354    scope: Option<SubagentMemoryScope>,
355) -> Result<Option<String>> {
356    let Some(scope) = scope else {
357        return Ok(None);
358    };
359
360    let memory_dir = agent_memory_dir(workspace_root, agent_name, scope)?;
361    VtCodePaths::ensure_user_dir(&memory_dir)
362        .with_context(|| format!("Failed to create subagent memory directory {}", memory_dir.display()))?;
363    let memory_file = memory_dir.join("MEMORY.md");
364    if !memory_file.exists() {
365        return Ok(Some(format!(
366            "Persistent memory file: {}. Create or update `MEMORY.md` with concise reusable notes when you discover stable repository conventions.",
367            memory_file.display()
368        )));
369    }
370
371    let content =
372        std::fs::read_to_string(&memory_file).with_context(|| format!("Failed to read {}", memory_file.display()))?;
373    Ok(Some(render_memory_appendix(&memory_file, &content)))
374}
375
376/// Async variant of [`load_memory_appendix`] for child-agent prompt assembly.
377///
378/// Directory creation, existence checks, and file reads use Tokio's filesystem
379/// boundary so launching a child agent does not block an executor worker.
380pub async fn load_memory_appendix_async(
381    workspace_root: &Path,
382    agent_name: &str,
383    scope: Option<SubagentMemoryScope>,
384) -> Result<Option<String>> {
385    let Some(scope) = scope else {
386        return Ok(None);
387    };
388
389    let memory_dir = agent_memory_dir(workspace_root, agent_name, scope)?;
390    VtCodePaths::ensure_user_dir(&memory_dir)
391        .with_context(|| format!("Failed to create subagent memory directory {}", memory_dir.display()))?;
392    let memory_file = memory_dir.join("MEMORY.md");
393    if !tokio::fs::try_exists(&memory_file).await.unwrap_or(false) {
394        return Ok(Some(format!(
395            "Persistent memory file: {}. Create or update `MEMORY.md` with concise reusable notes when you discover stable repository conventions.",
396            memory_file.display()
397        )));
398    }
399
400    let content = tokio::fs::read_to_string(&memory_file)
401        .await
402        .with_context(|| format!("Failed to read {}", memory_file.display()))?;
403    Ok(Some(render_memory_appendix(&memory_file, &content)))
404}
405
406fn render_memory_appendix(memory_file: &Path, content: &str) -> String {
407    let (excerpt, truncated) = memory_excerpt(content);
408    let highlights = extract_memory_highlights(&excerpt, SUBAGENT_MEMORY_HIGHLIGHT_LIMIT);
409    let mut appendix = String::new();
410    appendix.push_str(&format!(
411        "Persistent memory file: {}.\nRead and maintain `MEMORY.md` for durable learnings.",
412        memory_file.display()
413    ));
414
415    if !highlights.is_empty() {
416        appendix.push_str("\n\nKey points:\n");
417        for highlight in highlights {
418            appendix.push_str("- ");
419            appendix.push_str(&highlight);
420            appendix.push('\n');
421        }
422    }
423
424    appendix.push_str("\nOpen `MEMORY.md` when exact wording or more detail matters.");
425    if truncated {
426        appendix.push_str("\nMemory indexing stopped after the configured startup budget.");
427    }
428
429    appendix
430}
431
432/// Loads a read-only memory appendix for the primary agent from a subagent's memory scope.
433///
434/// Unlike [`load_memory_appendix`], this does not create directories or prompt for writes.
435pub fn load_primary_memory_appendix(
436    workspace_root: &Path,
437    agent_name: &str,
438    scope: Option<SubagentMemoryScope>,
439) -> Result<Option<String>> {
440    let Some(scope) = scope else {
441        return Ok(None);
442    };
443
444    load_primary_memory_appendix_cached(agent_memory_dir(workspace_root, agent_name, scope)?.join("MEMORY.md"))
445}
446
447/// Async variant of [`load_primary_memory_appendix`] for prompt assembly.
448/// Cache misses, metadata scans, and memory parsing run on Tokio's blocking
449/// pool so an interactive request never monopolizes a runtime worker with
450/// synchronous filesystem work.
451pub async fn load_primary_memory_appendix_async(
452    workspace_root: &Path,
453    agent_name: &str,
454    scope: Option<SubagentMemoryScope>,
455) -> Result<Option<String>> {
456    let Some(scope) = scope else {
457        return Ok(None);
458    };
459
460    let memory_file = agent_memory_dir(workspace_root, agent_name, scope)?.join("MEMORY.md");
461    tokio::task::spawn_blocking(move || load_primary_memory_appendix_cached(memory_file))
462        .await
463        .context("primary-agent memory cache task failed")?
464}
465
466fn load_primary_memory_appendix_cached(memory_file: PathBuf) -> Result<Option<String>> {
467    let cache_key = canonical_cache_path(&memory_file);
468    if let Some(cached) = primary_memory_cache().fast_get(&cache_key) {
469        return Ok((*cached).clone());
470    }
471
472    primary_memory_cache().with_load_gate(|| {
473        if let Some(cached) = primary_memory_cache().fast_get(&cache_key) {
474            return Ok((*cached).clone());
475        }
476
477        let fingerprint = fingerprint_files(&[memory_file.as_path()]);
478        if let Some(cached) = primary_memory_cache().get_if_unchanged(&cache_key, &fingerprint) {
479            return Ok((*cached).clone());
480        }
481
482        let appendix = load_primary_memory_appendix_uncached(&memory_file)?;
483        primary_memory_cache().insert(cache_key, appendix.clone(), fingerprint);
484        Ok(appendix)
485    })
486}
487
488fn load_primary_memory_appendix_uncached(memory_file: &Path) -> Result<Option<String>> {
489    let content = match std::fs::read_to_string(memory_file) {
490        Ok(content) => content,
491        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
492        Err(error) => {
493            return Err(error).with_context(|| format!("Failed to read {}", memory_file.display()));
494        }
495    };
496    let (excerpt, truncated) = memory_excerpt(&content);
497    let highlights = extract_memory_highlights(&excerpt, SUBAGENT_MEMORY_HIGHLIGHT_LIMIT);
498    let mut appendix = String::new();
499    appendix.push_str(&format!(
500        "Primary-agent memory file: {}.\nLoaded read-only for this request.",
501        memory_file.display()
502    ));
503
504    if !highlights.is_empty() {
505        appendix.push_str("\n\nKey points:\n");
506        for highlight in highlights {
507            appendix.push_str("- ");
508            appendix.push_str(&highlight);
509            appendix.push('\n');
510        }
511    }
512
513    if truncated {
514        appendix.push_str("\nMemory indexing stopped after the configured startup budget.");
515    }
516
517    Ok(Some(appendix))
518}
519
520static PRIMARY_MEMORY_APPENDIX_CACHE: OnceLock<ResourceCache<PathBuf, Option<String>>> = OnceLock::new();
521
522fn primary_memory_cache() -> &'static ResourceCache<PathBuf, Option<String>> {
523    PRIMARY_MEMORY_APPENDIX_CACHE.get_or_init(ResourceCache::default)
524}
525
526fn agent_memory_dir(workspace_root: &Path, agent_name: &str, scope: SubagentMemoryScope) -> Result<PathBuf> {
527    match scope {
528        SubagentMemoryScope::Project => Ok(workspace_root.join(".vtcode/agent-memory").join(agent_name)),
529        SubagentMemoryScope::Local => Ok(workspace_root.join(".vtcode/agent-memory-local").join(agent_name)),
530        SubagentMemoryScope::User => VtCodePaths::resolve()
531            .and_then(|paths| paths.state_path("agent-memory"))
532            .map(|path| path.join(agent_name))
533            .context("could not resolve VT Code state directory for user subagent memory"),
534    }
535}
536
537fn memory_excerpt(content: &str) -> (String, bool) {
538    let total_lines = content.lines().count();
539    let mut bytes = 0usize;
540    let mut excerpt_lines = Vec::new();
541    for line in content.lines().take(SUBAGENT_MEMORY_LINE_LIMIT) {
542        // Only lines already accepted contribute a separator in `join("\n")`;
543        // counting a trailing newline for every line overcharges by one byte
544        // and can drop a line that actually fits the budget.
545        let separator = usize::from(!excerpt_lines.is_empty());
546        let next_bytes = bytes.saturating_add(separator).saturating_add(line.len());
547        if next_bytes > SUBAGENT_MEMORY_BYTES_LIMIT {
548            break;
549        }
550        bytes = next_bytes;
551        excerpt_lines.push(line);
552    }
553
554    let truncated = excerpt_lines.len() < total_lines;
555    (excerpt_lines.join("\n"), truncated)
556}
557
558#[cfg(test)]
559mod memory_cache_tests {
560    use super::{load_primary_memory_appendix, load_primary_memory_appendix_async, primary_memory_cache};
561    use tempfile::TempDir;
562    use vtcode_config::SubagentMemoryScope;
563
564    fn memory_file(workspace: &TempDir) -> std::path::PathBuf {
565        workspace.path().join(".vtcode/agent-memory/reviewer/MEMORY.md")
566    }
567
568    #[test]
569    #[serial_test::serial]
570    fn primary_memory_cache_refreshes_edits_and_missing_files() {
571        primary_memory_cache().clear();
572        let workspace = TempDir::new().expect("workspace");
573
574        assert!(
575            load_primary_memory_appendix(workspace.path(), "reviewer", Some(SubagentMemoryScope::Project))
576                .expect("missing memory")
577                .is_none()
578        );
579
580        let path = memory_file(&workspace);
581        std::fs::create_dir_all(path.parent().expect("memory parent")).expect("memory directory");
582        std::fs::write(&path, "# Reviewer Memory\n\n- old guidance\n").expect("old memory");
583        primary_memory_cache().force_metadata_poll();
584        let first = load_primary_memory_appendix(workspace.path(), "reviewer", Some(SubagentMemoryScope::Project))
585            .expect("first memory")
586            .expect("memory appendix");
587        assert!(first.contains("old guidance"));
588
589        std::fs::write(&path, "# Reviewer Memory\n\n- new guidance\n").expect("new memory");
590        primary_memory_cache().force_metadata_poll();
591        let second = load_primary_memory_appendix(workspace.path(), "reviewer", Some(SubagentMemoryScope::Project))
592            .expect("updated memory")
593            .expect("updated appendix");
594        assert!(second.contains("new guidance"));
595    }
596
597    #[test]
598    #[serial_test::serial]
599    fn primary_memory_cache_honors_ttl_refresh() {
600        primary_memory_cache().clear();
601        let workspace = TempDir::new().expect("workspace");
602        let path = memory_file(&workspace);
603        std::fs::create_dir_all(path.parent().expect("memory parent")).expect("memory directory");
604        std::fs::write(&path, "# Reviewer Memory\n\n- old guidance\n").expect("old memory");
605
606        let first = load_primary_memory_appendix(workspace.path(), "reviewer", Some(SubagentMemoryScope::Project))
607            .expect("first memory")
608            .expect("memory appendix");
609        assert!(first.contains("old guidance"));
610        std::fs::write(&path, "# Reviewer Memory\n\n- new guidance\n").expect("new memory");
611        primary_memory_cache().force_expiration();
612        let second = load_primary_memory_appendix(workspace.path(), "reviewer", Some(SubagentMemoryScope::Project))
613            .expect("expired memory")
614            .expect("expired appendix");
615        assert!(second.contains("new guidance"));
616    }
617
618    #[tokio::test(flavor = "current_thread")]
619    #[serial_test::serial]
620    async fn concurrent_primary_memory_misses_return_identical_appendices() {
621        primary_memory_cache().clear();
622        let workspace = TempDir::new().expect("workspace");
623        let path = memory_file(&workspace);
624        std::fs::create_dir_all(path.parent().expect("memory parent")).expect("memory directory");
625        std::fs::write(&path, "# Reviewer Memory\n\n- shared guidance\n").expect("memory");
626
627        let (first, second) = tokio::join!(
628            load_primary_memory_appendix_async(workspace.path(), "reviewer", Some(SubagentMemoryScope::Project)),
629            load_primary_memory_appendix_async(workspace.path(), "reviewer", Some(SubagentMemoryScope::Project)),
630        );
631        assert_eq!(first.expect("first appendix"), second.expect("second appendix"));
632    }
633}
634
635#[cfg(test)]
636mod memory_excerpt_tests {
637    use super::{SUBAGENT_MEMORY_BYTES_LIMIT, SUBAGENT_MEMORY_LINE_LIMIT, memory_excerpt};
638
639    #[test]
640    fn byte_budget_counts_join_separators_not_trailing_newlines() {
641        let separators = SUBAGENT_MEMORY_LINE_LIMIT - 1;
642        let short_line_len = 127;
643        let last_line_len = SUBAGENT_MEMORY_BYTES_LIMIT - separators - short_line_len * separators;
644        let mut lines = vec!["x".repeat(short_line_len); separators];
645        lines.push("y".repeat(last_line_len));
646        let content = lines.join("\n");
647        assert_eq!(content.len(), SUBAGENT_MEMORY_BYTES_LIMIT);
648
649        let (excerpt, truncated) = memory_excerpt(&content);
650        assert_eq!(excerpt, content, "a byte-exact fit must not lose its last line");
651        assert!(!truncated);
652
653        let one_byte_over = format!("{content}z");
654        let (excerpt, truncated) = memory_excerpt(&one_byte_over);
655        assert_eq!(excerpt.lines().count(), separators);
656        assert!(truncated);
657    }
658}
659
660#[cfg(test)]
661mod lightweight_model_tests {
662    use super::{CustomProviderConfig, VTCodeConfig, resolve_lightweight_model};
663
664    fn config_with_gateway_declaring(declared_models: &[&str]) -> VTCodeConfig {
665        let mut vt_cfg = VTCodeConfig::default();
666        vt_cfg.agent.small_model.model = "gpt-5.6-luna".to_string();
667        vt_cfg.custom_providers.push(CustomProviderConfig {
668            name: "my-gateway".to_string(),
669            models: declared_models.iter().map(|model| (*model).to_string()).collect(),
670            ..Default::default()
671        });
672        vt_cfg
673    }
674
675    #[test]
676    fn declared_custom_provider_small_model_wins_over_builtin_provider_inference() {
677        let vt_cfg = config_with_gateway_declaring(&["gpt-5.6-luna"]);
678
679        assert_eq!(resolve_lightweight_model(&vt_cfg, "my-gateway", "auto", "reviewer"), "gpt-5.6-luna");
680    }
681
682    #[test]
683    fn undeclared_cross_provider_small_model_still_falls_back() {
684        let vt_cfg = config_with_gateway_declaring(&["other-model"]);
685
686        let resolved = resolve_lightweight_model(&vt_cfg, "my-gateway", "auto", "reviewer");
687        assert_ne!(resolved, "gpt-5.6-luna", "an undeclared model must keep the cross-provider guard");
688    }
689}
690
691#[cfg(test)]
692mod model_identity_tests {
693    use super::*;
694
695    fn gateway_config(declared: &[&str]) -> VTCodeConfig {
696        let mut vt_cfg = VTCodeConfig::default();
697        vt_cfg.custom_providers.push(CustomProviderConfig {
698            name: "my-gateway".to_string(),
699            models: declared.iter().map(|model| (*model).to_string()).collect(),
700            ..Default::default()
701        });
702        vt_cfg
703    }
704
705    #[test]
706    fn declared_catalog_slug_keeps_active_provider_identity() {
707        let vt_cfg = gateway_config(&["gpt-5.6-sol"]);
708        let sources = RuntimeModelSources::from_config(&vt_cfg);
709
710        let parsed = parse_model_or_custom(&sources, "gpt-5.6-sol", "my-gateway").unwrap();
711        assert_eq!(parsed, ModelId::Custom("my-gateway".to_string(), "gpt-5.6-sol".to_string()));
712
713        // Control: the same slug without an active declaration stays catalog.
714        let catalog = parse_model_or_custom(&sources, "gpt-5.6-sol", "unrelated-gateway").unwrap();
715        assert_eq!(catalog, ModelId::GPT56Sol);
716    }
717
718    #[test]
719    fn inherited_parent_model_agrees_with_cli_resolution() {
720        let vt_cfg = gateway_config(&["gpt-5.6-sol"]);
721        let inherited = resolve_inherit_model(&vt_cfg, "gpt-5.6-sol", "my-gateway", "reviewer").unwrap();
722        let cli =
723            ModelId::from_config("gpt-5.6-sol", "my-gateway", &vt_cfg.provider_overrides, &vt_cfg.custom_providers)
724                .unwrap();
725
726        assert_eq!(inherited, cli);
727        assert_eq!(inherited, ModelId::Custom("my-gateway".to_string(), "gpt-5.6-sol".to_string()));
728    }
729
730    #[test]
731    fn same_provider_declaration_keeps_catalog_identity() {
732        let mut overrides = BTreeMap::new();
733        overrides.insert(
734            "openai".to_string(),
735            ProviderOverrideConfig {
736                models: vec!["gpt-5.6-sol".to_string()],
737                base_url: None,
738                api_key_env: None,
739            },
740        );
741        let sources = RuntimeModelSources {
742            provider_overrides: &overrides,
743            custom_providers: &[],
744        };
745
746        // Declaring a catalog slug under its own provider must not degrade the
747        // picker's variant-only metadata (display name, generation sort, tiers).
748        let parsed = parse_model_or_custom(&sources, "gpt-5.6-sol", "openai").unwrap();
749        assert_eq!(parsed, ModelId::GPT56Sol);
750    }
751}