supercode-harness 0.4.14

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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
//! ORCH-10 — the `profile` noun at the OBSERVED tier: one uniform row for
//! every named, routable config home supercode can see, read from each
//! harness's own files and never written.
//!
//! Four sources, four kinds:
//!
//! * `preset` — supercode's own [`crate::presets::RESERVED_PRESET_NAMES`];
//!   the analog of a Codex profile for supercode itself (no home directory).
//! * `codex_profile` — `[profiles.<name>]` tables in `$CODEX_HOME/config.toml`,
//!   with the top-level `profile = "<name>"` naming the default.
//! * `hermes_profile` — `HERMES_HOME/profiles/<name>/` directories plus the
//!   implicit `default` profile (HERMES_HOME itself), routed by
//!   `gateway.profile_routes` in `HERMES_HOME/config.yaml` and partitioned in
//!   `state.db` by the `profile_name` column.
//! * `openclaw_agent` — `<openclaw home>/agents/<id>/` directories plus the
//!   `agents.entries` map in `openclaw.json`, routed by `bindings[]`.
//!
//! Everything here is read-only: no harness home is created, written, or
//! migrated. A harness with no profile concept is refused with
//! [`ProfileError::UnsupportedHarness`], never a silent empty list.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

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

use crate::{HarnessHomes, HarnessId};

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

/// Harnesses that have a profile concept supercode reads, in product order.
/// Every other harness id is [`ProfileError::UnsupportedHarness`].
pub const PROFILE_HARNESSES: &[&str] = &[
    HarnessId::SUPERCODE,
    HarnessId::CODEX,
    HarnessId::HERMES,
    HarnessId::OPENCLAW,
    HarnessId::ORCHESTRATOR,
];

/// Hermes's implicit profile: HERMES_HOME itself, the `profile_name IS NULL`
/// partition of `state.db` and the target when no route matches.
pub const HERMES_DEFAULT_PROFILE: &str = "default";

/// OpenClaw's conventional default agent — the id behind the
/// `agent:<id>:main` session key and the `agents/main` config home. Used only
/// when no entry declares `default: true`.
pub const OPENCLAW_DEFAULT_AGENT: &str = "main";

/// Which harness concept a row came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProfileKind {
    /// A supercode built-in preset.
    Preset,
    /// A `[profiles.<name>]` table in `$CODEX_HOME/config.toml`.
    CodexProfile,
    /// A `HERMES_HOME/profiles/<name>` config home.
    HermesProfile,
    /// An `<openclaw home>/agents/<id>` config home.
    OpenclawAgent,
    /// An orchestrator profile FOLDER: the root of
    /// `SUPERCODE_ORCHESTRATOR_HOME` for `default`, `profiles/<name>/`
    /// otherwise (`docs/ORCHESTRATOR-IR.md` §6).
    OrchestratorProfile,
}

impl ProfileKind {
    /// Stable wire spelling, identical to the serde representation.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Preset => "preset",
            Self::CodexProfile => "codex_profile",
            Self::HermesProfile => "hermes_profile",
            Self::OpenclawAgent => "openclaw_agent",
            Self::OrchestratorProfile => "orchestrator_profile",
        }
    }
}

/// One named config home, uniform across harnesses.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProfileRow {
    /// Profile / agent / preset name, unique within its harness.
    pub name: String,
    /// Owning harness id.
    pub harness: String,
    /// Which harness concept this row came from.
    pub kind: ProfileKind,
    /// The profile's own directory, when it has one.
    pub home: Option<PathBuf>,
    /// Whether the harness routes here when nothing more specific matches.
    pub default: bool,
    /// Routing entries that target this profile; `None` when the harness's
    /// routing table could not be read (no config file), not zero.
    pub routes: Option<u64>,
    /// Sessions this profile owns; `None` when the store could not be read.
    pub sessions: Option<u64>,
    /// Model the profile pins, when it pins one.
    pub model: Option<String>,
    /// The worker harness this profile runs its conversations on, when the
    /// harness's profile concept has one. Only the orchestrator does: its
    /// `worker:` block names any registry id (`docs/ORCHESTRATOR-IR.md`
    /// §2.2). Additive on the wire, like every other optional row field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worker: Option<String>,
}

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

