ultron-kernel-apis 1.0.0

Host operations behind the thin Python kernel APIs: code skills and the skill catalog, memory, hints, images
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
//! `schedules.*` and `goals.*` (port of `ultron/schedules.ts`): recurring task firings and goals with required
//! checks. Firings are admitted through [`TaskHost::spawn`] with a slot-derived key (`schedule:<id>:<slot>`), and
//! each slot is claimed durably (`last_slot`, `pending_slot`) before admission, so duplicate ticks and restarts never
//! run a slot twice; a claimed slot that fails is recorded once and never retried. Missed slots coalesce into one run
//! of the latest slot (`skipped`). A goal is achieved only when every required check succeeds with `passed: true`;
//! `max_tasks` caps firings, verification and attachments. The document is `{version: 1, schedules, goals}`.
//!
//! The TS module ticks on a background interval timer (1 s). Here [`crate::schedule_tick::ScheduleTicker`] sleeps
//! until the earliest due slot ([`SchedulesModule::next_fire`], derived from each schedule's durable `start_at`,
//! `every_ms`, `last_slot` and `pending_slot`, so a reopened module recomputes it) and is woken by every committed
//! change; the model may still send `schedules.tick`.

use crate::store::read_versioned;
use crate::tasks::TaskHost;
use crate::util::Clock;
use kernel::store::DocumentStore;
use serde_json::{Map, Value, json};
use std::collections::HashSet;
use std::sync::{Arc, Mutex};

const MAX_EVERY_MS: i64 = 366 * 24 * 60 * 60 * 1000;

fn definition_key(value: Option<&Value>, name: &str) -> Result<String, String> {
    match value.and_then(Value::as_str) {
        Some(text) if crate::util::valid_definition(text) => Ok(text.to_string()),
        _ => Err(format!("{name} must be id@version")),
    }
}

fn integer(value: Option<&Value>, name: &str, min: i64, max: i64) -> Result<i64, String> {
    value
        .filter(|value| value.is_number())
        .and_then(jsrt::number::safe_integer)
        .filter(|number| (min..=max).contains(number))
        .ok_or_else(|| format!("{name} must be an integer between {min} and {max}"))
}

fn optional_integer(value: Option<&Value>, name: &str, min: i64) -> Result<Option<i64>, String> {
    match value {
        None | Some(Value::Null) => Ok(None),
        value => integer(value, name, min, jsrt::number::MAX_SAFE_INTEGER).map(Some),
    }
}

fn validate_document(saved: Value) -> Result<Value, String> {
    let invalid = || "Invalid schedule document".to_string();
    let map = saved.as_object().ok_or_else(invalid)?;
    let (Some(schedules), Some(goals)) = (
        map.get("schedules").and_then(Value::as_array),
        map.get("goals").and_then(Value::as_array),
    ) else {
        return Err(invalid());
    };
    if map.get("version") != Some(&json!(1)) {
        return Err(invalid());
    }
    let mut ids = HashSet::new();
    for item in schedules.iter().chain(goals) {
        let id = item
            .as_object()
            .and_then(|item| item.get("id"))
            .and_then(Value::as_str)
            .ok_or_else(invalid)?;
        if !ids.insert(id.to_string()) {
            return Err(invalid());
        }
    }
    Ok(saved)
}

/// Slot index for `now`; negative before the schedule starts.
pub fn schedule_slot(start_at: i64, every_ms: i64, now: i64) -> i64 {
    (now - start_at).div_euclid(every_ms)
}

fn schedule_key(schedule: &Value, slot: i64) -> String {
    format!("schedule:{}:{slot}", schedule["id"].as_str().unwrap_or(""))
}

