algocline-app 0.44.3

algocline application layer — execution orchestration, package management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
use std::collections::HashMap;
use std::sync::Arc;

use algocline_core::{EngineApi, QueryResponse};
use algocline_engine::state::{ResetReport, StateError};
use async_trait::async_trait;

use super::list_opts::ListOpts;
use super::AppService;

/// Delegates each [`EngineApi`] method to the corresponding `AppService`
/// inherent method via fully-qualified syntax (`AppService::method(self, …)`).
///
/// This avoids ambiguity between the trait method and the inherent method
/// of the same name, preventing accidental infinite recursion if the
/// inherent method is ever removed or renamed.
#[async_trait]
impl EngineApi for AppService {
    // ─── Core execution ──────────────────────────────────────

    async fn run(
        &self,
        code: Option<String>,
        code_file: Option<String>,
        ctx: Option<serde_json::Value>,
        project_root: Option<String>,
        host_mode: Option<bool>,
    ) -> Result<String, String> {
        AppService::run(self, code, code_file, ctx, project_root, host_mode).await
    }

    async fn advice(
        &self,
        strategy: &str,
        task: Option<String>,
        opts: Option<serde_json::Value>,
        project_root: Option<String>,
    ) -> Result<String, String> {
        AppService::advice(self, strategy, task, opts, project_root).await
    }

    async fn continue_single(
        &self,
        session_id: &str,
        response: String,
        query_id: Option<&str>,
        usage: Option<algocline_core::TokenUsage>,
    ) -> Result<String, String> {
        AppService::continue_single(self, session_id, response, query_id, usage).await
    }

    async fn continue_batch(
        &self,
        session_id: &str,
        responses: Vec<QueryResponse>,
    ) -> Result<String, String> {
        AppService::continue_batch(self, session_id, responses).await
    }

    // ─── Session status ──────────────────────────────────────

    async fn status(
        &self,
        session_id: Option<&str>,
        pending_filter: Option<serde_json::Value>,
        include_history: bool,
    ) -> Result<String, String> {
        AppService::status(self, session_id, pending_filter, include_history).await
    }

    // ─── Evaluation ──────────────────────────────────────────

    async fn eval(
        &self,
        scenario: Option<String>,
        scenario_file: Option<String>,
        scenario_name: Option<String>,
        strategy: &str,
        strategy_opts: Option<serde_json::Value>,
        auto_card: bool,
    ) -> Result<String, String> {
        AppService::eval(
            self,
            scenario,
            scenario_file,
            scenario_name,
            strategy,
            strategy_opts,
            auto_card,
        )
        .await
    }

    async fn eval_history(&self, strategy: Option<&str>, limit: usize) -> Result<String, String> {
        AppService::eval_history(self, strategy, limit)
    }

    async fn eval_detail(&self, eval_id: &str) -> Result<String, String> {
        AppService::eval_detail(self, eval_id)
    }

    async fn eval_compare(&self, eval_id_a: &str, eval_id_b: &str) -> Result<String, String> {
        AppService::eval_compare(self, eval_id_a, eval_id_b).await
    }

    // ─── Scenarios ───────────────────────────────────────────

    async fn scenario_list(&self) -> Result<String, String> {
        AppService::scenario_list(self)
    }

    async fn scenario_show(&self, name: &str) -> Result<String, String> {
        AppService::scenario_show(self, name)
    }

    async fn scenario_install(&self, url: String) -> Result<String, String> {
        AppService::scenario_install(self, url).await
    }

    // ─── Packages ────────────────────────────────────────────

    async fn pkg_link(
        &self,
        path: String,
        name: Option<String>,
        force: Option<bool>,
        scope: Option<String>,
        project_root: Option<String>,
    ) -> Result<String, String> {
        AppService::pkg_link(self, path, name, force, scope, project_root).await
    }

    async fn pkg_unlink(&self, name: String) -> Result<String, String> {
        AppService::pkg_unlink(self, name).await
    }

