thirdshift 0.33.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! Interpret a Harness session once, including optional retained records.

use std::fmt;
use std::os::unix::process::ExitStatusExt;
use std::path::Path;
use std::process::{ExitStatus, Output};

use anyhow::{Context, Result, anyhow, bail};

use super::said;
use crate::interrupt;

mod stream;
pub(super) use stream::Stream;
pub mod event;
#[cfg(test)]
mod event_tests;
pub(crate) mod limits;
mod models;
mod security;
pub use security::SafeguardRefusal;
use security::Security;

/// Live interpretation has only line condensation. Consume it after the
/// process owner has stopped or waited for the child and joined its workers.
pub struct Interpretation {
    cli: &'static str,
    decoder: Box<dyn Decoder>,
    retained: Option<Box<dyn Retained>>,
    security: Option<Security>,
    models: models::Models,
    events: Option<Vec<event::Event>>,
    work_started: bool,
    plan_limit: Option<limits::Limit>,
    /// Plan usage seen since the recorder last took it.
    plan_usage: Vec<crate::plan_usage::Observation>,
    /// Whether a structured wire frame said the subscription refused
    /// included work: sticky once seen, since the recorder takes the
    /// observations themselves.
    plan_usage_exhausted: bool,
    /// The first such refusal's Harness, Plan window, utilization and reset.
    plan_usage_limit: Option<limits::Limit>,
}

/// Reporting survives ordinary failures; only success supplies Resume facts.
pub struct Completion {
    pub report: Option<Report>,
    pub outcome: Result<Ended>,
}

#[derive(Default)]
pub struct Report {
    /// Raw Harness records recovered after exit, in their original encoding.
    pub retained_records: Vec<RetainedRecord>,
    /// Normalized timeline captured by `decode`, enriched by retained records.
    /// Progress-only callers receive only facts recovered at completion.
    pub events: Vec<event::Event>,
    /// Ordered progress supplied after retained completion.
    pub completion_progress: Vec<String>,
    pub warnings: Vec<String>,
    pub summary: Option<String>,
    /// Models reported by session output or retained records.
    pub models: Vec<String>,
}

/// A recovered Harness event keeps its raw body paired with the facts decoded
/// from it, so recording retains the event's clock and call association.
pub struct RetainedRecord {
    pub raw: String,
    pub events: Vec<event::Event>,
}

impl Report {
    /// Retained adapters opt into completion Model progress after reconciliation.
    pub(super) fn set_model_progress(&mut self) {
        self.completion_progress = self
            .models
            .iter()
            .map(|model| format!("Model: {model}"))
            .collect();
    }
}

#[derive(Debug)]
pub struct Ended {
    pub session_id: Option<String>,
    pub killed: Vec<String>,
    pub final_message: Option<String>,
    /// The protocol supplied a terminal result, independently of its text.
    pub completed: bool,
}

impl Ended {
    pub fn killed_work(&self) -> Vec<&str> {
        self.killed.iter().map(String::as_str).collect()
    }

    /// One-shot callers require completed work and nonblank final text.
    pub fn require_final_message(self, label: &str) -> Result<String> {
        if !self.killed.is_empty() {
            bail!(
                "{label} ended with unfinished background work: {}",
                self.killed.join("; ")
            );
        }
        if !self.completed {
            bail!("{label} ended before completing its turn");
        }
        self.final_message
            .filter(|text| !text.trim().is_empty())
            .with_context(|| format!("{label} ended without a final message"))
    }
}

/// Each real protocol must supply its outcome explicitly. Streams with no
/// terminal outcome remain accepted, as before, unless execution failed.
pub(super) enum TurnOutcome {
    NotFailed,
    Failed,
}

impl TurnOutcome {
    pub(super) fn from_failed(failed: bool) -> Self {
        if failed {
            Self::Failed
        } else {
            Self::NotFailed
        }
    }
}

pub(super) struct Facts {
    pub report: Report,
    pub ended: Ended,
    pub outcome: TurnOutcome,
    /// May be a retried diagnostic even when the turn did not fail.
    pub diagnostic: Option<String>,
}

pub(super) trait Decoder: Send {
    fn condense(&mut self, raw: &str) -> StreamUpdate;
    fn complete(self: Box<Self>) -> Facts;
    /// Optional live quota records absent from the Harness's stdout.
    fn limit_records(&mut self) -> Vec<String> {
        Vec::new()
    }
    fn set_home(&mut self, _home: &Path) {}
}

/// Live protocol knowledge stays in the decoder, including evidence from
/// events its progress or completion guards otherwise ignore.
#[derive(Default)]
pub(super) struct StreamUpdate {
    pub progress: Vec<String>,
    pub evidence: Vec<Evidence>,
    pub events: Vec<event::Event>,
}

