supercode-harness 0.4.17

The optional native Supercode agent and tool harness
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! ORCH-14 — the `channel` noun at the OBSERVED tier: one uniform row per
//! transport + account a gateway harness is reachable on, read from the
//! harness's own config file and never written.
//!
//! Two sources, one row shape:
//!
//! * **Hermes** — the platform blocks of `HERMES_HOME/config.yaml`, keyed by
//!   `gateway.config.Platform` values (`telegram`, `slack`, `discord`,
//!   `api_server`, `webhook`, …) and carrying `enabled`, `extra.*` and the
//!   platform's own credential keys. `load_gateway_config` merges FOUR
//!   places into one map, so all four are read — see [`hermes_rows`]. Hermes
//!   also enables a platform from the ENVIRONMENT alone
//!   (`_apply_env_overrides`), so a platform with no config block but with
//!   its credential env var set is reported too — by the var's PRESENCE,
//!   never its value.
//! * **OpenClaw** — `channels.<name>` in `<openclaw home>/openclaw.json`
//!   (JSON5), with `channels.<name>.accounts` splitting a channel into one
//!   row per account id.
//!
//! **Claude Code is deliberately absent.** Its channels are MCP servers that
//! declare the channel capability over the MCP protocol at connect time
//! (`docs/composable-harness/inventory/claude-code.md` §7 "Channels": the
//! channel contract is "capability declaration, notification events, reply
//! tools, sender gating, permission relay"). Nothing in `settings.json` or
//! `.mcp.json` marks a server as a channel — `channelsEnabled` and
//! `allowedChannelPlugins` are enterprise GATES, not declarations — so
//! supercode cannot tell a channel server from any other MCP server without
//! connecting to it. Guessing a key name would fabricate rows, so
//! `claude-code` is refused with [`ChannelError::UnsupportedHarness`].
//!
//! # Secrecy
//!
//! This module never emits a token, key, secret or password, and never reads
//! one to decide anything but PRESENCE. Two mechanisms enforce that:
//!
//! * values are read only for key names on [`HERMES_ACCOUNT_KEYS`] /
//!   [`OPENCLAW_ACCOUNT_KEYS`] — public identifiers (`app_id`, `client_id`,
//!   `phone_number_id`, …), never a credential;
//! * `configured` is decided by [`is_credential_key`], which looks at the
//!   key NAME only, and by `std::env::var_os(..).is_some()` for the env
//!   fallbacks — the value never leaves the check.
//!
//! Everything here is read-only: no harness home is created or written. A
//! harness with no channel concept is refused, never answered with an empty
//! list.

use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::profiles::{read_json5, yaml_key, yaml_scalar};
use crate::{HarnessHomes, HarnessId};

/// Stable row schema shared by Rust, JSON-RPC, the SDKs, and the CLI.
pub const CHANNELS_SCHEMA: &str = "supercode.channels.v1";

/// Harnesses with a channel concept supercode reads, in product order.
/// Every other harness id is [`ChannelError::UnsupportedHarness`].
pub const CHANNEL_HARNESSES: &[&str] = &[
    HarnessId::HERMES,
    HarnessId::OPENCLAW,
    HarnessId::ORCHESTRATOR,
];

/// Key names whose VALUE is a public account identifier, safe to emit. Read
/// from a Hermes platform block's `extra` first, then its top level. Nothing
/// outside this list is ever read for a value.
///
/// Transcribed from the identifiers `gateway/config.py::_apply_env_overrides`
/// stores in `PlatformConfig.extra` (hermes-agent 0.21.0 on the build box):
/// `client_id` (DingTalk), `app_id` (Feishu, QQ, Yuanbao), `bot_id` (WeCom),
/// `corp_id` (WeCom callback), `phone_number_id` (WhatsApp Cloud), `account`
/// (Signal), `account_id` (Weixin).
pub const HERMES_ACCOUNT_KEYS: &[&str] = &[
    "account",
    "account_id",
    "app_id",
    "bot_id",
    "client_id",
    "corp_id",
    "phone_number_id",
    "user_id",
];