    #[allow(clippy::too_many_arguments)]
    async fn pkg_list(
        &self,
        project_root: Option<String>,
        limit: Option<i32>,
        sort: Option<String>,
        filter: Option<serde_json::Value>,
        fields: Option<Vec<String>>,
        verbose: Option<String>,
    ) -> Result<String, String> {
        // `filter` is a free-form JSON Value at the MCP boundary (so the
        // trait stays core-crate-pure). If the caller sends something
        // that is not a JSON object we treat it as "no filter" and log
        // the drop so operators can diagnose unexpected filter shapes
        // in production.
        let filter_map = match filter {
            None => None,
            Some(v) => match serde_json::from_value::<HashMap<String, serde_json::Value>>(v) {
                Ok(map) => Some(map),
                Err(e) => {
                    tracing::warn!(error = %e, "pkg_list: filter value is not a JSON object — treating as no filter");
                    None
                }
            },
        };

        // Negative limit values from MCP callers are clamped to 0 rather
        // than wrapping to a huge usize (unchecked-user-bound-input pattern).
        // Downstream semantics: `Some(0)` means "no limit" (return all) —
        // the truncate path in `AppService::pkg_list` short-circuits on 0.
        let opts = ListOpts {
            limit: limit.map(|n| n.max(0) as usize),
            sort,
            filter: filter_map,
            fields,
            verbose,
        };

        AppService::pkg_list(self, project_root, opts)
            .await
            .map_err(|e| e.to_string())
    }

    async fn pkg_install(
        &self,
        url: String,
        name: Option<String>,
        force: Option<bool>,
    ) -> Result<String, String> {
        AppService::pkg_install(self, url, name, force).await
    }

    async fn pkg_remove(
        &self,
        name: &str,
        project_root: Option<String>,
        version: Option<String>,
        scope: Option<String>,
    ) -> Result<String, String> {
        AppService::pkg_remove(self, name, project_root, version, scope).await
    }

    async fn pkg_repair(
        &self,
        name: Option<String>,
        project_root: Option<String>,
    ) -> Result<String, String> {
        AppService::pkg_repair(self, name, project_root).await
    }

    async fn pkg_doctor(
        &self,
        name: Option<String>,
        project_root: Option<String>,
    ) -> Result<String, String> {
        AppService::pkg_doctor(self, name, project_root).await
    }

    /// Run mlua-lspec tests for a package, a single file, or inline code.
    ///
    /// Forwards to [`AppService::pkg_test`]. See trait doc for full contract.
    #[allow(clippy::too_many_arguments)]
    async fn pkg_test(
        &self,
        pkg: Option<String>,
        code_file: Option<String>,
        code: Option<String>,
        spec_dir: Option<String>,
        filter: Option<String>,
        search_paths: Option<Vec<String>>,
        project_root: Option<String>,
        auto_search_paths: Option<bool>,
    ) -> Result<String, String> {
        AppService::pkg_test(
            self,
            pkg,
            code_file,
            code,
            spec_dir,
            filter,
            search_paths,
            project_root,
            auto_search_paths,
        )
        .await
    }

    // ─── Logging ─────────────────────────────────────────────

    async fn add_note(
        &self,
        session_id: &str,
        content: &str,
        title: Option<&str>,
    ) -> Result<String, String> {
        AppService::add_note(self, session_id, content, title).await
    }

    async fn log_view(
        &self,
        session_id: Option<&str>,
        limit: Option<usize>,
        max_chars: Option<usize>,
    ) -> Result<String, String> {
        AppService::log_view(self, session_id, limit, max_chars).await
    }

    async fn stats(
        &self,
        strategy_filter: Option<&str>,
        days: Option<u64>,
    ) -> Result<String, String> {
        AppService::stats(self, strategy_filter, days)
    }

    // ─── Project lifecycle ────────────────────────────────────

    async fn init(&self, project_root: Option<String>) -> Result<String, String> {
        AppService::init(self, project_root).await
    }

    async fn update(&self, project_root: Option<String>) -> Result<String, String> {
        AppService::update(self, project_root).await
    }

    async fn migrate(&self, project_root: Option<String>) -> Result<String, String> {
        AppService::migrate(self, project_root).await
    }

    // ─── Session activation (issue #1776627475) ──────────────

