ultron-harness 1.0.2

Durable task runtime: the Pi Durable scheduler and conversation runtime (submissions, generation, durable REPL cells, children, swarm state), the RLM task journal, the lane snapshot reducer and the effect gate
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
//! Port of `packages/coding-agent/src/ultron/rlm/task-store.ts`: the session-scoped journal of RLM tasks
//! (frames, spawns, agents). One owner per store; every change rewrites one JSON document and is
//! published only after the write commits. A failed write poisons the journal; reopening turns
//! unfinished tasks into `interrupted` and never replays them, except a subagent its new owner reattaches
//! ([`TaskJournal::reopen`]), which stays `running` until its end is recorded.

use std::fmt;

use kernel::store::DocumentStore;
use serde_json::{Map, Value, json};

/// Finished tasks kept in the persisted document: the newest ones. Memory keeps every task.
pub(crate) const MAX_PERSISTED_FINISHED_TASKS: usize = 100;

const RESULT_KEYS: [&str; 8] = [
    "status",
    "value",
    "error",
    "verification",
    "verdict",
    "check",
    "unverified",
    "worktree",
];
const TASK_KEYS: [&str; 7] = ["id", "key", "fingerprint", "definition", "state", "result", "parentId"];

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TaskState {
    Admitted,
    Running,
    Completed,
    Failed,
    Cancelled,
    Interrupted,
}

impl TaskState {
    pub fn parse(text: &str) -> Option<TaskState> {
        Some(match text {
            "admitted" => TaskState::Admitted,
            "running" => TaskState::Running,
            "completed" => TaskState::Completed,
            "failed" => TaskState::Failed,
            "cancelled" => TaskState::Cancelled,
            "interrupted" => TaskState::Interrupted,
            _ => return None,
        })
    }

    pub fn as_str(self) -> &'static str {
        match self {
            TaskState::Admitted => "admitted",
            TaskState::Running => "running",
            TaskState::Completed => "completed",
            TaskState::Failed => "failed",
            TaskState::Cancelled => "cancelled",
            TaskState::Interrupted => "interrupted",
        }
    }

    pub fn is_terminal(self) -> bool {
        !matches!(self, TaskState::Admitted | TaskState::Running)
    }

    /// The result status a terminal state must carry (`completed` pairs with `succeeded`).
    fn result_status(self) -> &'static str {
        match self {
            TaskState::Completed => "succeeded",
            other => other.as_str(),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct Task {
    pub id: String,
    pub key: String,
    pub fingerprint: String,
    pub definition: String,
    pub state: TaskState,
    /// A validated result object; present exactly when the state is terminal.
    pub result: Option<Value>,
    /// Spawning task; absent for tasks started by the root lane.
    pub parent_id: Option<String>,
}

impl Task {
    pub fn to_json(&self) -> Value {
        let mut map = Map::new();
        map.insert("id".into(), self.id.clone().into());
        map.insert("definition".into(), self.definition.clone().into());
        map.insert("fingerprint".into(), self.fingerprint.clone().into());
        map.insert("key".into(), self.key.clone().into());
        map.insert("state".into(), self.state.as_str().into());
        if let Some(parent) = &self.parent_id {
            map.insert("parentId".into(), parent.clone().into());
        }
        if let Some(result) = &self.result {
            map.insert("result".into(), result.clone());
        }
        Value::Object(map)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum TaskStoreError {
    Durability,
    ReadFailed,
    InvalidDocument,
    UnsupportedVersion(Value),
    InvalidResult,
    InvalidDefinition,
    InvalidFingerprint,
    InvalidKey,
    KeyReused,
    InvalidId,
    UnknownTask,
    InvalidTransition,
    StateResultMismatch,
}

impl fmt::Display for TaskStoreError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TaskStoreError::Durability => f.write_str("Task store durability is uncertain; reopen the owner"),
            TaskStoreError::ReadFailed => f.write_str("Task store could not be read"),
            TaskStoreError::InvalidDocument => f.write_str("Invalid task document"),
            TaskStoreError::UnsupportedVersion(version) => write!(
                f,
                "Cannot resume: session value ultron.tasks/root has format version {}, but this Ultron reads only \
                 format version 1. It was left unchanged; open the session with the Ultron version that wrote it, or upgrade.",
                jsrt::json::stringify(version)
            ),
            TaskStoreError::InvalidResult => f.write_str("Invalid task result"),
            TaskStoreError::InvalidDefinition => f.write_str("definition must be id@version"),
            TaskStoreError::InvalidFingerprint => f.write_str("fingerprint must be a lowercase SHA-256 hex string"),
            TaskStoreError::InvalidKey => f.write_str("idempotency key must be nonempty"),
            TaskStoreError::KeyReused => f.write_str("Idempotency key reused for a different task"),
            TaskStoreError::InvalidId => f.write_str("task ID must be nonempty"),
            TaskStoreError::UnknownTask => f.write_str("Unknown Ultron task"),
            TaskStoreError::InvalidTransition => f.write_str("Invalid task transition"),
            TaskStoreError::StateResultMismatch => f.write_str("Task state and result do not match"),
        }
    }
}

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

