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
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
//! Controlled-tier scheduled jobs (Domain 11, concept 6) โ€” the FIRST
//! controlled-tier noun, and the shape the rest of wave 2 copies.
//!
//! Charter (`docs/plans/orchestration-domain-11-2026-09-02.md` ยง0.4):
//! **supercode never runs a cron engine.** Every mutation here is the
//! harness's OWN verb, executed as a subprocess, with supercode acting as the
//! uniform client:
//!
//! * **Hermes** โ€” `hermes cron create | edit | pause | resume | run | remove`
//!   with `HERMES_HOME` in the environment (a profile IS a HERMES_HOME:
//!   upstream `hermes_cli/profiles.py` spawns profile work with
//!   `HERMES_HOME=<home>/profiles/<name>`).
//! * **OpenClaw** โ€” `openclaw cron add | edit | disable | enable | run | rm`.
//!   Every one of these goes through the Gateway websocket, so the endpoint
//!   and credential are resolved from OPENCLAW's OWN config
//!   (`<state dir>/openclaw.json`, pointers `/gateway/remote/url`,
//!   `/gateway/port`, `/gateway/auth/token`) through the very same
//!   [`crate::RuntimeConnectLaunch`] the connect descriptor uses โ€” never from
//!   supercode's own config, and never from an inherited environment variable.
//! * **The orchestrator** โ€” its own package (ORC-13). The write door is the
//!   daemon's local socket while it is up and `node bin/orchestrator.mjs
//!   <op> โ€ฆ` when it is down, both landing in the SAME `applyOperator` โ†’
//!   reducer โ†’ `save()` path inside `sdk/orchestrator`, which owns the
//!   folder's byte-stability and its residue rules
//!   (`docs/ORCHESTRATOR-IR.md` ยง4.6, ยง6). supercode writes no file of that
//!   folder itself; [`crate::orchestrator_door`] is the uniform client.
//! * **Claude Code** โ€” refused. Its jobs are session-scoped runtime state
//!   created by the model inside a session (`CronCreate`); the harness
//!   publishes no verb a client can call.
//!
//! Three rules the whole tier inherits:
//!
//! 1. **The harness's answer is the answer.** After the verb exits 0 the row
//!    is re-read through the ORCH-7 loader ([`crate::jobs`]) and returned. A
//!    non-zero exit surfaces the harness's own stderr as the error โ€” never a
//!    silent success, never a supercode-invented row.
//! 2. **The command is narrated.** Every outcome carries `ran`: the exact
//!    argv that was executed, with any credential rendered as `<redacted>`.
//!    Tokens are never printed, logged, or stored.
//! 3. **A field the harness has no verb for is refused**
//!    ([`JobControlError::Unsupported`] โ†’ `UnsupportedAction`), never dropped.

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

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

pub(crate) use crate::harness_command::shell_quote;
pub(crate) use crate::harness_command::HarnessCommand;
use crate::{HarnessHomes, HarnessId, ScheduledJob};

pub use crate::harness_command::{HERMES_BIN_ENV, OPENCLAW_BIN_ENV};

/// Harnesses whose scheduled jobs supercode can MUTATE through their own CLI
/// verb. Strictly narrower than [`crate::jobs::JOB_HARNESSES`]: Claude Code is
/// readable but not controllable.
pub const CONTROLLED_JOB_HARNESSES: &[&str] = &[
    HarnessId::HERMES,
    HarnessId::OPENCLAW,
    HarnessId::ORCHESTRATOR,
];

/// Why Claude Code refuses every mutating job verb.
pub const CLAUDE_CODE_REFUSAL: &str =
    "claude-code scheduled jobs are session-scoped runtime state: they are created by the model \
     inside a session (`CronCreate`) and restored on resume. Claude Code publishes no harness verb \
     a client can call, so supercode refuses rather than inventing one";

/// One uniform mutating verb.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JobVerb {
    /// Create a new scheduled job.
    Create,
    /// Patch an existing job's fields.
    Update,
    /// Stop the scheduler from firing a job.
    Pause,
    /// Let the scheduler fire a job again.
    Resume,
    /// Fire a job now, out of schedule.
    Run,
    /// Remove a job.
    Delete,
}

impl JobVerb {
    /// Uniform spelling used in the RPC method and in outcomes.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Create => "create",
            Self::Update => "update",
            Self::Pause => "pause",
            Self::Resume => "resume",
            Self::Run => "run",
            Self::Delete => "delete",
        }
    }

    /// Whether the verb needs an existing job id.
    const fn needs_id(self) -> bool {
        !matches!(self, Self::Create)
    }
}

/// Uniform firing rule for a create/update.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct JobScheduleSpec {
    /// `interval` | `cron` | `once`.
    pub kind: String,
    /// Interval length, for `kind = "interval"`.
    pub minutes: Option<f64>,
    /// Cron expression, for `kind = "cron"`.
    pub expr: Option<String>,
    /// Absolute instant, for `kind = "once"`.
    pub run_at: Option<String>,
}

/// Uniform payload for a create/update.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct JobPayloadSpec {
    /// `prompt` | `system_event` | `command` | `script`.
    pub kind: String,
    /// The prompt, event, command line, or script the fire carries.
    pub text: Option<String>,
}