/// List every profile supercode can see, optionally restricted to one
/// harness. Rows are ordered by harness (as in [`PROFILE_HARNESSES`]) then
/// by name.
pub fn list_profiles(
    homes: &HarnessHomes,
    harness: Option<&str>,
) -> Result<Vec<ProfileRow>, ProfileError> {
    if let Some(harness) = harness {
        if !PROFILE_HARNESSES.contains(&harness) {
            return Err(ProfileError::UnsupportedHarness {
                harness: harness.to_string(),
            });
        }
    }
    let mut rows = Vec::new();
    for id in PROFILE_HARNESSES {
        if harness.is_some_and(|requested| requested != *id) {
            continue;
        }
        match *id {
            HarnessId::SUPERCODE => rows.extend(preset_rows()),
            HarnessId::CODEX => rows.extend(codex_rows(&homes.codex)),
            HarnessId::HERMES => rows.extend(hermes_rows(&homes.hermes)),
            HarnessId::OPENCLAW => rows.extend(openclaw_rows(&homes.openclaw)),
            HarnessId::ORCHESTRATOR => rows.extend(orchestrator_rows(&homes.orchestrator)),
            _ => {}
        }
    }
    Ok(rows)
}

/// Read one profile by harness and name.
pub fn get_profile(
    homes: &HarnessHomes,
    harness: &str,
    name: &str,
) -> Result<ProfileRow, ProfileError> {
    list_profiles(homes, Some(harness))?
        .into_iter()
        .find(|row| row.name == name)
        .ok_or_else(|| ProfileError::NotFound {
            harness: harness.to_string(),
            name: name.to_string(),
        })
}

// ---------------------------------------------------------------------------
// supercode presets
// ---------------------------------------------------------------------------

/// supercode's own analog of a named profile. A preset is compiled in, so it
/// has no home directory and no store to count sessions from; `default` is
/// the preset the CLI extends when a config names none.
fn preset_rows() -> Vec<ProfileRow> {
    let mut rows: Vec<ProfileRow> = crate::presets::RESERVED_PRESET_NAMES
        .iter()
        .map(|name| ProfileRow {
            name: (*name).to_string(),
            harness: HarnessId::SUPERCODE.to_string(),
            kind: ProfileKind::Preset,
            home: None,
            default: *name == "supercode-default",
            routes: None,
            sessions: None,
            model: crate::presets::lookup(name)
                .and_then(|text| toml::from_str::<toml::Value>(text).ok())
                .and_then(|doc| {
                    doc.get("core")
                        .and_then(|core| core.get("model"))
                        .and_then(toml::Value::as_str)
                        .map(str::to_string)
                }),
            worker: None,
        })
        .collect();
    rows.sort_by(|left, right| left.name.cmp(&right.name));
    rows
}

// ---------------------------------------------------------------------------
// Codex
// ---------------------------------------------------------------------------

/// Codex profiles are `[profiles.<name>]` tables in `$CODEX_HOME/config.toml`
/// (`inventory/codex.md` §6), selected at launch with `-p/--profile`. They
/// are tables in ONE file, not directories, so `home` is null; the top-level
/// `profile = "<name>"` key names the one Codex uses by default.
///
/// `sessions_root` is `HarnessHomes::codex` (`$CODEX_HOME/sessions`).
fn codex_rows(sessions_root: &Path) -> Vec<ProfileRow> {
    let Some(codex_home) = sessions_root.parent() else {
        return Vec::new();
    };
    let Ok(text) = std::fs::read_to_string(codex_home.join("config.toml")) else {
        return Vec::new();
    };
    let Ok(doc) = toml::from_str::<toml::Value>(&text) else {
        return Vec::new();
    };
    let selected = doc.get("profile").and_then(toml::Value::as_str);
    let Some(profiles) = doc.get("profiles").and_then(toml::Value::as_table) else {
        return Vec::new();
    };
    profiles
        .iter()
        .map(|(name, table)| ProfileRow {
            name: name.clone(),
            harness: HarnessId::CODEX.to_string(),
            kind: ProfileKind::CodexProfile,
            home: None,
            default: selected == Some(name.as_str()),
            routes: None,
            sessions: None,
            model: table
                .get("model")
                .and_then(toml::Value::as_str)
                .map(str::to_string),
            worker: None,
        })
        .collect()
}

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