fn check_outcome(definition: &str, task_id: Option<&str>, result: &Value) -> Value {
    let status = result["status"].clone();
    let mut outcome = json!({"definition": definition, "task_id": task_id, "status": status, "passed": false});
    if result["status"] != "succeeded" {
        let error = match result.get("error").and_then(Value::as_str).filter(|e| !e.is_empty()) {
            Some(error) => format!(": {error}"),
            None => String::new(),
        };
        outcome["reason"] = format!("{definition} {}{error}", result["status"].as_str().unwrap_or("")).into();
        return outcome;
    }
    match result["value"]
        .get("passed")
        .and_then(Value::as_bool)
        .filter(|_| result["value"].is_object())
    {
        None => outcome["reason"] = format!("{definition} did not report a boolean passed value").into(),
        Some(passed) => {
            outcome["passed"] = passed.into();
            if !passed {
                outcome["reason"] = format!("{definition} reported passed=false").into();
            }
        }
    }
    outcome
}

fn missing(definition: &str, task_id: Option<&str>, error: &str) -> Value {
    json!({"definition": definition, "task_id": task_id, "status": "missing", "passed": false,
        "reason": format!("{definition}: {error}")})
}

fn find<'a>(items: &'a mut Value, key: &str, id: &str) -> Option<&'a mut Value> {
    items[key].as_array_mut()?.iter_mut().find(|item| item["id"] == id)
}

fn lookup(document: &Value, key: &str, id: Option<&Value>, unknown: &str) -> Result<Value, String> {
    let id = jsrt::payload::nonempty_string(id, "id")?;
    document[key]
        .as_array()
        .and_then(|items| items.iter().find(|item| item["id"] == id.as_str()))
        .cloned()
        .ok_or_else(|| unknown.to_string())
}

/// Remaining task slots of a goal (`None`: unlimited).
fn capacity(goal: &Value) -> Option<i64> {
    let used = goal["task_ids"].as_array().map_or(0, Vec::len) as i64;
    goal["max_tasks"].as_i64().map(|max| max - used)
}

fn has_capacity(goal: &Value, needed: i64) -> bool {
    capacity(goal).is_none_or(|left| left >= needed)
}

fn push_task(goal: &mut Value, task_id: &Value) {
    if let Some(ids) = goal["task_ids"].as_array_mut()
        && !ids.contains(task_id)
    {
        ids.push(task_id.clone());
    }
}

/// When `schedule` next fires: a claimed slot whose admission was not recorded is due at once (`i64::MIN`); else the
/// start of the slot after `last_slot` (slot 0 at `start_at`). `None` when it does not fire: not active, or its goal is
/// missing or not active. A time in the past means due now; missed slots then coalesce into one run.
pub fn next_fire_at(schedule: &Value, goals: &[Value]) -> Option<i64> {
    if schedule["state"] != "active" {
        return None;
    }
    if let Some(goal_id) = schedule["goal_id"].as_str()
        && !goals
            .iter()
            .any(|goal| goal["id"] == goal_id && goal["state"] == "active")
    {
        return None;
    }
    if schedule["pending_slot"].is_i64() {
        return Some(i64::MIN);
    }
    let every_ms = schedule["every_ms"].as_i64().filter(|every| *every > 0)?;
    let next_slot = schedule["last_slot"].as_i64().map_or(0, |last| last.saturating_add(1));
    Some(
        schedule["start_at"]
            .as_i64()
            .unwrap_or(0)
            .saturating_add(next_slot.saturating_mul(every_ms)),
    )
}

/// Called after every committed change (the ticker re-reads the next fire time).
pub type ChangeHook = Arc<dyn Fn() + Send + Sync>;

pub struct SchedulesModule {
    store: Arc<dyn DocumentStore>,
    on_change: Mutex<Option<ChangeHook>>,
    /// `None`: the host's clock.
    clock: Option<Clock>,
    /// The loaded document; every read-modify-write runs under this lock.
    document: Mutex<Option<Value>>,
}

impl SchedulesModule {
    pub fn new(store: Arc<dyn DocumentStore>, clock: Option<Clock>) -> Self {
        Self {
            store,
            on_change: Mutex::new(None),
            clock,
            document: Mutex::new(None),
        }
    }

    /// Calls `hook` after every committed change (the ticker's wake-up).
    pub fn on_change(&self, hook: Option<ChangeHook>) {
        *jsrt::sync::lock(&self.on_change) = hook;
    }

    fn changed(&self) {
        let hook = jsrt::sync::lock(&self.on_change).clone();
        if let Some(hook) = hook {
            hook();
        }
    }