/// Uniform delivery for a create/update.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct JobDeliverSpec {
    /// Hermes `deliver` grammar (`origin` | `local` | `<platform>`), or an
    /// OpenClaw delivery mode (`announce` | `webhook` | `none`).
    pub target: Option<String>,
    /// Chat / destination the delivery is addressed to.
    pub chat_id: Option<String>,
}

/// One mutating request, in the uniform Domain 11 vocabulary.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct JobMutation {
    /// Harness that owns the job.
    pub harness: String,
    /// Job id, for every verb but `create`.
    #[serde(default)]
    pub id: Option<String>,
    /// Human-friendly job name.
    #[serde(default)]
    pub name: Option<String>,
    /// When the job fires.
    #[serde(default)]
    pub schedule: Option<JobScheduleSpec>,
    /// What fires.
    #[serde(default)]
    pub payload: Option<JobPayloadSpec>,
    /// OpenClaw `sessionTarget` (`main` | `isolated`).
    #[serde(default)]
    pub session_target: Option<String>,
    /// Where the fire's output goes.
    #[serde(default)]
    pub deliver: Option<JobDeliverSpec>,
    /// Hermes profile name / OpenClaw agent id.
    #[serde(default)]
    pub profile: Option<String>,
    /// Storage roots, so an isolated home is addressed the same way the
    /// read side addresses it.
    #[serde(default)]
    pub homes: HarnessHomes,
}

/// What one mutation did, with the harness's own row read back afterwards.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobMutationOutcome {
    /// Harness that ran the verb.
    pub harness: String,
    /// Uniform verb that was asked for.
    pub verb: String,
    /// The exact harness command that ran, credentials redacted.
    pub ran: String,
    /// Affected job id.
    pub id: String,
    /// The job as the harness's own store reports it AFTER the verb.
    /// Absent for `delete`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job: Option<ScheduledJob>,
    /// `true` on a successful `delete`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deleted: Option<bool>,
}

/// Why a mutation could not be performed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JobControlError {
    /// The harness has no verb for what was asked (refused, never faked).
    Unsupported(String),
    /// The request itself is incoherent.
    Invalid(String),
    /// The harness verb ran and failed; the message carries its stderr.
    Failed(String),
}

impl std::fmt::Display for JobControlError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unsupported(message) | Self::Invalid(message) | Self::Failed(message) => {
                formatter.write_str(message)
            }
        }
    }
}

impl std::error::Error for JobControlError {}

type Result<T> = std::result::Result<T, JobControlError>;

/// Whether `harness` can have its scheduled jobs mutated at all.
pub fn supports_job_control(harness: &str) -> bool {
    CONTROLLED_JOB_HARNESSES.contains(&harness)
}

pub fn harness_program(harness: &str) -> Result<String> {
    crate::harness_command::harness_program(harness).map_err(|detail| {
        JobControlError::Unsupported(detail.unwrap_or_else(|| unsupported_harness(harness)))
    })
}

fn unsupported_harness(harness: &str) -> String {
    if harness == HarnessId::CLAUDE_CODE {
        return CLAUDE_CODE_REFUSAL.to_string();
    }
    format!(
        "`{harness}` has no mutable scheduled jobs; mutating job verbs are supported for: {}",
        CONTROLLED_JOB_HARNESSES.join(", ")
    )
}

/// `HERMES_HOME` for this request: the profile's own home when one is named
/// (upstream treats a profile as a full HERMES_HOME), else the install root.
fn hermes_home(mutation: &JobMutation) -> PathBuf {
    // `HarnessHomes::hermes` addresses `state.db`; HERMES_HOME is its parent,
    // the same derivation the read side uses.
    let root = mutation
        .homes
        .hermes
        .parent()
        .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
    match mutation.profile.as_deref() {
        Some(profile) => root.join("profiles").join(profile),
        None => root,
    }
}

/// Resolve OpenClaw's gateway endpoint and credential from OPENCLAW's own
/// config, through the registry's connect descriptor.
///
/// The pointers are never re-spelled here: the descriptor
/// (`/gateway/remote/url` โ†’ `/gateway/port` โ†’ the documented default, auth at
/// `/gateway/auth/token`) is taken from the compiled registry and only its
/// `config_path` is re-anchored onto the state dir the caller addressed, so an
/// isolated home resolves ITS token and the default home resolves the real
/// one. supercode's own config is never consulted.
fn openclaw_connection(homes: &HarnessHomes) -> Result<crate::ResolvedRuntimeConnection> {
    let registry = crate::harness_support_registry();
    let descriptor = registry
        .harnesses
        .iter()
        .find(|descriptor| descriptor.id.as_str() == HarnessId::OPENCLAW)
        .ok_or_else(|| {
            JobControlError::Unsupported("the registry has no openclaw descriptor".into())
        })?;
    let connect = descriptor.runtime.connect_launch.as_ref().ok_or_else(|| {
        JobControlError::Unsupported(
            "openclaw has no registered connect-mode launch, so its gateway cannot be located"
                .into(),
        )
    })?;
    let mut connect = connect.clone();
    connect.config_path = homes
        .openclaw
        .join("openclaw.json")
        .to_string_lossy()
        .into_owned();
    connect.resolve(Path::new("/")).map_err(|error| {
        JobControlError::Unsupported(format!(
            "openclaw's gateway endpoint could not be resolved from its own config: {error}"
        ))
    })
}