/// Hermes profiles are config HOMES under `HERMES_HOME/profiles/<name>`, plus
/// the implicit `default` profile which is HERMES_HOME itself. All profiles
/// share one `state.db`, partitioned by the `profile_name` column (NULL for
/// the default profile), and routing lives in `gateway.profile_routes`.
///
/// `state_db` is `HarnessHomes::hermes` (`HERMES_HOME/state.db`).
fn hermes_rows(state_db: &Path) -> Vec<ProfileRow> {
    let Some(home) = state_db.parent() else {
        return Vec::new();
    };
    if !home.is_dir() {
        return Vec::new();
    }
    let config = std::fs::read_to_string(home.join("config.yaml")).ok();
    let gateway = yaml_child(config.as_deref().unwrap_or_default(), "gateway");
    let profile_routes = yaml_child(&gateway, "profile_routes");
    let routes = config
        .as_ref()
        .map(|_| count_yaml_route_targets(&profile_routes));

    let mut names = vec![HERMES_DEFAULT_PROFILE.to_string()];
    if let Ok(entries) = std::fs::read_dir(home.join("profiles")) {
        let mut found: Vec<String> = entries
            .flatten()
            .filter(|entry| entry.path().is_dir())
            .filter_map(|entry| entry.file_name().into_string().ok())
            .collect();
        found.sort();
        names.extend(found);
    }
    names
        .into_iter()
        .map(|name| {
            let is_default = name == HERMES_DEFAULT_PROFILE;
            let profile_home = if is_default {
                home.to_path_buf()
            } else {
                home.join("profiles").join(&name)
            };
            let model = if is_default {
                config.as_deref().and_then(hermes_model)
            } else {
                std::fs::read_to_string(profile_home.join("config.yaml"))
                    .ok()
                    .as_deref()
                    .and_then(hermes_model)
            };
            ProfileRow {
                name: name.clone(),
                harness: HarnessId::HERMES.to_string(),
                kind: ProfileKind::HermesProfile,
                home: Some(profile_home),
                default: is_default,
                routes: routes
                    .as_ref()
                    .map(|counts| counts.get(name.as_str()).copied().unwrap_or(0)),
                sessions: hermes_session_count(state_db, (!is_default).then_some(name.as_str())),
                model,
                worker: None,
            }
        })
        .collect()
}

// ---------------------------------------------------------------------------
// The orchestrator
// ---------------------------------------------------------------------------

/// The orchestrator's profiles are FOLDERS (`docs/ORCHESTRATOR-IR.md` §6):
/// the root of `SUPERCODE_ORCHESTRATOR_HOME` is the implicit `default`
/// profile and each `profiles/<name>/` is a named one. Every folder is a
/// complete home — its own `config.yaml`, `cron/`, and `state.db` — so unlike
/// Hermes there is no shared store to partition.
///
/// Two columns differ from Hermes's and are read from the folder's own
/// `worker:` block: `worker` (the harness this profile's conversations run
/// on) and `model` (the model that worker is started with).
fn orchestrator_rows(root: &Path) -> Vec<ProfileRow> {
    let dirs = crate::orchestrator_profile_dirs(root);
    // Routes are declared per folder and target profile NAMES, so the count
    // for a profile is over every folder's table.
    let mut routes: Option<BTreeMap<String, u64>> = None;
    for (_, dir) in &dirs {
        let Ok(config) = std::fs::read_to_string(dir.join("config.yaml")) else {
            continue;
        };
        let block = yaml_child(&yaml_child(&config, "gateway"), "profile_routes");
        let counts = routes.get_or_insert_with(BTreeMap::new);
        for (target, found) in count_yaml_route_targets(&block) {
            *counts.entry(target).or_default() += found;
        }
    }
    dirs.into_iter()
        .map(|(name, dir)| {
            let config = std::fs::read_to_string(dir.join("config.yaml")).ok();
            let worker = config.as_deref().map(|text| yaml_child(text, "worker"));
            ProfileRow {
                name: name.clone(),
                harness: HarnessId::ORCHESTRATOR.to_string(),
                kind: ProfileKind::OrchestratorProfile,
                default: name == HERMES_DEFAULT_PROFILE,
                routes: routes
                    .as_ref()
                    .map(|counts| counts.get(name.as_str()).copied().unwrap_or(0)),
                sessions: orchestrator_binding_count(&dir.join("state.db")),
                model: worker
                    .as_deref()
                    .and_then(|block| yaml_scalar(block, "model")),
                worker: worker
                    .as_deref()
                    .and_then(|block| yaml_scalar(block, "harness")),
                home: Some(dir),
            }
        })
        .collect()
}

