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
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
//! The durable REPL cell: the RLM equivalent of upstream's `ultron.tool` (spec ยง8.4), the task behind every call of the
//! model's one tool. Port of upstream `harness/tool.ts` for model-issued calls.
//!
//! `call` reads the call from its assistant entry, checks the tool and arguments, and commits intent (the code, its
//! lane, and the replay policy) before the cell runs. The cell then runs through a [`CellExecutor`] (normally the
//! lane's persistent kernel), publishing throttled partial output into its `ultron.live` slot, and one commit appends the
//! result entry and completes. `execute` is reached only by recovery: a cell whose intent was committed before a
//! crash is never run again unless both the recorded and the current policy say it is replay-safe; otherwise the
//! model gets an `interrupted` result carrying the committed partial output, exactly once.

use std::sync::{Arc, LazyLock, Mutex};
use std::time::{Duration, Instant};

use ai::{AssistantContent, Message, Tool};
use durable::{
    ConversationId, EntryDraft, EntryId, EntryRecord, TaskDefinition, TaskId, TaskOutcome, TaskOutcomeError,
    TaskRecord, TaskState, Tx,
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::Services;
use super::entries;
use super::generation::Control;
use super::live::{CELL_KIND, clear_progress, finish_slot, live, slot, slot_index, slot_path};
use super::throttle::Throttle;
use super::usage::{Bucket, record_usage};
use super::util::{d, from_value, strict, to_value};
use crate::scheduler::cancel::lock;
use crate::scheduler::{Cancel, HarnessError, NextState, Result, Task, TaskRuntime};

/// Bytes of running output a slot retains.
pub const DEFAULT_MAX_BYTES: usize = 50 * 1024;
/// Lines of running output a slot retains.
pub const DEFAULT_MAX_LINES: usize = 2000;

/// Whether a cell whose intent was committed may run again after a restart.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Replay {
    Safe,
    #[default]
    Unsafe,
}

/// One diagnostic of a result; rendered into the content the model reads.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Diagnostic {
    pub severity: String,
    pub code: String,
    pub message: String,
}

impl Diagnostic {
    pub fn error(code: &str, message: &str) -> Diagnostic {
        Diagnostic {
            severity: "error".into(),
            code: code.into(),
            message: message.into(),
        }
    }

    fn warn(code: &str, message: &str) -> Diagnostic {
        Diagnostic {
            severity: "warn".into(),
            code: code.into(),
            message: message.into(),
        }
    }
}

/// What a cell produced.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CellResult {
    /// Content blocks (`{type: "text", text}` or images); `None` uses the running output the cell published.
    pub output: Option<Vec<Value>>,
    pub is_error: bool,
    pub details: Option<Value>,
    /// Spend of host operations the cell made (pi-ai `Usage` JSON), recorded under the tool's name.
    pub usage: Option<Value>,
    pub diagnostics: Vec<Diagnostic>,
    /// Ask the run to end (`terminate`) or to continue in a fresh context (`handoff`).
    pub control: Option<Control>,
}

impl CellResult {
    pub fn text(text: impl Into<String>) -> CellResult {
        CellResult {
            output: Some(vec![json!({ "type": "text", "text": text.into() })]),
            ..CellResult::default()
        }
    }

    /// An error result the Harness writes itself: no content and one `error` diagnostic.
    pub fn error(code: &str, message: &str) -> CellResult {
        CellResult {
            output: Some(Vec::new()),
            is_error: true,
            diagnostics: vec![Diagnostic::error(code, message)],
            ..CellResult::default()
        }
    }
}

/// One cell call as the executor sees it.
#[derive(Clone, Debug, PartialEq)]
pub struct CellCall {
    pub conversation_id: ConversationId,
    pub task_id: TaskId,
    pub call_id: String,
    pub name: String,
    /// The final arguments recorded with the intent: `code`, and `lane` when the call names one.
    pub arguments: Value,
}

impl CellCall {
    pub fn code(&self) -> &str {
        self.arguments["code"].as_str().unwrap_or_default()
    }