/// Perform one mutation: translate to the harness's own verb, run it, then
/// re-read the row through the ORCH-7 loader.
pub fn mutate(verb: JobVerb, mutation: &JobMutation) -> Result<JobMutationOutcome> {
    if !supports_job_control(&mutation.harness) {
        return Err(JobControlError::Unsupported(unsupported_harness(
            &mutation.harness,
        )));
    }
    if verb.needs_id() && mutation.id.as_deref().unwrap_or("").trim().is_empty() {
        return Err(JobControlError::Invalid(format!(
            "`jobs.{}` needs the job id to act on",
            verb.as_str()
        )));
    }
    if matches!(verb, JobVerb::Create) && mutation.schedule.is_none() {
        return Err(JobControlError::Invalid(
            "`jobs.create` needs a schedule (interval, cron, or once)".into(),
        ));
    }
    // ORC-13: the orchestrator's verb is not a CLI subprocess but its own
    // package's operator door, so it branches before the command table.
    if mutation.harness == HarnessId::ORCHESTRATOR {
        return orchestrator_mutate(verb, mutation);
    }
    let command = match mutation.harness.as_str() {
        HarnessId::HERMES => hermes_command(verb, mutation)?,
        HarnessId::OPENCLAW => openclaw_command(verb, mutation)?,
        other => return Err(JobControlError::Unsupported(unsupported_harness(other))),
    };
    let ran = command.narrate();
    let before = matches!(verb, JobVerb::Create).then(|| known_ids(mutation));
    let stdout = command.run().map_err(JobControlError::Failed)?;
    let id = match (verb, before) {
        (JobVerb::Create, Some(before)) => created_id(mutation, &before, &stdout, &ran)?,
        _ => mutation.id.clone().unwrap_or_default(),
    };
    // The harness's own store is the answer: re-read, never echo the request.
    let read = crate::jobs::get_job(&mutation.harness, &id, &mutation.homes).map_err(|error| {
        JobControlError::Failed(format!(
            "`{ran}` succeeded but the job store could not be re-read: {error}"
        ))
    })?;
    match verb {
        JobVerb::Delete => {
            if read.is_some() {
                return Err(JobControlError::Failed(format!(
                    "`{ran}` reported success but `{id}` is still in {}'s job store",
                    mutation.harness
                )));
            }
            Ok(JobMutationOutcome {
                harness: mutation.harness.clone(),
                verb: verb.as_str().to_string(),
                ran,
                id,
                job: None,
                deleted: Some(true),
            })
        }
        _ => {
            let (job, _) = read.ok_or_else(|| {
                JobControlError::Failed(format!(
                    "`{ran}` reported success but `{}` has no job `{id}` afterwards",
                    mutation.harness
                ))
            })?;
            Ok(JobMutationOutcome {
                harness: mutation.harness.clone(),
                verb: verb.as_str().to_string(),
                ran,
                id,
                job: Some(job),
                deleted: None,
            })
        }
    }
}

// ---------------------------------------------------------------------------
// The orchestrator โ€” its own package's operator door (ORC-13)
// ---------------------------------------------------------------------------

/// The orchestrator profile this mutation acts in: `--profile`, else the
/// root folder, which IS the `default` profile (`docs/ORCHESTRATOR-IR.md` ยง6).
fn orchestrator_profile(mutation: &JobMutation) -> &str {
    mutation
        .profile
        .as_deref()
        .map(str::trim)
        .filter(|profile| !profile.is_empty())
        .unwrap_or("default")
}

/// The uniform row translated onto the orchestrator's OWN job vocabulary
/// (`docs/ORCHESTRATOR-IR.md` ยง2.6) โ€” the same words its MCP tools and its
/// chat commands use. A field the model has no home for is refused by name,
/// never dropped.
fn orchestrator_args(verb: JobVerb, mutation: &JobMutation) -> Result<Value> {
    let mut args = serde_json::Map::new();
    if let Some(id) = mutation.id.as_deref().filter(|id| !id.trim().is_empty()) {
        args.insert("id".into(), Value::String(id.trim().to_string()));
    }
    if matches!(verb, JobVerb::Create | JobVerb::Update) {
        if mutation.session_target.is_some() {
            return Err(JobControlError::Unsupported(
                "an orchestrator cron fire opens its own binding on the job's origin surface \
                 (`docs/ORCHESTRATOR-IR.md` ยง4.3); the model has no session-target field, so \
                 supercode refuses rather than dropping it"
                    .into(),
            ));
        }
        if let Some(name) = &mutation.name {
            args.insert("name".into(), Value::String(name.clone()));
        }
        if let Some(schedule) = &mutation.schedule {
            args.insert("schedule".into(), orchestrator_schedule(schedule)?);
        }
        if let Some(payload) = &mutation.payload {
            match payload_kind(payload) {
                "prompt" => {
                    args.insert(
                        "prompt".into(),
                        Value::String(payload_text(payload)?.to_string()),
                    );
                }
                other => {
                    return Err(JobControlError::Unsupported(format!(
                        "an orchestrator job carries a `prompt` โ€” the fire opens a worker session \
                         and sends it (ยง4.3); there is no `{other}` payload, so supercode refuses \
                         rather than inventing one"
                    )))
                }
            }
        }
        if let Some(deliver) = &mutation.deliver {
            if let Some(target) = hermes_deliver(deliver) {
                // The orchestrator's `deliver` grammar IS Hermes's
                // (`origin | local | home | <platform>[:<chat_id>]`, ยง2.6).
                args.insert("deliver".into(), Value::String(target));
            }
        }
    } else if mutation.name.is_some()
        || mutation.schedule.is_some()
        || mutation.payload.is_some()
        || mutation.deliver.is_some()
        || mutation.session_target.is_some()
    {
        return Err(JobControlError::Invalid(format!(
            "`jobs.{}` changes no fields; pass definition fields to `jobs.update`",
            verb.as_str()
        )));
    }
    Ok(Value::Object(args))
}

