printobserver-oneharness 0.7.1

oneharness adapter for printobserver.
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
//! The port itself: one supervision turn, and the closing of a session.

use std::path::Path;
use std::sync::Arc;

use oneharness_core::domain::harness::HarnessIdentity as EngineIdentity;
use oneharness_core::domain::mode::PermissionMode;
use oneharness_core::domain::report::{RunReport, RunResult, SessionReport, Status};
use oneharness_core::domain::session::SessionPhase as HarnessPhase;
use oneharness_core::errors::OneharnessError;
use oneharness_core::io::run::{RunControls, RunOutcome, RunRequest, run_supervised};
use oneharness_core::io::runner::ProcessSupervisor;
use printobserver_supervisor_api::AgentAssessment;
use printobserver_supervisor_api::{
    BoxFuture, CREDENTIAL_ENV, SERVER_ENV, SupervisorError, SupervisorPort, TurnAccess,
    TurnOutcome, TurnPass, TurnRequest, TurnSession,
};
use printobserver_supervisor_api::{SessionPhase, SupervisionSession};
use printobserver_types::serde_json::Value;
use printobserver_types::{PrintId, Timestamp};

use crate::config::{HarnessIdentity, SupervisorConfig, TurnSeam};
use crate::ledger::{PrintLedger, RecordedTurn, SessionName};
use crate::prompt::{NO_IMAGE, PromptTemplate};
use crate::skill::skill_prose;

/// The directory under the state directory `OneHarness` keeps its own session
/// store in. Naming it here is what makes a restart continue a conversation:
/// the store is beside this port's ledger rather than in a platform default
/// that a differently-configured process would not find.
pub const HARNESS_SESSIONS_DIRECTORY: &str = "harness-sessions";

/// The harness whose turns are granted a shell narrowed to the agent's
/// commands. Another harness keeps `OneHarness`'s read-only mode, which gives it
/// no shell at all.
const CLAUDE_CODE: &str = "claude-code";

/// The Claude Code tools a turn with agent commands has, and there is no other:
/// the three that only read, and the shell those commands run in.
const CLAUDE_TURN_TOOLS: [&str; 4] = ["Read", "Grep", "Glob", "Bash"];

/// The tools of [`CLAUDE_TURN_TOOLS`] that are allowed outright. The shell is
/// allowed only for the configured commands.
const CLAUDE_READ_TOOLS: [&str; 3] = ["Read", "Grep", "Glob"];

/// How many characters of an answer that failed validation are kept with the
/// failure: enough to read what the agent said, bounded so a runaway answer
/// cannot swell the record it lands in.
pub const ANSWER_EXCERPT_CHARS: usize = 2000;

/// What follows an excerpt that was cut short.
pub const ANSWER_CUT: &str = " …";

/// What joins the reason an answer was refused to what the agent said.
pub const ANSWER_SAID: &str = "; the agent answered: ";

/// The supervising agent, reached through `OneHarness` in this process.
#[derive(Debug)]
pub struct OneharnessSupervisor {
    /// How the agent is reached and where its sessions live.
    config: SupervisorConfig,
    /// Where a caller watches what a turn does.
    seam: TurnSeam,
    /// The `PrintObserver` skill's prose, read from the configured path when
    /// this port was built and with its frontmatter split off.
    skill: String,
    /// The committed prompt template, read from the tree when this port was
    /// built.
    template: PromptTemplate,
}

impl OneharnessSupervisor {
    /// Build the port, reading the skill and the prompt template from the tree.
    ///
    /// # Errors
    ///
    /// Returns [`SupervisorError::Unavailable`] when either file cannot be read,
    /// when the skill opens a frontmatter block it never closes, or when the
    /// template does not declare the five slots a turn fills.
    pub fn open(config: SupervisorConfig) -> Result<Self, SupervisorError> {
        Self::observed(config, TurnSeam::default())
    }

    /// Build the port with a caller watching its requests and its processes.
    ///
    /// # Errors
    ///
    /// The same as [`OneharnessSupervisor::open`].
    pub fn observed(config: SupervisorConfig, seam: TurnSeam) -> Result<Self, SupervisorError> {
        let skill = skill_prose(&read(&config.skill_path)?)
            .map_err(|error| SupervisorError::Unavailable {
                detail: format!("{}: {error}", config.skill_path.display()),
            })?
            .to_owned();
        let template =
            PromptTemplate::parse(&read(&config.prompt_template_path)?).map_err(|error| {
                SupervisorError::Unavailable {
                    detail: format!("{}: {error}", config.prompt_template_path.display()),
                }
            })?;
        Ok(Self {
            config,
            seam,
            skill,
            template,
        })
    }

