supercode-cli 0.4.16

supercode — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
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
//! Compile a Claude Code session's carried schedules into orchestrator jobs.
//!
//! A resumed Claude Code session carries its `CronCreate` jobs and its pending
//! `ScheduleWakeup` in the runtime manifest, and supercode fires none of them.
//! This module is the one door that turns those records into something that
//! WILL fire: it writes them into the orchestrator's own `cron/jobs.json`, in
//! the Hermes job schema the orchestrator loads (`sdk/orchestrator/ir.mjs`,
//! `HERMES_JOB_ORDER`), and stops. Nothing here fires, claims, or contacts a
//! running daemon; the orchestrator's tick owns every fire that follows.
//!
//! Two properties the writer holds:
//!
//! * **Other jobs keep their bytes.** The target file is read, the records it
//!   already holds are carried through as the verbatim values they were parsed
//!   from, and only a record this import owns is written or replaced. The file
//!   is re-emitted the way the orchestrator's own writer emits it
//!   (`JSON.stringify(jobs, null, 2) + "\n"`), so a round trip through the
//!   Node loader/saver is a no-op.
//! * **The zone is stated, not assumed.** A Claude cron record carries no
//!   timezone — Claude's own scheduler may use local wall-clock time, and that
//!   offset is not in the transcript. UTC is therefore written onto the
//!   schedule explicitly, as residue, so the assumption is visible in the file
//!   rather than buried in whichever evaluator reads it.

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

use anyhow::{Context, Result};
use serde_json::{Map, Value};
use supercode::{ClaudeCronJob, ClaudeRuntimeManifest, ClaudeWakeup};

/// Key order the orchestrator's `encodeJob` emits (`HERMES_JOB_ORDER`,
/// restricted to the keys a job we author actually has). Writing them in this
/// order is what makes our file and the orchestrator's own re-save identical.
const JOB_KEY_ORDER: &[&str] = &[
    "id",
    "schedule",
    "prompt",
    "skills",
    "model",
    "workdir",
    "context_from",
    "deliver",
    "failure_deliver",
    "attach_to_session",
    "origin",
    "repeat",
    "enabled",
    "next_run_at",
    "last_run_at",
    "last_status",
    "created_at",
];

/// What one import did to the target store.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportOutcome {
    /// The `cron/jobs.json` written.
    pub path: PathBuf,
    /// Ids appended to the file.
    pub added: Vec<String>,
    /// Ids that already existed and were rewritten in place.
    pub replaced: Vec<String>,
    /// Ids the file already held that this import did not touch.
    pub untouched: usize,
}

/// Compile `manifest` into orchestrator jobs and merge them into
/// `<root>/cron/jobs.json`.
///
/// `now_unix` is supplied by the caller, never read from the clock here, so
/// the compilation is a pure function of (manifest, session, instant).
pub fn import_claude_session(
    root: &Path,
    session_id: &str,
    manifest: &ClaudeRuntimeManifest,
    now_unix: i64,
) -> Result<ImportOutcome> {
    let mut compiled = Vec::new();
    for cron in &manifest.active_crons {
        compiled.push(compile_cron(session_id, cron, manifest, now_unix)?);
    }
    for wakeup in &manifest.pending_wakeups {
        compiled.push(compile_wakeup(session_id, wakeup, manifest, now_unix)?);
    }
    merge_into_store(root, compiled)
}

/// `<session>-<claude id>`: unique in a store several sessions may import
/// into, and readable as the provenance it is. Both halves are already
/// filename-safe (a Claude session id is a UUID; a cron id is the harness's
/// own slug), and the fire ids the orchestrator derives from a job id
/// (`cron_<job_id>_<ts>`) stay parseable.
fn job_id(session_id: &str, native_id: &str) -> String {
    format!("{session_id}-{native_id}")
}