/// Key names whose VALUE is a public account identifier in an OpenClaw
/// channel entry. The `accounts` MAP's keys are account ids in their own
/// right and are used first; this list covers a single-account entry that
/// names its account inline.
pub const OPENCLAW_ACCOUNT_KEYS: &[&str] = &[
    "accountId",
    "account_id",
    "account",
    "teamId",
    "appId",
    "userId",
];

/// Env vars whose PRESENCE enables a Hermes platform, per platform.
///
/// Transcribed from `gateway/config.py::_ENV_ENABLE_CREDENTIALS`
/// ("Env var(s) whose presence drives each platform's env-enable branch")
/// plus the `api_server` branch, whose credential is `API_SERVER_KEY` and
/// which that map does not carry because its branch is terminal.
///
/// The bool mirrors the branch's own conjunction: WhatsApp Cloud, e-mail,
/// DingTalk, Feishu, WeCom, WeCom callback, BlueBubbles and Yuanbao require
/// BOTH of their vars (`if a and b:`); Matrix, Weixin and QQ accept EITHER
/// (`if a or b:`); single-var platforms read the same under both.
const HERMES_ENV_CREDENTIALS: &[(&str, &[&str], bool)] = &[
    ("telegram", &["TELEGRAM_BOT_TOKEN"], false),
    ("discord", &["DISCORD_BOT_TOKEN"], false),
    ("slack", &["SLACK_BOT_TOKEN"], false),
    (
        "whatsapp_cloud",
        &[
            "WHATSAPP_CLOUD_PHONE_NUMBER_ID",
            "WHATSAPP_CLOUD_ACCESS_TOKEN",
        ],
        true,
    ),
    ("signal", &["SIGNAL_HTTP_URL"], false),
    ("mattermost", &["MATTERMOST_TOKEN"], false),
    ("matrix", &["MATRIX_ACCESS_TOKEN", "MATRIX_PASSWORD"], false),
    ("homeassistant", &["HASS_TOKEN"], false),
    (
        "email",
        &[
            "EMAIL_ADDRESS",
            "EMAIL_PASSWORD",
            "EMAIL_IMAP_HOST",
            "EMAIL_SMTP_HOST",
        ],
        true,
    ),
    ("sms", &["TWILIO_ACCOUNT_SID"], false),
    (
        "dingtalk",
        &["DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"],
        true,
    ),
    ("feishu", &["FEISHU_APP_ID", "FEISHU_APP_SECRET"], true),
    ("wecom", &["WECOM_BOT_ID", "WECOM_SECRET"], true),
    (
        "wecom_callback",
        &["WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"],
        true,
    ),
    ("weixin", &["WEIXIN_TOKEN", "WEIXIN_ACCOUNT_ID"], false),
    (
        "bluebubbles",
        &["BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD"],
        true,
    ),
    ("qqbot", &["QQ_APP_ID", "QQ_CLIENT_SECRET"], false),
    ("yuanbao", &["YUANBAO_APP_ID", "YUANBAO_APP_SECRET"], true),
    ("relay", &["GATEWAY_RELAY_URL"], false),
    ("api_server", &["API_SERVER_KEY"], false),
];