    /// Every session opened for one print, in order, read from the state
    /// directory.
    ///
    /// # Errors
    ///
    /// Returns [`SupervisorError::Unavailable`] when the ledger cannot be read.
    pub fn recorded_sessions(
        &self,
        print_id: &PrintId,
    ) -> Result<Vec<SupervisionSession>, SupervisorError> {
        Ok(self.ledger(print_id)?.sessions().to_vec())
    }

    /// Every turn recorded for one print, in order, read from the state
    /// directory.
    ///
    /// # Errors
    ///
    /// Returns [`SupervisorError::Unavailable`] when the ledger cannot be read.
    pub fn recorded_turns(&self, print_id: &PrintId) -> Result<Vec<RecordedTurn>, SupervisorError> {
        Ok(self.ledger(print_id)?.turns().to_vec())
    }

    /// One print's ledger.
    fn ledger(&self, print_id: &PrintId) -> Result<PrintLedger, SupervisorError> {
        PrintLedger::read(&self.config.state_dir, print_id).map_err(|error| {
            SupervisorError::Unavailable {
                detail: format!(
                    "the supervision ledger of print {print_id} is unreadable: {error}"
                ),
            }
        })
    }

    /// Write one print's ledger back.
    fn save(&self, ledger: &PrintLedger, print_id: &PrintId) -> Result<(), SupervisorError> {
        ledger
            .write(&self.config.state_dir)
            .map_err(|error| SupervisorError::Unavailable {
                detail: format!(
                    "the supervision ledger of print {print_id} could not be written: {error}"
                ),
            })
    }

    /// The prompt for one turn in one session: the committed template with its
    /// five slots filled, and nothing else.
    ///
    /// Built for the session the turn runs in, because the actor the agent
    /// names itself by is that session's: an agent left to guess the shape of
    /// its own actor is refused by every request it guesses wrong.
    fn prompt_for(
        &self,
        request: &TurnRequest,
        session: &SessionName,
    ) -> Result<String, SupervisorError> {
        let event = serde_json::to_string_pretty(&request.event).map_err(|error| {
            SupervisorError::Unavailable {
                detail: format!("the triggering event cannot be written down: {error}"),
            }
        })?;
        let situation = serde_json::to_string_pretty(&request.situation).map_err(|error| {
            SupervisorError::Unavailable {
                detail: format!("the turn's situation cannot be written down: {error}"),
            }
        })?;
        let image = request
            .image_path
            .as_ref()
            .map_or_else(|| NO_IMAGE.to_owned(), |path| path.display().to_string());
        let actor = serde_json::json!({ "agent": { "session_name": session.as_str() } });
        Ok(self.template.fill(
            &event,
            &situation,
            &image,
            &request.context_command,
            &actor.to_string(),
        ))
    }

    /// How the harness is permitted to act during a turn, and the arguments that
    /// narrow it.
    ///
    /// With no agent commands configured, or on a harness other than Claude
    /// Code, a turn is `OneHarness`'s read-only mode: the agent reads files and
    /// has no shell. A turn that has agent commands runs Claude Code in
    /// `dontAsk` mode instead — what [`PermissionMode::Default`] maps to — which
    /// refuses any tool call no rule allows and carries on. Its tool set is
    /// narrowed to [`CLAUDE_TURN_TOOLS`], and its rules allow the read tools
    /// outright and the shell only for a command beginning with one of the
    /// configured prefixes.
    fn permissions(&self) -> (PermissionMode, Vec<String>) {
        let on_claude_code = self
            .config
            .harness
            .as_str()
            .parse::<EngineIdentity>()
            .is_ok_and(|identity| identity.base() == CLAUDE_CODE);
        if !on_claude_code || self.config.agent_commands.is_empty() {
            return (PermissionMode::ReadOnly, Vec::new());
        }
        let mut arguments = vec!["--tools".to_owned()];
        arguments.extend(CLAUDE_TURN_TOOLS.map(str::to_owned));
        arguments.push("--allowedTools".to_owned());
        // llmlint: ignore[least_privilege_grants] suppressions.toml has the reason.
        arguments.extend(CLAUDE_READ_TOOLS.map(str::to_owned));
        arguments.extend(
            self.config
                .agent_commands
                .iter()
                // llmlint: ignore[least_privilege_grants] suppressions.toml has the reason.
                .map(|command| format!("Bash({command}:*)")),
        );
        (PermissionMode::Default, arguments)
    }