    async fn session_new(
        &self,
        project_root: Option<String>,
        mode: Option<String>,
    ) -> Result<String, String> {
        let session = self.activate_session(project_root.as_deref(), mode.as_deref())?;
        let result = serde_json::json!({
            "session_id": session.session_id,
            "project_root": session
                .project_root
                .as_ref()
                .map(|p| p.to_string_lossy().to_string()),
            "mode": session.mode.as_str(),
        });
        serde_json::to_string_pretty(&result).map_err(|e| e.to_string())
    }

    // ─── Cards ───────────────────────────────────────────────

    async fn card_list(&self, pkg: Option<String>) -> Result<String, String> {
        AppService::card_list(self, pkg.as_deref())
    }

    async fn card_get(&self, card_id: &str) -> Result<String, String> {
        AppService::card_get(self, card_id)
    }

    async fn card_find(
        &self,
        pkg: Option<String>,
        where_: Option<serde_json::Value>,
        order_by: Option<serde_json::Value>,
        limit: Option<usize>,
        offset: Option<usize>,
    ) -> Result<String, String> {
        AppService::card_find(self, pkg, where_, order_by, limit, offset)
    }

    async fn card_alias_list(&self, pkg: Option<String>) -> Result<String, String> {
        AppService::card_alias_list(self, pkg.as_deref())
    }

    async fn card_get_by_alias(&self, name: &str) -> Result<String, String> {
        AppService::card_get_by_alias(self, name)
    }

    async fn card_alias_set(
        &self,
        name: &str,
        card_id: &str,
        pkg: Option<String>,
        note: Option<String>,
    ) -> Result<String, String> {
        AppService::card_alias_set(self, name, card_id, pkg.as_deref(), note.as_deref())
    }

    async fn card_append(
        &self,
        card_id: &str,
        fields: serde_json::Value,
    ) -> Result<String, String> {
        AppService::card_append(self, card_id, fields)
    }

    async fn card_install(&self, url: String) -> Result<String, String> {
        AppService::card_install(self, url).await
    }

    async fn card_samples(
        &self,
        card_id: &str,
        offset: Option<usize>,
        limit: Option<usize>,
        where_: Option<serde_json::Value>,
    ) -> Result<String, String> {
        AppService::card_samples(self, card_id, offset.unwrap_or(0), limit, where_)
    }

    async fn card_lineage(
        &self,
        card_id: &str,
        direction: Option<String>,
        depth: Option<usize>,
        include_stats: Option<bool>,
        relation_filter: Option<Vec<String>>,
    ) -> Result<String, String> {
        AppService::card_lineage(
            self,
            card_id,
            direction.as_deref(),
            depth,
            include_stats,
            relation_filter,
        )
    }

    async fn card_sink_backfill(&self, sink: String, dry_run: bool) -> Result<String, String> {
        AppService::card_sink_backfill(self, super::card::SinkBackfillParams { sink, dry_run })
    }

    async fn card_analyze(&self, card_id: &str, pkg: Option<String>) -> Result<String, String> {
        AppService::card_analyze(self, card_id, pkg).await
    }

    async fn card_publish(
        &self,
        card_id: &str,
        target_repo: &str,
        commit_message: Option<&str>,
    ) -> Result<String, String> {
        AppService::card_publish(self, card_id, target_repo, commit_message).await
    }

    // ─── Hub ─────────────────────────────────────────────────

    async fn hub_reindex(
        &self,
        output_path: Option<String>,
        source_dir: Option<String>,
    ) -> Result<String, String> {
        self.hub_reindex(output_path.as_deref(), source_dir.as_deref())
            .await
    }

    async fn hub_gendoc(
        &self,
        source_dir: String,
        out_dir: Option<String>,
        projections: Option<Vec<String>>,
        config_path: Option<String>,
        lint_strict: Option<bool>,
    ) -> Result<String, String> {
        let svc = self.clone();
        tokio::task::spawn_blocking(move || {
            crate::AppService::hub_gendoc(
                &svc,
                &source_dir,
                out_dir.as_deref(),
                projections.as_deref(),
                config_path.as_deref(),
                lint_strict,
            )
        })
        .await
        .map_err(|e| format!("hub_gendoc task panicked: {e}"))?
    }

