supercode-harness 0.4.4

The optional native Supercode agent and tool harness
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
//! Lossless, non-executing reconstruction of Claude Code runtime state.
//!
//! Claude Code persists scheduling, queue, permission, and background-agent
//! events in the same JSONL stream as chat messages.  Those records are not
//! part of the provider-neutral [`crate::ChatMessage`] view, but they are
//! required to decide whether a resumed session is semantically complete.
//! This module folds the verbatim [`crate::Session::raw`] records into a
//! serializable manifest.  It deliberately does **not** start jobs, agents, or
//! timers; activation is a separate policy decision.

use std::collections::{BTreeMap, HashMap, VecDeque};

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{Error, Result, Session, SessionSource};

/// Version of the persisted Claude runtime-state manifest schema.
pub const CLAUDE_RUNTIME_MANIFEST_VERSION: u32 = 1;

/// A pure, serializable reconstruction of runtime state in a Claude transcript.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeRuntimeManifest {
    /// Manifest schema version.
    pub schema_version: u32,
    /// Imported schedulers are always restored inert.  Merely loading this
    /// manifest must never start a timer or child agent.
    #[serde(default)]
    pub execution_state: ClaudeRuntimeExecutionState,
    /// Deterministic scheduler cursor state. Absent in manifests written
    /// before active emulation existed and therefore defaults empty.
    #[serde(default)]
    pub scheduler: crate::claude_runtime_scheduler::ClaudeRuntimeSchedulerState,
    /// Latest permission, prompt-leaf, and harness posture.
    pub posture: ClaudeRuntimePosture,
    /// Jobs created successfully and not subsequently cancelled.
    pub active_crons: Vec<ClaudeCronJob>,
    /// Successful wakeups for which no matching scheduled prompt has fired.
    pub pending_wakeups: Vec<ClaudeWakeup>,
    /// Queue totals and any content still enqueued at end of transcript.
    pub queue: ClaudeQueueState,
    /// Background Claude Agent calls and their latest known terminal/live state.
    pub background_children: Vec<ClaudeBackgroundChild>,
    /// Latest harness-reported background-child count, when present.
    pub reported_pending_background_children: Option<u64>,
    /// Verbatim runtime-affecting records, including records not interpreted.
    pub residue: Vec<ClaudeRuntimeResidue>,
}

/// Execution posture for imported Claude runtime state.
///
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClaudeRuntimeExecutionState {
    /// State is inspectable and mutable, but no timer or prompt is executed.
    #[default]
    Paused,
    /// Explicitly activated for deterministic scheduler claims.
    Active,
}

/// Latest Claude CLI mode and permission posture.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeRuntimePosture {
    /// Latest `permission-mode.permissionMode` value.
    pub permission_mode: Option<String>,
    /// Latest `last-prompt.leafUuid`, identifying Claude's selected prompt leaf.
    pub last_prompt_leaf_uuid: Option<String>,
    /// Latest abbreviated `last-prompt.lastPrompt` value.
    pub last_prompt: Option<String>,
    /// Latest runtime record timestamp.
    pub timestamp: Option<String>,
    /// Latest Claude CLI entrypoint (normally `cli`).
    pub entrypoint: Option<String>,
    /// Latest Claude user posture (normally `external`).
    pub user_type: Option<String>,
    /// Latest Claude Code version recorded by the runtime.
    pub version: Option<String>,
    /// Latest working directory recorded by the runtime.
    pub cwd: Option<String>,
}

/// One active Claude Cron job.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeCronJob {
    /// Harness-assigned job ID recovered from the successful tool result.
    pub id: String,
    /// Tool-use ID of the `CronCreate` call.
    pub tool_use_id: String,
    /// Cron expression supplied by the model.
    pub schedule: String,
    /// Whether the job repeats.
    pub recurring: bool,
    /// Whether durable scheduling was requested by the caller.
    pub durable_requested: bool,
    /// Prompt to inject when the job fires.
    pub prompt: String,
    /// Timestamp of the create call, when present.
    pub created_at: Option<String>,
    /// Relative expiry advertised by Claude's result, when recoverable.
    pub expires_after_seconds: Option<u64>,
    /// Exact successful tool-result text that assigned the ID.
    pub creation_result: String,
}

