roboticus-cli 0.11.4

CLI commands and migration engine for the Roboticus agent runtime
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
async fn run_mechanic_text_gateway_checks(
    base_url: &str,
    roboticus_dir: &Path,
    repair: bool,
    allow_jobs: &[String],
    fixed: &mut u32,
) -> Result<(), Box<dyn std::error::Error>> {
    let (_, BOLD, _, _, _, _, _, RESET, _) = colors();
    let (OK, ACTION, WARN, DETAIL, ERR) = icons();
    let gateway_up = match super::http_client()?
        .get(format!("{base_url}/api/health"))
        .send()
        .await
    {
        Ok(resp) if resp.status().is_success() => {
            println!("  {OK} Gateway reachable at {base_url}");
            true
        }
        Ok(resp) => {
            println!("  {WARN} Gateway returned HTTP {}", resp.status());
            false
        }
        Err(_) => {
            println!("  {WARN} Gateway not running at {base_url}");
            false
        }
    };

    if gateway_up {
        let mut channels_status: Option<Vec<serde_json::Value>> = None;
        let mut runtime_diag: Option<serde_json::Value> = None;

        run_gateway_config_and_diag_checks(base_url, &mut runtime_diag).await?;
        run_gateway_skill_checks(base_url, roboticus_dir, repair, fixed).await?;
        run_gateway_plugin_checks(roboticus_dir, repair, fixed)?;
        run_gateway_wallet_and_channel_checks(base_url, &mut channels_status).await?;
        run_gateway_provider_and_revenue_checks(base_url, roboticus_dir, repair).await;
        run_gateway_log_and_runtime_diagnostics(
            roboticus_dir,
            channels_status.as_ref(),
            runtime_diag.as_ref(),
        );
        match probe_subagent_integrity_via_gateway(base_url, repair).await {
            Ok(probe) if probe.hollow_subagents == 0 => {}
            Ok(probe) => {
                if repair {
                    println!(
                        "  {ACTION} Repaired {} hollow subagent(s) (skills={}, sessions={})",
                        probe.hollow_subagents, probe.repaired_skills, probe.repaired_sessions
                    );
                } else {
                    println!(
                        "  {WARN} Found {} hollow subagent(s); run `roboticus mechanic --repair` to restore skills/sessions.",
                        probe.hollow_subagents
                    );
                }
            }
            Err(e) => println!("  {WARN} Could not inspect subagent integrity via gateway: {e}"),
        }
        run_gateway_allowlisted_job_recovery(base_url, repair, allow_jobs, fixed).await?;
    } else {
        println!("    {DETAIL} Skipping server checks (config, skills, wallet, channels)");
    }

    if repair {
        println!("\n  {BOLD}Mechanic Integrated Sweep{RESET}\n");
        run_gateway_integrated_repair_sweep(base_url, roboticus_dir, gateway_up).await?;
    }

    Ok(())
}

async fn run_gateway_config_and_diag_checks(
    base_url: &str,
    runtime_diag: &mut Option<serde_json::Value>,
) -> Result<(), Box<dyn std::error::Error>> {
    let (OK, _, WARN, _, _) = icons();
    match super::http_client()?
        .get(format!("{base_url}/api/config"))
        .send()
        .await
    {
        Ok(resp) if resp.status().is_success() => println!("  {OK} Configuration loaded on server"),
        Ok(resp) => println!("  {WARN} Config endpoint returned HTTP {}", resp.status()),
        Err(e) => println!("  {WARN} Config check failed: {e}"),
    }

    match super::http_client()?
        .get(format!("{base_url}/api/agent/status"))
        .send()
        .await
    {
        Ok(resp) if resp.status().is_success() => {
            let body: serde_json::Value = resp.json().await.unwrap_or_default();
            *runtime_diag = body.get("diagnostics").cloned();
            println!("  {OK} Runtime diagnostics available");
        }
        Ok(resp) => println!(
            "  {WARN} Agent status endpoint returned HTTP {}",
            resp.status()
        ),
        Err(e) => println!("  {WARN} Agent status check failed: {e}"),
    }
    Ok(())
}