fn compile_cron(
    session_id: &str,
    cron: &ClaudeCronJob,
    manifest: &ClaudeRuntimeManifest,
    now_unix: i64,
) -> Result<Map<String, Value>> {
    let schedule = CronSchedule::parse(&cron.schedule)
        .with_context(|| format!("Claude cron `{}` has an unusable schedule", cron.id))?;
    let next = schedule
        .next_after(now_unix)
        .with_context(|| format!("Claude cron `{}` has no next UTC minute", cron.id))?;

    let mut sched = Map::new();
    sched.insert("kind".into(), "cron".into());
    sched.insert("expr".into(), cron.schedule.clone().into());
    // Residue, stated: the Claude record carries no zone (see the module doc).
    sched.insert("tz".into(), "UTC".into());

    let mut job = Map::new();
    job.insert("id".into(), job_id(session_id, &cron.id).into());
    job.insert("schedule".into(), Value::Object(sched));
    job.insert("prompt".into(), cron.prompt.clone().into());
    // A Claude cron that does not repeat fires once. The orchestrator spends a
    // job whose remaining-run count reaches zero, so one remaining run is how
    // a non-recurring cron is said in this schema.
    job.insert(
        "repeat".into(),
        if cron.recurring {
            Value::Null
        } else {
            Value::from(1)
        },
    );
    job.insert("next_run_at".into(), rfc3339(next).into());
    job.insert("created_at".into(), value_or_null(cron.created_at.as_ref()));
    Ok(finish_job(job, manifest))
}

fn compile_wakeup(
    session_id: &str,
    wakeup: &ClaudeWakeup,
    manifest: &ClaudeRuntimeManifest,
    now_unix: i64,
) -> Result<Map<String, Value>> {
    // Claude's own answer to "when" is `scheduled_for`, taken from the tool
    // result. When the transcript never recorded one, the request itself still
    // says it: creation instant plus the requested delay. A wakeup already
    // overdue at import time is due now, not re-dated into the future.
    let due = wakeup
        .scheduled_for
        .as_deref()
        .and_then(rfc3339_to_unix)
        .or_else(|| {
            wakeup
                .created_at
                .as_deref()
                .and_then(rfc3339_to_unix)
                .and_then(|created| {
                    i64::try_from(wakeup.delay_seconds)
                        .ok()
                        .and_then(|delay| created.checked_add(delay))
                })
        })
        .unwrap_or_else(|| {
            now_unix.saturating_add(i64::try_from(wakeup.delay_seconds).unwrap_or(i64::MAX))
        })
        .max(now_unix);

    let mut sched = Map::new();
    sched.insert("kind".into(), "once".into());
    sched.insert("run_at".into(), rfc3339(due).into());

    let mut job = Map::new();
    job.insert("id".into(), job_id(session_id, &wakeup.tool_use_id).into());
    job.insert("schedule".into(), Value::Object(sched));
    job.insert(
        "prompt".into(),
        value_or_null(wakeup.prompt.as_ref().or(wakeup.reason.as_ref())),
    );
    job.insert("repeat".into(), Value::Null);
    job.insert("next_run_at".into(), rfc3339(due).into());
    job.insert(
        "created_at".into(),
        value_or_null(wakeup.created_at.as_ref()),
    );
    Ok(finish_job(job, manifest))
}

/// Fill the keys every emitted job carries, in `JOB_KEY_ORDER`.
fn finish_job(partial: Map<String, Value>, manifest: &ClaudeRuntimeManifest) -> Map<String, Value> {
    let mut job = partial;
    job.entry("skills".to_string())
        .or_insert_with(|| Value::Array(Vec::new()));
    job.entry("model".to_string()).or_insert(Value::Null);
    // The directory the source session ran in: the job's own provenance, not
    // a default this command chose.
    job.entry("workdir".to_string())
        .or_insert_with(|| value_or_null(manifest.posture.cwd.as_ref()));
    job.entry("context_from".to_string()).or_insert(Value::Null);
    // A Claude fire answers in the session that scheduled it. That session is
    // not this store's to attach to, so the fire's own output is the delivery.
    job.entry("deliver".to_string())
        .or_insert_with(|| "local".into());
    job.entry("failure_deliver".to_string())
        .or_insert(Value::Null);
    job.entry("attach_to_session".to_string())
        .or_insert(Value::Null);
    job.entry("origin".to_string()).or_insert(Value::Null);
    job.entry("enabled".to_string())
        .or_insert_with(|| Value::Bool(true));
    job.entry("last_run_at".to_string()).or_insert(Value::Null);
    job.entry("last_status".to_string()).or_insert(Value::Null);

    let mut ordered = Map::new();
    for key in JOB_KEY_ORDER {
        if let Some(value) = job.remove(*key) {
            ordered.insert((*key).to_string(), value);
        }
    }
    // Nothing should remain, but a key added above and not listed in
    // `JOB_KEY_ORDER` must still reach the file rather than vanish.
    for (key, value) in job {
        ordered.insert(key, value);
    }
    ordered
}