/// Every key name that parses as a Hermes `Platform`, so a config key can be
/// told apart from an ordinary setting.
///
/// The built-in members of `gateway/config.py::Platform` (hermes-agent 0.21.0
/// on the build box) plus the bundled plugin adapters, which `Platform`
/// admits through `_missing_` after scanning `plugins/platforms/`. `local` is
/// omitted on purpose: it is Hermes's own CLI/TUI surface, not a transport
/// into an external identity space, and `load_gateway_config`'s shared-key
/// loop skips it too.
pub const HERMES_PLATFORMS: &[&str] = &[
    "a2a",
    "api_server",
    "bluebubbles",
    "buzz",
    "dingtalk",
    "discord",
    "email",
    "feishu",
    "google_chat",
    "homeassistant",
    "irc",
    "line",
    "matrix",
    "mattermost",
    "msgraph_webhook",
    "ntfy",
    "photon",
    "qqbot",
    "raft",
    "relay",
    "signal",
    "simplex",
    "slack",
    "sms",
    "teams",
    "telegram",
    "webhook",
    "wecom",
    "wecom_callback",
    "weixin",
    "whatsapp",
    "whatsapp_cloud",
    "yuanbao",
];

/// Whether a live probe answered, and what it said.
///
/// At the OBSERVED tier every row answers [`ChannelStatus::Unknown`]: both
/// harnesses report a channel's connection state from a RUNNING gateway
/// (`hermes gateway status`, `openclaw channels status` over the Gateway
/// socket), which is the gateway-health concept, not this one. Reporting
/// `up` from a config file would be a claim about a process nobody asked.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChannelStatus {
    /// A probe reached the channel's transport.
    Up,
    /// A probe ran and the channel's transport did not answer.
    Down,
    /// No cheap local probe exists for this harness's channels.
    Unknown,
}

impl ChannelStatus {
    /// Stable wire spelling, identical to the serde representation.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
            Self::Unknown => "unknown",
        }
    }
}

/// One transport + account a harness is reachable on, uniform across
/// harnesses.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelRow {
    /// Unique handle within the harness: the transport id for a single
    /// account (`telegram`), `<transport>/<account>` when the harness's
    /// config splits one transport across several accounts.
    pub name: String,
    /// Owning harness id.
    pub harness: String,
    /// Transport id: a Hermes `Platform` value or an OpenClaw channel key
    /// (`telegram`, `slack`, `discord`, `api_server`, `webhook`, …).
    pub kind: String,
    /// Public account id or label; `None` when the config names none. Never
    /// a token, key or secret.
    pub account: Option<String>,
    /// Whether the harness would start this channel. `None` when the config
    /// does not say and the harness's own default is not stated in a source
    /// this workspace pins.
    pub enabled: Option<bool>,
    /// Whether the entry has what the harness needs to start it, judged
    /// only by the PRESENCE of a credential key or credential env var.
    pub configured: bool,
    /// Connection state; always [`ChannelStatus::Unknown`] at this tier.
    pub status: ChannelStatus,
    /// Discovered sessions whose surface platform is this row's `kind`;
    /// `None` when discovery could not run. Rows that share a `kind` across
    /// accounts share the count — a session key names the transport, not
    /// the account.
    pub sessions: Option<u64>,
}

/// Read-only channel failures.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ChannelError {
    /// The harness has no channel concept supercode reads.
    #[error("harness `{harness}` has no channel concept (channels exist for: {})", CHANNEL_HARNESSES.join(", "))]
    UnsupportedHarness {
        /// The harness id that was asked for.
        harness: String,
    },
    /// The harness has channels, but not this one.
    #[error("`{harness}` has no channel `{name}`")]
    NotFound {
        /// Harness that was searched.
        harness: String,
        /// Channel name that was not found.
        name: String,
    },
}