    /// The REPL lane the cell runs in: `main` unless the call names another.
    pub fn lane(&self) -> &str {
        self.arguments["lane"].as_str().unwrap_or("main")
    }
}

/// Runs cells: normally one persistent kernel per lane. The model's tool list is exactly [`CellExecutor::tool`].
pub trait CellExecutor: Send + Sync {
    /// The REPL tool the model is offered.
    fn tool(&self) -> Tool;

    /// Check and normalize a call's arguments, or say why they are invalid. Default: a `code` string and an optional
    /// `lane` string.
    fn prepare(&self, arguments: &Value) -> std::result::Result<Value, String> {
        if !arguments["code"].is_string() {
            return Err("rlm needs a `code` string".into());
        }
        if arguments.get("lane").is_some_and(|lane| !lane.is_string()) {
            return Err("rlm's `lane` must be a string".into());
        }
        Ok(arguments.clone())
    }

    /// Whether a recorded intent may run again after a restart. Cells are unsafe unless the executor knows better.
    fn replay(&self, call: &CellCall) -> Replay {
        let _ = call;
        Replay::Unsafe
    }

    /// Run one cell. `progress` publishes running output; `signal` is cancelled by an abort mark or close, and an
    /// `Err` after it is the cancellation.
    fn execute(
        &self,
        call: &CellCall,
        progress: &CellProgress,
        signal: &Cancel,
    ) -> std::result::Result<CellResult, String>;
}

/// The running output a cell retains (its head, within the limits) and what the limits dropped.
#[derive(Clone, Debug, Default, PartialEq)]
struct Retained {
    text: String,
    lines: usize,
    dropped_bytes: usize,
    dropped_lines: usize,
}

impl Retained {
    fn push(&mut self, chunk: &str) {
        if self.dropped_bytes > 0 {
            self.dropped_bytes += chunk.len();
            self.dropped_lines += chunk.matches('\n').count();
            return;
        }
        let mut taken = 0;
        for (index, character) in chunk.char_indices() {
            let end = index + character.len_utf8();
            let lines = self.lines + usize::from(character == '\n');
            if self.text.len() + end > DEFAULT_MAX_BYTES || lines > DEFAULT_MAX_LINES {
                break;
            }
            taken = end;
            self.lines = lines;
        }
        self.text.push_str(&chunk[..taken]);
        let rest = &chunk[taken..];
        if !rest.is_empty() {
            self.dropped_bytes += rest.len();
            self.dropped_lines += rest.matches('\n').count().max(1);
        }
    }
}

/// What a running cell has published: its retained output and last details.
type Published = (Retained, Option<Value>);

/// Publishes a running cell's output and details into its `ultron.live` slot, throttled.
/// Clones share it, so a host request served on another thread (the cell's `cell.output`) can publish too.
#[derive(Clone)]
pub struct CellProgress {
    retained: Arc<Mutex<(Retained, Option<Value>)>>,
    throttle: Arc<Mutex<Option<Throttle<Published>>>>,
}

impl CellProgress {
    fn new(runtime: &TaskRuntime, interval: Duration) -> CellProgress {
        let committer = runtime.clone();
        let throttle = Throttle::new(interval, move |(retained, details): (Retained, Option<Value>)| {
            let conversation_id = committer.conversation_id();
            let task_id = committer.task_id();
            let result = committer.commit(&committer.ctx(), |tx, _| {
                let live = live(tx, conversation_id)?;
                let Some(index) = slot_index(&live, task_id)? else {
                    return Ok(None);
                };
                let current = d(live.get(&slot_path(index, Some("output"))))?;
                if current.as_ref().and_then(Value::as_str).unwrap_or_default() != retained.text {
                    d(live.set(&slot_path(index, Some("output")), json!(retained.text)))?;
                }
                if retained.dropped_bytes > 0 {
                    d(live.set(&slot_path(index, Some("droppedBytes")), json!(retained.dropped_bytes)))?;
                    d(live.set(&slot_path(index, Some("droppedLines")), json!(retained.dropped_lines)))?;
                }
                if let Some(details) = details {
                    d(live.set(&slot_path(index, Some("details")), details))?;
                }
                Ok(None)
            });
            if let Err(error) = result
                && !committer.signal().is_cancelled()
            {
                let _ = committer.report(&error);
            }
        });
        CellProgress {
            retained: Arc::new(Mutex::new((Retained::default(), None))),
            throttle: Arc::new(Mutex::new(Some(throttle))),
        }
    }