async fn run_gateway_skill_checks(
    base_url: &str,
    roboticus_dir: &Path,
    repair: bool,
    fixed: &mut u32,
) -> Result<(), Box<dyn std::error::Error>> {
    let (OK, ACTION, WARN, DETAIL, _) = icons();
    if repair {
        match super::http_client()?
            .post(format!("{base_url}/api/skills/reload"))
            .json(&serde_json::json!({}))
            .send()
            .await
        {
            Ok(resp) if resp.status().is_success() => {
                println!("  {ACTION} Reloaded skills from disk to repair skill DB drift");
                *fixed += 1;
            }
            Ok(resp) => println!(
                "  {WARN} Skills reload failed during repair (HTTP {})",
                resp.status()
            ),
            Err(e) => println!("  {WARN} Skills reload failed during repair: {e}"),
        }
    }

    match super::http_client()?
        .get(format!("{base_url}/api/skills"))
        .send()
        .await
    {
        Ok(resp) if resp.status().is_success() => {
            let body: serde_json::Value = resp.json().await.unwrap_or_default();
            let count = body
                .get("skills")
                .and_then(|v| v.as_array())
                .map(|a| a.len())
                .unwrap_or(0);
            if count == 0 {
                println!(
                    "  {WARN} Skills loaded (0 skills) — builtin skills may be missing from DB"
                );
            } else {
                println!("  {OK} Skills loaded ({count} skills)");
            }
            let db_parity = evaluate_capability_skill_parity(&roboticus_dir.join("state.db"));
            if db_parity.missing_in_db.is_empty() {
                println!("  {OK} Loaded skill DB satisfies capability-to-skill parity");
            } else {
                println!("  {WARN} Loaded skill DB missing required capability skills");
                println!("    {DETAIL} {}", db_parity.missing_in_db.join("; "));
            }
        }
        Ok(resp) => println!("  {WARN} Skills endpoint returned HTTP {}", resp.status()),
        Err(e) => println!("  {WARN} Skills check failed: {e}"),
    }
    Ok(())
}

fn run_gateway_plugin_checks(
    roboticus_dir: &Path,
    repair: bool,
    fixed: &mut u32,
) -> Result<(), Box<dyn std::error::Error>> {
    use roboticus_plugin_sdk::manifest::PluginManifest;

    let (OK, ACTION, WARN, _, ERR) = icons();
    let plugins_dir = roboticus_dir.join("plugins");
    if !plugins_dir.exists() {
        return Ok(());
    }

    let mut orphan_dirs: Vec<PathBuf> = Vec::new();
    let mut valid_plugins: Vec<(PathBuf, PluginManifest)> = Vec::new();
    if let Ok(entries) = std::fs::read_dir(&plugins_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            let manifest_path = path.join("plugin.toml");
            if !manifest_path.exists() {
                orphan_dirs.push(path);
                continue;
            }
            match PluginManifest::from_file(&manifest_path) {
                Ok(manifest) => valid_plugins.push((path, manifest)),
                Err(_) => orphan_dirs.push(path),
            }
        }
    }

    if orphan_dirs.is_empty() && valid_plugins.is_empty() {
        println!("  {OK} Plugins directory empty (no plugins installed)");
        return Ok(());
    }

    for orphan in &orphan_dirs {
        let dir_name = orphan.file_name().unwrap_or_default().to_string_lossy();
        if repair {
            if prompt_yes_no(&format!(
                "  Remove orphan plugin directory '{dir_name}'? (no valid plugin.toml)"
            )) {
                if let Err(e) = std::fs::remove_dir_all(orphan) {
                    println!("  {ERR} Failed to remove {}: {e}", orphan.display());
                } else {
                    println!("  {ACTION} Removed orphan plugin directory: {dir_name}");
                    *fixed += 1;
                }
            }
        } else {
            println!(
                "  {WARN} Orphan plugin directory: {dir_name} (no valid plugin.toml — use --repair to remove)"
            );
        }
    }

    let skills_dir = roboticus_dir.join("skills");
    for (plugin_dir, manifest) in &valid_plugins {
        let report = manifest.vet(plugin_dir);
        if report.is_ok() && report.warnings.is_empty() {
            println!(
                "  {OK} Plugin '{}' v{} — healthy",
                manifest.name, manifest.version
            );
        } else {
            for w in &report.warnings {
                println!("  {WARN} Plugin '{}': {w}", manifest.name);
            }
            for e in &report.errors {
                println!("  {ERR} Plugin '{}': {e}", manifest.name);
            }
        }
        if repair {
            for skill_rel in &manifest.companion_skills {
                let src = plugin_dir.join(skill_rel);
                let installed_name =
                    super::plugins::companion_skill_install_name(&manifest.name, skill_rel);
                let dest = skills_dir.join(&installed_name);
                if src.exists() && !dest.exists() {
                    // best-effort: dir creation failure caught by subsequent copy
                    std::fs::create_dir_all(&skills_dir).ok();
                    if let Err(e) = std::fs::copy(&src, &dest) {
                        println!(
                            "  {ERR} Failed to re-deploy companion skill {installed_name}: {e}"
                        );
                    } else {
                        println!(
                            "  {ACTION} Re-deployed missing companion skill: {installed_name}"
                        );
                        *fixed += 1;
                    }
                }
            }
        }
    }
    Ok(())
}