/// List every channel supercode can see, optionally restricted to one
/// harness. Rows are ordered by harness (as in [`CHANNEL_HARNESSES`]) then
/// by name.
pub fn list_channels(
    homes: &HarnessHomes,
    harness: Option<&str>,
) -> Result<Vec<ChannelRow>, ChannelError> {
    if let Some(harness) = harness {
        if !CHANNEL_HARNESSES.contains(&harness) {
            return Err(ChannelError::UnsupportedHarness {
                harness: harness.to_string(),
            });
        }
    }
    let mut rows = Vec::new();
    for id in CHANNEL_HARNESSES {
        if harness.is_some_and(|requested| requested != *id) {
            continue;
        }
        let sessions = session_counts(homes, id);
        match *id {
            HarnessId::HERMES => rows.extend(hermes_rows(
                HarnessId::HERMES,
                homes.hermes.parent().unwrap_or(Path::new(".")),
                sessions.as_ref(),
                true,
            )),
            HarnessId::OPENCLAW => rows.extend(openclaw_rows(&homes.openclaw, sessions.as_ref())),
            // ORC-7: the orchestrator declares its adapters in each profile
            // folder's `platforms:` block, Hermes-shaped
            // (`docs/ORCHESTRATOR-IR.md` §6), so the same reader runs per
            // folder. Its env fallback is OFF: a credential is a
            // `{dotenv: NAME}` / `{env: NAME}` REF in the folder, so an
            // environment variable Hermes happens to read never conjures a
            // channel the orchestrator never declared. A ref is a MAP under a
            // credential-shaped key, which `is_credential_key` already counts
            // as configured by name — the value is never read.
            HarnessId::ORCHESTRATOR => {
                for (_, dir) in crate::orchestrator_profile_dirs(&homes.orchestrator) {
                    rows.extend(hermes_rows(
                        HarnessId::ORCHESTRATOR,
                        &dir,
                        sessions.as_ref(),
                        false,
                    ));
                }
            }
            _ => {}
        }
    }
    Ok(rows)
}

/// Read one channel's row by harness and name. `status` is
/// [`ChannelStatus::Unknown`] at this tier for every harness; the verb
/// exists so the noun is complete and the driven tier has one door to fill.
pub fn channel_status(
    homes: &HarnessHomes,
    harness: &str,
    name: &str,
) -> Result<ChannelRow, ChannelError> {
    list_channels(homes, Some(harness))?
        .into_iter()
        .find(|row| row.name == name)
        .ok_or_else(|| ChannelError::NotFound {
            harness: harness.to_string(),
            name: name.to_string(),
        })
}

// ---------------------------------------------------------------------------
// Session counts
// ---------------------------------------------------------------------------

/// Sessions per surface platform, from the SAME discovery rows
/// `supercode sessions list` shows. `None` means discovery failed, which is
/// unknown — never zero.
fn session_counts(homes: &HarnessHomes, harness: &str) -> Option<BTreeMap<String, u64>> {
    let query = crate::DiscoveryQuery {
        harnesses: vec![HarnessId::new(harness)],
        homes: homes.clone(),
        ..Default::default()
    };
    let sessions = crate::HarnessCatalog::new().discover(&query).ok()?;
    let mut counts: BTreeMap<String, u64> = BTreeMap::new();
    for session in sessions {
        if let Some(platform) = session
            .nouns
            .surface
            .as_ref()
            .and_then(|surface| surface.platform.as_ref())
        {
            *counts.entry(platform.clone()).or_default() += 1;
        }
    }
    Some(counts)
}

// ---------------------------------------------------------------------------
// Credentials — presence only
// ---------------------------------------------------------------------------

/// Whether a key NAME is a credential. Used to decide `configured` without
/// ever reading the value, so a config full of tokens produces booleans and
/// nothing else. Matches the credential spellings both harnesses write:
/// `token`, `api_key`, `botToken`, `appToken`, `access_token`, `app_secret`,
/// `client_secret`, `password`, and api_server's bare `key`.
fn is_credential_key(key: &str) -> bool {
    let lower = key.to_ascii_lowercase();
    ["token", "key", "secret", "password", "credential"]
        .iter()
        .any(|marker| lower.ends_with(marker))
}