/// SHA-256 of the canonical JSON (object keys sorted by UTF-16 code units, as JavaScript's sort does).
pub fn task_fingerprint(request: &Value) -> String {
    fn canonical(item: &Value, out: &mut String) {
        match item {
            Value::Array(items) => {
                out.push('[');
                for (n, item) in items.iter().enumerate() {
                    if n > 0 {
                        out.push(',');
                    }
                    canonical(item, out);
                }
                out.push(']');
            }
            Value::Object(map) => {
                let mut keys: Vec<&String> = map.keys().collect();
                jsrt::utf16::sort(&mut keys);
                out.push('{');
                for (n, key) in keys.into_iter().enumerate() {
                    if n > 0 {
                        out.push(',');
                    }
                    out.push_str(&jsrt::json::stringify(&Value::String(key.clone())));
                    out.push(':');
                    canonical(&map[key], out);
                }
                out.push('}');
            }
            other => out.push_str(&jsrt::json::stringify(other)),
        }
    }
    let mut text = String::new();
    canonical(request, &mut text);
    jsrt::hash::sha256_hex(text)
}

/// `id@version`: a lowercase id (`[a-z][a-z0-9-]*`) and a decimal version.
pub fn is_definition(text: &str) -> bool {
    let Some((name, version)) = text.split_once('@') else {
        return false;
    };
    let mut chars = name.chars();
    chars.next().is_some_and(|c| c.is_ascii_lowercase())
        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
        && !version.is_empty()
        && version.bytes().all(|b| b.is_ascii_digit())
}