/// One decoded line. Consumers needing normalized facts use this interface;
/// progress-only callers keep using `condense`, with no event buffering.
pub struct Decoded {
    pub progress: Vec<String>,
    pub events: Vec<event::Event>,
}

pub(super) enum Evidence {
    PlanLimit(limits::Limit),
    /// Any Plan usage report, at every status and utilization.
    PlanUsage(crate::plan_usage::Observation),
    WorkStarted,
    ObservedModel {
        name: String,
        scope: ModelScope,
    },
    RequestedModelFallback,
    SafeguardRefusal(SafeguardRefusal),
}

pub(super) enum ModelScope {
    MainLoop,
    AttributionOnly,
}

/// Optional retained reconciliation belongs to the supplying Harness adapter.
/// Owned implementations follow Interpretation into the transcript reader.
pub(super) trait Retained: Send {
    fn reconcile(self: Box<Self>, facts: &mut Facts) -> Result<()>;
    fn set_home(&mut self, _home: &Path) {}
}

enum Failure {
    Execution(anyhow::Error),
    Rejected {
        status: ExitStatus,
        diagnostic: Option<String>,
        refusal: Option<SafeguardRefusal>,
        before_first_turn: bool,
        session_id: Option<String>,
        plan_usage_exhausted: bool,
        /// Boxed so the rarely-set limit doesn't bloat every `Result`.
        plan_usage_limit: Option<Box<limits::Limit>>,
    },
}

/// A failed session keeps the Harness's diagnostic separate from its exit
/// status so callers can report it without parsing the error's display text.
#[derive(Debug)]
pub struct SessionFailure {
    pub harness: &'static str,
    pub diagnostic: Option<String>,
    /// No completed turn, tokens, assistant work or tool calls were observed.
    pub before_first_turn: bool,
    /// Retained on failure too, so a Trial can identify the session it ran.
    pub session_id: Option<String>,
    /// Kernel or manager evidence supplied by the Session's execution owner.
    pub oom_killed: bool,
    /// A structured Harness wire frame, never agent-writable text, said the
    /// subscription's Plan usage refused included work during the session:
    /// the failure a Step may be routed away from.
    pub plan_usage_exhausted: bool,
    /// What that wire frame said stopped the session, for a Paused
    /// Command's record.
    pub plan_usage_limit: Option<limits::Limit>,
    status: ExitStatus,
}

impl fmt::Display for SessionFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.harness)?;
        if self.status.success() {
            f.write_str("'s turn failed")?;
        } else if let Some(code) = self.status.code() {
            write!(f, " exited {code}")?;
        } else {
            f.write_str(" exited by signal")?;
            if let Some(signal) = self.status.signal() {
                write!(f, " {signal}")?;
                let name = match signal {
                    libc::SIGKILL => Some("SIGKILL"),
                    libc::SIGTERM => Some("SIGTERM"),
                    libc::SIGABRT => Some("SIGABRT"),
                    libc::SIGSEGV => Some("SIGSEGV"),
                    libc::SIGINT => Some("SIGINT"),
                    libc::SIGHUP => Some("SIGHUP"),
                    libc::SIGPIPE => Some("SIGPIPE"),
                    _ => None,
                };
                if let Some(name) = name {
                    write!(f, " ({name})")?;
                }
            }
        }
        if !self.status.success() && self.oom_killed {
            f.write_str(" (scope OOM-killed)")?;
        }
        if let Some(diagnostic) = &self.diagnostic {
            write!(f, ": {diagnostic}")?;
        }
        Ok(())
    }
}

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

impl SessionFailure {
    /// How the session ended, without the Harness's diagnostic: the session's
    /// agent can write that, so it stays off GitHub.
    pub fn without_diagnostic(&self) -> String {
        Self {
            harness: self.harness,
            diagnostic: None,
            before_first_turn: self.before_first_turn,
            session_id: None,
            oom_killed: self.oom_killed,
            plan_usage_exhausted: self.plan_usage_exhausted,
            plan_usage_limit: None,
            status: self.status,
        }
        .to_string()
    }

    /// The Harness never ran: before any turn, it exited with the shell's
    /// "cannot execute" (126) or "not found" (127). macOS runs a file it can't
    /// execute through `/bin/sh`, which reports either, where Linux refuses to
    /// spawn it at all.
    pub fn never_launched(&self) -> bool {
        self.before_first_turn && matches!(self.status.code(), Some(126 | 127))
    }

    /// A session of `harness` that exited `code` after its first turn.
    #[cfg(test)]
    pub fn exited(harness: &'static str, code: i32) -> Self {
        use std::os::unix::process::ExitStatusExt;
        Self {
            harness,
            diagnostic: None,
            before_first_turn: false,
            session_id: None,
            oom_killed: false,
            plan_usage_exhausted: false,
            plan_usage_limit: None,
            status: ExitStatus::from_raw(code << 8),
        }
    }