/// Whether the env credential(s) for a Hermes platform are present. Only
/// presence is tested; no value is read. `None` means Hermes lists no env
/// credential for this platform at all.
fn hermes_env_credentials_present(platform: &str) -> Option<bool> {
    let (_, vars, all) = HERMES_ENV_CREDENTIALS
        .iter()
        .find(|(name, _, _)| *name == platform)?;
    let present = |name: &&str| std::env::var_os(name).is_some();
    Some(if *all {
        vars.iter().all(present)
    } else {
        vars.iter().any(present)
    })
}

// ---------------------------------------------------------------------------
// Hermes
// ---------------------------------------------------------------------------

/// Hermes channels are the platform blocks of `HERMES_HOME/config.yaml`.
///
/// `load_gateway_config` merges FOUR places into one platform map, later
/// winning (`gateway/config.py::_merge_platform_map` and the shared-key loop
/// after it) — verified against the real `~/.hermes/config.yaml` on the build
/// box, which writes NONE of the first three and would have read as empty had
/// only the documented `platforms:` key been honoured:
///
/// 1. `gateway.platforms.<platform>`
/// 2. `platforms.<platform>` (the shape the ORCH-5 probe writes)
/// 3. `gateway.<platform>` for any key that parses as a `Platform` value
/// 4. a TOP-LEVEL `<platform>:` block, which is the only one whose `enabled`
///    is treated as explicit (`enabled_was_explicit = _cfg_toplevel and …`)
///
/// [`HERMES_PLATFORMS`] is what makes 3 and 4 decidable: a key is a platform
/// block only when its name is a `Platform` value. A platform Hermes would
/// enable from the environment alone (`_apply_env_overrides`) is listed too,
/// so an env-only install is not reported as empty.
///
/// `state_db` is `HarnessHomes::hermes` (`HERMES_HOME/state.db`).
fn hermes_rows(
    harness: &str,
    home: &Path,
    sessions: Option<&BTreeMap<String, u64>>,
    env_fallback: bool,
) -> Vec<ChannelRow> {
    let config = std::fs::read_to_string(home.join("config.yaml")).unwrap_or_default();
    let platforms = hermes_platform_blocks(&config);

    let mut names: Vec<String> = platforms.iter().map(|(name, _)| name.clone()).collect();
    if env_fallback {
        for (platform, _, _) in HERMES_ENV_CREDENTIALS {
            if hermes_env_credentials_present(platform) == Some(true)
                && !names.iter().any(|name| name == platform)
            {
                names.push((*platform).to_string());
            }
        }
    }
    names.sort();
    names.dedup();

    names
        .into_iter()
        .map(|name| {
            // Every place that declares this platform, lowest precedence
            // first, so `enabled` reads the last one that says anything and
            // `configured` / `account` see the union.
            let blocks: Vec<&String> = platforms
                .iter()
                .filter(|(platform, _)| *platform == name)
                .map(|(_, block)| block)
                .collect();
            // The `extra:` maps first, so an account id a platform bridges
            // there wins over a same-named key at the block's top level.
            let scopes: Vec<String> = blocks
                .iter()
                .map(|block| yaml_root_child(block, "extra"))
                .chain(blocks.iter().map(|block| (*block).clone()))
                .collect();
            let env_present = env_fallback
                .then(|| hermes_env_credentials_present(&name))
                .flatten();
            // `PlatformConfig.enabled` defaults to false, and
            // `_enable_from_env` flips it on when the platform's credentials
            // are in the environment and `enabled:` is not explicitly false.
            let enabled = match blocks
                .iter()
                .filter_map(|block| yaml_scalar(block, "enabled"))
                .next_back()
            {
                Some(explicit) => explicit == "true",
                None => env_present == Some(true),
            };
            let configured = env_present == Some(true)
                || scopes
                    .iter()
                    .flat_map(|scope| yaml_block_keys(scope))
                    .any(|key| is_credential_key(&key))
                // A platform Hermes lists no credential for authenticates
                // some other way (session files, a bound port): declaring it
                // is all it needs.
                || env_present.is_none();
            ChannelRow {
                name: name.clone(),
                harness: harness.to_string(),
                kind: name.clone(),
                account: HERMES_ACCOUNT_KEYS
                    .iter()
                    .find_map(|key| scopes.iter().find_map(|scope| yaml_scalar(scope, key)))
                    .filter(|value| !value.is_empty()),
                enabled: Some(enabled),
                configured,
                status: ChannelStatus::Unknown,
                sessions: sessions.map(|counts| counts.get(&name).copied().unwrap_or(0)),
            }
        })
        .collect()
}