/// Read `<root>/cron/jobs.json`, merge `compiled` in, write it back.
fn merge_into_store(root: &Path, compiled: Vec<Map<String, Value>>) -> Result<ImportOutcome> {
    let path = root.join("cron/jobs.json");
    let mut existing: Vec<Value> = if path.exists() {
        let text = std::fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        match serde_json::from_str::<Value>(&text)
            .with_context(|| format!("{} is not JSON", path.display()))?
        {
            Value::Array(items) => items,
            other => anyhow::bail!(
                "{} holds {} where the orchestrator expects an array of jobs",
                path.display(),
                match other {
                    Value::Object(_) => "an object",
                    Value::Null => "null",
                    _ => "a scalar",
                }
            ),
        }
    } else {
        Vec::new()
    };

    let before = existing.len();
    let mut added = Vec::new();
    let mut replaced = Vec::new();
    for job in compiled {
        let id = job
            .get("id")
            .and_then(Value::as_str)
            .expect("every compiled job has an id")
            .to_string();
        match existing
            .iter()
            .position(|item| item.get("id").and_then(Value::as_str) == Some(id.as_str()))
        {
            // Re-importing the same session updates its own rows in place;
            // every other record keeps both its position and its bytes.
            Some(index) => {
                existing[index] = Value::Object(job);
                replaced.push(id);
            }
            None => {
                existing.push(Value::Object(job));
                added.push(id);
            }
        }
    }

    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
    }
    // The orchestrator's own encoding: two-space indent, trailing newline.
    let text = format!("{}\n", serde_json::to_string_pretty(&existing)?);
    std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?;

    Ok(ImportOutcome {
        path,
        untouched: before - replaced.len(),
        added,
        replaced,
    })
}

fn value_or_null(text: Option<&String>) -> Value {
    text.map_or(Value::Null, |text| Value::String(text.clone()))
}

// ---------------------------------------------------------------------------
// UTC cron expressions
// ---------------------------------------------------------------------------
//
// A five-field cron expression and the next UTC minute that matches it. This
// is the whole reason the import can write a `next_run_at` at all: the
// orchestrator never fires a job whose `next_run_at` is null, and Hermes arms
// that field at creation, so an import that skipped it would write jobs that
// silently never run.

/// One cron field as the set of values it matches.
#[derive(Debug, Clone)]
struct CronField {
    allowed: Vec<bool>,
}

impl CronField {
    fn parse(text: &str, min: u32, max: u32, dow: bool) -> Result<Self> {
        if text.is_empty() {
            anyhow::bail!("empty cron field");
        }
        let mut allowed = vec![false; (max - min + 1) as usize];
        for item in text.split(',') {
            if item.is_empty() {
                anyhow::bail!("invalid empty item in cron field `{text}`");
            }
            let mut parts = item.split('/');
            let base = parts.next().unwrap_or_default();
            let step = parts
                .next()
                .map(str::parse::<u32>)
                .transpose()
                .map_err(|_| anyhow::anyhow!("invalid cron step in `{item}`"))?
                .unwrap_or(1);
            if parts.next().is_some() || step == 0 {
                anyhow::bail!("invalid cron step in `{item}`");
            }
            let (start, end) = if base == "*" {
                (min, max)
            } else if let Some((start, end)) = base.split_once('-') {
                (
                    parse_cron_num(start, min, max, dow)?,
                    parse_cron_num(end, min, max, dow)?,
                )
            } else {
                let start = parse_cron_num(base, min, max, dow)?;
                (start, if item.contains('/') { max } else { start })
            };
            if start > end {
                anyhow::bail!("descending cron range `{base}` is unsupported");
            }
            let mut value = start;
            while value <= end {
                let normalized = if dow && value == 7 { 0 } else { value };
                allowed[(normalized - min) as usize] = true;
                let Some(next) = value.checked_add(step) else {
                    break;
                };
                value = next;
            }
        }
        if !allowed.iter().any(|allowed| *allowed) {
            anyhow::bail!("cron field `{text}` matches no values");
        }
        Ok(Self { allowed })
    }