    /// A progress sink that publishes nothing, for executors driven outside a task (tests, tools).
    pub fn detached() -> CellProgress {
        CellProgress {
            retained: Arc::new(Mutex::new((Retained::default(), None))),
            throttle: Arc::new(Mutex::new(None)),
        }
    }

    pub fn output(&self, chunk: &str) {
        let snapshot = {
            let mut state = lock(&self.retained);
            state.0.push(chunk);
            state.clone()
        };
        if let Some(throttle) = lock(&self.throttle).as_ref() {
            throttle.mark(snapshot);
        }
    }

    /// Replace the running details.
    pub fn details(&self, value: Value) {
        let snapshot = {
            let mut state = lock(&self.retained);
            state.1 = Some(strict(value));
            state.clone()
        };
        if let Some(throttle) = lock(&self.throttle).as_ref() {
            throttle.mark(snapshot);
        }
    }

    /// Stop publishing (later output is kept but not committed) and return what was retained.
    fn stop(self) -> (Retained, Option<Value>) {
        let throttle = lock(&self.throttle).take();
        if let Some(throttle) = throttle {
            throttle.stop();
        }
        lock(&self.retained).clone()
    }
}

/// The cell task's input and checkpoint (spec ยง8.4).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "phase", rename_all = "camelCase")]
pub(crate) enum CellCheckpoint {
    Call,
    /// Durable intent: the final arguments and the replay policy recorded before execution.
    Execute {
        arguments: Value,
        replay: Replay,
    },
}

static CELL_DEFINITION: LazyLock<TaskDefinition> =
    LazyLock::new(|| TaskDefinition::new(CELL_KIND, 2, |_| to_value(&CellCheckpoint::Call)));

pub(crate) fn cell_definition() -> &'static TaskDefinition {
    &CELL_DEFINITION
}

pub(crate) fn cell_task(services: Arc<Services>) -> Task {
    let (call, execute, abort) = (services.clone(), services.clone(), services);
    Task::define(CELL_KIND, 2, |input| (CELL_DEFINITION.initial)(input))
        // Version 1 had only model-issued calls.
        .migrate(|input, checkpoint, _| {
            let mut input = input.clone();
            if input.get("kind").is_none() {
                input["kind"] = json!("model");
            }
            Ok((input, checkpoint.clone()))
        })
        .phase("call", move |task, runtime| call_phase(&call, task, runtime))
        .phase("execute", move |task, runtime| execute_phase(&execute, task, runtime))
        .abort(move |task, runtime| abort_handler(&abort, task, runtime))
        .build()
}

fn checkpoint_of(task: &TaskRecord) -> Result<CellCheckpoint> {
    match &task.state {
        TaskState::Pending { checkpoint }
        | TaskState::Running { checkpoint }
        | TaskState::Waiting { checkpoint, .. } => from_value(checkpoint.clone(), "cell checkpoint"),
        _ => Err(HarnessError::msg("A terminal cell has no checkpoint")),
    }
}

/// The call (`id`, `name`, `arguments`) from the assistant entry.
fn read_call(runtime: &TaskRuntime, task: &TaskRecord) -> Result<(String, String, Value)> {
    let assistant = EntryId(task.input["assistant"].as_u64().unwrap_or_default());
    let call_id = task.input["callId"].as_str().unwrap_or_default().to_owned();
    let entry = runtime.read(|tx| Ok(tx.entry_of(entries::ASSISTANT, assistant)?))?;
    let message = entry
        .and_then(|entry| entry.model)
        .and_then(|model| model.into_iter().next());
    if let Some(message) = message
        && let Message::Assistant(message) = super::context::message_of(message)?
    {
        for content in message.content {
            if let AssistantContent::ToolCall(call) = content
                && call.id == call_id
            {
                return Ok((call.id, call.name, call.arguments));
            }
        }
    }
    Err(HarnessError::Error(format!(
        "Entry {} has no tool call {call_id}",
        assistant.0
    )))
}