async fn run_gateway_wallet_and_channel_checks(
    base_url: &str,
    channels_status: &mut Option<Vec<serde_json::Value>>,
) -> Result<(), Box<dyn std::error::Error>> {
    let (OK, _, WARN, _, _) = icons();
    match super::http_client()?
        .get(format!("{base_url}/api/wallet/balance"))
        .send()
        .await
    {
        Ok(resp) if resp.status().is_success() => println!("  {OK} Wallet accessible"),
        Ok(resp) => println!("  {WARN} Wallet endpoint returned HTTP {}", resp.status()),
        Err(e) => println!("  {WARN} Wallet check failed: {e}"),
    }

    match super::http_client()?
        .get(format!("{base_url}/api/channels/status"))
        .send()
        .await
    {
        Ok(resp) if resp.status().is_success() => {
            let body: Vec<serde_json::Value> = resp.json().await.unwrap_or_default();
            let active = body
                .iter()
                .filter(|c| {
                    c.get("connected")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(false)
                })
                .count();
            println!("  {OK} Channels ({active}/{} connected)", body.len());
            *channels_status = Some(body);
        }
        Ok(resp) => println!("  {WARN} Channels endpoint returned HTTP {}", resp.status()),
        Err(e) => println!("  {WARN} Channels check failed: {e}"),
    }
    Ok(())
}