/// Every `(platform, block)` pair the config declares, in Hermes's own merge
/// order — `gateway.platforms.*`, then `platforms.*`, then Platform-named
/// keys under `gateway:`, then top-level Platform-named blocks. A platform
/// declared in several places appears once per place, so the caller can take
/// the last `enabled` and the union of the keys.
fn hermes_platform_blocks(config: &str) -> Vec<(String, String)> {
    let is_platform = |name: &String| HERMES_PLATFORMS.contains(&name.as_str());
    let top = yaml_block_names(config);
    let gateway = yaml_root_child(config, "gateway");
    let gateway_children = yaml_block_names(&gateway);

    let mut blocks = yaml_block_names(&yaml_root_child(&gateway, "platforms"));
    blocks.extend(yaml_block_names(&yaml_root_child(config, "platforms")));
    blocks.extend(
        gateway_children
            .into_iter()
            .filter(|(name, _)| is_platform(name)),
    );
    blocks.extend(top.into_iter().filter(|(name, _)| is_platform(name)));
    blocks
}

/// The body of `key` at the block's OWN outermost indent, empty when the
/// block has no such key.
///
/// `profiles::yaml_child` matches its key at ANY indent, which is right for
/// the one nested path ORCH-10 reads but wrong here: a config with both
/// `gateway.platforms:` and a top-level `platforms:` would answer the first
/// occurrence for both, silently dropping one of Hermes's four merge
/// sources.
fn yaml_root_child(block: &str, key: &str) -> String {
    yaml_block_names(block)
        .into_iter()
        .find(|(name, _)| name == key)
        .map(|(_, body)| body)
        .unwrap_or_default()
}

/// The immediate children of a YAML block — every key at the block's own
/// outermost indent with the lines nested under it — in declaration order.
/// One pass, so a key nested deeper can never be mistaken for a child.
fn yaml_block_names(block: &str) -> Vec<(String, String)> {
    let mut children: Vec<(String, String)> = Vec::new();
    let Some(root) = yaml_root_indent(block) else {
        return children;
    };
    let mut current: Option<String> = None;
    for line in block.lines() {
        let trimmed = line.trim_start();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let indent = line.len() - trimmed.len();
        if indent > root {
            if let Some(key) = &current {
                if let Some((_, body)) = children.iter_mut().find(|(name, _)| name == key) {
                    body.push_str(line);
                    body.push('\n');
                }
            }
            continue;
        }
        current = yaml_key(trimmed).map(str::to_string);
        if let Some(key) = &current {
            if !children.iter().any(|(name, _)| name == key) {
                children.push((key.clone(), String::new()));
            }
        }
    }
    children
}

/// The key names at a YAML block's own outermost indent. Names only — this
/// is how `configured` is judged without reading a value.
fn yaml_block_keys(block: &str) -> Vec<String> {
    yaml_block_names(block)
        .into_iter()
        .map(|(name, _)| name)
        .collect()
}

/// The outermost indent of a block's live (non-blank, non-comment) lines.
fn yaml_root_indent(block: &str) -> Option<usize> {
    block
        .lines()
        .filter(|line| {
            let trimmed = line.trim_start();
            !trimmed.is_empty() && !trimmed.starts_with('#')
        })
        .map(|line| line.len() - line.trim_start().len())
        .min()
}

// ---------------------------------------------------------------------------
// OpenClaw
// ---------------------------------------------------------------------------

