printobserver-oneharness 0.9.0

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
//! What the port is built with, and the seam a caller watches a turn through.
//!
//! Every field of a configuration that could be wrong carries a type that
//! cannot: a harness identity and a pinned model are non-empty because the only
//! way to make one rejects the empty string, a turn timeout is non-zero because
//! it wraps a non-zero integer, an environment assignment has a `KEY=VALUE`
//! shape because it is a name and a value rather than a line somebody wrote,
//! and an assessment schema is a document because making one reads it. A
//! configuration this module hands back is therefore one no later step has to
//! re-examine — there is no representable value for it to find.

use core::fmt;
use core::num::NonZeroU64;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use oneharness_core::domain::report::RunReport;
use oneharness_core::io::run::RunRequest;
use oneharness_core::io::runner::ProcessSupervisor;

/// Why a value a configuration is built from is not one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
    /// The harness identity was empty, or was nothing but whitespace.
    HarnessIdentityEmpty,
    /// The turn timeout was zero, which is a turn that has expired before it
    /// starts rather than a turn with no bound.
    TurnTimeoutZero,
    /// An environment assignment did not carry a `KEY=VALUE` shape.
    EnvAssignmentMalformed {
        /// What was offered as an assignment.
        text: String,
        /// Why it is not one.
        detail: &'static str,
    },
    /// The model was named as nothing, or as whitespace. A model nobody pinned
    /// is `None`; an empty name is a pin nothing can honour.
    ModelNameEmpty,
    /// The file named as the assessment schema is not a schema document.
    AssessmentSchemaInvalid {
        /// The path that was named.
        path: String,
        /// Why nothing there constrains an answer.
        detail: String,
    },
    /// A command the agent is allowed to run is not one a permission rule can
    /// name.
    AgentCommandInvalid {
        /// What was offered as a command.
        text: String,
        /// Why no rule can name it.
        detail: &'static str,
    },
}

impl fmt::Display for ConfigError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::HarnessIdentityEmpty => {
                write!(formatter, "the harness identity is empty")
            }
            Self::TurnTimeoutZero => {
                write!(
                    formatter,
                    "a turn timeout of zero seconds is a turn that has expired before it starts"
                )
            }
            Self::EnvAssignmentMalformed { text, detail } => {
                write!(
                    formatter,
                    "`{text}` is not a KEY=VALUE environment assignment: {detail}"
                )
            }
            Self::ModelNameEmpty => write!(formatter, "the model is named as nothing"),
            Self::AssessmentSchemaInvalid { path, detail } => {
                write!(formatter, "`{path}` does not constrain an answer: {detail}")
            }
            Self::AgentCommandInvalid { text, detail } => {
                write!(
                    formatter,
                    "`{text}` cannot be allowed as an agent command: {detail}"
                )
            }
        }
    }
}

impl core::error::Error for ConfigError {}

/// The harness identity turns run on, as `OneHarness` names it.
///
/// Non-empty by construction: `OneHarness` selects a harness by this name, and
/// an empty one selects nothing while reading as a configuration that was
/// merely left at its default.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HarnessIdentity(String);

impl HarnessIdentity {
    /// The identity named by this text.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::HarnessIdentityEmpty`] when the text is empty or
    /// is nothing but whitespace.
    pub fn new(name: &str) -> Result<Self, ConfigError> {
        let trimmed = name.trim();
        if trimmed.is_empty() {
            return Err(ConfigError::HarnessIdentityEmpty);
        }
        Ok(Self(trimmed.to_owned()))
    }

    /// The identity as `OneHarness` spells it.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for HarnessIdentity {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

/// One command line prefix a supervising agent may run during a turn, such as
/// `printobserver context`.
///
/// A turn reads its print's context, and acts, through this program's own
/// commands, and a harness that withholds a shell entirely can do neither. So
/// the shell is granted, and every command line it runs must begin with one of
/// these prefixes; every other command is refused.
///
/// A prefix is one line of words carrying no character a permission rule gives
/// a meaning to, because a prefix that could close the rule early or widen it
/// with a wildcard would allow more than it names.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AgentCommand(String);

/// The characters a Claude Code permission rule interprets: the parentheses
/// that delimit a rule's specifier, the wildcard, and the colon that separates
/// a prefix from its wildcard.
const RULE_SYNTAX: [char; 4] = ['(', ')', '*', ':'];

impl AgentCommand {
    /// The command prefix spelled by this text, its surrounding whitespace
    /// trimmed.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::AgentCommandInvalid`] when the text is empty or
    /// only whitespace, spans more than one line, or carries a character a
    /// permission rule interprets (`(`, `)`, `*` or `:`).
    pub fn new(text: &str) -> Result<Self, ConfigError> {
        let trimmed = text.trim();
        let refuse = |detail| ConfigError::AgentCommandInvalid {
            text: text.to_owned(),
            detail,
        };
        if trimmed.is_empty() {
            return Err(refuse("it is empty"));
        }
        if trimmed.contains(['\n', '\r']) {
            return Err(refuse("it spans more than one line"));
        }
        if trimmed.contains(RULE_SYNTAX) {
            return Err(refuse(
                "it carries `(`, `)`, `*` or `:`, which a permission rule interprets",
            ));
        }
        Ok(Self(trimmed.to_owned()))
    }