/// The uniform schedule in the orchestrator's typed form (ยง2.6).
fn orchestrator_schedule(schedule: &JobScheduleSpec) -> Result<Value> {
    match schedule.kind.as_str() {
        "interval" => schedule
            .minutes
            .map(|minutes| serde_json::json!({"kind": "interval", "minutes": minutes}))
            .ok_or_else(|| JobControlError::Invalid("an interval schedule needs `minutes`".into())),
        "cron" => schedule
            .expr
            .as_deref()
            .map(|expr| serde_json::json!({"kind": "cron", "expr": expr}))
            .ok_or_else(|| JobControlError::Invalid("a cron schedule needs `expr`".into())),
        "once" => schedule
            .run_at
            .as_deref()
            .map(|run_at| serde_json::json!({"kind": "once", "run_at": run_at}))
            .ok_or_else(|| JobControlError::Invalid("a once schedule needs `run_at`".into())),
        other => Err(JobControlError::Invalid(format!(
            "unknown schedule kind `{other}`; use interval, cron, or once"
        ))),
    }
}

/// One orchestrator job mutation: through the package's door, then re-read
/// through the ORC-7 loader like every other harness's row.
fn orchestrator_mutate(verb: JobVerb, mutation: &JobMutation) -> Result<JobMutationOutcome> {
    let args = orchestrator_args(verb, mutation)?;
    let root = mutation.homes.orchestrator.clone();
    let profile = orchestrator_profile(mutation);
    let op = format!("jobs.{}", verb.as_str());
    let answer = crate::orchestrator_door::call(&root, &op, &args, profile).map_err(|error| {
        match error {
            // The package refused: its sentence is the answer, in the same
            // shape a harness's stderr takes for the other two.
            crate::orchestrator_door::DoorError::Refused(message) => {
                JobControlError::Failed(message)
            }
            crate::orchestrator_door::DoorError::Failed(message) => {
                JobControlError::Failed(message)
            }
        }
    })?;
    let ran = format!("{} [{}]", answer.ran, answer.door.as_str());
    let id = answer
        .result
        .pointer("/job_id")
        .and_then(Value::as_str)
        .map(str::to_string)
        .or_else(|| mutation.id.clone())
        .ok_or_else(|| JobControlError::Failed(format!("`{ran}` succeeded but named no job id")))?;
    // The FOLDER is the answer, re-read through the same loader `jobs list`
    // uses โ€” never the door's echo of what it wrote.
    let read = crate::jobs::get_job(&mutation.harness, &id, &mutation.homes).map_err(|error| {
        JobControlError::Failed(format!(
            "`{ran}` succeeded but the job store could not be re-read: {error}"
        ))
    })?;
    match verb {
        JobVerb::Delete => {
            if read.is_some() {
                return Err(JobControlError::Failed(format!(
                    "`{ran}` reported success but `{id}` is still in the orchestrator's job store"
                )));
            }
            Ok(JobMutationOutcome {
                harness: mutation.harness.clone(),
                verb: verb.as_str().to_string(),
                ran,
                id,
                job: None,
                deleted: Some(true),
            })
        }
        _ => {
            let (job, _) = read.ok_or_else(|| {
                JobControlError::Failed(format!(
                    "`{ran}` reported success but the orchestrator has no job `{id}` afterwards"
                ))
            })?;
            Ok(JobMutationOutcome {
                harness: mutation.harness.clone(),
                verb: verb.as_str().to_string(),
                ran,
                id,
                job: Some(job),
                deleted: None,
            })
        }
    }
}

/// Every job id the harness's store holds right now.
fn known_ids(mutation: &JobMutation) -> BTreeSet<String> {
    crate::jobs::list_jobs(&crate::jobs::JobsQuery {
        harness: Some(mutation.harness.clone()),
        homes: mutation.homes.clone(),
        ..crate::jobs::JobsQuery::default()
    })
    .map(|listing| listing.jobs.into_iter().map(|job| job.id).collect())
    .unwrap_or_default()
}