/// One scheduled one-shot wakeup that has not yet observably fired.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeWakeup {
    /// Tool-use ID of the `ScheduleWakeup` call.
    pub tool_use_id: String,
    /// Requested delay in seconds.
    pub delay_seconds: u64,
    /// Human-readable reason supplied to the tool.
    pub reason: Option<String>,
    /// Prompt to inject, or the reason when Claude omitted a distinct prompt.
    pub prompt: Option<String>,
    /// Timestamp of the schedule call, when present.
    pub created_at: Option<String>,
    /// Harness-reported next wall-clock wake time, when recoverable.
    pub scheduled_for: Option<String>,
    /// Exact successful tool-result text.
    pub creation_result: String,
}

/// End-of-transcript queue state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeQueueState {
    /// Total enqueue records folded.
    pub enqueued: u64,
    /// Total dequeue records folded.
    pub dequeued: u64,
    /// Total explicit `remove` records folded.
    pub removed: u64,
    /// FIFO content left enqueued at end of transcript.
    pub pending: Vec<String>,
}

/// Latest known state of a Claude `Agent` tool call.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeBackgroundChild {
    /// Parent tool-use ID.
    pub tool_use_id: String,
    /// Whether the originating tool call was present in this JSONL stream.
    pub origin_observed: bool,
    /// Claude task/agent ID, when the async launch returned one.
    pub agent_id: Option<String>,
    /// Agent definition requested by the parent.
    pub agent_type: Option<String>,
    /// Human-readable task description.
    pub description: Option<String>,
    /// Model requested by the parent.
    pub requested_model: Option<String>,
    /// Model Claude resolved for the child.
    pub resolved_model: Option<String>,
    /// Child prompt.
    pub prompt: Option<String>,
    /// Async transcript/output file, when Claude returned one.
    pub output_file: Option<String>,
    /// Latest known child state.
    pub state: ClaudeBackgroundState,
    /// Timestamp of the Agent call.
    pub started_at: Option<String>,
    /// Timestamp of a terminal result/notification.
    pub finished_at: Option<String>,
    /// Terminal summary, when present.
    pub summary: Option<String>,
}

/// Lifecycle state recovered for a Claude background child.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClaudeBackgroundState {
    /// The tool call was emitted but no launch result was observed.
    LaunchPending,
    /// Claude reported an async child was launched and no terminal event followed.
    Running,
    /// A successful synchronous result or `completed` notification was observed.
    Completed,
    /// Claude reported a terminal failure/error.
    Failed,
    /// Claude reported that the task or background command was killed.
    Killed,
    /// A terminal state unknown to this manifest schema was observed.
    UnknownTerminal,
}

/// Verbatim evidence for one runtime-affecting source record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeRuntimeResidue {
    /// One-based line number in the source JSONL.
    pub line: usize,
    /// Stable classification, or `unknown-runtime-record` for unmodeled data.
    pub kind: String,
    /// Original JSONL line, byte-for-byte excluding its line terminator.
    pub raw: String,
}

#[derive(Debug, Clone)]
enum PendingRuntimeCall {
    Invalid {
        name: String,
    },
    CronCreate {
        tool_use_id: String,
        schedule: String,
        recurring: bool,
        durable_requested: bool,
        prompt: String,
        created_at: Option<String>,
    },
    CronDelete {
        id: String,
    },
    Wakeup {
        tool_use_id: String,
        delay_seconds: u64,
        reason: Option<String>,
        prompt: Option<String>,
        created_at: Option<String>,
    },
    CronList,
}

