supercode-harness 0.4.19

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
//! 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`).
/// Hermes's profiles as the orchestration codec reads the home: the root
/// and every `profiles/<name>` folder, its model from the config residue,
/// its route count from the routes that name it.
fn hermes_rows(state_db: &Path) -> Vec<ProfileRow> {
    let Some(home) = state_db.parent() else {
        return Vec::new();
    };
    let Ok(loaded) = supercode_interchange::orchestration::codec::from_hermes(home) else {
        return Vec::new();
    };
    let routes = loaded
        .io
        .get(HERMES_DEFAULT_PROFILE)
        .is_some_and(|io| io.raw.contains_key("config.yaml"))
        .then(|| route_counts(&loaded.orchestration));
    let mut names: Vec<&String> = loaded.orchestration.profiles.keys().collect();
    names.sort_by_key(|name| (name.as_str() != HERMES_DEFAULT_PROFILE, name.as_str()));
    names
        .into_iter()
        .map(|name| {
            let profile = &loaded.orchestration.profiles[name];
            let is_default = name == HERMES_DEFAULT_PROFILE;
            ProfileRow {
                name: name.clone(),
                harness: HarnessId::HERMES.to_string(),
                kind: ProfileKind::HermesProfile,
                home: Some(profile.dir.clone()),
                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: hermes_model(profile),
                worker: None,
            }
        })
        .collect()
}

/// Routes by the profile they name, across the whole orchestration.
fn route_counts(
    orchestration: &supercode_interchange::orchestration::Orchestration,
) -> BTreeMap<String, u64> {
    let mut counts: BTreeMap<String, u64> = BTreeMap::new();
    for profile in orchestration.profiles.values() {
        for route in &profile.routes {
            *counts.entry(route.profile.clone()).or_default() += 1;
        }
    }
    counts
}

/// Our own folder's profiles as the orchestration codec reads it: the
/// worker's harness and model, the bindings the profile's store holds.
fn orchestrator_rows(root: &Path) -> Vec<ProfileRow> {
    use supercode_interchange::orchestration::codec::{load_home, Flavor};
    let Ok(loaded) = load_home(root, Flavor::Orchestrator) else {
        return Vec::new();
    };
    let routes = loaded
        .io
        .values()
        .any(|io| io.raw.contains_key("config.yaml"))
        .then(|| route_counts(&loaded.orchestration));
    let mut names: Vec<&String> = loaded.orchestration.profiles.keys().collect();
    names.sort_by_key(|name| (name.as_str() != HERMES_DEFAULT_PROFILE, name.as_str()));
    names
        .into_iter()
        .map(|name| {
            let profile = &loaded.orchestration.profiles[name];
            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: profile
                    .dir
                    .join("state.db")
                    .is_file()
                    .then(|| profile.bindings.len() as u64),
                model: profile.worker.as_ref().and_then(|w| w.model.clone()),
                worker: profile
                    .worker
                    .as_ref()
                    .map(|w| w.harness.as_str().to_string()),
                home: Some(profile.dir.clone()),
            }
        })
        .collect()
}

/// The model a Hermes config pins: a top-level `model` scalar, else the
/// `model` block's `default` / `model`.
fn hermes_model(profile: &supercode_interchange::orchestration::Profile) -> Option<String> {
    match profile.residue.config.get("model")? {
        Value::String(pinned) => Some(pinned.clone()),
        Value::Object(block) => block
            .get("default")
            .or_else(|| block.get("model"))
            .and_then(Value::as_str)
            .map(str::to_string),
        _ => None,
    }
}

/// 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.
/// OpenClaw's agents as the orchestration codec reads the state directory:
/// every declared agent (a profile; the default agent is the root profile),
/// plus any agent folder on disk that holds something, its model from the
/// agent entry the codec kept, its route count from the bindings naming it.
fn openclaw_rows(home: &Path) -> Vec<ProfileRow> {
    let Ok(loaded) = supercode_interchange::orchestration::codec::from_openclaw(home) else {
        return Vec::new();
    };
    let by_agent: BTreeMap<&str, &str> = loaded
        .profiles
        .iter()
        .map(|(name, io)| (io.agent_id.as_str(), name.as_str()))
        .collect();
    let mut names: Vec<String> = by_agent.keys().map(|id| (*id).to_string()).collect();
    if let Ok(dirs) = std::fs::read_dir(home.join("agents")) {
        names.extend(
            dirs.flatten()
                .filter(|entry| entry.path().is_dir())
                .filter(|entry| !directory_is_empty(&entry.path()))
                .filter_map(|entry| entry.file_name().into_string().ok()),
        );
    }
    names.sort();
    names.dedup();
    let route_counts = loaded.root.config_present.then(|| {
        let mut counts: BTreeMap<String, u64> = BTreeMap::new();
        for route in loaded
            .orchestration
            .profiles
            .values()
            .flat_map(|profile| profile.routes.iter())
        {
            if let Some(agent) = route.residue.0.get("agent_id").and_then(Value::as_str) {
                *counts.entry(agent.to_string()).or_default() += 1;
            }
        }
        counts
    });
    names
        .into_iter()
        .map(|name| {
            let agent_home = home.join("agents").join(&name);
            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 = by_agent
                .get(name.as_str())
                .and_then(|profile| loaded.orchestration.profiles.get(*profile))
                .and_then(|profile| profile.residue.config.get("openclaw_agent"));
            ProfileRow {
                name: name.clone(),
                harness: HarnessId::OPENCLAW.to_string(),
                kind: ProfileKind::OpenclawAgent,
                home: Some(agent_home),
                default: loaded.root.default_agent == name,
                routes: route_counts
                    .as_ref()
                    .map(|counts| counts.get(name.as_str()).copied().unwrap_or(0)),
                sessions,
                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()
}

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())
}

/// 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.

#[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()
            }
        );
    }

    /// 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 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);
    }
}