/// Identify the job the create verb just made: the id the harness's own store
/// gained. When several appeared (a concurrent writer), the harness's stdout
/// decides between them.
fn created_id(
    mutation: &JobMutation,
    before: &BTreeSet<String>,
    stdout: &str,
    ran: &str,
) -> Result<String> {
    let after = known_ids(mutation);
    let mut fresh: Vec<String> = after.difference(before).cloned().collect();
    if fresh.len() == 1 {
        return Ok(fresh.remove(0));
    }
    if let Some(named) = fresh.iter().find(|id| stdout.contains(id.as_str())) {
        return Ok(named.clone());
    }
    // Last resort: an id the harness printed that the store now holds (a
    // store that reuses an existing id, e.g. an idempotent declaration key).
    if let Some(id) = stdout_id(stdout).filter(|id| after.contains(id)) {
        return Ok(id);
    }
    Err(JobControlError::Failed(format!(
        "`{ran}` reported success but {} gained {} job(s), so the new job cannot be identified",
        mutation.harness,
        fresh.len()
    )))
}

/// An `id` field from a harness's JSON stdout, when it prints one.
fn stdout_id(stdout: &str) -> Option<String> {
    let value: Value = serde_json::from_str(stdout.trim()).ok()?;
    for pointer in ["/id", "/job/id", "/jobId", "/job_id", "/result/id"] {
        if let Some(id) = value.pointer(pointer).and_then(Value::as_str) {
            return Some(id.to_string());
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Hermes โ€” `hermes cron โ€ฆ` over HERMES_HOME
// ---------------------------------------------------------------------------

/// Hermes's schedule argument: one positional string its own parser reads
/// (`cron/jobs.py::parse_schedule` โ€” `every 10m`, a cron expression, or an
/// ISO instant for a one-shot).
fn hermes_schedule(schedule: &JobScheduleSpec) -> Result<String> {
    match schedule.kind.as_str() {
        "interval" => schedule
            .minutes
            .map(|minutes| format!("every {}m", trim_float(minutes)))
            .ok_or_else(|| JobControlError::Invalid("an interval schedule needs `minutes`".into())),
        "cron" => schedule
            .expr
            .clone()
            .ok_or_else(|| JobControlError::Invalid("a cron schedule needs `expr`".into())),
        "once" => schedule
            .run_at
            .clone()
            .ok_or_else(|| JobControlError::Invalid("a once schedule needs `run_at`".into())),
        other => Err(JobControlError::Invalid(format!(
            "unknown schedule kind `{other}`; use interval, cron, or once"
        ))),
    }
}

fn trim_float(value: f64) -> String {
    if value.fract().abs() < f64::EPSILON {
        format!("{}", value as i64)
    } else {
        format!("{value}")
    }
}

/// Hermes's delivery argument, in hermes's own grammar
/// (`origin | local | <platform> | <platform>:<chat_id>`).
fn hermes_deliver(deliver: &JobDeliverSpec) -> Option<String> {
    let target = deliver.target.as_deref()?.trim().to_string();
    match deliver.chat_id.as_deref() {
        Some(chat) if !target.contains(':') && !chat.trim().is_empty() => {
            Some(format!("{target}:{}", chat.trim()))
        }
        _ => Some(target),
    }
}

fn hermes_command(verb: JobVerb, mutation: &JobMutation) -> Result<HarnessCommand> {
    if mutation.session_target.is_some() {
        return Err(JobControlError::Unsupported(
            "hermes cron fires always open their own `platform=cron` session; hermes has no \
             session-target verb, so supercode refuses rather than dropping the field"
                .into(),
        ));
    }
    let mut command = HarnessCommand::new(harness_program(HarnessId::HERMES)?);
    command.env("HERMES_HOME", hermes_home(mutation).to_string_lossy());
    command.args(["cron"]);
    let id = mutation.id.clone().unwrap_or_default();
    match verb {
        JobVerb::Create => {
            command.arg("create");
            if let Some(name) = &mutation.name {
                command.args(["--name", name]);
            }
            if let Some(deliver) = mutation.deliver.as_ref().and_then(hermes_deliver) {
                command.args(["--deliver", &deliver]);
            }
            if let Some(payload) = &mutation.payload {
                if payload_kind(payload) == "script" {
                    command.args(["--script", payload_text(payload)?]);
                }
            }
            // The schedule is positional and must precede the prompt.
            let schedule = hermes_schedule(
                mutation
                    .schedule
                    .as_ref()
                    .expect("create validates a schedule"),
            )?;
            command.arg(schedule);
            if let Some(payload) = &mutation.payload {
                match payload_kind(payload) {
                    "prompt" => {
                        command.arg(payload_text(payload)?);
                    }
                    "script" => {}
                    other => return Err(hermes_payload_refusal(other)),
                }
            }
        }
        JobVerb::Update => {
            command.args(["edit", &id]);
            if let Some(schedule) = &mutation.schedule {
                command.args(["--schedule", &hermes_schedule(schedule)?]);
            }
            if let Some(name) = &mutation.name {
                command.args(["--name", name]);
            }
            if let Some(deliver) = mutation.deliver.as_ref().and_then(hermes_deliver) {
                command.args(["--deliver", &deliver]);
            }
            if let Some(payload) = &mutation.payload {
                match payload_kind(payload) {
                    "prompt" => {
                        command.args(["--prompt", payload_text(payload)?]);
                    }
                    "script" => {
                        command.args(["--script", payload_text(payload)?]);
                    }
                    other => return Err(hermes_payload_refusal(other)),
                }
            }
        }
        JobVerb::Pause => {
            command.args(["pause", &id]);
        }
        JobVerb::Resume => {
            command.args(["resume", &id]);
        }
        JobVerb::Run => {
            command.args(["run", &id]);
        }
        JobVerb::Delete => {
            command.args(["remove", &id]);
        }
    }
    Ok(command)
}

fn hermes_payload_refusal(kind: &str) -> JobControlError {
    JobControlError::Unsupported(format!(
        "hermes cron carries a `prompt` or a `--script` payload; it has no verb for a `{kind}` \
         payload"
    ))
}

fn payload_kind(payload: &JobPayloadSpec) -> &str {
    if payload.kind.trim().is_empty() {
        "prompt"
    } else {
        payload.kind.trim()
    }
}

fn payload_text(payload: &JobPayloadSpec) -> Result<&str> {
    payload
        .text
        .as_deref()
        .filter(|text| !text.trim().is_empty())
        .ok_or_else(|| {
            JobControlError::Invalid(format!(
                "a `{}` payload needs its text",
                payload_kind(payload)
            ))
        })
}

// ---------------------------------------------------------------------------
// OpenClaw โ€” `openclaw cron โ€ฆ` through the Gateway
// ---------------------------------------------------------------------------

fn openclaw_command(verb: JobVerb, mutation: &JobMutation) -> Result<HarnessCommand> {
    let connection = openclaw_connection(&mutation.homes)?;
    let mut command = HarnessCommand::new(harness_program(HarnessId::OPENCLAW)?);
    // Point the spawned CLI at the SAME state the read side addresses, using
    // openclaw's own environment contract (`OPENCLAW_STATE_DIR` names the
    // state dir; `OPENCLAW_CONFIG_PATH` names the config file inside it).
    command.env(
        "OPENCLAW_STATE_DIR",
        mutation.homes.openclaw.to_string_lossy(),
    );
    command.env(
        "OPENCLAW_CONFIG_PATH",
        mutation
            .homes
            .openclaw
            .join("openclaw.json")
            .to_string_lossy(),
    );
    command.arg("cron");
    let id = mutation.id.clone().unwrap_or_default();
    match verb {
        JobVerb::Create => {
            command.arg("add");
        }
        JobVerb::Update => {
            command.args(["edit", &id]);
        }
        // OpenClaw spells pause/resume `disable`/`enable`.
        JobVerb::Pause => {
            command.args(["disable", &id]);
        }
        JobVerb::Resume => {
            command.args(["enable", &id]);
        }
        JobVerb::Run => {
            command.args(["run", &id]);
        }
        JobVerb::Delete => {
            command.args(["rm", &id]);
        }
    }
    command.args(["--url", &connection.address]);
    if let Some(token) = &connection.auth {
        command.arg("--token");
        command.secret(token.secret());
    }
    if matches!(verb, JobVerb::Create | JobVerb::Update) {
        if let Some(name) = &mutation.name {
            command.args(["--name", name]);
        }
        if let Some(schedule) = &mutation.schedule {
            match schedule.kind.as_str() {
                "interval" => {
                    let minutes = schedule.minutes.ok_or_else(|| {
                        JobControlError::Invalid("an interval schedule needs `minutes`".into())
                    })?;
                    command.args(["--every", &format!("{}m", trim_float(minutes))]);
                }
                "cron" => {
                    let expr = schedule.expr.as_deref().ok_or_else(|| {
                        JobControlError::Invalid("a cron schedule needs `expr`".into())
                    })?;
                    command.args(["--cron", expr]);
                }
                "once" => {
                    let run_at = schedule.run_at.as_deref().ok_or_else(|| {
                        JobControlError::Invalid("a once schedule needs `run_at`".into())
                    })?;
                    command.args(["--at", run_at]);
                }
                other => {
                    return Err(JobControlError::Invalid(format!(
                        "unknown schedule kind `{other}`; use interval, cron, or once"
                    )))
                }
            }
        }
        if let Some(payload) = &mutation.payload {
            match payload_kind(payload) {
                "prompt" => {
                    command.args(["--message", payload_text(payload)?]);
                }
                "system_event" => {
                    command.args(["--system-event", payload_text(payload)?]);
                }
                "command" => {
                    command.args(["--command", payload_text(payload)?]);
                }
                other => {
                    return Err(JobControlError::Unsupported(format!(
                        "openclaw cron carries `message`, `system-event` or `command` payloads; \
                         it has no verb for a `{other}` payload"
                    )))
                }
            }
        }
        if let Some(target) = &mutation.session_target {
            command.args(["--session", target]);
        }
        if let Some(profile) = &mutation.profile {
            command.args(["--agent", profile]);
        }
        if let Some(deliver) = &mutation.deliver {
            openclaw_deliver(deliver, &mut command)?;
        }
        // Measured against the pin (receipt orch18-openclaw-jobs-receipt):
        // `cron add|rm|list` accept `--json`, `cron edit` REJECTS it
        // ("OpenClaw does not recognize option \"--json\""). The flag is only
        // an id hint for create anyway โ€” the answer always comes from the
        // re-read.
        if matches!(verb, JobVerb::Create) {
            command.arg("--json");
        }
    } else if mutation.profile.is_some()
        || mutation.session_target.is_some()
        || mutation.deliver.is_some()
        || mutation.name.is_some()
        || mutation.schedule.is_some()
        || mutation.payload.is_some()
    {
        return Err(JobControlError::Invalid(format!(
            "`jobs.{}` changes no fields; pass definition fields to `jobs.update`",
            verb.as_str()
        )));
    }
    Ok(command)
}

/// OpenClaw's delivery flags. `target` is the delivery MODE the observed row
/// reports (`announce` | `webhook` | `none`); `chat_id` is the destination.
fn openclaw_deliver(deliver: &JobDeliverSpec, command: &mut HarnessCommand) -> Result<()> {
    let Some(target) = deliver.target.as_deref().map(str::trim) else {
        if let Some(chat) = deliver.chat_id.as_deref() {
            command.args(["--to", chat]);
        }
        return Ok(());
    };
    match target {
        "announce" => {
            command.arg("--announce");
            if let Some(chat) = deliver.chat_id.as_deref() {
                command.args(["--to", chat]);
            }
        }
        "webhook" => {
            let url = deliver.chat_id.as_deref().ok_or_else(|| {
                JobControlError::Invalid(
                    "an openclaw `webhook` delivery needs the URL in `chat_id`".into(),
                )
            })?;
            command.args(["--webhook", url]);
        }
        "none" => {
            command.arg("--no-deliver");
        }
        other => {
            return Err(JobControlError::Unsupported(format!(
                "openclaw delivers `announce`, `webhook`, or `none`; it has no `{other}` delivery \
                 mode"
            )))
        }
    }
    Ok(())
}

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

    fn homes(root: &Path) -> HarnessHomes {
        HarnessHomes {
            hermes: root.join("hermes_home/state.db"),
            openclaw: root.join("openclaw_home"),
            ..HarnessHomes::default()
        }
    }

    #[test]
    fn the_program_comes_from_the_registry_launch() {
        // Guard: the registry's hermes launch is the ACP BRIDGE (`hermes-acp`);
        // the cron verb lives on the base CLI.
        assert_eq!(harness_program(HarnessId::HERMES).unwrap(), "hermes");
        assert_eq!(harness_program(HarnessId::OPENCLAW).unwrap(), "openclaw");
    }

    #[test]
    fn claude_code_refuses_every_mutating_verb() {
        let error = mutate(
            JobVerb::Pause,
            &JobMutation {
                harness: HarnessId::CLAUDE_CODE.into(),
                id: Some("release-watch".into()),
                ..JobMutation::default()
            },
        )
        .unwrap_err();
        assert!(matches!(error, JobControlError::Unsupported(_)), "{error}");
        assert!(error.to_string().contains("CronCreate"), "{error}");
    }

    #[test]
    fn a_harness_without_jobs_refuses() {
        let error = mutate(
            JobVerb::Delete,
            &JobMutation {
                harness: "codex".into(),
                id: Some("x".into()),
                ..JobMutation::default()
            },
        )
        .unwrap_err();
        assert!(matches!(error, JobControlError::Unsupported(_)), "{error}");
    }

    #[test]
    fn hermes_translates_the_uniform_row_onto_its_own_verb() {
        let root = PathBuf::from("/tmp/orch18-unit");
        let command = hermes_command(
            JobVerb::Create,
            &JobMutation {
                harness: HarnessId::HERMES.into(),
                name: Some("health".into()),
                schedule: Some(JobScheduleSpec {
                    kind: "interval".into(),
                    minutes: Some(10.0),
                    ..JobScheduleSpec::default()
                }),
                payload: Some(JobPayloadSpec {
                    kind: "prompt".into(),
                    text: Some("nightly health check".into()),
                }),
                deliver: Some(JobDeliverSpec {
                    target: Some("local".into()),
                    chat_id: None,
                }),
                homes: homes(&root),
                ..JobMutation::default()
            },
        )
        .unwrap();
        assert_eq!(
            command.narrate(),
            "hermes cron create --name health --deliver local 'every 10m' 'nightly health check'"
        );
        assert_eq!(
            command.env,
            vec![(
                "HERMES_HOME".to_string(),
                root.join("hermes_home").to_string_lossy().into_owned()
            )]
        );
    }

    #[test]
    fn a_hermes_profile_is_its_own_home() {
        let root = PathBuf::from("/tmp/orch18-unit");
        let command = hermes_command(
            JobVerb::Pause,
            &JobMutation {
                harness: HarnessId::HERMES.into(),
                id: Some("abc".into()),
                profile: Some("ops".into()),
                homes: homes(&root),
                ..JobMutation::default()
            },
        )
        .unwrap();
        assert_eq!(command.narrate(), "hermes cron pause abc");
        assert_eq!(
            command.env[0].1,
            root.join("hermes_home/profiles/ops")
                .to_string_lossy()
                .into_owned()
        );
    }

    #[test]
    fn hermes_refuses_a_field_it_has_no_verb_for() {
        let error = hermes_command(
            JobVerb::Update,
            &JobMutation {
                harness: HarnessId::HERMES.into(),
                id: Some("abc".into()),
                session_target: Some("isolated".into()),
                ..JobMutation::default()
            },
        )
        .unwrap_err();
        assert!(matches!(error, JobControlError::Unsupported(_)), "{error}");
    }

    /// ORC-13: the uniform row translated onto the ORCHESTRATOR's own job
    /// vocabulary (`docs/ORCHESTRATOR-IR.md` ยง2.6) โ€” the typed schedule, the
    /// prompt, and Hermes's own `deliver` grammar.
    #[test]
    fn the_orchestrator_translates_the_uniform_row_onto_its_own_operator_args() {
        let args = orchestrator_args(
            JobVerb::Create,
            &JobMutation {
                harness: HarnessId::ORCHESTRATOR.into(),
                name: Some("health".into()),
                schedule: Some(JobScheduleSpec {
                    kind: "interval".into(),
                    minutes: Some(10.0),
                    ..JobScheduleSpec::default()
                }),
                payload: Some(JobPayloadSpec {
                    kind: "prompt".into(),
                    text: Some("nightly health check".into()),
                }),
                deliver: Some(JobDeliverSpec {
                    target: Some("loopback".into()),
                    chat_id: Some("ops-room".into()),
                }),
                ..JobMutation::default()
            },
        )
        .unwrap();
        assert_eq!(
            args,
            serde_json::json!({
                "name": "health",
                "schedule": {"kind": "interval", "minutes": 10.0},
                "prompt": "nightly health check",
                "deliver": "loopback:ops-room",
            })
        );
    }

    /// A field the orchestrator's model has no home for is REFUSED, never
    /// dropped โ€” the same rule the other two harnesses inherit.
    #[test]
    fn the_orchestrator_refuses_a_field_its_model_does_not_have() {
        for (mutation, needle) in [
            (
                JobMutation {
                    harness: HarnessId::ORCHESTRATOR.into(),
                    session_target: Some("isolated".into()),
                    ..JobMutation::default()
                },
                "no session-target field",
            ),
            (
                JobMutation {
                    harness: HarnessId::ORCHESTRATOR.into(),
                    payload: Some(JobPayloadSpec {
                        kind: "command".into(),
                        text: Some("ls".into()),
                    }),
                    ..JobMutation::default()
                },
                "there is no `command` payload",
            ),
        ] {
            let error = orchestrator_args(JobVerb::Create, &mutation).unwrap_err();
            assert!(matches!(error, JobControlError::Unsupported(_)), "{error}");
            assert!(error.to_string().contains(needle), "{error}");
        }
        // A verb that sets no fields refuses definition fields outright.
        let error = orchestrator_args(
            JobVerb::Pause,
            &JobMutation {
                harness: HarnessId::ORCHESTRATOR.into(),
                id: Some("job_x".into()),
                name: Some("renamed".into()),
                ..JobMutation::default()
            },
        )
        .unwrap_err();
        assert!(matches!(error, JobControlError::Invalid(_)), "{error}");
    }

    /// The root folder IS the `default` profile (ยง6), so an unnamed profile
    /// addresses it rather than defaulting to nothing.
    #[test]
    fn the_orchestrators_unnamed_profile_is_the_root_folder() {
        assert_eq!(
            orchestrator_profile(&JobMutation {
                harness: HarnessId::ORCHESTRATOR.into(),
                ..JobMutation::default()
            }),
            "default"
        );
        assert_eq!(
            orchestrator_profile(&JobMutation {
                harness: HarnessId::ORCHESTRATOR.into(),
                profile: Some("  coder ".into()),
                ..JobMutation::default()
            }),
            "coder"
        );
    }

    #[test]
    fn openclaw_carries_the_gateway_endpoint_and_never_prints_the_token() {
        let root = std::env::temp_dir().join(format!(
            "supercode-orch18-unit-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let state = root.join("openclaw_home");
        std::fs::create_dir_all(&state).unwrap();
        std::fs::write(
            state.join("openclaw.json"),
            r#"{"gateway": {"port": 18999, "auth": {"token": "super-secret-token"}}}"#,
        )
        .unwrap();
        let command = openclaw_command(
            JobVerb::Create,
            &JobMutation {
                harness: HarnessId::OPENCLAW.into(),
                name: Some("digest".into()),
                schedule: Some(JobScheduleSpec {
                    kind: "cron".into(),
                    expr: Some("0 9 * * 1".into()),
                    ..JobScheduleSpec::default()
                }),
                payload: Some(JobPayloadSpec {
                    kind: "system_event".into(),
                    text: Some("weekly digest".into()),
                }),
                session_target: Some("main".into()),
                homes: homes(&root),
                ..JobMutation::default()
            },
        )
        .unwrap();
        assert_eq!(
            command.narrate(),
            "openclaw cron add --url ws://127.0.0.1:18999 --token <redacted> --name digest --cron \
             '0 9 * * 1' --system-event 'weekly digest' --session main --json"
        );
        assert_eq!(command.secrets, vec!["super-secret-token".to_string()]);
        assert!(
            !command.narrate().contains("super-secret-token"),
            "the credential must never be narrated"
        );
        std::fs::remove_dir_all(&root).ok();
    }
}