    async fn hub_dist(
        &self,
        source_dir: String,
        output_path: Option<String>,
        out_dir: Option<String>,
        preset: Option<String>,
        project_root: Option<String>,
        projections: Option<Vec<String>>,
        config_path: Option<String>,
        lint_strict: Option<bool>,
    ) -> Result<String, String> {
        self.hub_dist(
            &source_dir,
            output_path.as_deref(),
            out_dir.as_deref(),
            preset.as_deref(),
            project_root.as_deref(),
            projections.as_deref(),
            config_path.as_deref(),
            lint_strict,
        )
        .await
    }

    async fn hub_info(&self, pkg: String) -> Result<String, String> {
        let svc = self.clone();
        tokio::task::spawn_blocking(move || AppService::hub_info(&svc, &pkg))
            .await
            .map_err(|e| format!("hub_info task panicked: {e}"))?
    }

    #[allow(clippy::too_many_arguments)]
    async fn hub_search(
        &self,
        query: Option<String>,
        category: Option<String>,
        installed_only: Option<bool>,
        limit: Option<i32>,
        sort: Option<String>,
        filter: Option<serde_json::Value>,
        fields: Option<Vec<String>>,
        verbose: Option<String>,
        local_indices: Option<Vec<String>>,
    ) -> Result<String, String> {
        let svc = self.clone();

        // `filter` is a free-form JSON Value at the MCP boundary (so the
        // trait stays core-crate-pure). If the caller sends something
        // that is not a JSON object we treat it as "no filter" — the
        // explicit category/installed_only params still cover the common
        // cases. The MCP `JsonSchema` layer will have already flagged
        // hard type errors. We log the drop so operators can diagnose
        // unexpected filter shapes in production.
        let filter_map = match filter {
            None => None,
            Some(v) => match serde_json::from_value::<HashMap<String, serde_json::Value>>(v) {
                Ok(map) => Some(map),
                Err(e) => {
                    tracing::warn!(error = %e, "hub_search: filter value is not a JSON object — treating as no filter");
                    None
                }
            },
        };

        // Negative limit values from MCP callers are clamped to 0 rather
        // than wrapping to a huge usize (unchecked-user-bound-input pattern).
        // Downstream semantics: `Some(0)` means "no limit" (return all) —
        // the truncate path in `AppService::hub_search` short-circuits on 0.
        let opts = ListOpts {
            limit: limit.map(|n| n.max(0) as usize),
            sort,
            filter: filter_map,
            fields,
            verbose,
        };

        tokio::task::spawn_blocking(move || {
            AppService::hub_search(
                &svc,
                query.as_deref(),
                category.as_deref(),
                installed_only,
                opts,
                local_indices,
            )
        })
        .await
        .map_err(|e| format!("hub_search task panicked: {e}"))?
    }

    // ─── Package read ─────────────────────────────────────────

    async fn pkg_read_init_lua(&self, name: &str) -> Result<String, String> {
        AppService::pkg_read_init_lua(self, name, None)
    }

    async fn pkg_get_narrative_md(&self, name: &str) -> Result<Option<String>, String> {
        AppService::pkg_get_narrative_md(self, name).await
    }