    fn contains(&self, value: u32, min: u32) -> bool {
        self.allowed
            .get((value - min) as usize)
            .copied()
            .unwrap_or(false)
    }

    fn unrestricted(&self) -> bool {
        self.allowed.iter().all(|allowed| *allowed)
    }
}

fn parse_cron_num(text: &str, min: u32, max: u32, dow: bool) -> Result<u32> {
    let value = text
        .parse::<u32>()
        .map_err(|_| anyhow::anyhow!("invalid cron number `{text}`"))?;
    let upper = if dow { 7 } else { max };
    if value < min || value > upper {
        anyhow::bail!("cron number `{value}` is outside {min}..={upper}");
    }
    Ok(value)
}

/// A parsed `minute hour day-of-month month day-of-week` expression.
#[derive(Debug, Clone)]
struct CronSchedule {
    minute: CronField,
    hour: CronField,
    day_of_month: CronField,
    month: CronField,
    day_of_week: CronField,
}

impl CronSchedule {
    fn parse(schedule: &str) -> Result<Self> {
        let fields: Vec<&str> = schedule.split_whitespace().collect();
        if fields.len() != 5 {
            anyhow::bail!("invalid Claude cron `{schedule}`: expected exactly 5 fields");
        }
        Ok(Self {
            minute: CronField::parse(fields[0], 0, 59, false)?,
            hour: CronField::parse(fields[1], 0, 23, false)?,
            day_of_month: CronField::parse(fields[2], 1, 31, false)?,
            month: CronField::parse(fields[3], 1, 12, false)?,
            day_of_week: CronField::parse(fields[4], 0, 6, true)?,
        })
    }

    /// The first matching UTC minute strictly after `after_unix`.
    fn next_after(&self, after_unix: i64) -> Result<i64> {
        let start_minute = after_unix
            .div_euclid(60)
            .checked_add(1)
            .ok_or_else(|| anyhow::anyhow!("cron search overflows Unix time"))?;
        // Eight years covers the Gregorian leap cycle plus a safety margin.
        // If no minute matches, the expression is calendar-impossible.
        const SEARCH_MINUTES: i64 = 8 * 366 * 24 * 60;
        for delta in 0..SEARCH_MINUTES {
            let unix = start_minute
                .checked_add(delta)
                .and_then(|minute| minute.checked_mul(60))
                .ok_or_else(|| anyhow::anyhow!("cron search overflows Unix time"))?;
            if self.matches(unix) {
                return Ok(unix);
            }
        }
        anyhow::bail!("cron expression has no matching UTC minute within eight years")
    }

    fn matches(&self, unix: i64) -> bool {
        let days = unix.div_euclid(86_400);
        let seconds = unix.rem_euclid(86_400);
        let (_, month, day) = civil_from_days(days);
        let hour = (seconds / 3600) as u32;
        let minute = ((seconds % 3600) / 60) as u32;
        let dow = (days + 4).rem_euclid(7) as u32;
        let dom_match = self.day_of_month.contains(day, 1);
        let dow_match = self.day_of_week.contains(dow, 0);
        // Vixie semantics: with both day fields restricted, either matching is
        // enough.
        let day_match = match (
            self.day_of_month.unrestricted(),
            self.day_of_week.unrestricted(),
        ) {
            (true, true) => true,
            (true, false) => dow_match,
            (false, true) => dom_match,
            (false, false) => dom_match || dow_match,
        };
        self.minute.contains(minute, 0)
            && self.hour.contains(hour, 0)
            && self.month.contains(month, 1)
            && day_match
    }
}

// Howard Hinnant's public-domain civil calendar conversion.
fn civil_from_days(days: i64) -> (i64, u32, u32) {
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 }.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let mut year = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    year += (month <= 2) as i64;
    (year, month as u32, day as u32)
}

fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
    let year = year - i64::from(month <= 2);
    let era = if year >= 0 { year } else { year - 399 }.div_euclid(400);
    let yoe = year - era * 400;
    let mp = if month > 2 { month - 3 } else { month + 9 } as i64;
    let doy = (153 * mp + 2) / 5 + i64::from(day) - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

/// `1970-01-01T00:00:00Z` spelling of a Unix second.
fn rfc3339(unix: i64) -> String {
    let days = unix.div_euclid(86_400);
    let seconds = unix.rem_euclid(86_400);
    let (year, month, day) = civil_from_days(days);
    format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
        seconds / 3600,
        (seconds % 3600) / 60,
        seconds % 60
    )
}

/// The inverse, for the RFC3339 instants Claude's own records carry. Only the
/// UTC spellings a Claude transcript uses are accepted; an offset form is a
/// zone claim this import will not silently reinterpret.
fn rfc3339_to_unix(text: &str) -> Option<i64> {
    let bytes = text.as_bytes();
    if bytes.len() < 19 || bytes[4] != b'-' || bytes[7] != b'-' {
        return None;
    }
    if !matches!(bytes[10], b'T' | b't' | b' ') || bytes[13] != b':' || bytes[16] != b':' {
        return None;
    }
    let tail = &text[19..];
    let zone_ok = tail.is_empty()
        || tail.eq_ignore_ascii_case("z")
        || tail.strip_prefix('.').is_some_and(|rest| {
            rest.trim_end_matches(|c: char| c == 'Z' || c == 'z').len() < rest.len()
                || rest.chars().all(|c| c.is_ascii_digit())
        });
    if !zone_ok {
        return None;
    }
    let year: i64 = text[0..4].parse().ok()?;
    let month: u32 = text[5..7].parse().ok()?;
    let day: u32 = text[8..10].parse().ok()?;
    let hour: i64 = text[11..13].parse().ok()?;
    let minute: i64 = text[14..16].parse().ok()?;
    let second: i64 = text[17..19].parse().ok()?;
    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
        return None;
    }
    Some(days_from_civil(year, month, day) * 86_400 + hour * 3600 + minute * 60 + second)
}

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

    fn manifest_with(
        crons: Vec<ClaudeCronJob>,
        wakeups: Vec<ClaudeWakeup>,
    ) -> ClaudeRuntimeManifest {
        let mut manifest: ClaudeRuntimeManifest = serde_json::from_value(serde_json::json!({
            "schema_version": 1,
            "posture": {
                "permission_mode": null, "last_prompt_leaf_uuid": null, "last_prompt": null,
                "timestamp": null, "entrypoint": "cli", "user_type": "external",
                "version": "2.1.197", "cwd": "/workspace/project"
            },
            "active_crons": [],
            "pending_wakeups": [],
            "queue": {"enqueued": 0, "dequeued": 0, "removed": 0, "pending": []},
            "background_children": [],
            "reported_pending_background_children": 0,
            "residue": []
        }))
        .unwrap();
        manifest.active_crons = crons;
        manifest.pending_wakeups = wakeups;
        manifest
    }

    fn cron(id: &str, schedule: &str, recurring: bool) -> ClaudeCronJob {
        ClaudeCronJob {
            id: id.into(),
            tool_use_id: format!("toolu_{id}"),
            schedule: schedule.into(),
            recurring,
            durable_requested: false,
            prompt: "Check the release branch.".into(),
            created_at: Some("2026-07-14T10:00:02.000Z".into()),
            expires_after_seconds: None,
            creation_result: String::new(),
        }
    }

    fn wakeup(id: &str, scheduled_for: Option<&str>) -> ClaudeWakeup {
        ClaudeWakeup {
            tool_use_id: id.into(),
            delay_seconds: 300,
            reason: Some("recheck".into()),
            prompt: Some("Re-read the release branch.".into()),
            created_at: Some("2026-07-14T10:00:04.000Z".into()),
            scheduled_for: scheduled_for.map(str::to_string),
            creation_result: String::new(),
        }
    }

    fn temp(label: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "orc11-{label}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    const NOW: i64 = 1_788_000_000; // 2026-09-04T...Z, well after the fixtures.

    #[test]
    fn rfc3339_round_trips_through_both_directions() {
        for unix in [0, 1_788_000_000, 1_784_023_202, -86_400] {
            assert_eq!(rfc3339_to_unix(&rfc3339(unix)), Some(unix), "{unix}");
        }
        assert_eq!(
            rfc3339_to_unix("2026-07-14T10:00:02.000Z"),
            Some(1_784_023_202)
        );
        assert_eq!(rfc3339_to_unix("2026-07-14T10:00:02"), Some(1_784_023_202));
        // An explicit offset is a zone claim, not a UTC instant.
        assert_eq!(rfc3339_to_unix("2026-07-14T10:00:02+02:00"), None);
        assert_eq!(rfc3339_to_unix("not a timestamp"), None);
    }

    #[test]
    fn the_next_utc_minute_is_strictly_after_now_and_matches_the_expression() {
        // 2026-09-04T00:00:00Z is a Friday; */10 lands on the next ten-minute
        // boundary and never on `now` itself.
        let at = CronSchedule::parse("*/10 * * * *")
            .unwrap()
            .next_after(1_788_000_000)
            .unwrap();
        assert!(at > 1_788_000_000);
        assert_eq!(at % 600, 0);
        assert!(CronSchedule::parse("*/10 * * * *").unwrap().matches(at));
        // A day-restricted expression still resolves.
        let monthly = CronSchedule::parse("0 3 1 * *")
            .unwrap()
            .next_after(NOW)
            .unwrap();
        assert!(
            rfc3339(monthly).ends_with("-01T03:00:00Z"),
            "{}",
            rfc3339(monthly)
        );
        assert!(CronSchedule::parse("61 * * * *").is_err());
        assert!(CronSchedule::parse("* * * *").is_err());
    }

    #[test]
    fn a_cron_and_a_wakeup_compile_to_the_orchestrators_own_key_order() {
        let root = temp("keyorder");
        let manifest = manifest_with(
            vec![cron("release-watch", "*/10 * * * *", true)],
            vec![wakeup("toolu_wake", Some("2026-07-14T10:05:04.000Z"))],
        );
        let outcome = import_claude_session(&root, "sess-1", &manifest, NOW).unwrap();
        assert_eq!(
            outcome.added,
            vec!["sess-1-release-watch", "sess-1-toolu_wake"]
        );
        assert!(outcome.replaced.is_empty());

        let text = std::fs::read_to_string(&outcome.path).unwrap();
        assert!(text.ends_with("]\n"), "the orchestrator's trailing newline");
        let jobs: Vec<Value> = serde_json::from_str(&text).unwrap();
        assert_eq!(jobs.len(), 2);

        let keys: Vec<&str> = jobs[0]
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        assert_eq!(keys, JOB_KEY_ORDER);

        assert_eq!(jobs[0]["schedule"]["kind"], "cron");
        assert_eq!(jobs[0]["schedule"]["expr"], "*/10 * * * *");
        // The zone Claude's record does not carry, stated rather than assumed.
        assert_eq!(jobs[0]["schedule"]["tz"], "UTC");
        assert_eq!(jobs[0]["prompt"], "Check the release branch.");
        assert_eq!(jobs[0]["workdir"], "/workspace/project");
        assert_eq!(jobs[0]["deliver"], "local");
        assert_eq!(jobs[0]["enabled"], true);
        assert_eq!(jobs[0]["repeat"], Value::Null);
        assert_eq!(jobs[0]["created_at"], "2026-07-14T10:00:02.000Z");
        let next = jobs[0]["next_run_at"].as_str().unwrap();
        assert!(rfc3339_to_unix(next).unwrap() > NOW, "{next}");

        assert_eq!(jobs[1]["schedule"]["kind"], "once");
        // The wakeup was already overdue at import; it is due now, not re-dated.
        assert_eq!(jobs[1]["schedule"]["run_at"], rfc3339(NOW));
        assert_eq!(jobs[1]["next_run_at"], rfc3339(NOW));
        assert_eq!(jobs[1]["prompt"], "Re-read the release branch.");
    }

    #[test]
    fn a_non_recurring_cron_carries_one_remaining_run() {
        let root = temp("once-cron");
        let manifest = manifest_with(vec![cron("one-shot", "5 4 * * *", false)], vec![]);
        import_claude_session(&root, "sess-2", &manifest, NOW).unwrap();
        let jobs: Vec<Value> =
            serde_json::from_str(&std::fs::read_to_string(root.join("cron/jobs.json")).unwrap())
                .unwrap();
        assert_eq!(jobs[0]["repeat"], 1);
    }

    #[test]
    fn a_wakeup_without_a_recorded_instant_falls_back_to_creation_plus_delay() {
        let root = temp("wake-fallback");
        let mut w = wakeup("toolu_bare", None);
        w.created_at = Some(rfc3339(NOW + 1_000));
        let manifest = manifest_with(vec![], vec![w]);
        import_claude_session(&root, "sess-3", &manifest, NOW).unwrap();
        let jobs: Vec<Value> =
            serde_json::from_str(&std::fs::read_to_string(root.join("cron/jobs.json")).unwrap())
                .unwrap();
        assert_eq!(jobs[0]["schedule"]["run_at"], rfc3339(NOW + 1_300));
    }

    #[test]
    fn other_jobs_keep_their_bytes_and_a_reimport_replaces_only_its_own() {
        let root = temp("merge");
        std::fs::create_dir_all(root.join("cron")).unwrap();
        // A job some other owner wrote, with a key this import never emits.
        let foreign = "[\n  {\n    \"id\": \"digest-15m\",\n    \"schedule\": {\n      \"kind\": \"interval\",\n      \"minutes\": 15\n    },\n    \"prompt\": \"digest\",\n    \"script\": \"/opt/digest.sh\",\n    \"enabled\": true\n  }\n]\n";
        std::fs::write(root.join("cron/jobs.json"), foreign).unwrap();

        let manifest = manifest_with(vec![cron("release-watch", "*/10 * * * *", true)], vec![]);
        let first = import_claude_session(&root, "sess-1", &manifest, NOW).unwrap();
        assert_eq!(first.added, vec!["sess-1-release-watch"]);
        assert_eq!(first.untouched, 1);

        let jobs: Vec<Value> =
            serde_json::from_str(&std::fs::read_to_string(root.join("cron/jobs.json")).unwrap())
                .unwrap();
        assert_eq!(jobs.len(), 2);
        // Byte-for-byte the record it was, key order and unmodeled key included.
        assert_eq!(
            serde_json::to_string_pretty(&jobs[0]).unwrap(),
            serde_json::to_string_pretty(&serde_json::from_str::<Vec<Value>>(foreign).unwrap()[0])
                .unwrap()
        );

        // A second import of the same session rewrites its own row in place and
        // still leaves exactly two jobs.
        let second = import_claude_session(&root, "sess-1", &manifest, NOW + 60).unwrap();
        assert!(second.added.is_empty());
        assert_eq!(second.replaced, vec!["sess-1-release-watch"]);
        assert_eq!(second.untouched, 1);
        let jobs: Vec<Value> =
            serde_json::from_str(&std::fs::read_to_string(root.join("cron/jobs.json")).unwrap())
                .unwrap();
        assert_eq!(jobs.len(), 2);
        assert_eq!(jobs[0]["id"], "digest-15m");
        assert_eq!(jobs[1]["id"], "sess-1-release-watch");

        // A different session lands beside it, never on top of it.
        let third = import_claude_session(&root, "sess-9", &manifest, NOW).unwrap();
        assert_eq!(third.added, vec!["sess-9-release-watch"]);
        assert_eq!(third.untouched, 2);
    }

    #[test]
    fn a_jobs_file_that_is_not_an_array_is_refused_by_name() {
        let root = temp("bad-store");
        std::fs::create_dir_all(root.join("cron")).unwrap();
        std::fs::write(root.join("cron/jobs.json"), "{\"jobs\": []}").unwrap();
        let manifest = manifest_with(vec![cron("c", "* * * * *", true)], vec![]);
        let error = import_claude_session(&root, "s", &manifest, NOW)
            .unwrap_err()
            .to_string();
        assert!(error.contains("cron/jobs.json"), "{error}");
        assert!(error.contains("an object"), "{error}");
    }
}