    /// The prefix as it is written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for AgentCommand {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

/// How long one supervision turn is given.
///
/// Non-zero by construction. A turn may watch its print for a while — several
/// fresh looks, each waiting up to a minute and a half — before it acts, so the
/// default leaves room for that; the bound exists to stop a turn nothing is
/// waiting for, and a bound of zero would stop every turn instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TurnTimeout(NonZeroU64);

impl TurnTimeout {
    /// The bound a configuration that names no other takes.
    pub const DEFAULT: Self = Self(NonZeroU64::new(900).expect("900 is not zero"));

    /// The bound of this many seconds.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::TurnTimeoutZero`] when the count is zero.
    pub fn new(seconds: u64) -> Result<Self, ConfigError> {
        NonZeroU64::new(seconds)
            .map(Self)
            .ok_or(ConfigError::TurnTimeoutZero)
    }

    /// The bound in seconds, as `OneHarness` takes it.
    #[must_use]
    pub fn seconds(self) -> u64 {
        self.0.get()
    }
}

impl fmt::Display for TurnTimeout {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}s", self.0)
    }
}

/// One `KEY=VALUE` assignment in a harness process's environment.
///
/// Held as the name and the value rather than as the line, so the line is
/// rendered rather than trusted: a value carrying its own `=` is ordinary and
/// stays part of the value, and there is no way to hold an assignment that has
/// no name at all.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EnvAssignment {
    /// The variable's name.
    name: String,
    /// What it is set to.
    value: String,
}

impl EnvAssignment {
    /// The assignment this text writes.
    ///
    /// The name is everything before the first `=` and the value is everything
    /// after it, so a value containing `=` needs no escaping.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::EnvAssignmentMalformed`] when the text carries no
    /// `=` at all, or when what precedes the first one is not a variable name.
    pub fn new(text: &str) -> Result<Self, ConfigError> {
        let malformed = |detail| ConfigError::EnvAssignmentMalformed {
            text: text.to_owned(),
            detail,
        };
        let (name, value) = text
            .split_once('=')
            .ok_or_else(|| malformed("it carries no `=`"))?;
        let mut characters = name.chars();
        let first = characters
            .next()
            .ok_or_else(|| malformed("it names no variable before the `=`"))?;
        if !(first.is_ascii_alphabetic() || first == '_')
            || !characters.all(|character| character.is_ascii_alphanumeric() || character == '_')
        {
            return Err(malformed(
                "a variable name is a letter or an underscore followed by \
                 letters, digits and underscores",
            ));
        }
        Ok(Self {
            name: name.to_owned(),
            value: value.to_owned(),
        })
    }

    /// The variable's name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// What the variable is set to.
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }
}

impl fmt::Display for EnvAssignment {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}={}", self.name, self.value)
    }
}

/// The model a turn is pinned to, when one is pinned.
///
/// A model nobody pinned is the absence of one of these rather than an empty
/// one: `OneHarness` reads an empty name as a model it cannot find, which
/// reaches a caller as a harness that will not run rather than as the
/// configuration mistake it is.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ModelName(String);

impl ModelName {
    /// The model this text names.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::ModelNameEmpty`] when the text is empty or is
    /// nothing but whitespace.
    pub fn new(name: &str) -> Result<Self, ConfigError> {
        let trimmed = name.trim();
        if trimmed.is_empty() {
            return Err(ConfigError::ModelNameEmpty);
        }
        Ok(Self(trimmed.to_owned()))
    }

    /// The model as `OneHarness` spells it.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ModelName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

/// A schema `OneHarness` can judge an answer against, named as a path it reads
/// per run.
///
/// Checked where it is named rather than where it is used: nothing about a
/// schema is read until a turn runs, so a path that is not there — or is there
/// and is not a schema at all — would otherwise surface as every answer being
/// refused, hours after the configuration that caused it.
///
/// **What this establishes, and what it does not.** It establishes that the
/// file is there, is JSON, is a document declaring something, and compiles as a
/// JSON Schema. It does *not* establish that the schema is strict, or that it
/// is the *generated* artifact rather than one somebody wrote — and neither is
/// this type's to establish. Whether a schema constrains a given answer is a
/// property of the pair rather than of the schema (`{"title": "assessment"}` is
/// a schema; so is one that admits every object), so short of judging an
/// instance there is nothing here to decide. And which target produced a
/// document is written nowhere in it: this crate could only tell by carrying a
/// copy of the contract to compare against, which is exactly the thing
/// `just check-repo` refuses it for. Both are claims about the tree and are
/// made there — the check refuses a tree in which this crate carries a schema
/// of its own, and one journey changes the generated artifact on disk and
/// watches what the port accepts move with it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssessmentSchema(PathBuf);

impl AssessmentSchema {
    /// The schema at this path, read and compiled to be sure it is one.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::AssessmentSchemaInvalid`] when the file cannot be
    /// read, is not JSON, is not a document declaring anything, or does not
    /// compile as a JSON Schema — each of them a file `OneHarness` could judge
    /// no answer against at all.
    pub fn at(path: impl Into<PathBuf>) -> Result<Self, ConfigError> {
        let path = path.into();
        let invalid = |detail: String| ConfigError::AssessmentSchemaInvalid {
            path: path.display().to_string(),
            detail,
        };
        let text = std::fs::read_to_string(&path).map_err(|error| invalid(error.to_string()))?;
        let document: serde_json::Value =
            serde_json::from_str(&text).map_err(|error| invalid(error.to_string()))?;
        match document.as_object() {
            None => return Err(invalid("it is JSON, but not a schema document".to_owned())),
            // `{}` compiles, and admits every answer there is. A schema that
            // declares nothing is the absent file with extra steps.
            Some(declarations) if declarations.is_empty() => {
                return Err(invalid("it is a schema that declares nothing".to_owned()));
            }
            Some(_) => {}
        }
        // Compiled rather than inspected: a document can be an object and still
        // be no schema — a `type` that is a number, a `$ref` to nothing — and
        // every such file constrains an answer exactly as little as an absent
        // one does. Compiling it is what tells those apart, and it is the same
        // work `OneHarness` does per run, hours later and about an answer
        // rather than about the configuration that caused it.
        jsonschema::validator_for(&document).map_err(|error| invalid(error.to_string()))?;
        Ok(Self(path))
    }