async fn run_gateway_provider_and_revenue_checks(
    base_url: &str,
    roboticus_dir: &Path,
    repair: bool,
) {
    let (OK, ACTION, WARN, DETAIL, _) = icons();
    match fetch_provider_health(base_url).await {
        Ok(rows) if rows.is_empty() => {
            println!("  {WARN} Provider health check returned no providers")
        }
        Ok(rows) => {
            println!(
                "  {OK} Provider health check completed ({} provider{})",
                rows.len(),
                if rows.len() == 1 { "" } else { "s" }
            );
            for row in rows {
                match row.status.as_str() {
                    "ok" if row.count > 0 => println!(
                        "    {OK} {}: reachable ({} model{})",
                        row.name,
                        row.count,
                        if row.count == 1 { "" } else { "s" }
                    ),
                    "ok" => {
                        println!(
                            "    {WARN} {}: reachable but no models discovered",
                            row.name
                        );
                        println!(
                            "      {DETAIL} Probe route: `{}`",
                            provider_scan_hint(Some(&row.name))
                        );
                    }
                    "unreachable" | "error" => {
                        let detail = row.error.as_deref().unwrap_or("unknown provider error");
                        println!("    {WARN} {}: {} ({detail})", row.name, row.status);
                        println!(
                            "      {DETAIL} Probe route: `{}`",
                            provider_scan_hint(Some(&row.name))
                        );
                    }
                    other => {
                        let detail = row.error.as_deref().unwrap_or("no extra detail");
                        println!("    {WARN} {}: {other} ({detail})", row.name);
                        println!(
                            "      {DETAIL} Probe route: `{}`",
                            provider_scan_hint(Some(&row.name))
                        );
                    }
                }
            }
        }
        Err(e) => println!("  {WARN} Provider health check failed: {e}"),
    }

    match probe_revenue_control_plane(&roboticus_dir.join("state.db"), repair) {
        Ok(health) if health.opportunities_total == 0 => {
            println!("  {OK} Revenue control plane: no opportunities recorded yet");
        }
        Ok(health) => {
            println!(
                "  {OK} Revenue control plane: {} opportunities ({} settled)",
                health.opportunities_total, health.opportunities_settled
            );
            if health.orphan_jobs > 0 {
                println!(
                    "    {WARN} Found {} orphan revenue opportunit{}",
                    health.orphan_jobs,
                    if health.orphan_jobs == 1 { "y" } else { "ies" }
                );
                if repair && health.repaired_orphans > 0 {
                    println!(
                        "    {ACTION} Repaired {} orphan opportunit{} (marked failed)",
                        health.repaired_orphans,
                        if health.repaired_orphans == 1 {
                            "y"
                        } else {
                            "ies"
                        }
                    );
                }
            }
            if health.missing_settlement_ledger > 0 {
                println!(
                    "    {WARN} Found {} settled opportunit{} missing ledger entries",
                    health.missing_settlement_ledger,
                    if health.missing_settlement_ledger == 1 {
                        "y"
                    } else {
                        "ies"
                    }
                );
                if repair && health.reconciled_ledger_rows > 0 {
                    println!(
                        "    {ACTION} Reconciled {} missing revenue settlement ledger entr{}",
                        health.reconciled_ledger_rows,
                        if health.reconciled_ledger_rows == 1 {
                            "y"
                        } else {
                            "ies"
                        }
                    );
                }
            }
            if health.revenue_swap_tasks_total > 0 {
                println!(
                    "    {OK} Revenue swap queue: total={} pending={} in_progress={} failed={}",
                    health.revenue_swap_tasks_total,
                    health.revenue_swap_tasks_pending,
                    health.revenue_swap_tasks_in_progress,
                    health.revenue_swap_tasks_failed
                );
            }
            if health.stale_revenue_swap_tasks > 0 {
                println!(
                    "    {WARN} Found {} stale revenue swap task{} stuck in in_progress",
                    health.stale_revenue_swap_tasks,
                    if health.stale_revenue_swap_tasks == 1 {
                        ""
                    } else {
                        "s"
                    }
                );
                if repair && health.reset_stale_revenue_swap_tasks > 0 {
                    println!(
                        "    {ACTION} Reset {} stale revenue swap task{} back to pending",
                        health.reset_stale_revenue_swap_tasks,
                        if health.reset_stale_revenue_swap_tasks == 1 {
                            ""
                        } else {
                            "s"
                        }
                    );
                }
            }
            if health.normalized_task_sources > 0 {
                println!(
                    "    {ACTION} Normalized {} malformed task source payload{}",
                    health.normalized_task_sources,
                    if health.normalized_task_sources == 1 {
                        ""
                    } else {
                        "s"
                    }
                );
            }
            if health.obvious_noise_tasks > 0 {
                println!(
                    "    {WARN} Found {} obvious test/noise task{} in the open queue",
                    health.obvious_noise_tasks,
                    if health.obvious_noise_tasks == 1 {
                        ""
                    } else {
                        "s"
                    }
                );
                if repair && health.dismissed_noise_tasks > 0 {
                    println!(
                        "    {ACTION} Dismissed {} obvious noise task{} from the open queue",
                        health.dismissed_noise_tasks,
                        if health.dismissed_noise_tasks == 1 {
                            ""
                        } else {
                            "s"
                        }
                    );
                }
            }
            if health.stale_revenue_tasks > 0 {
                println!(
                    "    {WARN} Found {} stale revenue task{} stuck in in_progress",
                    health.stale_revenue_tasks,
                    if health.stale_revenue_tasks == 1 {
                        ""
                    } else {
                        "s"
                    }
                );
                if repair && health.marked_stale_revenue_tasks_needs_review > 0 {
                    println!(
                        "    {ACTION} Marked {} stale revenue task{} as needs_review",
                        health.marked_stale_revenue_tasks_needs_review,
                        if health.marked_stale_revenue_tasks_needs_review == 1 {
                            ""
                        } else {
                            "s"
                        }
                    );
                }
            }
        }
        Err(e) => println!("  {WARN} Revenue control-plane probe failed: {e}"),
    }

    match probe_revenue_swap_reconcile(base_url, repair).await {
        Ok(health) if health.submitted_tasks == 0 => {}
        Ok(health) => {
            println!(
                "    {OK} Submitted swap receipts awaiting reconciliation: {}",
                health.submitted_tasks
            );
            if !repair {
                println!(
                    "      {DETAIL} Run `roboticus mechanic --repair` to reconcile submitted swap receipts against chain state"
                );
            } else {
                if health.confirmed_repairs > 0 {
                    println!(
                        "    {ACTION} Confirmed {} submitted swap{} from chain receipts",
                        health.confirmed_repairs,
                        if health.confirmed_repairs == 1 {
                            ""
                        } else {
                            "s"
                        }
                    );
                }
                if health.failed_repairs > 0 {
                    println!(
                        "    {ACTION} Marked {} submitted swap{} failed from chain receipts",
                        health.failed_repairs,
                        if health.failed_repairs == 1 { "" } else { "s" }
                    );
                }
                if health.pending_receipts > 0 {
                    println!(
                        "    {DETAIL} {} submitted swap receipt{} still pending on-chain",
                        health.pending_receipts,
                        if health.pending_receipts == 1 {
                            ""
                        } else {
                            "s"
                        }
                    );
                }
            }
        }
        Err(e) => println!("  {WARN} Revenue swap reconcile probe failed: {e}"),
    }

    match probe_revenue_tax_reconcile(base_url, repair).await {
        Ok(health) if health.submitted_tasks == 0 => {}
        Ok(health) => {
            println!(
                "    {OK} Submitted tax payout receipts awaiting reconciliation: {}",
                health.submitted_tasks
            );
            if !repair {
                println!(
                    "      {DETAIL} Run `roboticus mechanic --repair` to reconcile submitted tax payout receipts against chain state"
                );
            } else {
                if health.confirmed_repairs > 0 {
                    println!(
                        "    {ACTION} Confirmed {} submitted tax payout{} from chain receipts",
                        health.confirmed_repairs,
                        if health.confirmed_repairs == 1 { "" } else { "s" }
                    );
                }
                if health.failed_repairs > 0 {
                    println!(
                        "    {ACTION} Marked {} submitted tax payout{} failed from chain receipts",
                        health.failed_repairs,
                        if health.failed_repairs == 1 { "" } else { "s" }
                    );
                }
                if health.pending_receipts > 0 {
                    println!(
                        "    {DETAIL} {} submitted tax payout receipt{} still pending on-chain",
                        health.pending_receipts,
                        if health.pending_receipts == 1 { "" } else { "s" }
                    );
                }
            }
        }
        Err(e) => println!("  {WARN} Revenue tax reconcile probe failed: {e}"),
    }
}