fn is_fingerprint(text: &str) -> bool {
    text.len() == 64 && text.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

fn is_result(result: &Value) -> bool {
    let Some(map) = result.as_object() else { return false };
    let status_ok = map
        .get("status")
        .and_then(Value::as_str)
        .is_some_and(|s| ["succeeded", "failed", "cancelled", "interrupted"].contains(&s));
    map.keys().all(|k| RESULT_KEYS.contains(&k.as_str()))
        && status_ok
        && map.get("verification").and_then(Value::as_str) == Some("unverified")
        && map.get("error").is_none_or(Value::is_string)
        && map.get("unverified").is_none_or(|v| v == &Value::Bool(true))
}

fn nonempty(value: Option<&Value>) -> Option<String> {
    value
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
}

fn parse_task(value: &Value) -> Option<Task> {
    let map = value.as_object()?;
    if !map.keys().all(|k| TASK_KEYS.contains(&k.as_str())) {
        return None;
    }
    let fingerprint = map.get("fingerprint")?.as_str().filter(|s| is_fingerprint(s))?;
    let definition = map.get("definition")?.as_str().filter(|s| is_definition(s))?;
    let state = TaskState::parse(map.get("state")?.as_str()?)?;
    let result = match map.get("result") {
        None => None,
        Some(result) if is_result(result) => Some(result.clone()),
        Some(_) => return None,
    };
    let parent_id = match map.get("parentId") {
        None => None,
        some => Some(nonempty(some)?),
    };
    let valid_result = match &result {
        None => !state.is_terminal(),
        Some(result) => state.is_terminal() && result["status"] == state.result_status(),
    };
    if !valid_result {
        return None;
    }
    Some(Task {
        id: nonempty(map.get("id"))?,
        key: nonempty(map.get("key"))?,
        fingerprint: fingerprint.into(),
        definition: definition.into(),
        state,
        result,
        parent_id,
    })
}

/// `readVersioned` then the schema and invariant checks of the saved document.
pub(crate) fn parse_document(saved: &Value) -> Result<Vec<Task>, TaskStoreError> {
    let map = saved.as_object().ok_or(TaskStoreError::InvalidDocument)?;
    if let Some(version) = map.get("version")
        && version.as_f64() != Some(1.0)
    {
        return Err(TaskStoreError::UnsupportedVersion(version.clone()));
    }
    if !map.keys().all(|k| k == "version" || k == "tasks") {
        return Err(TaskStoreError::InvalidDocument);
    }
    let items = map
        .get("tasks")
        .and_then(Value::as_array)
        .ok_or(TaskStoreError::InvalidDocument)?;
    let mut tasks: Vec<Task> = Vec::with_capacity(items.len());
    for item in items {
        let task = parse_task(item).ok_or(TaskStoreError::InvalidDocument)?;
        if tasks.iter().any(|seen| seen.id == task.id || seen.key == task.key) {
            return Err(TaskStoreError::InvalidDocument);
        }
        tasks.push(task);
    }
    Ok(tasks)
}

/// `json` with the keys of `order` first, in that order, then the rest.
fn ordered(json: Value, order: Option<&Vec<String>>) -> Value {
    let (Some(order), Value::Object(mut map)) = (order, json.clone()) else {
        return json;
    };
    let mut out = Map::new();
    for key in order {
        if let Some(value) = map.shift_remove(key) {
            out.insert(key.clone(), value);
        }
    }
    out.extend(map);
    Value::Object(out)
}

impl<S> TaskJournal<S> {
    /// A record as the journal stores it (its stored key order kept).
    pub fn stored_json(&self, task: &Task) -> Value {
        ordered(task.to_json(), self.orders.get(&task.id))
    }
}

/// The tasks to persist: every unfinished task and the newest finished ones up to the bound.
pub(crate) fn persisted_tasks(records: &[Task]) -> Vec<Task> {
    let finished = records.iter().filter(|t| t.state.is_terminal()).count();
    let mut excess = finished.saturating_sub(MAX_PERSISTED_FINISHED_TASKS);
    records
        .iter()
        .filter(|task| {
            if excess > 0 && task.state.is_terminal() {
                excess -= 1;
                return false;
            }
            true
        })
        .cloned()
        .collect()
}

/// An unfinished task as reopening records it: its owner ended, and it is never replayed.
fn interrupted(task: Task) -> Task {
    Task {
        state: TaskState::Interrupted,
        result: Some(json!({
            "status": "interrupted",
            "error": "Owner ended; automatic replay is disabled",
            "verification": "unverified",
        })),
        ..task
    }
}

fn random_task_id() -> String {
    format!("ultron-task-{}", jsrt::random::uuid_v4())
}

/// Serialized, commit-before-publish task records. `&mut self` serializes changes the way the
/// TypeScript promise chain does.
pub struct TaskJournal<S> {
    store: S,
    records: Vec<Task>,
    /// Key order of each record as it was stored: task-store.ts rewrites a loaded record by spreading it, so its keys
    /// keep their stored order and new ones follow.
    orders: std::collections::HashMap<String, Vec<String>>,
    loaded: Option<Result<(), TaskStoreError>>,
    /// The tasks this owner recorded `interrupted` when it opened the journal, until [`TaskJournal::reopen`].
    recovered: Vec<String>,
    broken: bool,
    mint: Box<dyn FnMut() -> String + Send>,
}

impl<S: DocumentStore> TaskJournal<S> {
    pub fn new(store: S) -> Self {
        Self::with_id_source(store, Box::new(random_task_id))
    }

    /// A journal whose new task IDs come from `mint` (replay of recorded IDs).
    pub fn with_id_source(store: S, mint: Box<dyn FnMut() -> String + Send>) -> Self {
        TaskJournal {
            store,
            records: Vec::new(),
            orders: std::collections::HashMap::new(),
            loaded: None,
            recovered: Vec::new(),
            broken: false,
            mint,
        }
    }

    pub fn store(&self) -> &S {
        &self.store
    }

    fn assert_healthy(&self) -> Result<(), TaskStoreError> {
        if self.broken {
            Err(TaskStoreError::Durability)
        } else {
            Ok(())
        }
    }

    /// Reads the stored document and records every unfinished task `interrupted`, except those `keep` accepts:
    /// they stay unfinished as `running` (a subagent its new owner reattached). One write when anything changed.
    fn load(&mut self, keep: &mut dyn FnMut(&Task) -> bool) -> Result<(), TaskStoreError> {
        let Some(saved) = self.store.read().map_err(|_| TaskStoreError::ReadFailed)? else {
            return Ok(());
        };
        let parsed = parse_document(&saved)?;
        for task in saved["tasks"].as_array().into_iter().flatten() {
            if let (Some(id), Some(map)) = (task["id"].as_str(), task.as_object()) {
                self.orders.insert(id.to_owned(), map.keys().cloned().collect());
            }
        }
        let unfinished = parsed.iter().any(|t| !t.state.is_terminal());
        let mut recovered = Vec::new();
        let records: Vec<Task> = parsed
            .into_iter()
            .map(|task| {
                if task.state.is_terminal() {
                    return task;
                }
                if keep(&task) {
                    return Task {
                        state: TaskState::Running,
                        ..task
                    };
                }
                recovered.push(task.id.clone());
                interrupted(task)
            })
            .collect();
        self.recovered = recovered;
        if unfinished {
            self.write(records)
        } else {
            self.records = records;
            Ok(())
        }
    }

    /// Opens the journal for a new owner: as the first use does, except that the unfinished tasks `keep` accepts
    /// stay `running` instead of `interrupted`, in the same write. On a journal this owner already opened, the tasks
    /// it recovered `interrupted` (and nothing has changed since) that `keep` accepts go back to `running`.
    pub fn reopen(&mut self, keep: &mut dyn FnMut(&Task) -> bool) -> Result<Vec<Task>, TaskStoreError> {
        self.assert_healthy()?;
        if self.loaded.is_none() {
            let outcome = self.load(keep);
            self.loaded = Some(outcome);
            self.loaded.clone().unwrap_or(Ok(()))?;
            self.assert_healthy()?;
            return Ok(self.records.clone());
        }
        self.begin()?;
        let recovered = std::mem::take(&mut self.recovered);
        let mut changed = false;
        let next: Vec<Task> = self
            .records
            .iter()
            .map(|task| {
                if task.state == TaskState::Interrupted && recovered.contains(&task.id) && keep(task) {
                    changed = true;
                    return Task {
                        state: TaskState::Running,
                        result: None,
                        ..task.clone()
                    };
                }
                task.clone()
            })
            .collect();
        if changed {
            self.write(next)?;
        }
        Ok(self.records.clone())
    }

    /// Loads once; a failed load stays failed for this owner.
    fn ensure_loaded(&mut self) -> Result<(), TaskStoreError> {
        if self.loaded.is_none() {
            let outcome = self.load(&mut |_| false);
            self.loaded = Some(outcome);
        }
        self.loaded.clone().unwrap_or(Ok(()))
    }

    fn write(&mut self, next: Vec<Task>) -> Result<(), TaskStoreError> {
        let tasks: Vec<Value> = persisted_tasks(&next)
            .iter()
            .map(|task| ordered(task.to_json(), self.orders.get(&task.id)))
            .collect();
        if self.store.write(&json!({ "version": 1, "tasks": tasks })).is_err() {
            self.broken = true;
            return Err(TaskStoreError::Durability);
        }
        self.records = next;
        Ok(())
    }

    fn begin(&mut self) -> Result<(), TaskStoreError> {
        self.assert_healthy()?;
        self.ensure_loaded()?;
        self.assert_healthy()
    }

    pub fn ready(&mut self) -> Result<(), TaskStoreError> {
        self.ensure_loaded()?;
        self.assert_healthy()
    }

    pub fn list(&mut self) -> Result<Vec<Task>, TaskStoreError> {
        self.begin()?;
        Ok(self.records.clone())
    }

    /// Admits a task under an idempotency key; a repeated key with the same fingerprint returns the
    /// existing task with `created == false`.
    pub fn admit(
        &mut self,
        definition: &str,
        fingerprint: &str,
        key: &str,
        parent_id: Option<&str>,
    ) -> Result<(Task, bool), TaskStoreError> {
        self.begin()?;
        if !is_definition(definition) {
            return Err(TaskStoreError::InvalidDefinition);
        }
        if !is_fingerprint(fingerprint) {
            return Err(TaskStoreError::InvalidFingerprint);
        }
        if key.is_empty() {
            return Err(TaskStoreError::InvalidKey);
        }
        if let Some(previous) = self.records.iter().find(|t| t.key == key) {
            if previous.fingerprint != fingerprint {
                return Err(TaskStoreError::KeyReused);
            }
            return Ok((previous.clone(), false));
        }
        let task = Task {
            id: (self.mint)(),
            key: key.into(),
            fingerprint: fingerprint.into(),
            definition: definition.into(),
            state: TaskState::Admitted,
            result: None,
            parent_id: parent_id.map(str::to_owned),
        };
        let mut next = self.records.clone();
        next.push(task.clone());
        self.write(next)?;
        Ok((task, true))
    }

    /// Moves a task forward. A task already terminal is returned unchanged, so a completion that
    /// races a committed cancellation observes the cancellation.
    pub fn transition(&mut self, id: &str, state: TaskState, result: Option<Value>) -> Result<Task, TaskStoreError> {
        self.begin()?;
        if id.is_empty() {
            return Err(TaskStoreError::InvalidId);
        }
        let index = self
            .records
            .iter()
            .position(|t| t.id == id)
            .ok_or(TaskStoreError::UnknownTask)?;
        let current = &self.records[index];
        if current.state.is_terminal() {
            return Ok(current.clone());
        }
        if state == TaskState::Running {
            if current.state != TaskState::Admitted || result.is_some() {
                return Err(TaskStoreError::InvalidTransition);
            }
        } else {
            let can_finish = current.state == TaskState::Running
                || (current.state == TaskState::Admitted && state == TaskState::Cancelled);
            let Some(result) = result.as_ref().filter(|_| can_finish && state.is_terminal()) else {
                return Err(TaskStoreError::InvalidTransition);
            };
            if !is_result(result) {
                return Err(TaskStoreError::InvalidResult);
            }
            if result["status"] != state.result_status() {
                return Err(TaskStoreError::StateResultMismatch);
            }
        }
        let next_task = Task {
            state,
            result,
            ..current.clone()
        };
        let mut next = self.records.clone();
        next[index] = next_task.clone();
        self.write(next)?;
        Ok(next_task)
    }
}