    /// The path handed to `OneHarness`, which reads it per run.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.0
    }
}

/// How the supervising agent is reached, and where its sessions live.
///
/// A path here is taken as it is given and resolved against the process's own
/// working directory, as every path a program is configured with is; nothing
/// requires it absolute, because a relative one is exactly right when the
/// caller is a test or a checkout. What each path names is read when the port
/// is built rather than when a turn runs — which is what makes editing the
/// skill or the template a restart rather than a rebuild, and what makes a path
/// that names nothing a refusal to build rather than a turn that fails hours
/// later.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SupervisorConfig {
    /// The state directory this port keeps its sessions under. It holds both
    /// this port's own per-print ledger and `OneHarness`'s session store, which
    /// is what a restart continues a conversation from.
    pub state_dir: PathBuf,
    /// The `PrintObserver` skill's `SKILL.md`, whose prose is sent as every
    /// turn's system prompt.
    pub skill_path: PathBuf,
    /// The committed prompt template, whose five slots one turn fills.
    pub prompt_template_path: PathBuf,
    /// The generated assessment schema the agent's answer is constrained by.
    pub assessment_schema: AssessmentSchema,
    /// The harness identity turns run on.
    pub harness: HarnessIdentity,
    /// The model, when one is pinned rather than left to the harness.
    pub model: Option<ModelName>,
    /// The working directory each harness process runs in. The composition
    /// root sets it to the directory holding the skill, so the skill's own
    /// relative links resolve from where the agent stands.
    pub working_dir: PathBuf,
    /// How long one turn is given.
    pub turn_timeout: TurnTimeout,
    /// The harness binary, when it is not the one `OneHarness` resolves by name.
    pub harness_bin: Option<PathBuf>,
    /// Extra environment for each harness process.
    pub harness_env: Vec<EnvAssignment>,
    /// The command prefixes the agent may run during a turn. Empty keeps the
    /// turn read-only, with no shell at all.
    pub agent_commands: Vec<AgentCommand>,
}

/// Receives every run request this port builds.
///
/// Observation only: a request is handed over after it is complete and before
/// `OneHarness` receives it, and an observer cannot change it.
pub trait RunRequestObserver: Send + Sync {
    /// One run request, exactly as it will be handed to `OneHarness`.
    fn built(&self, request: &RunRequest);
}

/// Receives the report of every run this port drives.
///
/// Observation only, and after the fact: a run's report carries far more than
/// the assessment a turn answers with — what the harness charged, how long it
/// took, what it said on the way — and a long-running host logs that rather
/// than losing it. It is also how a caller sees a run this port refused to
/// record.
pub trait RunReportObserver: Send + Sync {
    /// One finished run's report, exactly as `OneHarness` answered it.
    fn answered(&self, report: &RunReport);
}

/// Where a caller watches what a turn does: the requests this port builds, the
/// processes `OneHarness` creates under them, and the reports it answers.
///
/// Both halves are the supervision a long-running host wants anyway — the
/// harness tree is what a watchdog reaps — and both are what a test observes a
/// turn through, so no test needs a double of the port to see either.
#[derive(Clone, Default)]
pub struct TurnSeam {
    /// Handed every run request this port builds, before `OneHarness` receives it.
    pub requests: Option<Arc<dyn RunRequestObserver>>,
    /// Handed every harness process `OneHarness` creates under the run.
    pub processes: Option<Arc<dyn ProcessSupervisor + Send + Sync>>,
    /// Handed the report of every run, as `OneHarness` answered it.
    pub reports: Option<Arc<dyn RunReportObserver>>,
}

impl core::fmt::Debug for TurnSeam {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("TurnSeam")
            .field("requests", &self.requests.is_some())
            .field("processes", &self.processes.is_some())
            .field("reports", &self.reports.is_some())
            .finish()
    }
}