/// How a cell task ends; the result entry is appended either way. `failed` (execution threw or was interrupted)
/// records cancellation intent for what the cell owns; a result with `is_error` still completes.
enum Ending {
    Completed,
    Aborted,
    Failed(String),
}

fn call_phase(services: &Services, task: &TaskRecord, runtime: &TaskRuntime) -> Result<()> {
    let (call_id, name, arguments) = read_call(runtime, task)?;
    let tool = services.cells.tool();
    if name != tool.name {
        let error = CellResult::error("tool_unavailable", &format!("Tool {name} is not available"));
        return settle(
            runtime,
            task,
            &call_id,
            &name,
            Ending::Completed,
            |_| error.clone(),
            None,
        );
    }
    let arguments = match services.cells.prepare(&arguments) {
        Ok(arguments) => strict(arguments),
        Err(message) => {
            let invalid = CellResult::error("invalid_arguments", &message);
            return settle(
                runtime,
                task,
                &call_id,
                &name,
                Ending::Completed,
                |_| invalid.clone(),
                None,
            );
        }
    };
    let call = CellCall {
        conversation_id: runtime.conversation_id(),
        task_id: runtime.task_id(),
        call_id: call_id.clone(),
        name: name.clone(),
        arguments: arguments.clone(),
    };
    // `before_tool`: a blocked cell never runs; its result is the reason (`immediateError`), and `terminate` ends
    // the run after the round.
    if let Some(gate) = &services.hooks.gate_tool {
        let run = runtime.read(|tx| super::gate::gate_run(tx, call.conversation_id))?;
        if let Some(block) = gate(&run, &call) {
            let blocked = CellResult {
                output: Some(vec![json!({ "type": "text", "text": block.reason })]),
                is_error: true,
                control: block.terminate.then_some(Control {
                    terminate: Some(true),
                    handoff: None,
                }),
                ..CellResult::default()
            };
            return settle(
                runtime,
                task,
                &call_id,
                &name,
                Ending::Completed,
                |_| blocked.clone(),
                None,
            );
        }
    }
    let replay = services.cells.replay(&call);
    let conversation_id = runtime.conversation_id();
    let task_id = runtime.task_id();
    runtime.commit(&runtime.ctx(), |tx, _| {
        let live = live(tx, conversation_id)?;
        if let Some(index) = slot_index(&live, task_id)? {
            d(live.set(&slot_path(index, Some("status")), json!("running")))?;
        }
        Ok(Some(NextState::Running {
            checkpoint: to_value(&CellCheckpoint::Execute {
                arguments: arguments.clone(),
                replay,
            }),
        }))
    })?;
    run(services, runtime, task, call)
}

/// Recovery after intent: run again only when the recorded and the current policy both say `safe`.
fn execute_phase(services: &Services, task: &TaskRecord, runtime: &TaskRuntime) -> Result<()> {
    let CellCheckpoint::Execute { arguments, replay } = checkpoint_of(task)? else {
        return Err(HarnessError::msg("execute phase without intent"));
    };
    let (call_id, name, _) = read_call(runtime, task)?;
    let call = CellCall {
        conversation_id: runtime.conversation_id(),
        task_id: runtime.task_id(),
        call_id: call_id.clone(),
        name: name.clone(),
        arguments,
    };
    if replay == Replay::Safe && name == services.cells.tool().name && services.cells.replay(&call) == Replay::Safe {
        // The rerun reports from scratch; clear what the interrupted attempt published.
        let conversation_id = runtime.conversation_id();
        let task_id = runtime.task_id();
        runtime.commit(&runtime.ctx(), |tx, _| {
            let live = live(tx, conversation_id)?;
            if let Some(index) = slot_index(&live, task_id)? {
                clear_progress(&live, index)?;
            }
            Ok(None)
        })?;
        return run(services, runtime, task, call);
    }
    let message = interrupted_message(&name);
    settle(
        runtime,
        task,
        &call_id,
        &name,
        Ending::Failed(message.clone()),
        |slot| from_slot(slot, "interrupted", &message),
        None,
    )
}