    /// The run request for one turn in one session.
    ///
    /// The run's environment carries the configured assignments and then the
    /// pass this run was issued: the server's address and the credential minted
    /// for this run, which is the only way a turn is handed either. A
    /// configured assignment of either variable is left out, so the pass is the
    /// one value of each the run sees. No file holding the credential is
    /// written, and the context command names none.
    fn build_request(&self, session: &SessionName, prompt: &str, pass: &TurnPass) -> RunRequest {
        let (mode, passthrough) = self.permissions();
        let mut env: Vec<String> = self
            .config
            .harness_env
            .iter()
            .map(ToString::to_string)
            .filter(|assigned| {
                ![SERVER_ENV, CREDENTIAL_ENV]
                    .iter()
                    .any(|name| assigned.starts_with(&format!("{name}=")))
            })
            .collect();
        env.extend(
            pass.environment()
                .into_iter()
                .map(|(name, value)| format!("{name}={value}")),
        );
        RunRequest {
            harness: vec![self.config.harness.to_string()],
            prompt: vec![prompt.to_owned()],
            model: self.config.model.iter().map(ToString::to_string).collect(),
            system: Some(self.skill.clone()),
            session: Some(session.to_string()),
            session_dir: Some(self.config.state_dir.join(HARNESS_SESSIONS_DIRECTORY)),
            schema: Some(self.config.assessment_schema.path().to_path_buf()),
            timeout: Some(self.config.turn_timeout.seconds()),
            cwd: Some(self.config.working_dir.clone()),
            env,
            mode: Some(mode),
            passthrough,
            // The supervisor's turns are decided here, not by whatever
            // configuration happens to be on the host it runs on.
            no_config: true,
            bin: self
                .config
                .harness_bin
                .iter()
                .map(|path| format!("{}={}", self.config.harness, path.display()))
                .collect(),
            ..RunRequest::default()
        }
    }

    /// Hand one run request to `OneHarness`, in this process, carrying the
    /// pass `access` issues for the session it runs in.
    fn drive(
        &self,
        session: &SessionName,
        prompt: &str,
        access: &dyn TurnAccess,
    ) -> Result<Result<RunOutcome, OneharnessError>, SupervisorError> {
        let pass = access.issue(&TurnSession::new(session.as_str())?)?;
        let request = self.build_request(session, prompt, &pass);
        if let Some(observer) = &self.seam.requests {
            observer.built(&request);
        }
        let supervisor: Option<&dyn ProcessSupervisor> = self
            .seam
            .processes
            .as_ref()
            .map(|processes| Arc::as_ref(processes) as &dyn ProcessSupervisor);
        let outcome = match run_supervised(&request, RunControls::default(), supervisor) {
            Ok(outcome) => outcome,
            Err(error) => return Ok(Err(error)),
        };
        if let Some(observer) = &self.seam.reports {
            observer.answered(&outcome.report);
        }
        Ok(Ok(outcome))
    }

    /// One supervision turn, from the ledger through the run and back.
    fn take_turn(
        &self,
        request: &TurnRequest,
        access: &dyn TurnAccess,
    ) -> Result<TurnOutcome, SupervisorError> {
        let print_id = &request.print_id;
        let mut ledger = self.ledger(print_id)?;
        let mut session = ledger.session_for_next_turn();

        let outcome = match self.drive(&session, &self.prompt_for(request, &session)?, access)? {
            Ok(outcome) => outcome,
            // The harness binds a session to the identity that created it and
            // refuses to continue it on another. That is a session that has
            // ended, not a turn the caller has to handle: it is closed carrying
            // the harness's own reason, and the turn runs in a new one.
            Err(OneharnessError::SessionHarnessConflict { was, now, .. }) => {
                let reason = format!(
                    "the harness refused to continue this session on `{now}`: \
                     it was created on `{was}`"
                );
                ledger.close_current(&reason, Timestamp::now());
                session = ledger.name_after_current();
                self.save(&ledger, print_id)?;
                // The prompt is built again, because the actor it hands the
                // agent names the session the turn now runs in — and so is the
                // credential, which is bound to that session.
                self.drive(&session, &self.prompt_for(request, &session)?, access)?
                    .map_err(|error| unavailable(&error))?
            }
            Err(error) => return Err(unavailable(&error)),
        };

        let reported = TurnReport::of(outcome.report, &session, &self.config.harness)?;
        self.record(&mut ledger, print_id, &reported)
    }

