platonic-core 0.1.0

Core Rust harness primitives for disciplined, replayable agent execution.
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
//! Pure readback projections derived from recorded run events.

use crate::{
    ActorId, ContextFragment, Error, HarnessEvent, Message, PolicyDecision, RecordedEvent,
    RunPhase, RunState, ToolCall, ToolCallId, ToolResult, TurnId,
};

/// Replay-validated readback for one run ledger.
#[derive(Clone, Debug, PartialEq)]
pub struct RunReadback {
    /// Chronological entries useful for replay output.
    pub entries: Vec<ReadbackEntry>,
    /// Final run phase after replaying all events.
    pub final_phase: RunPhase,
    /// Next expected sequence number after replay.
    pub next_seq: u64,
}

impl RunReadback {
    /// Replays an ordered ledger and rejects the first invalid recorded event.
    pub fn from_events(events: &[RecordedEvent]) -> Result<Self, Error> {
        let mut state = RunState::new();
        let mut entries = Vec::new();

        for record in events {
            state.apply(record)?;
            collect_entry(&record.event, &mut entries);
        }

        Ok(Self {
            entries,
            final_phase: state.phase().clone(),
            next_seq: state.next_seq(),
        })
    }
}

/// One deterministic readback entry projected from the ledger.
#[derive(Clone, Debug, PartialEq)]
pub enum ReadbackEntry {
    /// One host-built context fragment that entered a model turn.
    ContextFragment {
        /// Turn that received the fragment.
        turn_id: TurnId,
        /// Exact fragment recorded in the turn context.
        fragment: ContextFragment,
    },
    /// Model response message.
    ModelMessage {
        /// Turn that received the response.
        turn_id: TurnId,
        /// Normalized model-authored message.
        message: Message,
    },
    /// Host-validated tool call consumed for a turn.
    ToolCall {
        /// Turn that proposed the call.
        turn_id: TurnId,
        /// Validated and effect-classified call.
        call: ToolCall,
    },
    /// Structured tool result.
    ToolResult {
        /// Exact result recorded after execution.
        result: ToolResult,
    },
    /// Policy denied a tool call before execution.
    PolicyDenied {
        /// Call rejected by policy.
        call_id: ToolCallId,
        /// Recorded policy explanation.
        reason: String,
    },
    /// Approval granted a tool call before execution.
    ApprovalGranted {
        /// Call approved for execution.
        call_id: ToolCallId,
        /// Human or host actor that granted approval.
        actor_id: ActorId,
    },
    /// Approval denied a tool call before execution.
    ApprovalDenied {
        /// Call denied before execution.
        call_id: ToolCallId,
        /// Human or host actor that denied approval.
        actor_id: ActorId,
        /// Recorded denial explanation.
        reason: String,
    },
    /// Tool execution failed.
    ToolFailed {
        /// Call whose execution failed.
        call_id: ToolCallId,
        /// Recorded host failure explanation.
        reason: String,
    },
}