/// Conversations one orchestrator profile holds: rows in its own `bindings`
/// table. An unreadable or absent store answers `None` — unknown, never zero.
fn orchestrator_binding_count(state_db: &Path) -> Option<u64> {
    let connection = Connection::open_with_flags(
        state_db,
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
    )
    .ok()?;
    let count: i64 = connection
        .query_row("SELECT COUNT(*) FROM bindings", [], |row| row.get(0))
        .ok()?;
    Some(count.max(0) as u64)
}

/// The model a Hermes `config.yaml` pins.
///
/// Hermes writes it as a `model:` BLOCK whose `default:` key holds the id —
/// and its own shipped config says of that block: "Both `default` and `model`
/// work as the key name here", so both are read. A bare top-level
/// `model: <id>` scalar is accepted as well.
fn hermes_model(config: &str) -> Option<String> {
    if let Some(pinned) = yaml_scalar(config, "model") {
        return Some(pinned);
    }
    let block = yaml_child(config, "model");
    yaml_scalar(&block, "default").or_else(|| yaml_scalar(&block, "model"))
}

/// Count the sessions one Hermes profile owns. `None` names the implicit
/// default profile, whose rows carry `profile_name IS NULL`. An unreadable
/// store answers `None` — unknown, never zero.
fn hermes_session_count(state_db: &Path, profile: Option<&str>) -> Option<u64> {
    let connection = Connection::open_with_flags(
        state_db,
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
    )
    .ok()?;
    let count: i64 = match profile {
        Some(name) => connection
            .query_row(
                "SELECT COUNT(*) FROM sessions WHERE profile_name = ?1",
                [name],
                |row| row.get(0),
            )
            .ok()?,
        None => connection
            .query_row(
                "SELECT COUNT(*) FROM sessions WHERE profile_name IS NULL",
                [],
                |row| row.get(0),
            )
            .ok()?,
    };
    Some(count.max(0) as u64)
}

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