    /// Write down what a finished run did, and answer the caller.
    fn record(
        &self,
        ledger: &mut PrintLedger,
        print_id: &PrintId,
        reported: &TurnReport,
    ) -> Result<TurnOutcome, SupervisorError> {
        let at = Timestamp::now();
        let session = ledger.record_session(
            &reported.name,
            &reported.result.harness_id,
            reported.phase(),
            at,
        );
        let answer = assessment(&reported.result);
        let failure = answer.as_ref().err().map(ToString::to_string);
        ledger.record_turn(&reported.name, at, failure.as_deref());
        self.save(ledger, print_id)?;

        Ok(TurnOutcome {
            session,
            phase: reported.phase(),
            assessment: answer?,
        })
    }
}

/// What a finished run answered, narrowed to what a turn is written down from:
/// the one result the run produced, and the session block naming the
/// conversation it ran in.
///
/// `OneHarness`'s report is the answer to every shape of run it serves — a run
/// under no session handle, whose session block is then absent; a fan-out over
/// several harnesses or models, whose results are then several. A turn is one
/// harness answering one prompt under one session, so the narrowing happens
/// once, here, and every step after it holds exactly one of each rather than a
/// shape nobody downstream can act on.
///
/// A report of any other shape is refused rather than written down. It answers
/// a run this port did not ask for, so nothing in it can be attributed to this
/// print's conversation: the session such a turn would be recorded under is one
/// this port planned and the harness never confirmed, and a ledger carrying
/// turns of a session that was never opened is a history that reads as though
/// the agent had been consulted.
#[derive(Debug, Clone)]
pub struct TurnReport {
    /// The result the run produced.
    result: RunResult,
    /// The session block the run answered with.
    session: SessionReport,
    /// The session the turn asked about, which the block above agrees with.
    name: SessionName,
}

impl TurnReport {
    /// Narrow one finished run's report to the turn it reports, given the
    /// session and the harness identity that turn asked for.
    ///
    /// Both are checked rather than read: what goes into the ledger is what a
    /// restart continues this print's conversation from, so a report about
    /// another session, or from another identity, is one this print's history
    /// must not absorb — however it came to be answered.
    ///
    /// # Errors
    ///
    /// Returns [`SupervisorError::Unavailable`] when the run answered no
    /// session block, no result at all, more than one result, or a session or
    /// identity other than the one asked for.
    pub fn of(
        report: RunReport,
        asked_session: &SessionName,
        asked_harness: &HarnessIdentity,
    ) -> Result<Self, SupervisorError> {
        let Some(session) = report.session else {
            return Err(SupervisorError::Unavailable {
                detail: NO_SESSION.to_owned(),
            });
        };
        if session.name != asked_session.as_str() {
            return Err(SupervisorError::Unavailable {
                detail: format!(
                    "the harness answered about session `{}`, and this turn asked about `{asked_session}`",
                    session.name
                ),
            });
        }
        let [result] = <[RunResult; 1]>::try_from(report.results).map_err(|results| {
            SupervisorError::Unavailable {
                detail: if results.is_empty() {
                    NO_RESULT.to_owned()
                } else {
                    format!("{}, and this turn asked one to answer once", results.len())
                },
            }
        })?;
        if result.harness_id != asked_harness.as_str() {
            return Err(SupervisorError::Unavailable {
                detail: format!(
                    "`{}` answered this turn, and it was asked of `{asked_harness}`",
                    result.harness_id
                ),
            });
        }
        Ok(Self {
            result,
            session,
            name: asked_session.clone(),
        })
    }

    /// The session block the run answered with.
    #[must_use]
    pub fn session(&self) -> &SessionReport {
        &self.session
    }

    /// The session the turn ran in.
    #[must_use]
    pub fn name(&self) -> &SessionName {
        &self.name
    }