    /// The earliest time a schedule fires (see [`next_fire_at`]), after the document loads; `None`: none will.
    pub fn next_fire(&self) -> Result<Option<i64>, String> {
        let mut guard = jsrt::sync::lock(&self.document);
        let document = self.loaded(&mut guard)?;
        let goals = document["goals"].as_array().cloned().unwrap_or_default();
        Ok(document["schedules"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|schedule| next_fire_at(schedule, &goals))
            .min())
    }

    fn now(&self, host: &dyn TaskHost) -> i64 {
        self.clock.as_ref().map_or_else(|| host.now(), |clock| clock())
    }

    fn loaded<'a>(&self, slot: &'a mut Option<Value>) -> Result<&'a mut Value, String> {
        if slot.is_none() {
            *slot = Some(match self.store.read()? {
                None => json!({"version": 1, "schedules": [], "goals": []}),
                saved => {
                    validate_document(read_versioned("ultron.module/schedules", saved, "version")?.unwrap_or_default())?
                }
            });
        }
        Ok(slot.as_mut().expect("loaded"))
    }

    /// Mutates a copy, commits it, then publishes it; a failed mutation or write leaves the old state.
    fn update<T>(
        &self,
        document: &mut Value,
        mutate: impl FnOnce(&mut Value) -> Result<T, String>,
    ) -> Result<T, String> {
        let mut draft = document.clone();
        let result = mutate(&mut draft)?;
        self.store.write(&draft)?;
        *document = draft;
        self.changed();
        Ok(result)
    }

    /// Recovers goal task links written by keys the host already admitted before a crash.
    fn reconcile(&self, document: &mut Value, host: &dyn TaskHost) -> Result<(), String> {
        if document["goals"].as_array().is_none_or(Vec::is_empty) {
            return Ok(());
        }
        let tasks = host.tasks()?;
        let mut draft = document.clone();
        let mut changed = false;
        for goal in draft["goals"].as_array_mut().into_iter().flatten() {
            let prefix = format!("goal:{}:", goal["id"].as_str().unwrap_or(""));
            for task in &tasks {
                if task["key"].as_str().is_some_and(|key| key.starts_with(&prefix))
                    && !goal["task_ids"].as_array().is_some_and(|ids| ids.contains(&task["id"]))
                {
                    push_task(goal, &task["id"]);
                    changed = true;
                }
            }
        }
        let schedules = draft["schedules"].as_array().cloned().unwrap_or_default();
        for schedule in schedules {
            let Some(goal_id) = schedule["goal_id"].as_str() else {
                continue;
            };
            let slot = schedule["pending_slot"]
                .as_i64()
                .or_else(|| schedule["last_slot"].as_i64());
            let task = slot.and_then(|slot| {
                let key = schedule_key(&schedule, slot);
                tasks.iter().find(|task| task["key"] == key.as_str())
            });
            if let (Some(goal), Some(task)) = (find(&mut draft, "goals", goal_id), task)
                && !goal["task_ids"].as_array().is_some_and(|ids| ids.contains(&task["id"]))
            {
                push_task(goal, &task["id"]);
                changed = true;
            }
        }
        if changed {
            self.store.write(&draft)?;
            *document = draft;
        }
        Ok(())
    }

    pub fn start(&self, host: &dyn TaskHost) -> Result<(), String> {
        let mut guard = jsrt::sync::lock(&self.document);
        let document = self.loaded(&mut guard)?;
        self.reconcile(document, host)
    }

    pub fn handle(
        &self,
        kind: &str,
        payload: &Map<String, Value>,
        caller: Option<&str>,
        host: &dyn TaskHost,
    ) -> Result<Value, String> {
        if kind == "goals.verify" {
            return self.verify(payload, caller, host);
        }
        let mut guard = jsrt::sync::lock(&self.document);
        let document = self.loaded(&mut guard)?;
        match kind {
            "schedules.create" => self.create_schedule(document, payload, caller, host),
            "schedules.list" => {
                kernel::ops::fields("schedules.list", payload)?;
                Ok(document["schedules"].clone())
            }
            "schedules.pause" => self.set_schedule_state(document, kind, payload, "paused"),
            "schedules.resume" => self.set_schedule_state(document, kind, payload, "active"),
            "schedules.delete" => {
                kernel::ops::fields("schedules.delete", payload)?;
                self.update(document, |draft| {
                    let schedule = lookup(draft, "schedules", payload.get("id"), "Unknown schedule")?;
                    if let Some(items) = draft["schedules"].as_array_mut() {
                        items.retain(|item| item["id"] != schedule["id"]);
                    }
                    Ok(json!({"deleted": true}))
                })
            }
            "schedules.tick" => {
                kernel::ops::fields("schedules.tick", payload)?;
                // Firings outlive the request that happened to drive the tick.
                self.tick_locked(document, host)
            }
            "goals.create" => self.create_goal(document, payload, caller, host),
            "goals.list" => {
                kernel::ops::fields("goals.list", payload)?;
                Ok(document["goals"].clone())
            }
            "goals.get" => {
                kernel::ops::fields("goals.get", payload)?;
                lookup(document, "goals", payload.get("id"), "Unknown goal")
            }
            "goals.pause" => self.set_goal_state(document, kind, payload, "paused"),
            "goals.resume" => self.set_goal_state(document, kind, payload, "active"),
            "goals.attach" => self.attach(document, payload, host),
            _ => Err(format!("Unknown schedule request: {kind}")),
        }
    }

    fn create_schedule(
        &self,
        document: &mut Value,
        payload: &Map<String, Value>,
        owner: Option<&str>,
        host: &dyn TaskHost,
    ) -> Result<Value, String> {
        kernel::ops::fields("schedules.create", payload)?;
        let definition = definition_key(payload.get("definition"), "definition")?;
        let input = payload.get("input").cloned().ok_or("input must be JSON")?;
        let every_ms = integer(payload.get("every_ms"), "every_ms", 1, MAX_EVERY_MS)?;
        let now = self.now(host);
        let start_at = optional_integer(payload.get("start_at"), "start_at", 0)?.unwrap_or(now);
        let max_runs = optional_integer(payload.get("max_runs"), "max_runs", 1)?;
        let model = match payload.get("model") {
            None | Some(Value::Null) => Value::Null,
            Some(model) => model_scope::model_ref(model)?.into(),
        };
        let goal_id = payload.get("goal_id").cloned().unwrap_or(Value::Null);
        self.update(document, |draft| {
            if !goal_id.is_null() && lookup(draft, "goals", Some(&goal_id), "Unknown goal")?["state"] == "achieved" {
                return Err("Cannot attach a schedule to an achieved goal".into());
            }
            let schedule = json!({
                "id": format!("schedule-{}", jsrt::random::uuid_v4()),
                "definition": definition, "input": input, "every_ms": every_ms, "start_at": start_at,
                "max_runs": max_runs, "goal_id": goal_id, "model": model, "owner": owner, "state": "active",
                "created_at": now, "runs": 0, "last_slot": null, "pending_slot": null, "last_task_id": null,
                "last_fired_at": null, "last_skipped": 0, "skipped_total": 0, "last_failure": null, "failures": 0,
            });
            if let Some(items) = draft["schedules"].as_array_mut() {
                items.push(schedule.clone());
            }
            Ok(schedule)
        })
    }

    fn set_schedule_state(
        &self,
        document: &mut Value,
        kind: &str,
        payload: &Map<String, Value>,
        state: &str,
    ) -> Result<Value, String> {
        kernel::ops::fields(kind, payload)?;
        self.update(document, |draft| {
            let id = lookup(draft, "schedules", payload.get("id"), "Unknown schedule")?["id"].clone();
            let schedule = find(draft, "schedules", id.as_str().unwrap_or("")).expect("found above");
            if schedule["state"] == "completed" {
                return Err("Schedule is completed".into());
            }
            schedule["state"] = state.into();
            Ok(schedule.clone())
        })
    }

    fn create_goal(
        &self,
        document: &mut Value,
        payload: &Map<String, Value>,
        owner: Option<&str>,
        host: &dyn TaskHost,
    ) -> Result<Value, String> {
        kernel::ops::fields("goals.create", payload)?;
        let title = jsrt::payload::nonempty_string(payload.get("title"), "title")?;
        let items = payload
            .get("required_checks")
            .and_then(Value::as_array)
            .ok_or("required_checks must be an array")?;
        let checks = items
            .iter()
            .map(|item| definition_key(Some(item), "required_checks entry"))
            .collect::<Result<Vec<_>, _>>()?;
        if checks.iter().collect::<HashSet<_>>().len() != checks.len() {
            return Err("required_checks must not repeat".into());
        }
        let max_tasks = optional_integer(payload.get("max_tasks"), "max_tasks", 0)?;
        let now = self.now(host);
        self.update(document, |draft| {
            let goal = json!({
                "id": format!("goal-{}", jsrt::random::uuid_v4()), "title": title, "required_checks": checks, "max_tasks": max_tasks,
                "owner": owner, "state": "active", "created_at": now, "task_ids": [], "verify_rounds": 0,
                "verification": null,
            });
            if let Some(items) = draft["goals"].as_array_mut() {
                items.push(goal.clone());
            }
            Ok(goal)
        })
    }

    fn set_goal_state(
        &self,
        document: &mut Value,
        kind: &str,
        payload: &Map<String, Value>,
        state: &str,
    ) -> Result<Value, String> {
        kernel::ops::fields(kind, payload)?;
        self.update(document, |draft| {
            let id = lookup(draft, "goals", payload.get("id"), "Unknown goal")?["id"].clone();
            let goal = find(draft, "goals", id.as_str().unwrap_or("")).expect("found above");
            if goal["state"] == "achieved" {
                return Err("Goal is already achieved".into());
            }
            goal["state"] = state.into();
            Ok(goal.clone())
        })
    }

    fn attach(&self, document: &mut Value, payload: &Map<String, Value>, host: &dyn TaskHost) -> Result<Value, String> {
        kernel::ops::fields("goals.attach", payload)?;
        let task_id = jsrt::payload::nonempty_string(payload.get("task_id"), "task_id")?;
        let goal_id = lookup(document, "goals", payload.get("id"), "Unknown goal")?["id"].clone();
        if !host.tasks()?.iter().any(|task| task["id"] == task_id.as_str()) {
            return Err("Unknown Ultron task".into());
        }
        self.update(document, |draft| {
            let goal = find(draft, "goals", goal_id.as_str().unwrap_or("")).ok_or("Unknown goal")?;
            let task = Value::from(task_id.clone());
            if !goal["task_ids"].as_array().is_some_and(|ids| ids.contains(&task)) {
                if !has_capacity(goal, 1) {
                    return Err(format!("Goal task limit reached ({})", goal["max_tasks"]));
                }
                push_task(goal, &task);
            }
            Ok(goal.clone())
        })
    }

    /// Fires due schedules (the TS background timer's work); returns `{fired, failed}`.
    pub fn tick(&self, host: &dyn TaskHost) -> Result<Value, String> {
        let mut guard = jsrt::sync::lock(&self.document);
        let document = self.loaded(&mut guard)?;
        self.tick_locked(document, host)
    }

    fn tick_locked(&self, document: &mut Value, host: &dyn TaskHost) -> Result<Value, String> {
        let mut fired = Vec::new();
        let mut failed = Vec::new();
        let now = self.now(host);
        let ids: Vec<String> = document["schedules"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|item| item["id"].as_str().map(str::to_string))
            .collect();
        for id in ids {
            let Some(current) = document["schedules"]
                .as_array()
                .and_then(|items| items.iter().find(|item| item["id"] == id.as_str()))
                .cloned()
            else {
                continue;
            };
            if current["state"] != "active" {
                continue;
            }
            let pending = current["pending_slot"].as_i64();
            let slot = pending.unwrap_or_else(|| {
                schedule_slot(
                    current["start_at"].as_i64().unwrap_or(0),
                    current["every_ms"].as_i64().unwrap_or(1),
                    now,
                )
            });
            if slot < 0 {
                continue;
            }
            let resuming = pending.is_some();
            let last = current["last_slot"].as_i64();
            if !resuming && last.is_some_and(|last| slot <= last) {
                continue;
            }
            let goal = current["goal_id"].as_str().and_then(|goal_id| {
                document["goals"]
                    .as_array()
                    .and_then(|goals| goals.iter().find(|goal| goal["id"] == goal_id))
                    .cloned()
            });
            // A missing goal cannot be verified or paused, so its schedules stay idle.
            if !current["goal_id"].is_null() && goal.as_ref().is_none_or(|goal| goal["state"] != "active") {
                continue;
            }
            let skipped = if resuming {
                current["last_skipped"].as_i64().unwrap_or(0)
            } else {
                slot - last.unwrap_or(-1) - 1
            };
            let claimed = self.update(document, |draft| {
                let schedule = find(draft, "schedules", &id).ok_or("Unknown schedule")?;
                schedule["last_slot"] = slot.into();
                schedule["pending_slot"] = slot.into();
                schedule["last_skipped"] = skipped.into();
                if !resuming {
                    schedule["skipped_total"] = (schedule["skipped_total"].as_i64().unwrap_or(0) + skipped).into();
                }
                Ok(schedule.clone())
            })?;
            let mut task = None;
            let mut failure = None;
            if let Some(goal) = goal.as_ref().filter(|goal| !has_capacity(goal, 1)) {
                failure = Some(format!("Goal task limit reached ({})", goal["max_tasks"]));
            } else {
                let mut request = json!({
                    "definition": claimed["definition"], "input": claimed["input"], "key": schedule_key(&claimed, slot),
                });
                if !claimed["model"].is_null() {
                    request["model"] = claimed["model"].clone();
                }
                match host.spawn(&request, claimed["owner"].as_str()) {
                    Ok(spawned) => task = Some(spawned),
                    Err(error) => failure = Some(error),
                }
            }
            // The slot stays claimed on failure: the next attempt is the next slot, never a retry loop.
            self.update(document, |draft| {
                let schedule = find(draft, "schedules", &id).ok_or("Unknown schedule")?;
                schedule["pending_slot"] = Value::Null;
                let mut linked = None;
                match &task {
                    Some(task) => {
                        let runs = schedule["runs"].as_i64().unwrap_or(0) + 1;
                        schedule["runs"] = runs.into();
                        schedule["last_task_id"] = task["id"].clone();
                        schedule["last_fired_at"] = now.into();
                        if schedule["max_runs"].as_i64().is_some_and(|max| runs >= max) {
                            schedule["state"] = "completed".into();
                        }
                        linked = schedule["goal_id"].as_str().map(str::to_string);
                    }
                    None => {
                        schedule["failures"] = (schedule["failures"].as_i64().unwrap_or(0) + 1).into();
                        schedule["last_failure"] = json!({"slot": slot,
                            "error": failure.clone().unwrap_or_else(|| "unknown failure".into()), "at": now});
                    }
                }
                if let (Some(goal_id), Some(task)) = (linked, &task)
                    && let Some(goal) = find(draft, "goals", &goal_id)
                {
                    push_task(goal, &task["id"]);
                }
                Ok(())
            })?;
            match task {
                Some(task) => {
                    fired.push(json!({"schedule_id": id, "slot": slot, "task_id": task["id"], "skipped": skipped}))
                }
                None => failed.push(json!({"schedule_id": id, "slot": slot,
                    "error": failure.unwrap_or_else(|| "unknown failure".into())})),
            }
        }
        Ok(json!({"fired": fired, "failed": failed}))
    }

    /// Runs every required check and accepts the goal only on unanimous, explicit passes. Admission is serialized
    /// with other mutations; waiting for results is not.
    fn verify(&self, payload: &Map<String, Value>, caller: Option<&str>, host: &dyn TaskHost) -> Result<Value, String> {
        kernel::ops::fields("goals.verify", payload)?;
        let (goal_id, round, spawned) = {
            let mut guard = jsrt::sync::lock(&self.document);
            let document = self.loaded(&mut guard)?;
            let goal = lookup(document, "goals", payload.get("id"), "Unknown goal")?;
            if goal["state"] == "achieved" {
                return Err("Goal is already achieved".into());
            }
            if goal["state"] == "paused" {
                return Err("Goal is paused".into());
            }
            let checks: Vec<String> = goal["required_checks"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(|check| check.as_str().map(str::to_string))
                .collect();
            if !has_capacity(&goal, checks.len() as i64) {
                return Err(format!(
                    "Goal task limit reached: verification needs {} tasks, {} remain",
                    checks.len(),
                    capacity(&goal).unwrap_or(0).max(0)
                ));
            }
            let goal_id = goal["id"].as_str().unwrap_or("").to_string();
            let round = self.update(document, |draft| {
                let target = find(draft, "goals", &goal_id).ok_or("Unknown goal")?;
                let round = target["verify_rounds"].as_i64().unwrap_or(0) + 1;
                target["verify_rounds"] = round.into();
                Ok(round)
            })?;
            let input = payload
                .get("input")
                .cloned()
                .unwrap_or_else(|| json!({"goal_id": goal_id, "title": goal["title"]}));
            let spawned: Vec<(String, Result<Value, String>)> = checks
                .iter()
                .enumerate()
                .map(|(index, definition)| {
                    let request = json!({"definition": definition, "input": input,
                        "key": format!("goal:{goal_id}:verify:{round}:{index}")});
                    (definition.clone(), host.spawn(&request, caller))
                })
                .collect();
            self.update(document, |draft| {
                let target = find(draft, "goals", &goal_id).ok_or("Unknown goal")?;
                for (_, task) in &spawned {
                    if let Ok(task) = task {
                        push_task(target, &task["id"]);
                    }
                }
                Ok(())
            })?;
            (goal_id, round, spawned)
        };
        let checks: Vec<Value> = spawned
            .iter()
            .map(|(definition, task)| match task {
                Err(error) => missing(definition, None, error),
                Ok(task) => {
                    let id = task["id"].as_str().unwrap_or("");
                    match host.result(id) {
                        Ok(result) => check_outcome(definition, Some(id), &result),
                        Err(error) => missing(definition, Some(id), &error),
                    }
                }
            })
            .collect();
        let mut guard = jsrt::sync::lock(&self.document);
        let document = self.loaded(&mut guard)?;
        let now = self.now(host);
        self.update(document, |draft| {
            let goal = find(draft, "goals", &goal_id).ok_or("Unknown goal")?;
            let mut reasons: Vec<Value> = checks.iter().filter_map(|check| check.get("reason").cloned()).collect();
            let status = if checks.is_empty() {
                reasons.push("Goal has no required checks".into());
                "unverified"
            } else if checks.iter().all(|check| check["passed"] == true) {
                "achieved"
            } else {
                "unachieved"
            };
            // A newer round supersedes this one; its record is the one that counts.
            if goal["verification"]["round"]
                .as_i64()
                .is_none_or(|recorded| recorded < round)
            {
                goal["verification"] =
                    json!({"round": round, "status": status, "at": now, "checks": checks, "reasons": reasons});
                let state = verified_state(goal["state"].as_str().unwrap_or_default(), status);
                goal["state"] = state.into();
            }
            Ok(goal.clone())
        })
    }
}

/// A goal's state once a verification round with `status` is recorded (the latest round decides, the check results
/// arrive with the lock released): an active goal it passes is achieved, an achieved goal it does not pass (an
/// older round passed first) is active again, and a goal paused meanwhile stays paused.
fn verified_state<'a>(state: &'a str, status: &str) -> &'a str {
    match (state, status) {
        ("active", "achieved") => "achieved",
        ("achieved", status) if status != "achieved" => "active",
        (state, _) => state,
    }
}

impl crate::ApiModule for SchedulesModule {
    fn prefixes(&self) -> &[&str] {
        &["schedules.", "goals."]
    }

    fn start(&self, host: &dyn TaskHost) -> Result<(), String> {
        SchedulesModule::start(self, host)
    }

    fn handle(&self, request: &crate::Request<'_>) -> Result<Value, String> {
        SchedulesModule::handle(self, request.kind, request.payload, request.caller_task, request.host)
    }
}