fn run_gateway_log_and_runtime_diagnostics(
    roboticus_dir: &Path,
    channels_status: Option<&Vec<serde_json::Value>>,
    runtime_diag: Option<&serde_json::Value>,
) {
    let (_, _, WARN, _, _) = icons();
    let log_snapshot = recent_log_snapshot(&roboticus_dir.join("logs"), 350_000);
    if let Some(snapshot) = log_snapshot.as_deref() {
        let tg_404_count =
            count_occurrences(snapshot, "Telegram API error\",\"status\":\"404 Not Found");
        let tg_poll_err_count = count_occurrences(snapshot, "Telegram poll error, backing off 5s");
        let tg_401_count =
            count_occurrences(snapshot, "Telegram API error\",\"status\":\"401");
        if tg_401_count >= 3 {
            // 401 Unauthorized is a clear token/auth issue
            println!(
                "  {WARN} Detected repeated Telegram 401 Unauthorized errors."
            );
            println!("         Likely cause: invalid/revoked Telegram bot token in keystore.");
            println!(
                "         Repair: `roboticus keystore set telegram_bot_token \"<TOKEN>\"` then `roboticus daemon restart`"
            );
        } else if tg_404_count >= 3 || tg_poll_err_count >= 3 {
            // 404 / poll backoff — transport issue, not necessarily a keystore problem
            println!(
                "  {WARN} Detected repeated Telegram transport failures ({tg_404_count} 404 errors, {tg_poll_err_count} poll backoffs)."
            );
            // Cross-reference channel connectivity to refine the diagnostic
            let tg_connected = channels_status
                .and_then(|cs| cs.iter().find(|c| c.get("name").and_then(|v| v.as_str()) == Some("telegram")))
                .and_then(|tg| tg.get("connected").and_then(|v| v.as_bool()))
                .unwrap_or(false);
            if tg_connected {
                println!("         Channel currently shows connected — failures may be transient network issues.");
            } else {
                println!("         Channel is disconnected. Check Telegram bot configuration, API connectivity, and bot status.");
            }
            println!(
                "         Diagnostic: `roboticus channels status` and inspect logs for specific error patterns."
            );
        }

        let unknown_action_count = count_occurrences(snapshot, "unknown action: unknown");
        if unknown_action_count >= 3 {
            println!("  {WARN} Detected recurring scheduler failures: `unknown action: unknown`.");
            println!(
                "         Repair: run `roboticus schedule recover --all --dry-run` and re-enable trusted jobs."
            );
        }
    }

    if let Some(channels) = channels_status {
        let telegram = channels
            .iter()
            .find(|c| c.get("name").and_then(|v| v.as_str()) == Some("telegram"));
        if let Some(tg) = telegram {
            let connected = tg
                .get("connected")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let received = tg
                .get("messages_received")
                .and_then(|v| v.as_i64())
                .unwrap_or(0);
            let sent = tg
                .get("messages_sent")
                .and_then(|v| v.as_i64())
                .unwrap_or(0);
            if connected && received == 0 && sent == 0 {
                println!("  {WARN} Telegram appears connected but has zero traffic.");
                println!(
                    "         If this is unexpected, run `roboticus channels status` and inspect logs for poll/webhook errors."
                );
            }
        }
    }

    if let Some(diag) = runtime_diag {
        let total = diag
            .get("taskable_subagents_total")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        let enabled = diag
            .get("taskable_subagents_enabled")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        let running = diag
            .get("taskable_subagents_running")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        let error = diag
            .get("taskable_subagents_error")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        let hollow = diag
            .get("taskable_subagents_hollow")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);

        if total > 0 && enabled > 0 && running == 0 {
            println!(
                "  {WARN} Delegation integrity risk: {enabled} taskable subagent(s) enabled, but 0 running."
            );
            println!(
                "         Any response attributed to a subagent cannot be runtime-verified right now."
            );
            println!(
                "         Repair: start/recover subagents and re-check with `roboticus status` / `roboticus mechanic`."
            );
        } else if enabled > running {
            println!(
                "  {WARN} Delegation degradation: enabled subagents ({enabled}) exceed running ({running})."
            );
            if error > 0 {
                println!("         {error} subagent(s) currently report error state.");
            }
            if hollow > 0 {
                println!("         {hollow} subagent(s) are hollow (no fixed skills).");
            }
            println!(
                "         Recommendation: treat subagent-attributed outputs as unverified until running count recovers."
            );
        } else if hollow > 0 {
            println!(
                "  {WARN} Delegation integrity drift: {hollow} enabled taskable subagent(s) are hollow."
            );
            println!("         Repair: repopulate fixed skills and ensure agent sessions before relying on delegation.");
        }
    }

}