    /// Whether the run opened the session or continued it, in this system's
    /// words.
    #[must_use]
    pub fn phase(&self) -> SessionPhase {
        match self.session.phase {
            HarnessPhase::Create => SessionPhase::Created,
            HarnessPhase::Continue => SessionPhase::Continued,
        }
    }
}

/// The detail an answer no schema verdict was reached about is refused with.
const NO_ANSWER: &str = "the answer carried no value the assessment schema could be applied to";

/// The detail a run that answered no session block is refused with.
const NO_SESSION: &str = "the harness exposed no session, so the conversation cannot be continued";

/// The detail a run that answered no result at all is refused with. A run that
/// answered more than one says how many instead: it is a different shape of run
/// rather than one that did not happen.
const NO_RESULT: &str = "the harness answered no result, so no turn was taken";

fn read(path: &Path) -> Result<String, SupervisorError> {
    std::fs::read_to_string(path).map_err(|error| SupervisorError::Unavailable {
        detail: format!("{} is unreadable: {error}", path.display()),
    })
}

/// Why an answer was refused, followed by what the agent actually said.
///
/// The reason alone ("no JSON value could be extracted") names the symptom
/// rather than the cause. The agent's own words usually name the cause — a
/// command it was refused, a sign-in the harness is missing — and nothing else
/// keeps them.
fn with_answer(why: String, text: Option<&str>) -> String {
    let Some(said) = text.map(str::trim).filter(|said| !said.is_empty()) else {
        return why;
    };
    let mut kept = said.char_indices().map(|(at, _)| at);
    match kept.nth(ANSWER_EXCERPT_CHARS) {
        Some(cut) => format!("{why}{ANSWER_SAID}{}{ANSWER_CUT}", &said[..cut]),
        None => format!("{why}{ANSWER_SAID}{said}"),
    }
}

/// Whatever `OneHarness` refused a run for, as this port's own error.
fn unavailable(error: &OneharnessError) -> SupervisorError {
    SupervisorError::Unavailable {
        detail: error.to_string(),
    }
}

/// The assessment one result carries, or why it carries none.
///
/// The answer has already been through `OneHarness`'s own validate-and-re-prompt
/// loop by the time it arrives here, so a result that still does not conform is
/// one no further attempt would fix.
fn assessment(result: &RunResult) -> Result<AgentAssessment, SupervisorError> {
    if result.status == Status::Timeout {
        return Err(SupervisorError::TimedOut);
    }
    if let Some(kind) = &result.failure_kind {
        return Err(SupervisorError::Unavailable {
            detail: format!(
                "the harness failed ({kind:?}): {}",
                result.error.as_deref().unwrap_or("no detail")
            ),
        });
    }
    if result.status != Status::Ok && result.status != Status::Nonzero {
        return Err(SupervisorError::Unavailable {
            detail: format!(
                "the harness did not run the turn ({:?}): {}",
                result.status,
                result.error.as_deref().unwrap_or("no detail")
            ),
        });
    }
    if result.schema_valid != Some(true) {
        let why = result
            .schema_error
            .clone()
            .unwrap_or_else(|| NO_ANSWER.to_owned());
        return Err(SupervisorError::InvalidAnswer {
            detail: with_answer(why, result.text.as_deref()),
        });
    }
    // The value is read back as the assessment itself rather than trusted for
    // having passed the schema: the two agree only while the schema is the one
    // generated from the type, and a schema saying otherwise is a bad answer
    // rather than a value this port hands on.
    serde_json::from_value(result.structured.clone().unwrap_or(Value::Null)).map_err(|error| {
        SupervisorError::InvalidAnswer {
            detail: error.to_string(),
        }
    })
}

impl SupervisorPort for OneharnessSupervisor {
    fn run_turn(
        &self,
        request: TurnRequest,
        access: Arc<dyn TurnAccess>,
    ) -> BoxFuture<'_, Result<TurnOutcome, SupervisorError>> {
        Box::pin(async move { self.take_turn(&request, access.as_ref()) })
    }

    fn close_session(
        &self,
        print_id: PrintId,
        close_reason: String,
    ) -> BoxFuture<'_, Result<(), SupervisorError>> {
        Box::pin(async move {
            let mut ledger = self.ledger(&print_id)?;
            ledger.close_current(&close_reason, Timestamp::now());
            self.save(&ledger, &print_id)
        })
    }
}