/// The result of a call a restart cut off: interrupted, its effect unknown (never replayed).
pub fn interrupted_message(name: &str) -> String {
    format!(
        "Tool {name} was interrupted by a restart; effect unknown: it may have partially run and was not replayed. \
         Check what it changed before you run it again"
    )
}

fn abort_handler(_services: &Services, task: &TaskRecord, runtime: &TaskRuntime) -> Result<()> {
    let (call_id, name, _) = read_call(runtime, task)?;
    let executing = matches!(checkpoint_of(task)?, CellCheckpoint::Execute { .. });
    let (code, message) = if task.abort_reason.is_none() {
        ("aborted", format!("Tool {name} was aborted"))
    } else if executing {
        ("interrupted", interrupted_message(&name))
    } else {
        (
            "abandoned",
            format!("Tool {name} was not started: its caller ended with a restart"),
        )
    };
    settle(
        runtime,
        task,
        &call_id,
        &name,
        Ending::Aborted,
        |slot| from_slot(slot, code, &message),
        None,
    )
}

fn run(services: &Services, runtime: &TaskRuntime, task: &TaskRecord, call: CellCall) -> Result<()> {
    let interval = Duration::from_millis((services.settings)().output_interval_ms);
    let progress = CellProgress::new(runtime, interval);
    let started = Instant::now();
    let executed = services.cells.execute(&call, &progress, runtime.signal());
    let duration = started.elapsed().as_millis() as u64;
    let (retained, details) = progress.stop();
    let (mut result, ending) = match executed {
        Ok(result) => (result, Ending::Completed),
        Err(message) => {
            runtime.signal().check()?;
            let result = CellResult {
                output: None,
                is_error: true,
                diagnostics: vec![Diagnostic::error("tool_error", &message)],
                ..CellResult::default()
            };
            (result, Ending::Failed(format!("Tool {} threw", call.name)))
        }
    };
    if result.output.is_none() {
        result.output = Some(if retained.text.is_empty() {
            Vec::new()
        } else {
            vec![json!({ "type": "text", "text": retained.text })]
        });
        if retained.dropped_bytes > 0 {
            result.diagnostics.insert(0, truncated(&retained, Some("head")));
        }
    }
    if result.details.is_none() {
        result.details = details;
    }
    settle(
        runtime,
        task,
        &call.call_id,
        &call.name,
        ending,
        |_| result.clone(),
        Some(duration),
    )
}

fn truncated(retained: &Retained, retain: Option<&str>) -> Diagnostic {
    let kept = match retain {
        Some("head") => " to its beginning",
        Some(_) => " to its end",
        None => "",
    };
    Diagnostic::warn(
        "truncated",
        &format!(
            "Output truncated{kept}: {} lines, {} bytes dropped",
            retained.dropped_lines, retained.dropped_bytes
        ),
    )
}

/// An error result from the slot's durable partial output, details and diagnostics.
fn from_slot(slot: Option<&Value>, code: &str, message: &str) -> CellResult {
    let mut diagnostics: Vec<Diagnostic> = slot
        .and_then(|slot| slot.get("diagnostics"))
        .and_then(|value| serde_json::from_value(value.clone()).ok())
        .unwrap_or_default();
    let dropped_bytes = slot.and_then(|slot| slot["droppedBytes"].as_u64()).unwrap_or(0) as usize;
    if dropped_bytes > 0 {
        let dropped_lines = slot.and_then(|slot| slot["droppedLines"].as_u64()).unwrap_or(0) as usize;
        diagnostics.push(truncated(
            &Retained {
                dropped_bytes,
                dropped_lines,
                ..Retained::default()
            },
            None,
        ));
    }
    diagnostics.push(Diagnostic::error(code, message));
    let output = slot
        .and_then(|slot| slot["output"].as_str())
        .filter(|text| !text.is_empty())
        .map(|text| vec![json!({ "type": "text", "text": text })])
        .unwrap_or_default();
    CellResult {
        output: Some(output),
        is_error: true,
        details: slot.and_then(|slot| slot.get("details").cloned()),
        diagnostics,
        ..CellResult::default()
    }
}

