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#[async_trait]
18impl EngineApi for AppService {
19 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 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 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 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 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 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 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 async fn add_note(
218 &self,
219 session_id: &str,
220 content: &str,
221 title: Option<&str>,
222 ) -> Result<String, String> {
223 AppService::add_note(self, session_id, content, title).await
224 }
225
226 async fn log_view(
227 &self,
228 session_id: Option<&str>,
229 limit: Option<usize>,
230 max_chars: Option<usize>,
231 ) -> Result<String, String> {
232 AppService::log_view(self, session_id, limit, max_chars).await
233 }
234
235 async fn stats(
236 &self,
237 strategy_filter: Option<&str>,
238 days: Option<u64>,
239 ) -> Result<String, String> {
240 AppService::stats(self, strategy_filter, days)
241 }
242
243 async fn init(&self, project_root: Option<String>) -> Result<String, String> {
246 AppService::init(self, project_root).await
247 }
248
249 async fn update(&self, project_root: Option<String>) -> Result<String, String> {
250 AppService::update(self, project_root).await
251 }
252
253 async fn migrate(&self, project_root: Option<String>) -> Result<String, String> {
254 AppService::migrate(self, project_root).await
255 }
256
257 async fn session_new(
260 &self,
261 project_root: Option<String>,
262 mode: Option<String>,
263 ) -> Result<String, String> {
264 let session = self.activate_session(project_root.as_deref(), mode.as_deref())?;
265 let result = serde_json::json!({
266 "session_id": session.session_id,
267 "project_root": session
268 .project_root
269 .as_ref()
270 .map(|p| p.to_string_lossy().to_string()),
271 "mode": session.mode.as_str(),
272 });
273 serde_json::to_string_pretty(&result).map_err(|e| e.to_string())
274 }
275
276 async fn card_list(&self, pkg: Option<String>) -> Result<String, String> {
279 AppService::card_list(self, pkg.as_deref())
280 }
281
282 async fn card_get(&self, card_id: &str) -> Result<String, String> {
283 AppService::card_get(self, card_id)
284 }
285
286 async fn card_find(
287 &self,
288 pkg: Option<String>,
289 where_: Option<serde_json::Value>,
290 order_by: Option<serde_json::Value>,
291 limit: Option<usize>,
292 offset: Option<usize>,
293 ) -> Result<String, String> {
294 AppService::card_find(self, pkg, where_, order_by, limit, offset)
295 }
296
297 async fn card_alias_list(&self, pkg: Option<String>) -> Result<String, String> {
298 AppService::card_alias_list(self, pkg.as_deref())
299 }
300
301 async fn card_get_by_alias(&self, name: &str) -> Result<String, String> {
302 AppService::card_get_by_alias(self, name)
303 }
304
305 async fn card_alias_set(
306 &self,
307 name: &str,
308 card_id: &str,
309 pkg: Option<String>,
310 note: Option<String>,
311 ) -> Result<String, String> {
312 AppService::card_alias_set(self, name, card_id, pkg.as_deref(), note.as_deref())
313 }
314
315 async fn card_append(
316 &self,
317 card_id: &str,
318 fields: serde_json::Value,
319 ) -> Result<String, String> {
320 AppService::card_append(self, card_id, fields)
321 }
322
323 async fn card_install(&self, url: String) -> Result<String, String> {
324 AppService::card_install(self, url).await
325 }
326
327 async fn card_samples(
328 &self,
329 card_id: &str,
330 offset: Option<usize>,
331 limit: Option<usize>,
332 where_: Option<serde_json::Value>,
333 ) -> Result<String, String> {
334 AppService::card_samples(self, card_id, offset.unwrap_or(0), limit, where_)
335 }
336
337 async fn card_lineage(
338 &self,
339 card_id: &str,
340 direction: Option<String>,
341 depth: Option<usize>,
342 include_stats: Option<bool>,
343 relation_filter: Option<Vec<String>>,
344 ) -> Result<String, String> {
345 AppService::card_lineage(
346 self,
347 card_id,
348 direction.as_deref(),
349 depth,
350 include_stats,
351 relation_filter,
352 )
353 }
354
355 async fn card_sink_backfill(&self, sink: String, dry_run: bool) -> Result<String, String> {
356 AppService::card_sink_backfill(self, super::card::SinkBackfillParams { sink, dry_run })
357 }
358
359 async fn hub_reindex(
362 &self,
363 output_path: Option<String>,
364 source_dir: Option<String>,
365 ) -> Result<String, String> {
366 let svc = self.clone();
367 tokio::task::spawn_blocking(move || {
368 AppService::hub_reindex(&svc, output_path.as_deref(), source_dir.as_deref())
369 })
370 .await
371 .map_err(|e| format!("hub_reindex task panicked: {e}"))?
372 }
373
374 async fn hub_gendoc(
375 &self,
376 source_dir: String,
377 out_dir: Option<String>,
378 projections: Option<Vec<String>>,
379 config_path: Option<String>,
380 lint_strict: Option<bool>,
381 ) -> Result<String, String> {
382 let svc = self.clone();
383 tokio::task::spawn_blocking(move || {
384 crate::AppService::hub_gendoc(
385 &svc,
386 &source_dir,
387 out_dir.as_deref(),
388 projections.as_deref(),
389 config_path.as_deref(),
390 lint_strict,
391 )
392 })
393 .await
394 .map_err(|e| format!("hub_gendoc task panicked: {e}"))?
395 }
396
397 async fn hub_dist(
398 &self,
399 source_dir: String,
400 output_path: Option<String>,
401 out_dir: Option<String>,
402 preset: Option<String>,
403 project_root: Option<String>,
404 projections: Option<Vec<String>>,
405 config_path: Option<String>,
406 lint_strict: Option<bool>,
407 ) -> Result<String, String> {
408 let svc = self.clone();
409 tokio::task::spawn_blocking(move || {
410 AppService::hub_dist(
411 &svc,
412 &source_dir,
413 output_path.as_deref(),
414 out_dir.as_deref(),
415 preset.as_deref(),
416 project_root.as_deref(),
417 projections.as_deref(),
418 config_path.as_deref(),
419 lint_strict,
420 )
421 })
422 .await
423 .map_err(|e| format!("hub_dist task panicked: {e}"))?
424 }
425
426 async fn hub_info(&self, pkg: String) -> Result<String, String> {
427 let svc = self.clone();
428 tokio::task::spawn_blocking(move || AppService::hub_info(&svc, &pkg))
429 .await
430 .map_err(|e| format!("hub_info task panicked: {e}"))?
431 }
432
433 #[allow(clippy::too_many_arguments)]
434 async fn hub_search(
435 &self,
436 query: Option<String>,
437 category: Option<String>,
438 installed_only: Option<bool>,
439 limit: Option<i32>,
440 sort: Option<String>,
441 filter: Option<serde_json::Value>,
442 fields: Option<Vec<String>>,
443 verbose: Option<String>,
444 ) -> Result<String, String> {
445 let svc = self.clone();
446
447 let filter_map = match filter {
455 None => None,
456 Some(v) => match serde_json::from_value::<HashMap<String, serde_json::Value>>(v) {
457 Ok(map) => Some(map),
458 Err(e) => {
459 tracing::warn!(error = %e, "hub_search: filter value is not a JSON object — treating as no filter");
460 None
461 }
462 },
463 };
464
465 let opts = ListOpts {
470 limit: limit.map(|n| n.max(0) as usize),
471 sort,
472 filter: filter_map,
473 fields,
474 verbose,
475 };
476
477 tokio::task::spawn_blocking(move || {
478 AppService::hub_search(
479 &svc,
480 query.as_deref(),
481 category.as_deref(),
482 installed_only,
483 opts,
484 )
485 })
486 .await
487 .map_err(|e| format!("hub_search task panicked: {e}"))?
488 }
489
490 async fn pkg_read_init_lua(&self, name: &str) -> Result<String, String> {
493 AppService::pkg_read_init_lua(self, name, None)
494 }
495
496 async fn pkg_resolve_narrative_path(&self, name: &str) -> Result<Option<String>, String> {
497 AppService::pkg_resolve_narrative_path(self, name).await
498 }
499
500 async fn pkg_meta(&self, name: &str) -> Result<String, String> {
501 let filter = serde_json::json!({ "name": name });
502 let json_str = EngineApi::pkg_list(
503 self,
504 None,
505 None,
506 None,
507 Some(filter),
508 None,
509 Some("full".to_string()),
510 )
511 .await?;
512 let val: serde_json::Value = serde_json::from_str(&json_str)
513 .map_err(|e| format!("pkg_meta: failed to parse pkg_list response: {e}"))?;
514 let pkgs = val
515 .get("packages")
516 .and_then(|p| p.as_array())
517 .ok_or_else(|| "pkg_meta: pkg_list response missing 'packages' field".to_string())?;
518 if pkgs.is_empty() {
519 return Err(format!("pkg not found: {name}"));
520 }
521 serde_json::to_string(&pkgs[0]).map_err(|e| format!("pkg_meta: serialize entry: {e}"))
522 }
523
524 async fn pkg_scaffold(
527 &self,
528 name: String,
529 target_dir: Option<String>,
530 category: Option<String>,
531 description: Option<String>,
532 ) -> Result<String, String> {
533 let svc = self.clone();
534 tokio::task::spawn_blocking(move || {
535 AppService::pkg_scaffold(
536 &svc,
537 &name,
538 target_dir.as_deref(),
539 category.as_deref(),
540 description.as_deref(),
541 )
542 })
543 .await
544 .map_err(|e| format!("pkg_scaffold task panicked: {e}"))?
545 }
546
547 async fn hub_index_aggregate(&self) -> Result<String, String> {
557 let svc = self.clone();
558 let (index, warnings) = tokio::task::spawn_blocking(move || {
559 AppService::aggregate_index(&svc).map_err(|e| e.to_string())
560 })
561 .await
562 .map_err(|e| format!("hub_index_aggregate task panicked: {e}"))??;
563
564 let mut json = serde_json::to_value(&index)
565 .map_err(|e| format!("hub_index_aggregate: serialize index: {e}"))?;
566 if !warnings.is_empty() {
567 if let Some(obj) = json.as_object_mut() {
568 obj.insert("warnings".to_string(), serde_json::json!(warnings));
569 }
570 }
571 serde_json::to_string(&json)
572 .map_err(|e| format!("hub_index_aggregate: serialize final: {e}"))
573 }
574
575 async fn info(&self) -> String {
578 AppService::info(self)
579 }
580
581 async fn pool_ensure(&self) -> Result<String, String> {
584 AppService::pool_ensure_impl(self).await
585 }
586
587 async fn pool_status(&self, sid: Option<String>) -> Result<String, String> {
588 AppService::pool_status_impl(self, sid).await
589 }
590
591 async fn pool_stop(&self, sid: Option<String>) -> Result<String, String> {
592 AppService::pool_stop_impl(self, sid).await
593 }
594}
595
596impl AppService {
599 pub(crate) async fn pool_ensure_impl(&self) -> Result<String, String> {
604 let reg_path = self.pool_reg_path.clone();
605 let lock_path = self.pool_lock_path.clone();
606
607 let sessions =
608 tokio::task::spawn_blocking(move || -> Result<Vec<serde_json::Value>, PoolError> {
609 with_registry_lock(&lock_path, || {
610 let mut reg = PoolRegistry::load_or_default(®_path)?;
611 let survivors = reg.scan_and_gc()?;
612 reg.save(®_path)?;
614 let entries = survivors
615 .iter()
616 .map(|e| {
617 serde_json::json!({
618 "sid": e.sid,
619 "pid": e.pid,
620 "sock": e.sock.to_string_lossy(),
621 "version": e.version,
622 })
623 })
624 .collect::<Vec<_>>();
625 Ok(entries)
626 })
627 })
628 .await
629 .map_err(|e| format!("pool_ensure: task panicked: {e}"))?
630 .map_err(|e| e.to_string())?;
631
632 let pool_version = env!("CARGO_PKG_VERSION");
633 serde_json::to_string(&serde_json::json!({
634 "sessions": sessions,
635 "pool_version": pool_version,
636 }))
637 .map_err(|e| format!("pool_ensure: serialize: {e}"))
638 }
639
640 pub(crate) async fn pool_status_impl(&self, sid: Option<String>) -> Result<String, String> {
645 let reg_path = self.pool_reg_path.clone();
646 let lock_path = self.pool_lock_path.clone();
647
648 let sessions =
649 tokio::task::spawn_blocking(move || -> Result<Vec<serde_json::Value>, PoolError> {
650 with_registry_lock(&lock_path, || {
651 let mut reg = PoolRegistry::load_or_default(®_path)?;
652 let _ = reg.scan_and_gc()?;
654 reg.save(®_path)?;
655
656 let entries: Vec<serde_json::Value> = reg
657 .sessions
658 .iter()
659 .filter(|e| sid.as_deref().map(|s| e.sid == s).unwrap_or(true))
660 .map(|e| {
661 serde_json::json!({
662 "sid": e.sid,
663 "pid": e.pid,
664 "sock": e.sock.to_string_lossy(),
665 "version": e.version,
666 "created_at": e.created_at,
667 "status": "running",
669 })
670 })
671 .collect();
672 Ok(entries)
673 })
674 })
675 .await
676 .map_err(|e| format!("pool_status: task panicked: {e}"))?
677 .map_err(|e| e.to_string())?;
678
679 let pool_version = env!("CARGO_PKG_VERSION");
680 serde_json::to_string(&serde_json::json!({
681 "sessions": sessions,
682 "pool_version": pool_version,
683 }))
684 .map_err(|e| format!("pool_status: serialize: {e}"))
685 }
686
687 pub(crate) async fn pool_stop_impl(&self, sid: Option<String>) -> Result<String, String> {
693 let reg_path = self.pool_reg_path.clone();
694 let lock_path = self.pool_lock_path.clone();
695
696 let result = tokio::task::spawn_blocking(
697 move || -> Result<(Vec<String>, Vec<String>), PoolError> {
698 with_registry_lock(&lock_path, || {
699 let mut reg = PoolRegistry::load_or_default(®_path)?;
700
701 let targets: Vec<_> = reg
703 .sessions
704 .iter()
705 .filter(|e| sid.as_deref().map(|s| e.sid == s).unwrap_or(true))
706 .cloned()
707 .collect();
708
709 let mut stopped: Vec<String> = Vec::new();
710 let mut errors: Vec<String> = Vec::new();
711
712 for entry in &targets {
713 #[cfg(unix)]
714 {
715 let pid_t = match i32::try_from(entry.pid) {
719 Ok(p) if p > 0 => p,
720 Ok(_) => {
721 errors.push(format!(
722 "sid={}: pid={} is not a valid POSIX target pid (must be > 0); skipping SIGTERM",
723 entry.sid, entry.pid
724 ));
725 reg.remove(&entry.sid);
726 continue;
727 }
728 Err(_) => {
729 errors.push(format!(
730 "sid={}: pid={} exceeds i32::MAX, cannot send SIGTERM (K-52)",
731 entry.sid, entry.pid
732 ));
733 reg.remove(&entry.sid);
735 continue;
736 }
737 };
738
739 let ret = unsafe { libc::kill(pid_t, libc::SIGTERM) };
743 if ret == 0 {
744 stopped.push(entry.sid.clone());
745 } else {
746 let os_err = std::io::Error::last_os_error();
747 if os_err.raw_os_error() == Some(libc::ESRCH) {
748 stopped.push(entry.sid.clone());
750 } else {
751 errors.push(format!(
752 "sid={}: SIGTERM failed: {}",
753 entry.sid, os_err
754 ));
755 }
756 }
757 }
758 #[cfg(not(unix))]
759 {
760 errors.push(format!(
762 "sid={}: SIGTERM not supported on this platform",
763 entry.sid
764 ));
765 }
766 reg.remove(&entry.sid);
769 }
770
771 reg.save(®_path)?;
773
774 Ok((stopped, errors))
775 })
776 },
777 )
778 .await
779 .map_err(|e| format!("pool_stop: task panicked: {e}"))?
780 .map_err(|e| e.to_string())?;
781
782 let (stopped, errors) = result;
783 serde_json::to_string(&serde_json::json!({
784 "stopped": stopped,
785 "errors": errors,
786 }))
787 .map_err(|e| format!("pool_stop: serialize: {e}"))
788 }
789}
790
791#[cfg(test)]
794mod tests {
795 use super::super::test_support::make_app_service_at;
796
797 #[tokio::test]
804 #[cfg(unix)]
805 async fn pool_stop_pid_zero_is_rejected() {
806 let tmp = tempfile::tempdir().expect("tempdir");
809 let root = tmp.path().to_path_buf();
810 let svc = make_app_service_at(root.clone()).await;
811
812 let pool_reg_path = root.join("state").join("pool").join("registry.json");
815 std::fs::create_dir_all(pool_reg_path.parent().unwrap()).expect("create pool dir");
816
817 let seeded = serde_json::json!({
818 "sessions": [{
819 "sid": "zero-pid-session",
820 "pid": 0u32,
821 "sock": "/tmp/alc-pool/zero.sock",
822 "version": "0.30.0",
823 "created_at": "2026-01-01T00:00:00Z"
824 }]
825 });
826 std::fs::write(&pool_reg_path, seeded.to_string()).expect("seed registry.json");
827
828 let json_str = svc.pool_stop_impl(None).await.expect("pool_stop_impl");
830 let result: serde_json::Value =
831 serde_json::from_str(&json_str).expect("response is valid JSON");
832
833 let errors = result["errors"].as_array().expect("errors array");
835 assert!(
836 !errors.is_empty(),
837 "expected at least one error for pid=0 entry"
838 );
839 let err_msg = errors[0].as_str().unwrap_or("");
840 assert!(
841 err_msg.contains("not a valid POSIX target pid"),
842 "unexpected error message: {err_msg}"
843 );
844
845 let stopped = result["stopped"].as_array().expect("stopped array");
847 assert!(
848 stopped.is_empty(),
849 "pid=0 entry must not appear in stopped list"
850 );
851
852 let on_disk: serde_json::Value =
854 serde_json::from_str(&std::fs::read_to_string(&pool_reg_path).expect("read registry"))
855 .expect("parse registry");
856 let sessions = on_disk["sessions"].as_array().expect("sessions array");
857 assert!(
858 sessions.is_empty(),
859 "pid=0 entry must be removed from on-disk registry"
860 );
861
862 }
865}