/// OpenClaw channels are `channels.<name>` entries in
/// `<openclaw home>/openclaw.json` (read as JSON5), the file
/// `openclaw channels add|remove|login|logout` writes and
/// `openclaw channels list` reads. The shape is verified against the real
/// `~/.openclaw/openclaw.json` on the build box: `channels.slack.enabled`
/// plus the channel's own credential keys. `channels.<name>.accounts` splits
/// one channel into one row per account id.
fn openclaw_rows(home: &Path, sessions: Option<&BTreeMap<String, u64>>) -> Vec<ChannelRow> {
    let config = read_json5(&home.join("openclaw.json"));
    let Some(channels) = config.pointer("/channels").and_then(Value::as_object) else {
        return Vec::new();
    };
    let mut rows = Vec::new();
    for (kind, entry) in channels {
        let count = sessions.map(|counts| counts.get(kind).copied().unwrap_or(0));
        let accounts = account_entries(entry);
        if accounts.is_empty() {
            rows.push(openclaw_row(kind, kind, entry, None, entry, count));
            continue;
        }
        for (id, account) in accounts {
            rows.push(openclaw_row(
                &format!("{kind}/{id}"),
                kind,
                entry,
                Some(id),
                &account,
                count,
            ));
        }
    }
    rows.sort_by(|left, right| left.name.cmp(&right.name));
    rows
}

/// One OpenClaw row. `entry` is the channel block and `scope` the block whose
/// keys decide `enabled` / `configured` — the account's own block when the
/// channel declares accounts, else the channel block itself.
fn openclaw_row(
    name: &str,
    kind: &str,
    entry: &Value,
    account: Option<String>,
    scope: &Value,
    sessions: Option<u64>,
) -> ChannelRow {
    let account = account.or_else(|| {
        OPENCLAW_ACCOUNT_KEYS
            .iter()
            .find_map(|key| entry.get(*key).and_then(Value::as_str))
            .map(str::to_string)
    });
    // Enablement comes from the account's own entry first, then the
    // channel's. `None` is honest: openclaw's default for an entry that
    // omits `enabled` is not stated in any source this workspace pins.
    let enabled = scope
        .get("enabled")
        .or_else(|| entry.get("enabled"))
        .and_then(Value::as_bool);
    let configured = has_credential_key(scope) || has_credential_key(entry);
    ChannelRow {
        name: name.to_string(),
        harness: HarnessId::OPENCLAW.to_string(),
        kind: kind.to_string(),
        account,
        enabled,
        configured,
        status: ChannelStatus::Unknown,
        sessions,
    }
}

/// `channels.<name>.accounts` as `(accountId, entry)` pairs, sorted by id.
/// Both the object-keyed map and an array of `{ id | accountId }` objects
/// are read; anything else means "this channel declares no accounts".
fn account_entries(entry: &Value) -> Vec<(String, Value)> {
    let mut accounts: Vec<(String, Value)> = match entry.get("accounts") {
        Some(Value::Object(map)) => map
            .iter()
            .map(|(id, account)| (id.clone(), account.clone()))
            .collect(),
        Some(Value::Array(list)) => list
            .iter()
            .filter_map(|account| {
                OPENCLAW_ACCOUNT_KEYS
                    .iter()
                    .find_map(|key| account.get(*key).and_then(Value::as_str))
                    .or_else(|| account.get("id").and_then(Value::as_str))
                    .map(|id| (id.to_string(), account.clone()))
            })
            .collect(),
        _ => Vec::new(),
    };
    accounts.sort_by(|left, right| left.0.cmp(&right.0));
    accounts
}