    /// A session of `harness` stopped at its Plan usage limit, before its
    /// first turn or after work began.
    #[cfg(test)]
    pub fn plan_usage_limit(harness: &'static str, before_first_turn: bool) -> Self {
        Self {
            before_first_turn,
            plan_usage_exhausted: true,
            ..Self::exited(harness, 1)
        }
    }
}

impl Failure {
    fn session_error(self, cli: &'static str) -> anyhow::Error {
        match self {
            Self::Execution(error) => error,
            Self::Rejected {
                status,
                diagnostic,
                refusal,
                before_first_turn,
                session_id,
                plan_usage_exhausted,
                plan_usage_limit,
            } => {
                let error = anyhow::Error::new(SessionFailure {
                    harness: cli,
                    diagnostic,
                    status,
                    before_first_turn,
                    session_id,
                    oom_killed: false,
                    plan_usage_exhausted,
                    plan_usage_limit: plan_usage_limit.map(|limit| *limit),
                });
                match refusal {
                    Some(refusal) => error.context(refusal),
                    None => error,
                }
            }
        }
    }
}

impl Interpretation {
    pub(super) fn new(cli: &'static str, decoder: Box<dyn Decoder>) -> Self {
        Self {
            cli,
            decoder,
            retained: None,
            security: None,
            models: models::Models::default(),
            events: None,
            work_started: false,
            plan_limit: None,
            plan_usage: Vec::new(),
            plan_usage_exhausted: false,
            plan_usage_limit: None,
        }
    }

    pub(super) fn with_retained(mut self, retained: Box<dyn Retained>) -> Self {
        self.retained = Some(retained);
        self
    }

    /// Native evidence belongs to the launched session's home, which a Trial
    /// sandbox can replace without changing the observing process's home.
    pub(crate) fn set_home(&mut self, home: &Path) {
        self.decoder.set_home(home);
        if let Some(retained) = &mut self.retained {
            retained.set_home(home);
        }
    }

    /// Historical replay must not launch a Harness to export today's state.
    /// Callers can still opt into a local retained reader (Codex patch files).
    pub(crate) fn without_retained(mut self) -> Self {
        self.retained = None;
        self
    }

    /// Apply refusal and Model reporting rules independently of the session's log label.
    pub fn for_security(mut self, requested_model: Option<&str>) -> Self {
        self.security = Some(Security::new(requested_model));
        self
    }

    /// Stream evidence already read, even when interruption suppresses
    /// completion reporting and retained-record reads.
    pub fn observed_models(&self) -> Vec<String> {
        self.models.names().to_vec()
    }

    /// Live quota evidence is sticky and independent of ordinary Run outcomes.
    pub fn plan_limit_reached(&self) -> bool {
        self.plan_limit.is_some()
    }

    pub(crate) fn plan_limit(&self) -> Option<&limits::Limit> {
        self.plan_limit.as_ref()
    }

    /// Supplied raw records go through the same decoding and trace recording
    /// as stdout. Only callers opting into the Eval stop policy poll these.
    pub fn limit_records(&mut self) -> Vec<String> {
        self.decoder.limit_records()
    }

    /// Read supplied raw records for Plan usage alone, leaving the Session
    /// trace as ordinary sessions keep it. The agent can write these files,
    /// so they report Plan windows only, never the exhaustion that routes a
    /// Step, pauses a Command or releases its Claim.
    pub fn observe_limit_records(&mut self) {
        let now = chrono::Utc::now();
        for raw in self.decoder.limit_records() {
            if let Ok(record) = serde_json::from_str(&raw)
                && let Some(observation) =
                    crate::plan_usage::observation::codex_token_count(&record, now)
            {
                self.note_plan_usage(crate::plan_usage::Observation {
                    exhausted: None,
                    ..observation
                });
            }
        }
    }

    /// The Plan usage observed since the last call, for the machine's
    /// snapshot.
    pub fn take_plan_usage(&mut self) -> Vec<crate::plan_usage::Observation> {
        std::mem::take(&mut self.plan_usage)
    }

    fn note_plan_usage(&mut self, observation: crate::plan_usage::Observation) {
        self.plan_usage_exhausted |= observation.exhausted.is_some();
        if self.plan_usage_limit.is_none() {
            self.plan_usage_limit = observation.limit();
        }
        self.plan_usage.push(observation);
    }

    /// The stream decoder's ID alone, without retained-record recovery or
    /// completion policy. Saved streams can supply this metadata even when
    /// interruption deliberately suppressed recovery during supervision.
    pub fn into_session_id(self) -> Option<String> {
        self.decoder.complete().ended.session_id
    }