/// OpenClaw agents are config homes under `<openclaw home>/agents/<id>`, each
/// with its own store, declared in `openclaw.json` under `agents.list` and
/// routed by `bindings[]` (`inventory/orchestration.md` rows 2 and 4). The
/// union of the directories and the declared entries is the row set: an
/// entry with no directory yet is still a routable agent, and a directory
/// with no entry is still a config home holding sessions.
///
/// One directory is NOT an agent: the empty shell OpenClaw's own
/// `agents delete` leaves behind. Measured at the pin (receipt
/// `orch21-openclaw-profiles-receipt-2026-09-03.json`), that verb prunes the
/// config entry, `agents/<id>/agent` and `agents/<id>/sessions` but leaves
/// `agents/<id>` itself in place; `openclaw agents list` reports it gone, so a
/// row for it would be supercode contradicting the harness about its own
/// store.
///
/// `agents.list` is the key a real install writes — verified against
/// `~/.openclaw/openclaw.json` on the build box, an array of
/// `{ id, name, workspace, agentDir, tools }` — with `agents.entries` read as
/// the object-keyed alternative.
fn openclaw_rows(home: &Path) -> Vec<ProfileRow> {
    let config_path = home.join("openclaw.json");
    let config = read_json5(&config_path);
    let entries = config.pointer("/agents/list").map(entry_map);
    let bindings = config.pointer("/bindings").and_then(Value::as_array);
    let entries = entries.or_else(|| config.pointer("/agents/entries").map(entry_map));
    // An unreadable config means the routing table is UNKNOWN; a readable one
    // with no `bindings[]` array declares no routes, which is zero.
    let route_counts = (!config.is_null()).then(|| {
        bindings
            .map(|list| count_binding_targets(list))
            .unwrap_or_default()
    });

    let declared_ids: Vec<&str> = entries
        .iter()
        .flatten()
        .map(|(id, _)| id.as_str())
        .collect();
    let mut names: Vec<String> = Vec::new();
    if let Ok(dirs) = std::fs::read_dir(home.join("agents")) {
        names.extend(
            dirs.flatten()
                .filter(|entry| entry.path().is_dir())
                .filter(|entry| {
                    // An undeclared, EMPTY directory is the shell
                    // `openclaw agents delete` leaves behind, not an agent.
                    declared_ids.contains(&entry.file_name().to_string_lossy().as_ref())
                        || !directory_is_empty(&entry.path())
                })
                .filter_map(|entry| entry.file_name().into_string().ok()),
        );
    }
    if let Some(declared) = &entries {
        names.extend(declared.iter().map(|(id, _)| id.clone()));
    }
    names.sort();
    names.dedup();

    // `default` is whichever entry declares it. Real configs declare none, so
    // the fallbacks are OpenClaw's own conventions: the agent literally named
    // `main` (the id behind the `agent:<id>:main` session key and the
    // `agents/main` home), then the first declared entry.
    let declared_default = entries.as_ref().and_then(|entries| {
        entries
            .iter()
            .find(|(_, entry)| entry.get("default").and_then(Value::as_bool) == Some(true))
            .map(|(id, _)| id.clone())
            .or_else(|| {
                entries
                    .iter()
                    .find(|(id, _)| id == OPENCLAW_DEFAULT_AGENT)
                    .map(|(id, _)| id.clone())
            })
            .or_else(|| entries.first().map(|(id, _)| id.clone()))
    });

    names
        .into_iter()
        .map(|name| {
            let agent_home = home.join("agents").join(&name);
            // The same filter OpenClaw discovery applies, so the count a row
            // reports is the count `sessions list` would show for the agent.
            let sessions = std::fs::read_dir(agent_home.join("sessions"))
                .ok()
                .map(|dir| {
                    dir.flatten()
                        .filter(|entry| {
                            let name = entry.file_name();
                            let name = name.to_string_lossy();
                            name.ends_with(".jsonl") && !name.ends_with(".trajectory.jsonl")
                        })
                        .count() as u64
                });
            let entry = entries.as_ref().and_then(|entries| {
                entries
                    .iter()
                    .find(|(id, _)| *id == name)
                    .map(|(_, entry)| entry)
            });
            ProfileRow {
                name: name.clone(),
                harness: HarnessId::OPENCLAW.to_string(),
                kind: ProfileKind::OpenclawAgent,
                home: Some(agent_home),
                default: declared_default.as_deref() == Some(name.as_str()),
                routes: route_counts
                    .as_ref()
                    .map(|counts| counts.get(name.as_str()).copied().unwrap_or(0)),
                sessions,
                // An entry pins a model either as a plain id or as the
                // `{ "primary": … }` object `agents.defaults.model` uses. A
                // row reports only what the ENTRY pins: the install-wide
                // `agents.defaults` is not this agent's pin.
                model: entry.and_then(|entry| match entry.get("model") {
                    Some(Value::String(id)) => Some(id.clone()),
                    Some(object) => object
                        .get("primary")
                        .and_then(Value::as_str)
                        .map(str::to_string),
                    None => None,
                }),
                worker: None,
            }
        })
        .collect()
}

/// Read a JSON5 config file, or [`Value::Null`] when it does not exist or
/// does not parse — the "unknown" answer the route counts distinguish from
/// an explicit empty table.
pub(crate) fn read_json5(path: &Path) -> Value {
    std::fs::read_to_string(path)
        .ok()
        .and_then(|text| serde_json::from_str::<Value>(&strip_json5(&text)).ok())
        .unwrap_or(Value::Null)
}

/// Whether a directory holds nothing at all. An unreadable directory is not
/// claimed to be empty.
fn directory_is_empty(path: &Path) -> bool {
    std::fs::read_dir(path).is_ok_and(|mut entries| entries.next().is_none())
}

/// Routing entries per target agent: one `bindings[]` element counts once
/// for the `agentId` it names.
fn count_binding_targets(list: &[Value]) -> BTreeMap<String, u64> {
    let mut counts: BTreeMap<String, u64> = BTreeMap::new();
    for binding in list {
        if let Some(agent) = binding.get("agentId").and_then(Value::as_str) {
            *counts.entry(agent.to_string()).or_default() += 1;
        }
    }
    counts
}

/// The declared agents as `(id, entry)` pairs IN DECLARATION ORDER, which is
/// what "the first entry" means when nothing declares itself the default.
///
/// `agents.list` is an array of `{ "id": … }` objects (the real shape).
/// `agents.entries` — an object keyed by agent id — is read too; its key
/// order is not preserved by the JSON parser, so an object-keyed config falls
/// back on the `main` convention rather than on declaration order.
fn entry_map(value: &Value) -> Vec<(String, Value)> {
    match value {
        Value::Array(list) => list
            .iter()
            .filter_map(|entry| {
                entry
                    .get("id")
                    .or_else(|| entry.get("agentId"))
                    .and_then(Value::as_str)
                    .map(|id| (id.to_string(), entry.clone()))
            })
            .collect(),
        Value::Object(map) => map
            .iter()
            .map(|(name, entry)| (name.clone(), entry.clone()))
            .collect(),
        _ => Vec::new(),
    }
}