impl ClaudeRuntimeManifest {
    /// Reconstruct a manifest from a loaded Claude Code session without
    /// executing or contacting a provider.
    pub fn from_session(session: &Session) -> Result<Self> {
        if session.meta.source != SessionSource::ClaudeCode {
            return Err(Error::Other(
                "Claude runtime state can only be extracted from a Claude Code session".into(),
            ));
        }
        if session.parse_error_lines != 0 {
            return Err(Error::Other(format!(
                "cannot reconstruct Claude runtime state: {} malformed JSONL line(s)",
                session.parse_error_lines
            )));
        }

        let mut posture = ClaudeRuntimePosture::default();
        let mut active_crons = BTreeMap::<String, ClaudeCronJob>::new();
        let mut pending_calls = HashMap::<String, PendingRuntimeCall>::new();
        let mut wakeups = BTreeMap::<String, ClaudeWakeup>::new();
        let mut queue = VecDeque::<String>::new();
        let mut enqueued = 0_u64;
        let mut dequeued = 0_u64;
        let mut removed = 0_u64;
        let mut children = BTreeMap::<String, ClaudeBackgroundChild>::new();
        let mut task_notifications = Vec::<(TaskNotification, Option<String>, usize)>::new();
        let mut reported_pending_background_children = None;
        let mut residue = Vec::new();

        // Claude's JSONL is append-only, but asynchronous runtime results can
        // be persisted before the assistant tool-use record that owns them.
        // Index every runtime call first so the state fold below can still
        // correlate those forward references. Result records remain folded
        // in source order because that is the observable state-transition
        // order (for example, create/delete/create of the same cron job).
        for (offset, raw) in session.raw.iter().enumerate() {
            if raw.trim().is_empty() {
                continue;
            }
            let line = offset + 1;
            let value: Value = serde_json::from_str(raw).map_err(|error| {
                Error::Other(format!(
                    "cannot reconstruct Claude runtime state: malformed JSON at line {line}: {error}"
                ))
            })?;
            if value.get("type").and_then(Value::as_str) == Some("assistant") {
                fold_assistant_calls(
                    &value,
                    line,
                    &mut pending_calls,
                    &mut children,
                    &mut residue,
                    raw,
                )?;
            }
        }

        for (offset, raw) in session.raw.iter().enumerate() {
            if raw.trim().is_empty() {
                continue;
            }
            let line = offset + 1;
            let value: Value = serde_json::from_str(raw).map_err(|error| {
                Error::Other(format!(
                    "cannot reconstruct Claude runtime state: malformed JSON at line {line}: {error}"
                ))
            })?;
            update_posture(&mut posture, &value);
            let record_type = value.get("type").and_then(Value::as_str).unwrap_or("");

            match record_type {
                "permission-mode" => {
                    let mode = required_str(&value, "permissionMode", line, "permission-mode")?;
                    posture.permission_mode = Some(mode.to_owned());
                    push_residue(&mut residue, line, "permission-mode", raw);
                }
                "last-prompt" => {
                    posture.last_prompt_leaf_uuid = value
                        .get("leafUuid")
                        .and_then(Value::as_str)
                        .map(str::to_owned);
                    posture.last_prompt = value
                        .get("lastPrompt")
                        .and_then(Value::as_str)
                        .map(str::to_owned);
                    push_residue(&mut residue, line, "last-prompt", raw);
                }
                "queue-operation" => {
                    let operation = required_str(&value, "operation", line, "queue-operation")?;
                    match operation {
                        "enqueue" => {
                            let content = required_str(&value, "content", line, "queue enqueue")?;
                            enqueued += 1;
                            queue.push_back(content.to_owned());
                            mark_matching_wakeup_fired(content, &mut wakeups);
                            if let Some(notification) = parse_task_notification(content) {
                                task_notifications.push((
                                    notification,
                                    value
                                        .get("timestamp")
                                        .and_then(Value::as_str)
                                        .map(str::to_owned),
                                    line,
                                ));
                            }
                        }
                        "dequeue" => {
                            dequeued += 1;
                            queue.pop_front().ok_or_else(|| {
                                Error::Other(format!(
                                    "malformed Claude queue reference at line {line}: dequeue with an empty queue"
                                ))
                            })?;
                        }
                        "remove" => {
                            removed += 1;
                            queue.pop_front().ok_or_else(|| {
                                Error::Other(format!(
                                    "malformed Claude queue reference at line {line}: remove with an empty queue"
                                ))
                            })?;
                        }
                        other => {
                            push_residue(
                                &mut residue,
                                line,
                                &format!("unknown-queue-operation:{other}"),
                                raw,
                            );
                            continue;
                        }
                    }
                    push_residue(&mut residue, line, "queue-operation", raw);
                }
                // Runtime calls were indexed in the pre-pass above so a
                // physically earlier async result can resolve its tool-use
                // id. The main fold intentionally leaves assistant records
                // alone rather than registering every call twice.
                "assistant" => {}
                "user" => {
                    fold_tool_results(
                        &value,
                        line,
                        &mut pending_calls,
                        &mut active_crons,
                        &mut wakeups,
                        &mut children,
                        &mut task_notifications,
                        &mut residue,
                        raw,
                    )?;
                }
                "system" => {
                    if let Some(count) = value
                        .get("pendingBackgroundAgentCount")
                        .and_then(Value::as_u64)
                    {
                        reported_pending_background_children = Some(count);
                        push_residue(&mut residue, line, "background-count", raw);
                    } else if value.get("subtype").and_then(Value::as_str)
                        == Some("scheduled_task_fire")
                    {
                        push_residue(&mut residue, line, "scheduled-task-fire", raw);
                    }
                }
                other if looks_runtime_type(other) => {
                    push_residue(&mut residue, line, "unknown-runtime-record", raw);
                }
                _ => {}
            }
        }

        for (notification, timestamp, line) in task_notifications {
            apply_task_notification(notification, timestamp, line, &mut children)?;
        }

        // The call-index pre-pass observes assistant residue before the main
        // fold sees other runtime records. Restore source order for the
        // manifest's verbatim evidence stream.
        residue.sort_by_key(|record| record.line);

        let pending_wakeups = wakeups.into_values().collect();
        Ok(Self {
            schema_version: CLAUDE_RUNTIME_MANIFEST_VERSION,
            execution_state: ClaudeRuntimeExecutionState::Paused,
            scheduler: Default::default(),
            posture,
            active_crons: active_crons.into_values().collect(),
            pending_wakeups,
            queue: ClaudeQueueState {
                enqueued,
                dequeued,
                removed,
                pending: queue.into_iter().collect(),
            },
            background_children: children.into_values().collect(),
            reported_pending_background_children,
            residue,
        })
    }

