supercode-cli 0.5.84

Volter Harness — 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
//! 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_harness::{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)
}