fn collect_entry(event: &HarnessEvent, entries: &mut Vec<ReadbackEntry>) {
    match event {
        HarnessEvent::ContextBuilt {
            turn_id, context, ..
        } => {
            entries.extend(context.fragments.iter().map(|fragment| {
                ReadbackEntry::ContextFragment {
                    turn_id: turn_id.clone(),
                    fragment: fragment.clone(),
                }
            }));
        }
        HarnessEvent::ModelResponded {
            turn_id, output, ..
        } => {
            entries.push(ReadbackEntry::ModelMessage {
                turn_id: turn_id.clone(),
                message: output.clone(),
            });
        }
        HarnessEvent::ToolCallProposed { turn_id, call, .. } => {
            entries.push(ReadbackEntry::ToolCall {
                turn_id: turn_id.clone(),
                call: call.clone(),
            });
        }
        HarnessEvent::ToolFinished { result, .. } => {
            entries.push(ReadbackEntry::ToolResult {
                result: result.clone(),
            });
        }
        HarnessEvent::PolicyEvaluated {
            call_id,
            decision: PolicyDecision::Deny { reason },
            ..
        } => {
            entries.push(ReadbackEntry::PolicyDenied {
                call_id: call_id.clone(),
                reason: reason.clone(),
            });
        }
        HarnessEvent::ApprovalGranted {
            call_id, actor_id, ..
        } => {
            entries.push(ReadbackEntry::ApprovalGranted {
                call_id: call_id.clone(),
                actor_id: actor_id.clone(),
            });
        }
        HarnessEvent::ApprovalDenied {
            call_id,
            actor_id,
            reason,
            ..
        } => {
            entries.push(ReadbackEntry::ApprovalDenied {
                call_id: call_id.clone(),
                actor_id: actor_id.clone(),
                reason: reason.clone(),
            });
        }
        HarnessEvent::ToolFailed {
            call_id, reason, ..
        } => {
            entries.push(ReadbackEntry::ToolFailed {
                call_id: call_id.clone(),
                reason: reason.clone(),
            });
        }
        HarnessEvent::RunStarted { .. }
        | HarnessEvent::ModelRequested { .. }
        | HarnessEvent::PolicyEvaluated {
            decision: PolicyDecision::Allow | PolicyDecision::RequireApproval { .. },
            ..
        }
        | HarnessEvent::ToolStarted { .. }
        | HarnessEvent::RunFinished { .. }
        | HarnessEvent::RunFailed { .. } => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        AgentId, ContextFragment, ContextLane, ContextPack, EffectClass, MessageRole, ModelName,
        ModelUsage, ResultVisibility, RunId, ToolName, ToolProposal,
    };
    use serde_json::json;

    fn run_id() -> RunId {
        RunId::new("run_1").unwrap()
    }

    fn agent_id() -> AgentId {
        AgentId::new("agent_1").unwrap()
    }

    fn turn_id() -> TurnId {
        TurnId::new("turn_1").unwrap()
    }

    fn second_turn_id() -> TurnId {
        TurnId::new("turn_2").unwrap()
    }

    fn call_id() -> ToolCallId {
        ToolCallId::new("call_1").unwrap()
    }

    fn actor_id() -> ActorId {
        ActorId::new("human_1").unwrap()
    }

    fn usage() -> ModelUsage {
        ModelUsage {
            input_tokens: 20,
            output_tokens: 8,
        }
    }

    fn rec(seq: u64, event: HarnessEvent) -> RecordedEvent {
        RecordedEvent {
            seq,
            occurred_at_ms: 1_700_000_000_000 + seq,
            event,
        }
    }

    fn context(turn_id: TurnId, content: &str) -> HarnessEvent {
        HarnessEvent::ContextBuilt {
            run_id: run_id(),
            turn_id,
            context: ContextPack {
                token_budget: 100,
                fragments: vec![ContextFragment {
                    lane: ContextLane::CurrentTask,
                    source: "user".into(),
                    content: content.into(),
                    estimated_tokens: 10,
                }],
            },
        }
    }

    fn model_requested(turn_id: TurnId, step: u32) -> HarnessEvent {
        HarnessEvent::ModelRequested {
            run_id: run_id(),
            turn_id,
            step,
            model: ModelName::new("claude-fable-5").unwrap(),
        }
    }

    fn model_responded(
        turn_id: TurnId,
        step: u32,
        content: &str,
        proposed_calls: Vec<ToolProposal>,
    ) -> HarnessEvent {
        HarnessEvent::ModelResponded {
            run_id: run_id(),
            turn_id,
            step,
            output: Message {
                role: MessageRole::Assistant,
                content: content.into(),
            },
            proposed_calls,
            usage: usage(),
        }
    }

    fn proposal() -> ToolProposal {
        ToolProposal {
            tool: ToolName::new("file.read").unwrap(),
            input: json!({ "path": "README.md" }),
        }
    }

    fn call() -> ToolCall {
        ToolCall {
            id: call_id(),
            tool: ToolName::new("file.read").unwrap(),
            effect: EffectClass::ReadOnly,
            input: json!({ "path": "README.md" }),
        }
    }

    fn result() -> ToolResult {
        ToolResult {
            call_id: call_id(),
            summary: "read README".into(),
            data: json!({ "bytes": 123 }),
            artifacts: vec![],
            visibility: ResultVisibility::Both,
        }
    }

    fn start_event(seq: u64) -> RecordedEvent {
        rec(
            seq,
            HarnessEvent::RunStarted {
                run_id: run_id(),
                agent_id: agent_id(),
            },
        )
    }

    #[test]
    fn one_turn_ledger_projects_context_message_and_final_state() {
        let events = vec![
            start_event(0),
            rec(1, context(turn_id(), "What is in README?")),
            rec(2, model_requested(turn_id(), 0)),
            rec(3, model_responded(turn_id(), 0, "It is a README.", vec![])),
            rec(4, HarnessEvent::RunFinished { run_id: run_id() }),
        ];

        let readback = RunReadback::from_events(&events).unwrap();

        assert_eq!(readback.final_phase, RunPhase::Finished);
        assert_eq!(readback.next_seq, 5);
        assert_eq!(
            readback.entries,
            vec![
                ReadbackEntry::ContextFragment {
                    turn_id: turn_id(),
                    fragment: ContextFragment {
                        lane: ContextLane::CurrentTask,
                        source: "user".into(),
                        content: "What is in README?".into(),
                        estimated_tokens: 10,
                    },
                },
                ReadbackEntry::ModelMessage {
                    turn_id: turn_id(),
                    message: Message {
                        role: MessageRole::Assistant,
                        content: "It is a README.".into(),
                    },
                },
            ]
        );
    }

    #[test]
    fn two_turn_ledger_projects_tool_result_continuation() {
        let events = vec![
            start_event(0),
            rec(1, context(turn_id(), "Read README")),
            rec(2, model_requested(turn_id(), 0)),
            rec(
                3,
                model_responded(turn_id(), 0, "I will read it.", vec![proposal()]),
            ),
            rec(
                4,
                HarnessEvent::ToolCallProposed {
                    run_id: run_id(),
                    turn_id: turn_id(),
                    call: call(),
                },
            ),
            rec(
                5,
                HarnessEvent::PolicyEvaluated {
                    run_id: run_id(),
                    call_id: call_id(),
                    decision: PolicyDecision::Allow,
                },
            ),
            rec(
                6,
                HarnessEvent::ToolStarted {
                    run_id: run_id(),
                    call_id: call_id(),
                },
            ),
            rec(
                7,
                HarnessEvent::ToolFinished {
                    run_id: run_id(),
                    result: result(),
                },
            ),
            rec(8, context(second_turn_id(), "Tool result: read README")),
            rec(9, model_requested(second_turn_id(), 1)),
            rec(
                10,
                model_responded(second_turn_id(), 1, "README was read.", vec![]),
            ),
            rec(11, HarnessEvent::RunFinished { run_id: run_id() }),
        ];

        let readback = RunReadback::from_events(&events).unwrap();

        assert_eq!(readback.final_phase, RunPhase::Finished);
        assert_eq!(readback.next_seq, 12);
        assert_eq!(
            readback.entries,
            vec![
                ReadbackEntry::ContextFragment {
                    turn_id: turn_id(),
                    fragment: ContextFragment {
                        lane: ContextLane::CurrentTask,
                        source: "user".into(),
                        content: "Read README".into(),
                        estimated_tokens: 10,
                    },
                },
                ReadbackEntry::ModelMessage {
                    turn_id: turn_id(),
                    message: Message {
                        role: MessageRole::Assistant,
                        content: "I will read it.".into(),
                    },
                },
                ReadbackEntry::ToolCall {
                    turn_id: turn_id(),
                    call: call(),
                },
                ReadbackEntry::ToolResult { result: result() },
                ReadbackEntry::ContextFragment {
                    turn_id: second_turn_id(),
                    fragment: ContextFragment {
                        lane: ContextLane::CurrentTask,
                        source: "user".into(),
                        content: "Tool result: read README".into(),
                        estimated_tokens: 10,
                    },
                },
                ReadbackEntry::ModelMessage {
                    turn_id: second_turn_id(),
                    message: Message {
                        role: MessageRole::Assistant,
                        content: "README was read.".into(),
                    },
                },
            ]
        );
    }

    #[test]
    fn denials_and_failures_are_projected_without_tool_results() {
        let policy_denied = vec![
            start_event(0),
            rec(1, context(turn_id(), "Read secret")),
            rec(2, model_requested(turn_id(), 0)),
            rec(
                3,
                model_responded(turn_id(), 0, "I will read it.", vec![proposal()]),
            ),
            rec(
                4,
                HarnessEvent::ToolCallProposed {
                    run_id: run_id(),
                    turn_id: turn_id(),
                    call: call(),
                },
            ),
            rec(
                5,
                HarnessEvent::PolicyEvaluated {
                    run_id: run_id(),
                    call_id: call_id(),
                    decision: PolicyDecision::Deny {
                        reason: "not allowed".into(),
                    },
                },
            ),
        ];
        let policy_readback = RunReadback::from_events(&policy_denied).unwrap();
        assert!(
            policy_readback
                .entries
                .contains(&ReadbackEntry::PolicyDenied {
                    call_id: call_id(),
                    reason: "not allowed".into(),
                })
        );
        assert!(
            !policy_readback
                .entries
                .iter()
                .any(|entry| matches!(entry, ReadbackEntry::ToolResult { .. }))
        );

        let approval_denied = vec![
            start_event(0),
            rec(1, context(turn_id(), "Write README")),
            rec(2, model_requested(turn_id(), 0)),
            rec(
                3,
                model_responded(turn_id(), 0, "I will write it.", vec![proposal()]),
            ),
            rec(
                4,
                HarnessEvent::ToolCallProposed {
                    run_id: run_id(),
                    turn_id: turn_id(),
                    call: call(),
                },
            ),
            rec(
                5,
                HarnessEvent::PolicyEvaluated {
                    run_id: run_id(),
                    call_id: call_id(),
                    decision: PolicyDecision::RequireApproval {
                        reason: "approval needed".into(),
                    },
                },
            ),
            rec(
                6,
                HarnessEvent::ApprovalDenied {
                    run_id: run_id(),
                    call_id: call_id(),
                    actor_id: actor_id(),
                    reason: "no".into(),
                },
            ),
        ];
        let approval_readback = RunReadback::from_events(&approval_denied).unwrap();
        assert!(
            approval_readback
                .entries
                .contains(&ReadbackEntry::ApprovalDenied {
                    call_id: call_id(),
                    actor_id: actor_id(),
                    reason: "no".into(),
                })
        );
        assert!(
            !approval_readback
                .entries
                .iter()
                .any(|entry| matches!(entry, ReadbackEntry::ToolResult { .. }))
        );

        let tool_failed = vec![
            start_event(0),
            rec(1, context(turn_id(), "Read README")),
            rec(2, model_requested(turn_id(), 0)),
            rec(
                3,
                model_responded(turn_id(), 0, "I will read it.", vec![proposal()]),
            ),
            rec(
                4,
                HarnessEvent::ToolCallProposed {
                    run_id: run_id(),
                    turn_id: turn_id(),
                    call: call(),
                },
            ),
            rec(
                5,
                HarnessEvent::PolicyEvaluated {
                    run_id: run_id(),
                    call_id: call_id(),
                    decision: PolicyDecision::Allow,
                },
            ),
            rec(
                6,
                HarnessEvent::ToolStarted {
                    run_id: run_id(),
                    call_id: call_id(),
                },
            ),
            rec(
                7,
                HarnessEvent::ToolFailed {
                    run_id: run_id(),
                    call_id: call_id(),
                    reason: "tool crashed".into(),
                },
            ),
        ];
        let failure_readback = RunReadback::from_events(&tool_failed).unwrap();
        assert!(
            failure_readback
                .entries
                .contains(&ReadbackEntry::ToolFailed {
                    call_id: call_id(),
                    reason: "tool crashed".into(),
                })
        );
        assert!(
            !failure_readback
                .entries
                .iter()
                .any(|entry| matches!(entry, ReadbackEntry::ToolResult { .. }))
        );
    }

    #[test]
    fn approval_grants_are_projected_with_actor() {
        let events = vec![
            start_event(0),
            rec(1, context(turn_id(), "Read README")),
            rec(2, model_requested(turn_id(), 0)),
            rec(
                3,
                model_responded(turn_id(), 0, "I will read it.", vec![proposal()]),
            ),
            rec(
                4,
                HarnessEvent::ToolCallProposed {
                    run_id: run_id(),
                    turn_id: turn_id(),
                    call: call(),
                },
            ),
            rec(
                5,
                HarnessEvent::PolicyEvaluated {
                    run_id: run_id(),
                    call_id: call_id(),
                    decision: PolicyDecision::RequireApproval {
                        reason: "approval needed".into(),
                    },
                },
            ),
            rec(
                6,
                HarnessEvent::ApprovalGranted {
                    run_id: run_id(),
                    call_id: call_id(),
                    actor_id: actor_id(),
                },
            ),
        ];

        let readback = RunReadback::from_events(&events).unwrap();

        assert_eq!(
            readback.final_phase,
            RunPhase::ReadyToExecuteTool { call: call() }
        );
        assert!(readback.entries.contains(&ReadbackEntry::ApprovalGranted {
            call_id: call_id(),
            actor_id: actor_id(),
        }));
    }

    #[test]
    fn invalid_ledger_returns_replay_error() {
        let events = vec![start_event(1)];

        let err = RunReadback::from_events(&events).unwrap_err();
        assert_eq!(
            err,
            Error::SequenceMismatch {
                expected: 0,
                actual: 1
            }
        );
    }
}