/// Reduce JSON5 to JSON: `openclaw.json` is read by a JSON5 parser, so a
/// hand-edited config may carry `//` and `/* */` comments and trailing
/// commas. String literals are scanned so a `//` inside a value survives.
fn strip_json5(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    let mut in_string = false;
    let mut escaped = false;
    while let Some(ch) = chars.next() {
        if in_string {
            out.push(ch);
            if escaped {
                escaped = false;
            } else if ch == '\\' {
                escaped = true;
            } else if ch == '"' {
                in_string = false;
            }
            continue;
        }
        match ch {
            '"' => {
                in_string = true;
                out.push(ch);
            }
            '/' if chars.peek() == Some(&'/') => {
                for next in chars.by_ref() {
                    if next == '\n' {
                        out.push('\n');
                        break;
                    }
                }
            }
            '/' if chars.peek() == Some(&'*') => {
                chars.next();
                let mut previous = '\0';
                for next in chars.by_ref() {
                    if previous == '*' && next == '/' {
                        break;
                    }
                    previous = next;
                }
                out.push(' ');
            }
            _ => out.push(ch),
        }
    }
    // Trailing commas: `,` followed only by whitespace before `}` or `]`.
    let bytes: Vec<char> = out.chars().collect();
    let mut cleaned = String::with_capacity(out.len());
    let mut index = 0usize;
    let mut in_string = false;
    let mut escaped = false;
    while index < bytes.len() {
        let ch = bytes[index];
        if in_string {
            cleaned.push(ch);
            if escaped {
                escaped = false;
            } else if ch == '\\' {
                escaped = true;
            } else if ch == '"' {
                in_string = false;
            }
            index += 1;
            continue;
        }
        if ch == '"' {
            in_string = true;
            cleaned.push(ch);
            index += 1;
            continue;
        }
        if ch == ',' {
            let mut lookahead = index + 1;
            while lookahead < bytes.len() && bytes[lookahead].is_whitespace() {
                lookahead += 1;
            }
            if lookahead < bytes.len() && (bytes[lookahead] == '}' || bytes[lookahead] == ']') {
                index += 1;
                continue;
            }
        }
        cleaned.push(ch);
        index += 1;
    }
    cleaned
}

// ---------------------------------------------------------------------------
// Minimal YAML reads
// ---------------------------------------------------------------------------
//
// Hermes's `config.yaml` is read here for exactly two things: a top-level
// `model:` pin and the `gateway.profile_routes` table. That is a nested block
// of plain scalars, so an indentation scanner reads it without taking a YAML
// dependency for two keys. Anchors, flow collections, and multi-line scalars
// are NOT supported: a config using them reports `routes: null` (unknown)
// rather than a wrong count.

/// The block nested under `key`, with its own indentation preserved.
pub(crate) fn yaml_child(text: &str, key: &str) -> String {
    let mut out = String::new();
    let mut parent_indent: Option<usize> = None;
    for line in text.lines() {
        let trimmed = line.trim_start();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let indent = line.len() - trimmed.len();
        match parent_indent {
            None => {
                if yaml_key(trimmed).is_some_and(|found| found == key) {
                    parent_indent = Some(indent);
                }
            }
            Some(parent) => {
                if indent <= parent {
                    break;
                }
                out.push_str(line);
                out.push('\n');
            }
        }
    }
    out
}

/// A top-level (outermost-indent) scalar value for `key`.
pub(crate) fn yaml_scalar(text: &str, key: &str) -> Option<String> {
    let root = text
        .lines()
        .filter(|line| !line.trim_start().is_empty() && !line.trim_start().starts_with('#'))
        .map(|line| line.len() - line.trim_start().len())
        .min()?;
    for line in text.lines() {
        let trimmed = line.trim_start();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if line.len() - trimmed.len() != root {
            continue;
        }
        if yaml_key(trimmed) != Some(key) {
            continue;
        }
        let value = yaml_value(trimmed)?;
        if !value.is_empty() {
            return Some(value);
        }
    }
    None
}

