Skip to main content

algocline_app/service/
engine_api_impl.rs

1use std::collections::HashMap;
2
3use algocline_core::{EngineApi, QueryResponse};
4use async_trait::async_trait;
5
6use crate::pool::{registry::with_registry_lock, PoolError, PoolRegistry};
7
8use super::list_opts::ListOpts;
9use super::AppService;
10
11/// Delegates each [`EngineApi`] method to the corresponding `AppService`
12/// inherent method via fully-qualified syntax (`AppService::method(self, …)`).
13///
14/// This avoids ambiguity between the trait method and the inherent method
15/// of the same name, preventing accidental infinite recursion if the
16/// inherent method is ever removed or renamed.
17#[async_trait]
18impl EngineApi for AppService {
19    // ─── Core execution ──────────────────────────────────────
20
21    async fn run(
22        &self,
23        code: Option<String>,
24        code_file: Option<String>,
25        ctx: Option<serde_json::Value>,
26        project_root: Option<String>,
27        host_mode: Option<bool>,
28    ) -> Result<String, String> {
29        AppService::run(self, code, code_file, ctx, project_root, host_mode).await
30    }
31
32    async fn advice(
33        &self,
34        strategy: &str,
35        task: Option<String>,
36        opts: Option<serde_json::Value>,
37        project_root: Option<String>,
38    ) -> Result<String, String> {
39        AppService::advice(self, strategy, task, opts, project_root).await
40    }
41
42    async fn continue_single(
43        &self,
44        session_id: &str,
45        response: String,
46        query_id: Option<&str>,
47        usage: Option<algocline_core::TokenUsage>,
48    ) -> Result<String, String> {
49        AppService::continue_single(self, session_id, response, query_id, usage).await
50    }
51
52    async fn continue_batch(
53        &self,
54        session_id: &str,
55        responses: Vec<QueryResponse>,
56    ) -> Result<String, String> {
57        AppService::continue_batch(self, session_id, responses).await
58    }
59
60    // ─── Session status ──────────────────────────────────────
61
62    async fn status(
63        &self,
64        session_id: Option<&str>,
65        pending_filter: Option<serde_json::Value>,
66        include_history: bool,
67    ) -> Result<String, String> {
68        AppService::status(self, session_id, pending_filter, include_history).await
69    }
70
71    // ─── Evaluation ──────────────────────────────────────────
72
73    async fn eval(
74        &self,
75        scenario: Option<String>,
76        scenario_file: Option<String>,
77        scenario_name: Option<String>,
78        strategy: &str,
79        strategy_opts: Option<serde_json::Value>,
80        auto_card: bool,
81    ) -> Result<String, String> {
82        AppService::eval(
83            self,
84            scenario,
85            scenario_file,
86            scenario_name,
87            strategy,
88            strategy_opts,
89            auto_card,
90        )
91        .await
92    }
93
94    async fn eval_history(&self, strategy: Option<&str>, limit: usize) -> Result<String, String> {
95        AppService::eval_history(self, strategy, limit)
96    }
97
98    async fn eval_detail(&self, eval_id: &str) -> Result<String, String> {
99        AppService::eval_detail(self, eval_id)
100    }
101
102    async fn eval_compare(&self, eval_id_a: &str, eval_id_b: &str) -> Result<String, String> {
103        AppService::eval_compare(self, eval_id_a, eval_id_b).await
104    }
105
106    // ─── Scenarios ───────────────────────────────────────────
107
108    async fn scenario_list(&self) -> Result<String, String> {
109        AppService::scenario_list(self)
110    }
111
112    async fn scenario_show(&self, name: &str) -> Result<String, String> {
113        AppService::scenario_show(self, name)
114    }
115
116    async fn scenario_install(&self, url: String) -> Result<String, String> {
117        AppService::scenario_install(self, url).await
118    }
119
120    // ─── Packages ────────────────────────────────────────────
121
122    async fn pkg_link(
123        &self,
124        path: String,
125        name: Option<String>,
126        force: Option<bool>,
127        scope: Option<String>,
128        project_root: Option<String>,
129    ) -> Result<String, String> {
130        AppService::pkg_link(self, path, name, force, scope, project_root).await
131    }
132
133    async fn pkg_unlink(&self, name: String) -> Result<String, String> {
134        AppService::pkg_unlink(self, name).await
135    }
136
137    #[allow(clippy::too_many_arguments)]
138    async fn pkg_list(
139        &self,
140        project_root: Option<String>,
141        limit: Option<i32>,
142        sort: Option<String>,
143        filter: Option<serde_json::Value>,
144        fields: Option<Vec<String>>,
145        verbose: Option<String>,
146    ) -> Result<String, String> {
147        // `filter` is a free-form JSON Value at the MCP boundary (so the
148        // trait stays core-crate-pure). If the caller sends something
149        // that is not a JSON object we treat it as "no filter" and log
150        // the drop so operators can diagnose unexpected filter shapes
151        // in production.
152        let filter_map = match filter {
153            None => None,
154            Some(v) => match serde_json::from_value::<HashMap<String, serde_json::Value>>(v) {
155                Ok(map) => Some(map),
156                Err(e) => {
157                    tracing::warn!(error = %e, "pkg_list: filter value is not a JSON object — treating as no filter");
158                    None
159                }
160            },
161        };
162
163        // Negative limit values from MCP callers are clamped to 0 rather
164        // than wrapping to a huge usize (unchecked-user-bound-input pattern).
165        // Downstream semantics: `Some(0)` means "no limit" (return all) —
166        // the truncate path in `AppService::pkg_list` short-circuits on 0.
167        let opts = ListOpts {
168            limit: limit.map(|n| n.max(0) as usize),
169            sort,
170            filter: filter_map,
171            fields,
172            verbose,
173        };
174
175        AppService::pkg_list(self, project_root, opts)
176            .await
177            .map_err(|e| e.to_string())
178    }
179
180    async fn pkg_install(
181        &self,
182        url: String,
183        name: Option<String>,
184        force: Option<bool>,
185    ) -> Result<String, String> {
186        AppService::pkg_install(self, url, name, force).await
187    }
188
189    async fn pkg_remove(
190        &self,
191        name: &str,
192        project_root: Option<String>,
193        version: Option<String>,
194        scope: Option<String>,
195    ) -> Result<String, String> {
196        AppService::pkg_remove(self, name, project_root, version, scope).await
197    }
198
199    async fn pkg_repair(
200        &self,
201        name: Option<String>,
202        project_root: Option<String>,
203    ) -> Result<String, String> {
204        AppService::pkg_repair(self, name, project_root).await
205    }
206
207    async fn pkg_doctor(
208        &self,
209        name: Option<String>,
210        project_root: Option<String>,
211    ) -> Result<String, String> {
212        AppService::pkg_doctor(self, name, project_root).await
213    }
214
215    /// Run mlua-lspec tests for a package, a single file, or inline code.
216    ///
217    /// Forwards to [`AppService::pkg_test`]. See trait doc for full contract.
218    #[allow(clippy::too_many_arguments)]
219    async fn pkg_test(
220        &self,
221        pkg: Option<String>,
222        code_file: Option<String>,
223        code: Option<String>,
224        spec_dir: Option<String>,
225        filter: Option<String>,
226        search_paths: Option<Vec<String>>,
227        project_root: Option<String>,
228        auto_search_paths: Option<bool>,
229    ) -> Result<String, String> {
230        AppService::pkg_test(
231            self,
232            pkg,
233            code_file,
234            code,
235            spec_dir,
236            filter,
237            search_paths,
238            project_root,
239            auto_search_paths,
240        )
241        .await
242    }
243
244    // ─── Logging ─────────────────────────────────────────────
245
246    async fn add_note(
247        &self,
248        session_id: &str,
249        content: &str,
250        title: Option<&str>,
251    ) -> Result<String, String> {
252        AppService::add_note(self, session_id, content, title).await
253    }
254
255    async fn log_view(
256        &self,
257        session_id: Option<&str>,
258        limit: Option<usize>,
259        max_chars: Option<usize>,
260    ) -> Result<String, String> {
261        AppService::log_view(self, session_id, limit, max_chars).await
262    }
263
264    async fn stats(
265        &self,
266        strategy_filter: Option<&str>,
267        days: Option<u64>,
268    ) -> Result<String, String> {
269        AppService::stats(self, strategy_filter, days)
270    }
271
272    // ─── Project lifecycle ────────────────────────────────────
273
274    async fn init(&self, project_root: Option<String>) -> Result<String, String> {
275        AppService::init(self, project_root).await
276    }
277
278    async fn update(&self, project_root: Option<String>) -> Result<String, String> {
279        AppService::update(self, project_root).await
280    }
281
282    async fn migrate(&self, project_root: Option<String>) -> Result<String, String> {
283        AppService::migrate(self, project_root).await
284    }
285
286    // ─── Session activation (issue #1776627475) ──────────────
287
288    async fn session_new(
289        &self,
290        project_root: Option<String>,
291        mode: Option<String>,
292    ) -> Result<String, String> {
293        let session = self.activate_session(project_root.as_deref(), mode.as_deref())?;
294        let result = serde_json::json!({
295            "session_id": session.session_id,
296            "project_root": session
297                .project_root
298                .as_ref()
299                .map(|p| p.to_string_lossy().to_string()),
300            "mode": session.mode.as_str(),
301        });
302        serde_json::to_string_pretty(&result).map_err(|e| e.to_string())
303    }
304
305    // ─── Cards ───────────────────────────────────────────────
306
307    async fn card_list(&self, pkg: Option<String>) -> Result<String, String> {
308        AppService::card_list(self, pkg.as_deref())
309    }
310
311    async fn card_get(&self, card_id: &str) -> Result<String, String> {
312        AppService::card_get(self, card_id)
313    }
314
315    async fn card_find(
316        &self,
317        pkg: Option<String>,
318        where_: Option<serde_json::Value>,
319        order_by: Option<serde_json::Value>,
320        limit: Option<usize>,
321        offset: Option<usize>,
322    ) -> Result<String, String> {
323        AppService::card_find(self, pkg, where_, order_by, limit, offset)
324    }
325
326    async fn card_alias_list(&self, pkg: Option<String>) -> Result<String, String> {
327        AppService::card_alias_list(self, pkg.as_deref())
328    }
329
330    async fn card_get_by_alias(&self, name: &str) -> Result<String, String> {
331        AppService::card_get_by_alias(self, name)
332    }
333
334    async fn card_alias_set(
335        &self,
336        name: &str,
337        card_id: &str,
338        pkg: Option<String>,
339        note: Option<String>,
340    ) -> Result<String, String> {
341        AppService::card_alias_set(self, name, card_id, pkg.as_deref(), note.as_deref())
342    }
343
344    async fn card_append(
345        &self,
346        card_id: &str,
347        fields: serde_json::Value,
348    ) -> Result<String, String> {
349        AppService::card_append(self, card_id, fields)
350    }
351
352    async fn card_install(&self, url: String) -> Result<String, String> {
353        AppService::card_install(self, url).await
354    }
355
356    async fn card_samples(
357        &self,
358        card_id: &str,
359        offset: Option<usize>,
360        limit: Option<usize>,
361        where_: Option<serde_json::Value>,
362    ) -> Result<String, String> {
363        AppService::card_samples(self, card_id, offset.unwrap_or(0), limit, where_)
364    }
365
366    async fn card_lineage(
367        &self,
368        card_id: &str,
369        direction: Option<String>,
370        depth: Option<usize>,
371        include_stats: Option<bool>,
372        relation_filter: Option<Vec<String>>,
373    ) -> Result<String, String> {
374        AppService::card_lineage(
375            self,
376            card_id,
377            direction.as_deref(),
378            depth,
379            include_stats,
380            relation_filter,
381        )
382    }
383
384    async fn card_sink_backfill(&self, sink: String, dry_run: bool) -> Result<String, String> {
385        AppService::card_sink_backfill(self, super::card::SinkBackfillParams { sink, dry_run })
386    }
387
388    async fn card_analyze(&self, card_id: &str, pkg: Option<String>) -> Result<String, String> {
389        AppService::card_analyze(self, card_id, pkg).await
390    }
391
392    // ─── Hub ─────────────────────────────────────────────────
393
394    async fn hub_reindex(
395        &self,
396        output_path: Option<String>,
397        source_dir: Option<String>,
398    ) -> Result<String, String> {
399        let svc = self.clone();
400        tokio::task::spawn_blocking(move || {
401            AppService::hub_reindex(&svc, output_path.as_deref(), source_dir.as_deref())
402        })
403        .await
404        .map_err(|e| format!("hub_reindex task panicked: {e}"))?
405    }
406
407    async fn hub_gendoc(
408        &self,
409        source_dir: String,
410        out_dir: Option<String>,
411        projections: Option<Vec<String>>,
412        config_path: Option<String>,
413        lint_strict: Option<bool>,
414    ) -> Result<String, String> {
415        let svc = self.clone();
416        tokio::task::spawn_blocking(move || {
417            crate::AppService::hub_gendoc(
418                &svc,
419                &source_dir,
420                out_dir.as_deref(),
421                projections.as_deref(),
422                config_path.as_deref(),
423                lint_strict,
424            )
425        })
426        .await
427        .map_err(|e| format!("hub_gendoc task panicked: {e}"))?
428    }
429
430    async fn hub_dist(
431        &self,
432        source_dir: String,
433        output_path: Option<String>,
434        out_dir: Option<String>,
435        preset: Option<String>,
436        project_root: Option<String>,
437        projections: Option<Vec<String>>,
438        config_path: Option<String>,
439        lint_strict: Option<bool>,
440    ) -> Result<String, String> {
441        let svc = self.clone();
442        tokio::task::spawn_blocking(move || {
443            AppService::hub_dist(
444                &svc,
445                &source_dir,
446                output_path.as_deref(),
447                out_dir.as_deref(),
448                preset.as_deref(),
449                project_root.as_deref(),
450                projections.as_deref(),
451                config_path.as_deref(),
452                lint_strict,
453            )
454        })
455        .await
456        .map_err(|e| format!("hub_dist task panicked: {e}"))?
457    }
458
459    async fn hub_info(&self, pkg: String) -> Result<String, String> {
460        let svc = self.clone();
461        tokio::task::spawn_blocking(move || AppService::hub_info(&svc, &pkg))
462            .await
463            .map_err(|e| format!("hub_info task panicked: {e}"))?
464    }
465
466    #[allow(clippy::too_many_arguments)]
467    async fn hub_search(
468        &self,
469        query: Option<String>,
470        category: Option<String>,
471        installed_only: Option<bool>,
472        limit: Option<i32>,
473        sort: Option<String>,
474        filter: Option<serde_json::Value>,
475        fields: Option<Vec<String>>,
476        verbose: Option<String>,
477        local_indices: Option<Vec<String>>,
478    ) -> Result<String, String> {
479        let svc = self.clone();
480
481        // `filter` is a free-form JSON Value at the MCP boundary (so the
482        // trait stays core-crate-pure). If the caller sends something
483        // that is not a JSON object we treat it as "no filter" — the
484        // explicit category/installed_only params still cover the common
485        // cases. The MCP `JsonSchema` layer will have already flagged
486        // hard type errors. We log the drop so operators can diagnose
487        // unexpected filter shapes in production.
488        let filter_map = match filter {
489            None => None,
490            Some(v) => match serde_json::from_value::<HashMap<String, serde_json::Value>>(v) {
491                Ok(map) => Some(map),
492                Err(e) => {
493                    tracing::warn!(error = %e, "hub_search: filter value is not a JSON object — treating as no filter");
494                    None
495                }
496            },
497        };
498
499        // Negative limit values from MCP callers are clamped to 0 rather
500        // than wrapping to a huge usize (unchecked-user-bound-input pattern).
501        // Downstream semantics: `Some(0)` means "no limit" (return all) —
502        // the truncate path in `AppService::hub_search` short-circuits on 0.
503        let opts = ListOpts {
504            limit: limit.map(|n| n.max(0) as usize),
505            sort,
506            filter: filter_map,
507            fields,
508            verbose,
509        };
510
511        tokio::task::spawn_blocking(move || {
512            AppService::hub_search(
513                &svc,
514                query.as_deref(),
515                category.as_deref(),
516                installed_only,
517                opts,
518                local_indices,
519            )
520        })
521        .await
522        .map_err(|e| format!("hub_search task panicked: {e}"))?
523    }
524
525    // ─── Package read ─────────────────────────────────────────
526
527    async fn pkg_read_init_lua(&self, name: &str) -> Result<String, String> {
528        AppService::pkg_read_init_lua(self, name, None)
529    }
530
531    async fn pkg_get_narrative_md(&self, name: &str) -> Result<Option<String>, String> {
532        AppService::pkg_get_narrative_md(self, name).await
533    }
534
535    async fn pkg_meta(&self, name: &str) -> Result<String, String> {
536        let filter = serde_json::json!({ "name": name });
537        let json_str = EngineApi::pkg_list(
538            self,
539            None,
540            None,
541            None,
542            Some(filter),
543            None,
544            Some("full".to_string()),
545        )
546        .await?;
547        let val: serde_json::Value = serde_json::from_str(&json_str)
548            .map_err(|e| format!("pkg_meta: failed to parse pkg_list response: {e}"))?;
549        let pkgs = val
550            .get("packages")
551            .and_then(|p| p.as_array())
552            .ok_or_else(|| "pkg_meta: pkg_list response missing 'packages' field".to_string())?;
553        if pkgs.is_empty() {
554            return Err(format!("pkg not found: {name}"));
555        }
556        serde_json::to_string(&pkgs[0]).map_err(|e| format!("pkg_meta: serialize entry: {e}"))
557    }
558
559    // ─── Package scaffold ─────────────────────────────────────
560
561    async fn pkg_scaffold(
562        &self,
563        name: String,
564        target_dir: Option<String>,
565        category: Option<String>,
566        description: Option<String>,
567    ) -> Result<String, String> {
568        let svc = self.clone();
569        tokio::task::spawn_blocking(move || {
570            AppService::pkg_scaffold(
571                &svc,
572                &name,
573                target_dir.as_deref(),
574                category.as_deref(),
575                description.as_deref(),
576            )
577        })
578        .await
579        .map_err(|e| format!("pkg_scaffold task panicked: {e}"))?
580    }
581
582    // ─── Hub resources ───────────────────────────────────────
583
584    /// Aggregate hub index across all registered cache sources.
585    ///
586    /// Delegates to `AppService::aggregate_index`, then serializes the
587    /// result to a JSON string. Individual source failures and registry-load
588    /// failures are embedded in the response JSON under a `"warnings"` field
589    /// so the MCP caller can observe partial failures without losing the
590    /// aggregate result.
591    async fn hub_index_aggregate(&self) -> Result<String, String> {
592        let svc = self.clone();
593        let (index, warnings) = tokio::task::spawn_blocking(move || {
594            AppService::aggregate_index(&svc).map_err(|e| e.to_string())
595        })
596        .await
597        .map_err(|e| format!("hub_index_aggregate task panicked: {e}"))??;
598
599        let mut json = serde_json::to_value(&index)
600            .map_err(|e| format!("hub_index_aggregate: serialize index: {e}"))?;
601        if !warnings.is_empty() {
602            if let Some(obj) = json.as_object_mut() {
603                obj.insert("warnings".to_string(), serde_json::json!(warnings));
604            }
605        }
606        serde_json::to_string(&json)
607            .map_err(|e| format!("hub_index_aggregate: serialize final: {e}"))
608    }
609
610    // ─── Settings ────────────────────────────────────────────
611
612    async fn setting_resolve(&self, target: Option<String>) -> Result<String, String> {
613        let app_dir = self.log_config.app_dir();
614        let project_root = self.resolve_root(None);
615        tokio::task::spawn_blocking(move || {
616            crate::service::setting::resolve_setting(
617                &app_dir,
618                project_root.as_deref(),
619                target.as_deref(),
620            )
621            .map_err(|e| e.to_string())
622            .and_then(|r| {
623                serde_json::to_string(&r).map_err(|e| format!("setting_resolve: serialize: {e}"))
624            })
625        })
626        .await
627        .map_err(|e| format!("setting_resolve: task panicked: {e}"))?
628    }
629
630    // ─── Diagnostics ─────────────────────────────────────────
631
632    async fn info(&self) -> String {
633        AppService::info(self)
634    }
635
636    // ─── Pool management ─────────────────────────────────────
637
638    async fn pool_ensure(&self) -> Result<String, String> {
639        AppService::pool_ensure_impl(self).await
640    }
641
642    async fn pool_status(&self, sid: Option<String>) -> Result<String, String> {
643        AppService::pool_status_impl(self, sid).await
644    }
645
646    async fn pool_stop(&self, sid: Option<String>) -> Result<String, String> {
647        AppService::pool_stop_impl(self, sid).await
648    }
649}
650
651// ─── Pool inherent helpers ────────────────────────────────────────────────────
652
653impl AppService {
654    /// Scan registry.json, GC dead workers, and return live sessions.
655    ///
656    /// Idempotent: calling twice produces the same result when no workers change
657    /// state between calls.  Does NOT spawn new workers.
658    pub(crate) async fn pool_ensure_impl(&self) -> Result<String, String> {
659        let reg_path = self.pool_reg_path.clone();
660        let lock_path = self.pool_lock_path.clone();
661
662        let sessions =
663            tokio::task::spawn_blocking(move || -> Result<Vec<serde_json::Value>, PoolError> {
664                with_registry_lock(&lock_path, || {
665                    let mut reg = PoolRegistry::load_or_default(&reg_path)?;
666                    let survivors = reg.scan_and_gc()?;
667                    // Persist GC result back to disk.
668                    reg.save(&reg_path)?;
669                    let entries = survivors
670                        .iter()
671                        .map(|e| {
672                            serde_json::json!({
673                                "sid": e.sid,
674                                "pid": e.pid,
675                                "sock": e.sock.to_string_lossy(),
676                                "version": e.version,
677                            })
678                        })
679                        .collect::<Vec<_>>();
680                    Ok(entries)
681                })
682            })
683            .await
684            .map_err(|e| format!("pool_ensure: task panicked: {e}"))?
685            .map_err(|e| e.to_string())?;
686
687        let pool_version = env!("CARGO_PKG_VERSION");
688        serde_json::to_string(&serde_json::json!({
689            "sessions": sessions,
690            "pool_version": pool_version,
691        }))
692        .map_err(|e| format!("pool_ensure: serialize: {e}"))
693    }
694
695    /// Return pool worker status from registry.json.
696    ///
697    /// When `sid` is `Some`, restricts output to that single worker.
698    /// Uses kill -0 liveness check for each returned entry.
699    pub(crate) async fn pool_status_impl(&self, sid: Option<String>) -> Result<String, String> {
700        let reg_path = self.pool_reg_path.clone();
701        let lock_path = self.pool_lock_path.clone();
702
703        let sessions =
704            tokio::task::spawn_blocking(move || -> Result<Vec<serde_json::Value>, PoolError> {
705                with_registry_lock(&lock_path, || {
706                    let mut reg = PoolRegistry::load_or_default(&reg_path)?;
707                    // GC dead entries in-place so status reflects reality.
708                    let _ = reg.scan_and_gc()?;
709                    reg.save(&reg_path)?;
710
711                    let entries: Vec<serde_json::Value> = reg
712                        .sessions
713                        .iter()
714                        .filter(|e| sid.as_deref().map(|s| e.sid == s).unwrap_or(true))
715                        .map(|e| {
716                            serde_json::json!({
717                                "sid": e.sid,
718                                "pid": e.pid,
719                                "sock": e.sock.to_string_lossy(),
720                                "version": e.version,
721                                "created_at": e.created_at,
722                                // Status is "running" for all live entries (UDS ping not required in POC).
723                                "status": "running",
724                            })
725                        })
726                        .collect();
727                    Ok(entries)
728                })
729            })
730            .await
731            .map_err(|e| format!("pool_status: task panicked: {e}"))?
732            .map_err(|e| e.to_string())?;
733
734        let pool_version = env!("CARGO_PKG_VERSION");
735        serde_json::to_string(&serde_json::json!({
736            "sessions": sessions,
737            "pool_version": pool_version,
738        }))
739        .map_err(|e| format!("pool_status: serialize: {e}"))
740    }
741
742    /// Send SIGTERM to all workers or a single worker identified by `sid`.
743    ///
744    /// After SIGTERM, removes the entry from registry.json.
745    /// Returns `{"stopped": [...], "errors": [...]}`.
746    /// SIGTERM send failures are surfaced in the `errors` array (not dropped silently).
747    pub(crate) async fn pool_stop_impl(&self, sid: Option<String>) -> Result<String, String> {
748        let reg_path = self.pool_reg_path.clone();
749        let lock_path = self.pool_lock_path.clone();
750
751        let result = tokio::task::spawn_blocking(
752            move || -> Result<(Vec<String>, Vec<String>), PoolError> {
753                with_registry_lock(&lock_path, || {
754                    let mut reg = PoolRegistry::load_or_default(&reg_path)?;
755
756                    // Determine targets.
757                    let targets: Vec<_> = reg
758                        .sessions
759                        .iter()
760                        .filter(|e| sid.as_deref().map(|s| e.sid == s).unwrap_or(true))
761                        .cloned()
762                        .collect();
763
764                    let mut stopped: Vec<String> = Vec::new();
765                    let mut errors: Vec<String> = Vec::new();
766
767                    for entry in &targets {
768                        #[cfg(unix)]
769                        {
770                            // K-52: guard u32 → i32 (pid_t) overflow; also reject pid == 0
771                            // (POSIX kill(2): pid=0 signals every process in the calling process
772                            // group, pid<0 signals a process group — both are unsafe here).
773                            let pid_t = match i32::try_from(entry.pid) {
774                                Ok(p) if p > 0 => p,
775                                Ok(_) => {
776                                    errors.push(format!(
777                                        "sid={}: pid={} is not a valid POSIX target pid (must be > 0); skipping SIGTERM",
778                                        entry.sid, entry.pid
779                                    ));
780                                    reg.remove(&entry.sid);
781                                    continue;
782                                }
783                                Err(_) => {
784                                    errors.push(format!(
785                                        "sid={}: pid={} exceeds i32::MAX, cannot send SIGTERM (K-52)",
786                                        entry.sid, entry.pid
787                                    ));
788                                    // Remove the entry anyway (PID is invalid, worker is unreachable).
789                                    reg.remove(&entry.sid);
790                                    continue;
791                                }
792                            };
793
794                            // SAFETY: libc::kill(pid, SIGTERM) is a thin syscall wrapper.
795                            // pid_t > 0, verified by the match arm above.
796                            // pid fits in i32 (verified above).
797                            let ret = unsafe { libc::kill(pid_t, libc::SIGTERM) };
798                            if ret == 0 {
799                                stopped.push(entry.sid.clone());
800                            } else {
801                                let os_err = std::io::Error::last_os_error();
802                                if os_err.raw_os_error() == Some(libc::ESRCH) {
803                                    // Process already dead — treat as stopped (idempotent).
804                                    stopped.push(entry.sid.clone());
805                                } else {
806                                    errors.push(format!(
807                                        "sid={}: SIGTERM failed: {}",
808                                        entry.sid, os_err
809                                    ));
810                                }
811                            }
812                        }
813                        #[cfg(not(unix))]
814                        {
815                            // Non-Unix: cannot send SIGTERM; report as unsupported.
816                            errors.push(format!(
817                                "sid={}: SIGTERM not supported on this platform",
818                                entry.sid
819                            ));
820                        }
821                        // Remove from registry regardless of SIGTERM result
822                        // (dead or dying, we no longer track it).
823                        reg.remove(&entry.sid);
824                    }
825
826                    // Persist updated registry (entries removed).
827                    reg.save(&reg_path)?;
828
829                    Ok((stopped, errors))
830                })
831            },
832        )
833        .await
834        .map_err(|e| format!("pool_stop: task panicked: {e}"))?
835        .map_err(|e| e.to_string())?;
836
837        let (stopped, errors) = result;
838        serde_json::to_string(&serde_json::json!({
839            "stopped": stopped,
840            "errors": errors,
841        }))
842        .map_err(|e| format!("pool_stop: serialize: {e}"))
843    }
844}
845
846// ─── Tests ────────────────────────────────────────────────────────────────────
847
848#[cfg(test)]
849mod tests {
850    use super::super::test_support::make_app_service_at;
851
852    /// pool_stop_impl rejects pid=0 without delivering SIGTERM.
853    ///
854    /// A registry.json containing `"pid": 0` must be handled as an invalid
855    /// POSIX target: the error is surfaced in the `errors` array, the entry is
856    /// removed from the on-disk registry, and the test process itself survives
857    /// (proving no SIGTERM was sent to the process group).
858    #[tokio::test]
859    #[cfg(unix)]
860    async fn pool_stop_pid_zero_is_rejected() {
861        // Arrange: build an AppService rooted at a tempdir so no real $HOME is
862        // touched, then seed registry.json with a single pid=0 entry.
863        let tmp = tempfile::tempdir().expect("tempdir");
864        let root = tmp.path().to_path_buf();
865        let svc = make_app_service_at(root.clone()).await;
866
867        // The pool registry lives at {app_dir}/state/pool/registry.json.
868        // AppDir::state_dir() resolves to {root}/state.
869        let pool_reg_path = root.join("state").join("pool").join("registry.json");
870        std::fs::create_dir_all(pool_reg_path.parent().unwrap()).expect("create pool dir");
871
872        let seeded = serde_json::json!({
873            "sessions": [{
874                "sid": "zero-pid-session",
875                "pid": 0u32,
876                "sock": "/tmp/alc-pool/zero.sock",
877                "version": "0.30.0",
878                "created_at": "2026-01-01T00:00:00Z"
879            }]
880        });
881        std::fs::write(&pool_reg_path, seeded.to_string()).expect("seed registry.json");
882
883        // Act: stop all sessions.
884        let json_str = svc.pool_stop_impl(None).await.expect("pool_stop_impl");
885        let result: serde_json::Value =
886            serde_json::from_str(&json_str).expect("response is valid JSON");
887
888        // Assert (1): the error message contains "not a valid POSIX target pid".
889        let errors = result["errors"].as_array().expect("errors array");
890        assert!(
891            !errors.is_empty(),
892            "expected at least one error for pid=0 entry"
893        );
894        let err_msg = errors[0].as_str().unwrap_or("");
895        assert!(
896            err_msg.contains("not a valid POSIX target pid"),
897            "unexpected error message: {err_msg}"
898        );
899
900        // Assert (2): stopped array is empty (no process was stopped).
901        let stopped = result["stopped"].as_array().expect("stopped array");
902        assert!(
903            stopped.is_empty(),
904            "pid=0 entry must not appear in stopped list"
905        );
906
907        // Assert (3): the entry is removed from the on-disk registry.
908        let on_disk: serde_json::Value =
909            serde_json::from_str(&std::fs::read_to_string(&pool_reg_path).expect("read registry"))
910                .expect("parse registry");
911        let sessions = on_disk["sessions"].as_array().expect("sessions array");
912        assert!(
913            sessions.is_empty(),
914            "pid=0 entry must be removed from on-disk registry"
915        );
916
917        // Assert (4): test process is still alive — trivially confirmed by
918        // reaching this line without being killed by SIGTERM.
919    }
920}