Skip to main content

algocline_app/service/
mod.rs

1pub(crate) mod alc_toml;
2mod card;
3mod config;
4mod dist;
5mod engine_api_impl;
6mod eval;
7mod eval_store;
8mod gendoc;
9mod hub;
10pub mod hub_dist_preset;
11mod init;
12pub(crate) mod list_opts;
13pub(crate) mod lock;
14pub(crate) mod lockfile;
15mod logging;
16pub(crate) mod manifest;
17mod migrate;
18pub(crate) mod path;
19mod pkg;
20mod pkg_link;
21mod pkg_unlink;
22pub(crate) mod project;
23pub mod resolve;
24mod run;
25mod scenario;
26pub(crate) mod source;
27mod status;
28mod transcript;
29mod update;
30
31#[cfg(test)]
32mod test_support;
33#[cfg(test)]
34mod tests;
35
36use std::path::Path;
37use std::sync::Arc;
38
39use algocline_engine::{Executor, FileCardStore, JsonFileStore, SessionRegistry, VariantPkg};
40
41pub use algocline_core::{EngineApi, TokenUsage};
42pub use config::{AppConfig, LogDirSource};
43pub use resolve::{QueryResponse, SearchPath};
44
45// ─── Application Service ────────────────────────────────────────
46
47/// Tracks in-flight eval sessions: session_id → strategy name.
48///
49/// Kept between `alc_eval` invocation and eventual completion (which may
50/// arrive via `alc_continue` after LLM round-trips). Used by
51/// `run.rs::maybe_save_eval` to persist the result to `~/.algocline/evals/`.
52/// Card emission is handled by `alc.eval()` Lua-side — no Rust tracking needed.
53///
54/// `std::sync::Mutex` is used (not tokio) because all operations are
55/// single HashMap insert/remove/get completing in microseconds, and no
56/// `.await` is held across the lock. Poison is silently skipped.
57type EvalSessions = std::sync::Mutex<std::collections::HashMap<String, String>>;
58
59/// Tracks session_id → strategy name for all strategy-based sessions (advice, eval).
60///
61/// Same locking rationale as `EvalSessions`. Used by `alc_status` and
62/// transcript logging. Poison is silently skipped — strategy name is
63/// non-critical metadata for observability.
64type SessionStrategies = std::sync::Mutex<std::collections::HashMap<String, String>>;
65
66#[derive(Clone)]
67pub struct AppService {
68    executor: Arc<Executor>,
69    registry: Arc<SessionRegistry>,
70    log_config: AppConfig,
71    /// Package search paths in priority order (first = highest).
72    search_paths: Vec<resolve::SearchPath>,
73    /// Persistent KV store backing `alc.state.*`.
74    ///
75    /// Rooted at `log_config.app_dir().state_dir()` and resolved once at
76    /// construction; `Arc`-wrapped so per-session clones are cheap.
77    state_store: Arc<JsonFileStore>,
78    /// Card store backing `alc.card.*`.
79    ///
80    /// Rooted at `log_config.app_dir().cards_dir()`, same `Arc` pattern.
81    card_store: Arc<FileCardStore>,
82    /// session_id → strategy name for eval sessions (cleared on completion).
83    eval_sessions: Arc<EvalSessions>,
84    /// session_id → strategy name for log/stats tracking (cleared on session completion).
85    session_strategies: Arc<SessionStrategies>,
86}
87
88impl AppService {
89    pub fn new(
90        executor: Arc<Executor>,
91        log_config: AppConfig,
92        search_paths: Vec<resolve::SearchPath>,
93    ) -> Self {
94        let registry = Arc::new(SessionRegistry::new());
95        // TTL = 3 hours. Complex strategies may run 30–60 min; 3h covers
96        // legitimate paused sessions while eventually reclaiming abandoned ones.
97        registry.spawn_gc_task(std::time::Duration::from_secs(10800));
98        let app_dir = log_config.app_dir();
99        let state_store = Arc::new(JsonFileStore::new(app_dir.state_dir()));
100        let card_store = Arc::new(FileCardStore::new(app_dir.cards_dir()));
101        Self {
102            executor,
103            registry,
104            log_config,
105            search_paths,
106            state_store,
107            card_store,
108            eval_sessions: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
109            session_strategies: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
110        }
111    }
112
113    /// Returns the log directory, or an error if file logging is unavailable.
114    fn require_log_dir(&self) -> Result<&Path, String> {
115        self.log_config
116            .log_dir
117            .as_deref()
118            .ok_or_else(|| "File logging is not available (no writable log directory)".to_string())
119    }
120
121    /// Resolve extra lib paths for a request.
122    ///
123    /// Merges two layers in priority order (first = highest = prepended
124    /// by the Executor to `package.path`):
125    ///
126    /// 1. `alc.local.toml` path entries — worktree-scoped override
127    ///    (git-ignored, not persisted to alc.lock, loaded every call).
128    /// 2. `alc.lock` path entries — alc.toml-derived, git-managed.
129    ///
130    /// Returns an empty `Vec` if no project root is found. Partial
131    /// failures (e.g. malformed `alc.local.toml`) are logged at `warn`
132    /// and degraded to the empty layer without failing the whole call.
133    pub(crate) fn resolve_extra_lib_paths(
134        &self,
135        project_root: Option<&str>,
136    ) -> Vec<std::path::PathBuf> {
137        let Some(root) = project::resolve_project_root(project_root) else {
138            return vec![];
139        };
140
141        // Local override layer (highest priority) — merged every call,
142        // never persisted to alc.lock (decisions.md FsResolver priority).
143        let local_paths: Vec<std::path::PathBuf> = match alc_toml::load_alc_local_toml(&root) {
144            Ok(Some(local)) => alc_toml::resolve_local_path_entries(&root, &local),
145            Ok(None) => Vec::new(),
146            Err(e) => {
147                tracing::warn!("failed to load alc.local.toml at {}: {e}", root.display());
148                Vec::new()
149            }
150        };
151
152        // Existing alc.lock layer.
153        let lock_paths: Vec<std::path::PathBuf> = match lockfile::load_lockfile(&root) {
154            Ok(Some(lock)) => {
155                self.warn_toml_lock_mismatch(&root, &lock);
156                lockfile::resolve_path_entries(&root, &lock)
157            }
158            Ok(None) => Vec::new(),
159            Err(e) => {
160                tracing::warn!("failed to load alc.lock at {}: {e}", root.display());
161                Vec::new()
162            }
163        };
164
165        let mut merged = local_paths;
166        merged.extend(lock_paths);
167        merged
168    }
169
170    /// Resolve variant pkg overrides for a request.
171    ///
172    /// Reads `alc.local.toml` (worktree-scoped, gitignored) and emits one
173    /// [`VariantPkg`] per `[packages.{name}] path = "..."` entry, preserving
174    /// the explicit `(name, pkg_dir)` mapping. Returns an empty `Vec` if no
175    /// project root is found or `alc.local.toml` is missing/malformed
176    /// (failures are logged at `warn`).
177    pub(crate) fn resolve_variant_pkgs(&self, project_root: Option<&str>) -> Vec<VariantPkg> {
178        let Some(root) = project::resolve_project_root(project_root) else {
179            return vec![];
180        };
181
182        match alc_toml::load_alc_local_toml(&root) {
183            Ok(Some(local)) => alc_toml::resolve_local_variant_pkgs(&root, &local),
184            Ok(None) => Vec::new(),
185            Err(e) => {
186                tracing::warn!("failed to load alc.local.toml at {}: {e}", root.display());
187                Vec::new()
188            }
189        }
190    }
191
192    fn warn_toml_lock_mismatch(&self, root: &Path, lock: &lockfile::LockFile) {
193        let toml = match alc_toml::load_alc_toml(root) {
194            Ok(Some(t)) => t,
195            _ => return,
196        };
197
198        use std::collections::BTreeSet;
199        let toml_names: BTreeSet<&str> = toml.packages.keys().map(|s| s.as_str()).collect();
200        let lock_names: BTreeSet<&str> = lock.packages.iter().map(|p| p.name.as_str()).collect();
201
202        for name in toml_names.difference(&lock_names) {
203            eprintln!(
204                "warning: '{name}' is declared in alc.toml but missing from alc.lock. Run `alc_update` to sync."
205            );
206        }
207        for name in lock_names.difference(&toml_names) {
208            eprintln!("warning: '{name}' is in alc.lock but not declared in alc.toml.");
209        }
210    }
211}