    /// Render this manifest as deterministic, pretty JSON for a no-provider
    /// dry report or persistence alongside a resumed session.
    pub fn to_pretty_json(&self) -> Result<String> {
        serde_json::to_string_pretty(self).map_err(Error::Decode)
    }
}

fn update_posture(posture: &mut ClaudeRuntimePosture, value: &Value) {
    for (key, target) in [
        ("timestamp", &mut posture.timestamp),
        ("entrypoint", &mut posture.entrypoint),
        ("userType", &mut posture.user_type),
        ("version", &mut posture.version),
        ("cwd", &mut posture.cwd),
    ] {
        if let Some(text) = value.get(key).and_then(Value::as_str) {
            *target = Some(text.to_owned());
        }
    }
}

fn fold_assistant_calls(
    value: &Value,
    line: usize,
    pending_calls: &mut HashMap<String, PendingRuntimeCall>,
    children: &mut BTreeMap<String, ClaudeBackgroundChild>,
    residue: &mut Vec<ClaudeRuntimeResidue>,
    raw: &str,
) -> Result<()> {
    let timestamp = value
        .get("timestamp")
        .and_then(Value::as_str)
        .map(str::to_owned);
    let Some(content) = value.pointer("/message/content").and_then(Value::as_array) else {
        return Ok(());
    };
    for block in content {
        if block.get("type").and_then(Value::as_str) != Some("tool_use") {
            continue;
        }
        let Some(name) = block.get("name").and_then(Value::as_str) else {
            continue;
        };
        let Some(id) = block.get("id").and_then(Value::as_str) else {
            if matches!(
                name,
                "CronCreate" | "CronDelete" | "ScheduleWakeup" | "Agent"
            ) {
                return Err(Error::Other(format!(
                    "malformed Claude runtime tool call at line {line}: {name} has no id"
                )));
            }
            continue;
        };
        let input = block.get("input").unwrap_or(&Value::Null);
        let call = match name {
            "CronCreate" => Some(PendingRuntimeCall::CronCreate {
                tool_use_id: id.to_owned(),
                schedule: required_str(input, "cron", line, "CronCreate")?.to_owned(),
                recurring: input
                    .get("recurring")
                    .and_then(Value::as_bool)
                    .unwrap_or(false),
                durable_requested: input
                    .get("durable")
                    .and_then(Value::as_bool)
                    .unwrap_or(false),
                prompt: required_str(input, "prompt", line, "CronCreate")?.to_owned(),
                created_at: timestamp.clone(),
            }),
            "CronDelete" => Some(match input.get("id").and_then(Value::as_str) {
                Some(id) => PendingRuntimeCall::CronDelete { id: id.to_owned() },
                // Stock Claude persists model-generated calls that fail input
                // validation. Keep the call pending so its error result can
                // be correlated and preserved as runtime residue; only a
                // successful result for invalid input is malformed state.
                None => PendingRuntimeCall::Invalid {
                    name: "CronDelete".to_owned(),
                },
            }),
            "ScheduleWakeup" => Some(PendingRuntimeCall::Wakeup {
                tool_use_id: id.to_owned(),
                delay_seconds: input
                    .get("delaySeconds")
                    .and_then(Value::as_u64)
                    .ok_or_else(|| {
                        Error::Other(format!(
                            "malformed ScheduleWakeup at line {line}: missing integer delaySeconds"
                        ))
                    })?,
                reason: input
                    .get("reason")
                    .and_then(Value::as_str)
                    .map(str::to_owned),
                prompt: input
                    .get("prompt")
                    .and_then(Value::as_str)
                    .map(str::to_owned),
                created_at: timestamp.clone(),
            }),
            "CronList" => Some(PendingRuntimeCall::CronList),
            "Agent" => {
                let child = ClaudeBackgroundChild {
                    tool_use_id: id.to_owned(),
                    origin_observed: true,
                    agent_id: None,
                    agent_type: input
                        .get("subagent_type")
                        .and_then(Value::as_str)
                        .map(str::to_owned),
                    description: input
                        .get("description")
                        .and_then(Value::as_str)
                        .map(str::to_owned),
                    requested_model: input
                        .get("model")
                        .and_then(Value::as_str)
                        .map(str::to_owned),
                    resolved_model: None,
                    prompt: input
                        .get("prompt")
                        .and_then(Value::as_str)
                        .map(str::to_owned),
                    output_file: None,
                    state: ClaudeBackgroundState::LaunchPending,
                    started_at: timestamp.clone(),
                    finished_at: None,
                    summary: None,
                };
                if children.insert(id.to_owned(), child).is_some() {
                    return Err(Error::Other(format!(
                        "malformed Claude Agent reference at line {line}: duplicate tool-use id {id}"
                    )));
                }
                push_residue(residue, line, "agent-call", raw);
                None
            }
            other if other.starts_with("Cron") || other.contains("Wakeup") => {
                push_residue(residue, line, "unknown-runtime-tool-call", raw);
                None
            }
            _ => None,
        };
        if let Some(call) = call {
            if pending_calls.insert(id.to_owned(), call).is_some() {
                return Err(Error::Other(format!(
                    "malformed Claude runtime reference at line {line}: duplicate tool-use id {id}"
                )));
            }
            push_residue(residue, line, "runtime-tool-call", raw);
        }
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn fold_tool_results(
    value: &Value,
    line: usize,
    pending_calls: &mut HashMap<String, PendingRuntimeCall>,
    active_crons: &mut BTreeMap<String, ClaudeCronJob>,
    wakeups: &mut BTreeMap<String, ClaudeWakeup>,
    children: &mut BTreeMap<String, ClaudeBackgroundChild>,
    task_notifications: &mut Vec<(TaskNotification, Option<String>, usize)>,
    residue: &mut Vec<ClaudeRuntimeResidue>,
    raw: &str,
) -> Result<()> {
    let timestamp = value
        .get("timestamp")
        .and_then(Value::as_str)
        .map(str::to_owned);
    let tool_use_result = value.get("toolUseResult");
    let Some(content) = value.pointer("/message/content").and_then(Value::as_array) else {
        return Ok(());
    };
    for block in content {
        if block.get("type").and_then(Value::as_str) != Some("tool_result") {
            continue;
        }
        let Some(tool_use_id) = block.get("tool_use_id").and_then(Value::as_str) else {
            continue;
        };
        let text = tool_result_text(block.get("content"));
        let is_error = block
            .get("is_error")
            .and_then(Value::as_bool)
            .unwrap_or(false);

        if let Some(child) = children.get_mut(tool_use_id) {
            if is_error {
                child.state = ClaudeBackgroundState::Failed;
                child.finished_at = timestamp.clone();
                child.summary = text.clone();
            } else if tool_use_result
                .and_then(|v| v.get("isAsync"))
                .and_then(Value::as_bool)
                == Some(true)
            {
                child.state = ClaudeBackgroundState::Running;
                child.agent_id = tool_use_result
                    .and_then(|v| v.get("agentId"))
                    .and_then(Value::as_str)
                    .map(str::to_owned);
                child.resolved_model = tool_use_result
                    .and_then(|v| v.get("resolvedModel"))
                    .and_then(Value::as_str)
                    .map(str::to_owned);
                child.output_file = tool_use_result
                    .and_then(|v| v.get("outputFile"))
                    .and_then(Value::as_str)
                    .map(str::to_owned);
            } else {
                child.state = ClaudeBackgroundState::Completed;
                child.finished_at = timestamp.clone();
                child.summary = text.clone();
            }
            push_residue(residue, line, "agent-result", raw);
            continue;
        }

        if let Some(notification) = text.as_deref().and_then(parse_task_notification) {
            task_notifications.push((notification, timestamp.clone(), line));
            push_residue(residue, line, "agent-notification", raw);
            continue;
        }

        let Some(call) = pending_calls.remove(tool_use_id) else {
            if text.as_deref().is_some_and(looks_runtime_result) {
                return Err(Error::Other(format!(
                    "malformed Claude runtime result at line {line}: unknown tool-use id {tool_use_id}"
                )));
            }
            continue;
        };
        push_residue(residue, line, "runtime-tool-result", raw);
        if is_error {
            continue;
        }
        let text = text.ok_or_else(|| {
            Error::Other(format!(
                "malformed Claude runtime result at line {line}: non-text result for {tool_use_id}"
            ))
        })?;
        match call {
            PendingRuntimeCall::Invalid { name } => {
                return Err(Error::Other(format!(
                    "malformed {name} result at line {line}: invalid input unexpectedly succeeded"
                )));
            }
            PendingRuntimeCall::CronCreate {
                tool_use_id,
                schedule,
                mut recurring,
                durable_requested,
                prompt,
                created_at,
            } => {
                let id = parse_created_cron_id(&text)
                    .ok_or_else(|| {
                        Error::Other(format!(
                            "malformed CronCreate result at line {line}: no assigned job id"
                        ))
                    })?
                    .to_owned();
                // The successful harness result is authoritative about the
                // job actually created. Claude may omit the optional
                // `recurring` request field while still returning the
                // unambiguous recurring result shape; treating the omitted
                // field as false incorrectly deletes that job after its first
                // delivery. Preserve legacy `Scheduled job` behavior because
                // that older result shape does not state either mode.
                if text.starts_with("Scheduled recurring job ") {
                    recurring = true;
                } else if text.starts_with("Scheduled one-shot task ") {
                    recurring = false;
                }
                let job = ClaudeCronJob {
                    id: id.clone(),
                    tool_use_id,
                    schedule,
                    recurring,
                    durable_requested,
                    prompt,
                    created_at,
                    expires_after_seconds: text
                        .contains("Auto-expires after 7 days")
                        .then_some(7 * 24 * 60 * 60),
                    creation_result: text,
                };
                if active_crons.insert(id.clone(), job).is_some() {
                    return Err(Error::Other(format!(
                        "malformed CronCreate result at line {line}: duplicate active job id {id}"
                    )));
                }
            }
            PendingRuntimeCall::CronDelete { id } => {
                if !text.starts_with("Cancelled job ") {
                    return Err(Error::Other(format!(
                        "malformed CronDelete result at line {line}: unexpected success text"
                    )));
                }
                active_crons.remove(&id).ok_or_else(|| {
                    Error::Other(format!(
                        "malformed CronDelete reference at line {line}: unknown active job id {id}"
                    ))
                })?;
            }
            PendingRuntimeCall::Wakeup {
                tool_use_id,
                delay_seconds,
                reason,
                prompt,
                created_at,
            } => {
                let scheduled_for =
                    parse_between(&text, "Next wakeup scheduled for ", " (in ").map(str::to_owned);
                if scheduled_for.is_none() {
                    return Err(Error::Other(format!(
                        "malformed ScheduleWakeup result at line {line}: no scheduled time"
                    )));
                }
                // Claude exposes a single "next wakeup" slot. A later
                // successful ScheduleWakeup supersedes an earlier one.
                wakeups.clear();
                wakeups.insert(
                    tool_use_id.clone(),
                    ClaudeWakeup {
                        tool_use_id,
                        delay_seconds,
                        reason,
                        prompt,
                        created_at,
                        scheduled_for,
                        creation_result: text,
                    },
                );
            }
            PendingRuntimeCall::CronList => {
                // Stock Claude records the structured listing in the
                // record-level `toolUseResult`.  Supercode's synthesized
                // Claude tail stores an intrinsic result as plain tool text,
                // so also accept the same `{jobs:[...]}` object serialized
                // there.  This makes a paused CronList call re-importable
                // instead of turning a valid continued transcript into a
                // manifest parse failure.
                let text_result = serde_json::from_str::<Value>(&text).ok();
                let jobs = tool_use_result
                    .or(text_result.as_ref())
                    .and_then(|result| result.get("jobs"))
                    .and_then(Value::as_array)
                    .ok_or_else(|| {
                        Error::Other(format!(
                            "malformed CronList result at line {line}: missing jobs array"
                        ))
                    })?;
                let mut listed = BTreeMap::new();
                for job in jobs {
                    let id = required_str(job, "id", line, "CronList job")?.to_owned();
                    let cron = required_str(job, "cron", line, "CronList job")?.to_owned();
                    let previous = active_crons.get(&id);
                    listed.insert(
                        id.clone(),
                        ClaudeCronJob {
                            id,
                            tool_use_id: previous
                                .map(|job| job.tool_use_id.clone())
                                .unwrap_or_else(|| tool_use_id.to_owned()),
                            schedule: cron,
                            recurring: job
                                .get("recurring")
                                .and_then(Value::as_bool)
                                .unwrap_or(false),
                            durable_requested: previous
                                .map(|job| job.durable_requested)
                                .unwrap_or_else(|| {
                                    job.get("durable").and_then(Value::as_bool).unwrap_or(false)
                                }),
                            prompt: required_str(job, "prompt", line, "CronList job")?.to_owned(),
                            created_at: previous.and_then(|job| job.created_at.clone()),
                            expires_after_seconds: previous
                                .and_then(|job| job.expires_after_seconds),
                            creation_result: previous
                                .map(|job| job.creation_result.clone())
                                .unwrap_or_else(|| text.clone()),
                        },
                    );
                }
                *active_crons = listed;
            }
        }
    }
    Ok(())
}

fn mark_matching_wakeup_fired(content: &str, wakeups: &mut BTreeMap<String, ClaudeWakeup>) {
    let matching = wakeups.iter().find_map(|(id, wakeup)| {
        let prompt = wakeup.prompt.as_deref().or(wakeup.reason.as_deref());
        (prompt == Some(content)).then(|| id.clone())
    });
    if let Some(id) = matching {
        wakeups.remove(&id);
    }
}

fn tool_result_text(content: Option<&Value>) -> Option<String> {
    match content? {
        Value::String(text) => Some(text.clone()),
        Value::Array(blocks) => {
            let joined = blocks
                .iter()
                .filter(|block| block.get("type").and_then(Value::as_str) == Some("text"))
                .filter_map(|block| block.get("text").and_then(Value::as_str))
                .collect::<Vec<_>>()
                .join("\n");
            (!joined.is_empty()).then_some(joined)
        }
        _ => None,
    }
}

#[derive(Debug)]
struct TaskNotification {
    task_id: Option<String>,
    tool_use_id: Option<String>,
    status: Option<String>,
    summary: Option<String>,
}

fn parse_task_notification(text: &str) -> Option<TaskNotification> {
    text.contains("<task-notification>")
        .then(|| TaskNotification {
            task_id: tag_value(text, "task-id"),
            tool_use_id: tag_value(text, "tool-use-id"),
            status: tag_value(text, "status"),
            summary: tag_value(text, "summary"),
        })
}

fn apply_task_notification(
    notification: TaskNotification,
    timestamp: Option<String>,
    line: usize,
    children: &mut BTreeMap<String, ClaudeBackgroundChild>,
) -> Result<()> {
    let referenced = notification
        .tool_use_id
        .clone()
        .or_else(|| {
            notification.task_id.as_deref().and_then(|task_id| {
                children
                    .iter()
                    .find(|(_, child)| child.agent_id.as_deref() == Some(task_id))
                    .map(|(id, _)| id.clone())
            })
        })
        .or_else(|| notification.task_id.as_ref().map(|id| format!("task:{id}")))
        .ok_or_else(|| {
            Error::Other(format!(
                "malformed Claude task notification at line {line}: missing tool-use-id and task-id"
            ))
        })?;
    if !children.contains_key(&referenced) {
        let child_type = notification
            .summary
            .as_deref()
            .filter(|summary| summary.starts_with("Background command "))
            .map(|_| "background-command")
            .unwrap_or("unresolved-task");
        children.insert(
            referenced.clone(),
            ClaudeBackgroundChild {
                tool_use_id: referenced.clone(),
                origin_observed: false,
                agent_id: notification.task_id.clone(),
                agent_type: Some(child_type.to_owned()),
                description: notification.summary.clone(),
                requested_model: None,
                resolved_model: None,
                prompt: None,
                output_file: None,
                state: ClaudeBackgroundState::LaunchPending,
                started_at: None,
                finished_at: None,
                summary: None,
            },
        );
    }
    let child = children
        .get_mut(&referenced)
        .expect("child inserted or observed above");
    child.agent_id = child.agent_id.clone().or(notification.task_id);
    child.state = match notification.status.as_deref() {
        Some("completed") => ClaudeBackgroundState::Completed,
        Some("failed") | Some("error") => ClaudeBackgroundState::Failed,
        Some("killed") => ClaudeBackgroundState::Killed,
        Some(_) => ClaudeBackgroundState::UnknownTerminal,
        None => ClaudeBackgroundState::UnknownTerminal,
    };
    child.finished_at = timestamp;
    child.summary = notification.summary;
    Ok(())
}

fn tag_value(text: &str, tag: &str) -> Option<String> {
    let start = format!("<{tag}>");
    let end = format!("</{tag}>");
    parse_between(text, &start, &end).map(str::to_owned)
}

fn parse_created_cron_id(text: &str) -> Option<&str> {
    let rest = text
        .strip_prefix("Scheduled recurring job ")
        .or_else(|| text.strip_prefix("Scheduled job "))
        .or_else(|| text.strip_prefix("Scheduled one-shot task "))?;
    rest.split_whitespace().next()
}

fn parse_between<'a>(text: &'a str, start: &str, end: &str) -> Option<&'a str> {
    let rest = text.split_once(start)?.1;
    Some(rest.split_once(end)?.0)
}

fn required_str<'a>(value: &'a Value, key: &str, line: usize, kind: &str) -> Result<&'a str> {
    value.get(key).and_then(Value::as_str).ok_or_else(|| {
        Error::Other(format!(
            "malformed Claude {kind} at line {line}: missing string {key}"
        ))
    })
}

fn looks_runtime_result(text: &str) -> bool {
    text.starts_with("Scheduled recurring job ")
        || text.starts_with("Scheduled job ")
        || text.starts_with("Scheduled one-shot task ")
        || text.starts_with("Cancelled job ")
        || text.starts_with("Next wakeup scheduled for ")
}

fn looks_runtime_type(record_type: &str) -> bool {
    record_type.contains("queue")
        || record_type.contains("permission")
        || record_type.contains("schedule")
        || record_type.contains("cron")
        || record_type.contains("background")
}

fn push_residue(residue: &mut Vec<ClaudeRuntimeResidue>, line: usize, kind: &str, raw: &str) {
    residue.push(ClaudeRuntimeResidue {
        line,
        kind: kind.to_owned(),
        raw: raw.to_owned(),
    });
}