/// Whether a JSON object declares a credential, by key NAME only.
fn has_credential_key(value: &Value) -> bool {
    value
        .as_object()
        .is_some_and(|map| map.keys().any(|key| is_credential_key(key)))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unsupported_harness_is_refused_not_silently_empty() {
        let error = list_channels(&HarnessHomes::default(), Some(HarnessId::CLAUDE_CODE))
            .expect_err("claude-code channels are MCP-protocol declarations");
        assert_eq!(
            error,
            ChannelError::UnsupportedHarness {
                harness: HarnessId::CLAUDE_CODE.to_string()
            }
        );
    }

    /// Credential detection is by key NAME, so no value is ever read.
    #[test]
    fn credential_keys_are_recognised_by_name_in_both_spellings() {
        for key in [
            "token",
            "api_key",
            "botToken",
            "appToken",
            "access_token",
            "app_secret",
            "client_secret",
            "password",
            "key",
        ] {
            assert!(is_credential_key(key), "`{key}` is a credential key");
        }
        for key in [
            "enabled",
            "port",
            "host",
            "app_id",
            "reply_to_mode",
            "extra",
        ] {
            assert!(!is_credential_key(key), "`{key}` is not a credential key");
        }
    }

    #[test]
    fn yaml_block_reader_lists_platform_entries_and_their_keys() {
        let config = "platforms:\n  telegram:\n    enabled: true\n    token: \"SECRET\"\n  api_server:\n    enabled: false\n    extra:\n      key: \"SECRET\"\n      port: 8642\ngateway:\n  port: 1\n";
        let platforms = yaml_root_child(config, "platforms");
        let names: Vec<String> = yaml_block_keys(&platforms);
        assert_eq!(names, ["telegram", "api_server"]);
        let api = yaml_root_child(&platforms, "api_server");
        assert_eq!(yaml_block_keys(&api), ["enabled", "extra"]);
        assert_eq!(
            yaml_block_keys(&yaml_root_child(&api, "extra")),
            ["key", "port"]
        );
    }

    /// Receipt-driven: the real `~/.hermes/config.yaml` on the build box
    /// writes NO top-level `platforms:` key, so a reader that honoured only
    /// the documented shape would report an install with channels as having
    /// none. All four places `load_gateway_config` merges must read, and a
    /// key that is not a `Platform` value must not become a channel.
    #[test]
    fn every_hermes_platform_block_shape_is_read() {
        let config = concat!(
            "gateway:\n",
            "  platforms:\n",
            "    discord:\n",
            "      enabled: true\n",
            "      token: \"x\"\n",
            "  api_server:\n",
            "    enabled: true\n",
            "    extra:\n",
            "      key: \"x\"\n",
            "  profile_routes:\n",
            "    - platform: slack\n",
            "platforms:\n",
            "  webhook:\n",
            "    enabled: true\n",
            "telegram:\n",
            "  enabled: false\n",
            "memory:\n",
            "  enabled: true\n",
        );
        let blocks = hermes_platform_blocks(config);
        let names: Vec<&str> = blocks.iter().map(|(name, _)| name.as_str()).collect();
        assert_eq!(names, ["discord", "webhook", "api_server", "telegram"]);
        // `memory` and `profile_routes` are settings, not transports.
        assert!(!names.contains(&"memory"), "{names:?}");
        assert!(!names.contains(&"profile_routes"), "{names:?}");
    }

    /// An account map splits one channel into one row per account, and the
    /// account id is the row's handle — never a token.
    #[test]
    fn openclaw_accounts_split_a_channel_into_one_row_each() {
        let entry: Value = serde_json::from_str(
            r#"{"enabled": true, "accounts": {"T2": {"botToken": "x"}, "T1": {"enabled": false}}}"#,
        )
        .unwrap();
        let ids: Vec<String> = account_entries(&entry)
            .into_iter()
            .map(|(id, _)| id)
            .collect();
        assert_eq!(ids, ["T1", "T2"]);
        let rows = openclaw_rows(Path::new("/nonexistent-openclaw-home"), None);
        assert!(rows.is_empty(), "a missing config declares no channels");
    }
}