/// Count routing entries per target profile inside a `profile_routes` block.
///
/// Two shapes are counted, both ending at a profile name:
/// * an entry with an explicit `profile: <name>` field (the documented shape:
///   a match spec — `platform`, `guild_id`, `chat_id`, `thread_id` — plus its
///   target), whether written as a list item or a nested mapping;
/// * a flat `<match>: <profile>` mapping at the block's own level.
fn count_yaml_route_targets(block: &str) -> BTreeMap<String, u64> {
    let mut counts: BTreeMap<String, u64> = BTreeMap::new();
    let entry_indent = block
        .lines()
        .filter(|line| !line.trim_start().is_empty() && !line.trim_start().starts_with('#'))
        .map(|line| line.len() - line.trim_start().len())
        .min();
    for line in block.lines() {
        let trimmed = line.trim_start();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let indent = line.len() - trimmed.len();
        let body = trimmed.strip_prefix("- ").unwrap_or(trimmed);
        let (Some(key), Some(value)) = (yaml_key(body), yaml_value(body)) else {
            continue;
        };
        if key == "profile" && !value.is_empty() {
            *counts.entry(value).or_default() += 1;
        } else if Some(indent) == entry_indent && !trimmed.starts_with("- ") && !value.is_empty() {
            *counts.entry(value).or_default() += 1;
        }
    }
    counts
}

pub(crate) fn yaml_key(line: &str) -> Option<&str> {
    let (head, _) = line.split_once(':')?;
    let head = head.trim();
    (!head.is_empty() && !head.contains(char::is_whitespace)).then_some(head)
}