    async fn pkg_meta(&self, name: &str) -> Result<String, String> {
        let filter = serde_json::json!({ "name": name });
        let json_str = EngineApi::pkg_list(
            self,
            None,
            None,
            None,
            Some(filter),
            None,
            Some("full".to_string()),
        )
        .await?;
        let val: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| format!("pkg_meta: failed to parse pkg_list response: {e}"))?;
        let pkgs = val
            .get("packages")
            .and_then(|p| p.as_array())
            .ok_or_else(|| "pkg_meta: pkg_list response missing 'packages' field".to_string())?;
        if pkgs.is_empty() {
            return Err(format!("pkg not found: {name}"));
        }
        serde_json::to_string(&pkgs[0]).map_err(|e| format!("pkg_meta: serialize entry: {e}"))
    }

    // ─── Package scaffold ─────────────────────────────────────

    async fn pkg_scaffold(
        &self,
        name: String,
        target_dir: Option<String>,
        category: Option<String>,
        description: Option<String>,
    ) -> Result<String, String> {
        let svc = self.clone();
        tokio::task::spawn_blocking(move || {
            AppService::pkg_scaffold(
                &svc,
                &name,
                target_dir.as_deref(),
                category.as_deref(),
                description.as_deref(),
            )
        })
        .await
        .map_err(|e| format!("pkg_scaffold task panicked: {e}"))?
    }

    // ─── Hub resources ───────────────────────────────────────

    /// Aggregate hub index across all registered cache sources.
    ///
    /// Delegates to `AppService::aggregate_index`, then serializes the
    /// result to a JSON string. Individual source failures and registry-load
    /// failures are embedded in the response JSON under a `"warnings"` field
    /// so the MCP caller can observe partial failures without losing the
    /// aggregate result.
    async fn hub_index_aggregate(&self) -> Result<String, String> {
        let svc = self.clone();
        let (index, warnings) = tokio::task::spawn_blocking(move || {
            AppService::aggregate_index(&svc).map_err(|e| e.to_string())
        })
        .await
        .map_err(|e| format!("hub_index_aggregate task panicked: {e}"))??;

        let mut json = serde_json::to_value(&index)
            .map_err(|e| format!("hub_index_aggregate: serialize index: {e}"))?;
        if !warnings.is_empty() {
            if let Some(obj) = json.as_object_mut() {
                obj.insert("warnings".to_string(), serde_json::json!(warnings));
            }
        }
        serde_json::to_string(&json)
            .map_err(|e| format!("hub_index_aggregate: serialize final: {e}"))
    }

    // ─── Settings ────────────────────────────────────────────

    async fn setting_resolve(&self, target: Option<String>) -> Result<String, String> {
        let app_dir = self.log_config.app_dir();
        let project_root = self.resolve_root(None);
        tokio::task::spawn_blocking(move || {
            crate::service::setting::resolve_setting(
                &app_dir,
                project_root.as_deref(),
                target.as_deref(),
            )
            .map_err(|e| e.to_string())
            .and_then(|r| {
                serde_json::to_string(&r).map_err(|e| format!("setting_resolve: serialize: {e}"))
            })
        })
        .await
        .map_err(|e| format!("setting_resolve: task panicked: {e}"))?
    }

    // ─── State management ────────────────────────────────────

    async fn state_list(&self, namespace: String) -> Result<String, String> {
        let store = Arc::clone(&self.state_store);
        tokio::task::spawn_blocking(move || {
            store
                .list_dispatched(&namespace)
                .map_err(AppService::state_err_to_wire)
                .and_then(|keys| {
                    // Wire shape: { "keys": [string] } per docs/state-management.md L92.
                    // TODO(ST2): verify this shape via real rmcp stdio in tests/e2e.rs
                    // (test_alc_state_list_* happy path should assert parsed["keys"].is_array()).
                    serde_json::to_string(&serde_json::json!({"keys": keys}))
                        .map_err(|e| format!("state_list: serialize: {e}"))
                })
        })
        .await
        .map_err(|e| format!("state_list: task panicked: {e}"))?
    }

    async fn state_show(&self, namespace: String, key: String) -> Result<String, String> {
        let store = Arc::clone(&self.state_store);
        tokio::task::spawn_blocking(move || {
            store
                .show_dispatched(&namespace, &key)
                .map_err(AppService::state_err_to_wire)
                .and_then(|value| {
                    serde_json::to_string(&value).map_err(|e| format!("state_show: serialize: {e}"))
                })
        })
        .await
        .map_err(|e| format!("state_show: task panicked: {e}"))?
    }

    async fn state_reset(
        &self,
        namespace: String,
        key: String,
        steps: Option<Vec<String>>,
        fields: Option<Vec<String>>,
    ) -> Result<String, String> {
        let store = Arc::clone(&self.state_store);
        // Clone input slices before moving into closure so we can echo them in the response.
        let steps_input: Vec<String> = steps.clone().unwrap_or_default();
        let fields_input: Vec<String> = fields.clone().unwrap_or_default();
        tokio::task::spawn_blocking(move || {
            let steps_slice: Vec<String> = steps.unwrap_or_default();
            let fields_slice: Vec<String> = fields.unwrap_or_default();
            store
                .reset_dispatched_with_backup(&namespace, &key, &steps_slice, &fields_slice)
                .map_err(AppService::state_err_to_wire)
                .and_then(|report: ResetReport| {
                    let v = serde_json::json!({
                        "ok": true,
                        "backup_path": report.backup_path.to_string_lossy(),
                        "steps_removed": report.steps_removed,
                        "steps_input": steps_input,
                        "fields_removed": report.fields_removed,
                        "fields_input": fields_input,
                    });
                    serde_json::to_string(&v).map_err(|e| format!("state_reset: serialize: {e}"))
                })
        })
        .await
        .map_err(|e| format!("state_reset: task panicked: {e}"))?
    }

    async fn state_set(
        &self,
        namespace: String,
        key: String,
        value: serde_json::Value,
    ) -> Result<String, String> {
        let store = Arc::clone(&self.state_store);
        tokio::task::spawn_blocking(move || {
            store
                .set_dispatched(&namespace, &key, &value)
                .map_err(AppService::state_err_to_wire)
                .map(|_| r#"{"ok":true}"#.to_string())
        })
        .await
        .map_err(|e| format!("state_set: task panicked: {e}"))?
    }

    async fn state_delete(&self, namespace: String, key: String) -> Result<String, String> {
        let store = Arc::clone(&self.state_store);
        tokio::task::spawn_blocking(move || {
            store
                .delete_dispatched(&namespace, &key)
                .map_err(AppService::state_err_to_wire)
                .and_then(|existed| {
                    serde_json::to_string(&serde_json::json!({"ok": true, "existed": existed}))
                        .map_err(|e| format!("state_delete: serialize: {e}"))
                })
        })
        .await
        .map_err(|e| format!("state_delete: task panicked: {e}"))?
    }

    // ─── Diagnostics ─────────────────────────────────────────

    async fn info(&self) -> String {
        let svc = self.clone();
        tokio::task::spawn_blocking(move || AppService::info(&svc))
            .await
            .unwrap_or_else(|e| format!("{{\"error\": \"info: task panicked: {e}\"}}"))
    }

    // ─── Pool management ─────────────────────────────────────

    async fn pool_ensure(&self) -> Result<String, String> {
        AppService::pool_ensure_impl(self).await
    }

    async fn pool_status(&self, sid: Option<String>) -> Result<String, String> {
        AppService::pool_status_impl(self, sid).await
    }

    async fn pool_stop(&self, sid: Option<String>) -> Result<String, String> {
        AppService::pool_stop_impl(self, sid).await
    }
}