/// Commit the cell's terminal state: append its result entry, mark its slot done with the entry, and complete with
/// `{ kind: "model", entryId, control? }`. `build` receives the slot so interruption and abort report the durable
/// partial output.
fn settle(
    runtime: &TaskRuntime,
    _task: &TaskRecord,
    call_id: &str,
    name: &str,
    ending: Ending,
    build: impl FnOnce(Option<&Value>) -> CellResult,
    duration_ms: Option<u64>,
) -> Result<()> {
    let conversation_id = runtime.conversation_id();
    let task_id = runtime.task_id();
    runtime.commit(&runtime.ctx(), |tx, _| {
        let live = live(tx, conversation_id)?;
        let current = slot(&live, task_id)?;
        let result = build(current.as_ref());
        let entry = append_tool_result(tx, conversation_id, call_id, name, &result, runtime.now()?, duration_ms)?;
        if let Some(index) = slot_index(&live, task_id)? {
            finish_slot(&live, index)?;
            d(live.set(&slot_path(index, Some("entry")), json!(entry.id.0)))?;
        }
        let mut settled = json!({ "kind": "model", "entryId": entry.id.0 });
        if let (Ending::Completed, Some(control)) = (&ending, &result.control) {
            settled["control"] = strict(to_value(control));
        }
        let outcome = match ending {
            Ending::Completed => TaskOutcome::Completed { result: settled },
            Ending::Aborted => TaskOutcome::Aborted {
                reason: None,
                result: Some(settled),
            },
            Ending::Failed(message) => TaskOutcome::Failed {
                error: TaskOutcomeError { message, detail: None },
                result: Some(settled),
            },
        };
        Ok(Some(NextState::Terminal { outcome }))
    })
}

fn render_diagnostics(diagnostics: &[Diagnostic]) -> String {
    let lines: Vec<String> = diagnostics
        .iter()
        .map(|diagnostic| format!("[{}] {}", diagnostic.severity, diagnostic.message))
        .collect();
    format!("<harness>\n{}\n</harness>", lines.join("\n"))
}

/// Append a `ultron.tool-result` entry. The content ends with the rendered diagnostics, so the stored message is exactly
/// what the model sees; `data` keeps the structured list. A result's usage is added to `ultron.usage` in the same commit.
pub(crate) fn append_tool_result(
    tx: &mut Tx<'_>,
    conversation_id: ConversationId,
    call_id: &str,
    name: &str,
    result: &CellResult,
    timestamp: u64,
    duration_ms: Option<u64>,
) -> Result<EntryRecord> {
    let mut content = result.output.clone().unwrap_or_default();
    if !result.diagnostics.is_empty() {
        content.push(json!({ "type": "text", "text": render_diagnostics(&result.diagnostics) }));
    }
    let mut message = json!({
        "role": "toolResult",
        "toolCallId": call_id,
        "toolName": name,
        "content": content,
    });
    if let Some(details) = &result.details {
        message["details"] = details.clone();
    }
    if let Some(usage) = &result.usage {
        message["usage"] = usage.clone();
    }
    message["isError"] = json!(result.is_error);
    if let Some(duration) = duration_ms {
        message["durationMs"] = json!(duration);
    }
    message["timestamp"] = json!(timestamp);
    if let Some(usage) = &result.usage {
        record_usage(tx, conversation_id, Bucket::Tools, name, usage)?;
    }
    Ok(tx.append_entry(
        conversation_id,
        EntryDraft {
            model: Some(vec![message]),
            data: Some(json!({ "diagnostics": result.diagnostics })),
            ..EntryDraft::new(entries::TOOL_RESULT)
        },
    )?)
}