async fn run_gateway_allowlisted_job_recovery(
    base_url: &str,
    repair: bool,
    allow_jobs: &[String],
    fixed: &mut u32,
) -> Result<(), Box<dyn std::error::Error>> {
    let (_, ACTION, WARN, _, _) = icons();
    if !repair || allow_jobs.is_empty() {
        return Ok(());
    }
    let allowset: std::collections::HashSet<String> =
        allow_jobs.iter().map(|s| s.to_string()).collect();
    let client = super::http_client()?;
    match super::http_client()?
        .get(format!("{base_url}/api/cron/jobs"))
        .send()
        .await
    {
        Ok(resp) if resp.status().is_success() => {
            let payload: serde_json::Value = resp.json().await.unwrap_or_default();
            let jobs = payload
                .get("jobs")
                .and_then(|v| v.as_array())
                .cloned()
                .unwrap_or_default();
            let mut recovered: Vec<String> = vec![];
            for job in jobs {
                let name = job.get("name").and_then(|v| v.as_str()).unwrap_or("");
                let id = job.get("id").and_then(|v| v.as_str()).unwrap_or("");
                let paused = job
                    .get("last_status")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    == "paused_unknown_action";
                if paused
                    && allowset.contains(name)
                    && !id.is_empty()
                    && let Ok(r) = client
                        .put(format!("{base_url}/api/cron/jobs/{id}"))
                        .json(&serde_json::json!({ "enabled": true }))
                        .send()
                        .await
                    && r.status().is_success()
                {
                    recovered.push(name.to_string());
                }
            }
            if !recovered.is_empty() {
                println!(
                    "  {ACTION} Re-enabled allowlisted paused jobs: {}",
                    recovered.join(", ")
                );
                *fixed += recovered.len() as u32;
            }
        }
        Ok(resp) => println!(
            "  {WARN} Could not inspect cron jobs for allowlisted recovery (HTTP {})",
            resp.status()
        ),
        Err(e) => println!("  {WARN} Cron allowlist recovery check failed: {e}"),
    }
    Ok(())
}