    /// Unknown or malformed lines produce no progress, never an error.
    pub fn condense(&mut self, raw: &str) -> Vec<String> {
        let decoded = self.read(raw);
        drop(decoded.events);
        decoded.progress
    }

    /// Return live facts and capture them for the authoritative completion
    /// timeline. Retained records refine calls by ID instead of adding calls.
    pub fn decode(&mut self, raw: &str) -> Decoded {
        let decoded = self.read(raw);
        event::reconcile(self.events.get_or_insert_default(), decoded.events.clone());
        decoded
    }

    fn read(&mut self, raw: &str) -> Decoded {
        let StreamUpdate {
            mut progress,
            evidence,
            events,
        } = self.decoder.condense(raw);
        self.work_started |= events.iter().any(work_started);
        for fact in evidence {
            if let Evidence::PlanLimit(limit) = &fact {
                self.plan_limit.get_or_insert_with(|| limit.clone());
            }
            if let Evidence::PlanUsage(observation) = fact {
                self.note_plan_usage(observation);
                continue;
            }
            if matches!(fact, Evidence::WorkStarted) {
                self.work_started = true;
            }
            if let Evidence::ObservedModel { name, .. } = &fact
                && !self.models.include(name)
            {
                continue;
            }
            if let Some(security) = &mut self.security
                && let Some(line) = security.apply(&fact)
            {
                progress.push(line);
            }
        }
        Decoded { progress, events }
    }

    pub fn finish(self, execution: Result<ExitStatus>) -> Completion {
        let cli = self.cli;
        let (report, outcome) = self.complete(execution);
        Completion {
            report,
            outcome: outcome.map_err(|failure| failure.session_error(cli)),
        }
    }

    /// Captured checks use exactly the same validation and retained policy,
    /// but keep their own refusal context and raw-output fallback.
    pub(super) fn check_output(mut self, output: &Output, refusal: &str) -> Result<()> {
        for line in String::from_utf8_lossy(&output.stdout).lines() {
            self.condense(line);
        }
        let (_, outcome) = self.complete(Ok(output.status));
        outcome.map(drop).map_err(|failure| match failure {
            Failure::Execution(error) => error,
            Failure::Rejected { diagnostic, .. } => {
                anyhow!("{refusal}: {}", diagnostic.unwrap_or_else(|| said(output)))
            }
        })
    }

    fn complete(self, execution: Result<ExitStatus>) -> (Option<Report>, Result<Ended, Failure>) {
        if let Err(error) = interrupt::check() {
            return (None, Err(Failure::Execution(error)));
        }
        let mut facts = self.decoder.complete();
        facts.report.events = self.events.unwrap_or_default();
        facts.report.models = self.models.into_names();
        let refusal = self.security.and_then(|security| security.refusal);
        if refusal.is_some() {
            facts.outcome = TurnOutcome::Failed;
        }
        let recovered = self
            .retained
            .map_or(Ok(()), |retained| retained.reconcile(&mut facts));
        if let Err(error) = interrupt::check() {
            return (None, Err(Failure::Execution(error)));
        }
        let outcome = execution
            .and_then(|status| recovered.map(|()| status))
            .map_err(Failure::Execution)
            .and_then(|status| {
                if !status.success() || matches!(facts.outcome, TurnOutcome::Failed) {
                    Err(Failure::Rejected {
                        status,
                        diagnostic: facts.diagnostic,
                        refusal,
                        before_first_turn: !self.work_started
                            && !facts.report.events.iter().any(work_started),
                        session_id: facts.ended.session_id,
                        plan_usage_exhausted: self.plan_usage_exhausted,
                        plan_usage_limit: self.plan_usage_limit.map(Box::new),
                    })
                } else {
                    Ok(facts.ended)
                }
            });
        (Some(facts.report), outcome)
    }
}

fn work_started(event: &event::Event) -> bool {
    use event::{Event, Outcome};
    let tokens = |usage: &event::Usage| {
        [
            usage.input,
            usage.output,
            usage.cache_read,
            usage.cache_write,
        ]
        .into_iter()
        .flatten()
        .any(|count| count > 0)
    };
    match event {
        Event::ToolCallStarted { .. } | Event::ToolCallEnded { .. } => true,
        Event::Message { role, text, .. } => role == "assistant" && !text.trim().is_empty(),
        Event::TurnEnded { usage, outcome, .. } => *outcome == Outcome::Succeeded || tokens(usage),
        Event::ModelCallEnded { usage, .. } | Event::Usage { usage, .. } => tokens(usage),
        Event::ModelCallStarted { .. }
        | Event::TurnStarted { .. }
        | Event::Error { .. }
        | Event::WorkEnded { .. }
        | Event::SubagentStarted { .. }
        | Event::SubagentEnded { .. } => false,
    }
}