// ─── State error → wire JSON mapper ───────────────────────────────────────

impl AppService {
    /// Convert a [`StateError`] into a typed wire error JSON string.
    ///
    /// Each variant maps to a distinct `"error"` code so callers can distinguish
    /// `NOT_FOUND` from generic I/O errors at the wire level.
    ///
    /// # Arguments
    /// - `e` — the engine-layer error to convert.
    ///
    /// # Returns
    /// A JSON string `{"error":"<CODE>",...}`. Falls back to an INTERNAL error JSON
    /// string if serialization itself fails (should never occur for string-only values).
    fn state_err_to_wire(e: StateError) -> String {
        let v = match e {
            StateError::KeyNotFound { namespace, key } => {
                serde_json::json!({"error": "NOT_FOUND", "namespace": namespace, "key": key})
            }
            StateError::UnsafeSegment { which, value } => {
                serde_json::json!({"error": "UNSAFE_SEGMENT", "which": which, "value": value})
            }
            StateError::IoBackup(io_err) => {
                serde_json::json!({"error": "IO_BACKUP", "message": io_err.to_string()})
            }
            StateError::IoRead(io_err) => {
                serde_json::json!({"error": "IO_READ", "message": io_err.to_string()})
            }
            StateError::IoWrite(io_err) => {
                serde_json::json!({"error": "IO_WRITE", "message": io_err.to_string()})
            }
            StateError::Serde(serde_err) => {
                serde_json::json!({"error": "SERDE", "message": serde_err.to_string()})
            }
            StateError::ShapeInvalid { reason } => {
                serde_json::json!({"error": "SHAPE_INVALID", "reason": reason})
            }
        };
        serde_json::to_string(&v).unwrap_or_else(|e| {
            // justification: the json! macro above only contains string values, so
            // to_string() cannot fail under normal conditions. The unwrap_or_else
            // is a purely defensive fallback.
            format!("{{\"error\":\"INTERNAL\",\"message\":\"serialize failed: {e}\"}}")
        })
    }
}