fn yaml_value(line: &str) -> Option<String> {
    let (_, tail) = line.split_once(':')?;
    let tail = tail.trim();
    let tail = tail.split_once(" #").map(|(head, _)| head).unwrap_or(tail);
    Some(
        tail.trim()
            .trim_matches(|ch| ch == '"' || ch == '\'')
            .to_string(),
    )
}

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

    #[test]
    fn presets_are_supercodes_profiles_with_the_default_flagged() {
        let rows = preset_rows();
        assert_eq!(rows.len(), crate::presets::RESERVED_PRESET_NAMES.len());
        let default: Vec<&str> = rows
            .iter()
            .filter(|row| row.default)
            .map(|row| row.name.as_str())
            .collect();
        assert_eq!(default, ["supercode-default"]);
        let cc = rows.iter().find(|row| row.name == "cc-parity").unwrap();
        assert_eq!(cc.kind, ProfileKind::Preset);
        assert_eq!(cc.model.as_deref(), Some("anthropic/claude-opus-4-8"));
        assert!(cc.home.is_none());
    }

    /// The shell `openclaw agents delete` leaves behind is not an agent —
    /// `openclaw agents list` does not report it, so neither does this — but a
    /// directory that still holds state is one even with no config entry.
    #[test]
    fn an_emptied_agent_directory_is_not_an_agent() {
        let root = std::env::temp_dir().join(format!(
            "supercode-profiles-shell-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(root.join("agents/deleted")).unwrap();
        std::fs::create_dir_all(root.join("agents/undeclared/sessions")).unwrap();
        std::fs::create_dir_all(root.join("agents/main")).unwrap();
        std::fs::write(
            root.join("openclaw.json"),
            r#"{"agents": {"list": [{"id": "main"}]}}"#,
        )
        .unwrap();
        let names: Vec<String> = openclaw_rows(&root)
            .into_iter()
            .map(|row| row.name)
            .collect();
        assert_eq!(names, ["main", "undeclared"], "{names:?}");
        std::fs::remove_dir_all(&root).ok();
    }

    /// ORC-7: the root folder IS the `default` profile and `profiles/<name>/`
    /// are the named ones, each with its own `worker:` block and its own
    /// bindings store.
    #[test]
    fn orchestrator_profiles_are_folders_carrying_their_own_worker() {
        let root = std::env::temp_dir().join(format!(
            "supercode-profiles-orchestrator-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(root.join("profiles/ops")).unwrap();
        std::fs::write(
            root.join("config.yaml"),
            "worker:\n  harness: claude-code\n  model: claude-opus-4-8\ngateway:\n  profile_routes:\n    - platform: slack\n      profile: ops\n",
        )
        .unwrap();
        std::fs::write(
            root.join("profiles/ops/config.yaml"),
            "worker:\n  harness: codex\n",
        )
        .unwrap();
        let rows = orchestrator_rows(&root);
        let names: Vec<&str> = rows.iter().map(|row| row.name.as_str()).collect();
        assert_eq!(names, ["default", "ops"], "{names:?}");
        assert!(rows[0].default && !rows[1].default);
        assert_eq!(rows[0].kind, ProfileKind::OrchestratorProfile);
        assert_eq!(rows[0].worker.as_deref(), Some("claude-code"));
        assert_eq!(rows[0].model.as_deref(), Some("claude-opus-4-8"));
        assert_eq!(rows[1].worker.as_deref(), Some("codex"));
        assert_eq!(rows[1].model, None);
        // The route in the ROOT config targets `ops`, and it is counted there.
        assert_eq!(rows[1].routes, Some(1));
        assert_eq!(rows[0].routes, Some(0));
        // No store yet is UNKNOWN, never zero.
        assert_eq!(rows[0].sessions, None);
        assert_eq!(rows[0].home.as_deref(), Some(root.as_path()));
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn unsupported_harness_is_refused_not_silently_empty() {
        let error = list_profiles(&HarnessHomes::default(), Some(HarnessId::CLAUDE_CODE))
            .expect_err("claude-code has no profile concept");
        assert_eq!(
            error,
            ProfileError::UnsupportedHarness {
                harness: HarnessId::CLAUDE_CODE.to_string()
            }
        );
    }

    #[test]
    fn yaml_reader_counts_both_documented_route_shapes() {
        let listed = "gateway:\n  profile_routes:\n    - platform: slack\n      chat_id: C1\n      profile: coder\n    - platform: discord\n      profile: coder\n";
        let block = yaml_child(&yaml_child(listed, "gateway"), "profile_routes");
        assert_eq!(count_yaml_route_targets(&block).get("coder"), Some(&2));

        let flat = "gateway:\n  profile_routes:\n    slack: coder\n    discord: main\n";
        let block = yaml_child(&yaml_child(flat, "gateway"), "profile_routes");
        let counts = count_yaml_route_targets(&block);
        assert_eq!(counts.get("coder"), Some(&1));
        assert_eq!(counts.get("main"), Some(&1));

        let nested = "gateway:\n  profile_routes:\n    slack:\n      profile: coder\n";
        let block = yaml_child(&yaml_child(nested, "gateway"), "profile_routes");
        assert_eq!(count_yaml_route_targets(&block).get("coder"), Some(&1));
    }

    /// Receipt-driven (hermes-agent 0.21.0 on the build box): the real
    /// `config.yaml` pins the model in a `model:` BLOCK under `default:`,
    /// not as a top-level scalar. All three spellings the shipped config
    /// admits must read.
    #[test]
    fn hermes_model_reads_the_block_form_the_real_config_writes() {
        let real = "model:\n  # Default model to use\n  default: \"anthropic/claude-opus-4.6\"\n\n  # provider: auto\ntools:\n  enabled: true\n";
        assert_eq!(
            hermes_model(real).as_deref(),
            Some("anthropic/claude-opus-4.6")
        );
        let alias = "model:\n  model: anthropic/claude-opus-4.6\n";
        assert_eq!(
            hermes_model(alias).as_deref(),
            Some("anthropic/claude-opus-4.6")
        );
        let flat = "model: anthropic/claude-opus-4.6\n";
        assert_eq!(
            hermes_model(flat).as_deref(),
            Some("anthropic/claude-opus-4.6")
        );
        assert_eq!(hermes_model("gateway:\n  port: 1\n"), None);
    }

    #[test]
    fn yaml_child_stops_at_the_next_sibling_key() {
        let text = "gateway:\n  profile_routes:\n    - profile: coder\nmodel: sonnet\n";
        assert_eq!(yaml_scalar(text, "model").as_deref(), Some("sonnet"));
        let block = yaml_child(&yaml_child(text, "gateway"), "profile_routes");
        assert!(!block.contains("model"), "{block}");
    }

    #[test]
    fn json5_comments_and_trailing_commas_are_tolerated() {
        let text = "{\n  // the default agent\n  \"agents\": { \"entries\": { \"main\": { \"default\": true, } } },\n  /* routes */\n  \"bindings\": [ { \"agentId\": \"main\" }, ],\n  \"note\": \"https://example.test/x\",\n}\n";
        let value: Value = serde_json::from_str(&strip_json5(text)).unwrap();
        assert_eq!(value["note"], "https://example.test/x");
        assert_eq!(value["bindings"].as_array().unwrap().len(), 1);
        assert_eq!(value["agents"]["entries"]["main"]["default"], true);
    }
}