split-brain-harness 1.1.0

Soul-injected two-stage LLM telemetry pipeline. Wraps any LLM with affective/intent/cognitive analysis, deterministic verification, and a Stage 0 deobfuscation normalizer. Drop-in OpenAI-compatible proxy.
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
/// Phase 1 — design-only schema for the Ephemeral Tool Forge.
///
/// The model may emit a capability_request field alongside its telemetry output.
/// No tool is generated or executed in Phase 1. The request is parsed, traced,
/// and stored in HarnessResult. The execution supervisor lives in a later phase.
///
/// Reference: EPHEMERAL_TOOL_FORGE_DESIGN.md
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Model output — what the model emits when it requests a capability
// ---------------------------------------------------------------------------

/// Constraints the model declares on the tool it is requesting.
/// All fields default to the most restrictive value if absent.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct CapabilityConstraints {
    #[serde(default = "default_true")]
    pub no_network: bool,
    #[serde(default = "default_true")]
    pub read_only_input: bool,
    #[serde(default = "default_runtime_ms")]
    pub max_runtime_ms: u64,
    #[serde(default = "default_memory_mb")]
    pub max_memory_mb: u64,
}

fn default_true() -> bool {
    true
}
fn default_runtime_ms() -> u64 {
    1000
}
fn default_memory_mb() -> u64 {
    64
}

impl Default for CapabilityConstraints {
    fn default() -> Self {
        Self {
            no_network: true,
            read_only_input: true,
            max_runtime_ms: 1000,
            max_memory_mb: 64,
        }
    }
}

/// A structured request the model emits when text reasoning is genuinely
/// insufficient for a computational task. The model NEVER generates or runs
/// code — it only describes what it needs.
///
/// The supervisor decides whether to fulfil the request.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct CapabilityRequest {
    /// Must be "capability_request" — validated after parse.
    pub kind: String,
    /// Short identifier for the capability class (e.g., "stream_parse_logs").
    pub capability: String,
    /// Human-readable description of the expected input format.
    pub input_contract: String,
    /// Human-readable description of the expected output format.
    pub output_contract: String,
    #[serde(default)]
    pub constraints: CapabilityConstraints,
    /// Why text reasoning alone is insufficient for this task.
    pub reason: String,
}

impl CapabilityRequest {
    /// Returns an error if the request is structurally invalid or exceeds
    /// field-length limits (guards against oversized strings from the model).
    pub fn validate(&self) -> Result<(), String> {
        if self.kind != "capability_request" {
            return Err(format!(
                "kind must be \"capability_request\", got {:?}",
                self.kind
            ));
        }
        if self.capability.trim().is_empty() {
            return Err("capability must not be empty".into());
        }
        if self.reason.trim().is_empty() {
            return Err("reason must not be empty".into());
        }
        if self.capability.len() > crate::input_validation::MAX_CAPABILITY_NAME_BYTES {
            return Err(format!(
                "capability too long: {} bytes (max {})",
                self.capability.len(),
                crate::input_validation::MAX_CAPABILITY_NAME_BYTES
            ));
        }
        if self.reason.len() > crate::input_validation::MAX_REASON_BYTES {
            return Err(format!(
                "reason too long: {} bytes (max {})",
                self.reason.len(),
                crate::input_validation::MAX_REASON_BYTES
            ));
        }
        if self.input_contract.len() > crate::input_validation::MAX_CONTRACT_BYTES {
            return Err(format!(
                "input_contract too long: {} bytes (max {})",
                self.input_contract.len(),
                crate::input_validation::MAX_CONTRACT_BYTES
            ));
        }
        if self.output_contract.len() > crate::input_validation::MAX_CONTRACT_BYTES {
            return Err(format!(
                "output_contract too long: {} bytes (max {})",
                self.output_contract.len(),
                crate::input_validation::MAX_CONTRACT_BYTES
            ));
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Supervisor-side types — Phase 2 additions
// ---------------------------------------------------------------------------

/// Measured execution metrics from one tool run (mock or real).
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct ToolMetrics {
    pub runtime_ms: u64,
    pub input_bytes: usize,
    pub output_bytes: usize,
    pub success: bool,
}

/// A policy rule that was violated. Returned as a list from policy::check_request.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PolicyViolation {
    pub rule: String,
    pub detail: String,
}

/// Per-session cost budget enforced by the supervisor.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Budget {
    /// Maximum distinct tool invocations per session.
    pub max_tools_per_session: usize,
    /// Cumulative wall-clock ms across all runs in this session.
    pub max_total_runtime_ms: u64,
    /// Require explicit approval after this many consecutive failures.
    pub require_approval_after_failures: usize,
}

impl Default for Budget {
    fn default() -> Self {
        Self {
            max_tools_per_session: 4,
            max_total_runtime_ms: 30_000,
            require_approval_after_failures: 2,
        }
    }
}

/// Full result returned by the supervisor after processing one CapabilityRequest.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ToolRunReport {
    /// True if the request passed policy checks and a mock was found.
    pub accepted: bool,
    /// Non-empty when the request was rejected — each entry is one violation.
    pub rejection_reasons: Vec<String>,
    /// Always true for Phase 2 mocks (no generated source to verify yet).
    pub verification_passed: bool,
    /// True if the mock function ran to completion (even if it returned an error).
    pub executed: bool,
    /// Stdout of the mock tool — a JSON string on success, None on rejection.
    pub output: Option<String>,
    pub metrics: ToolMetrics,
    /// Always true after execution — marks the lifecycle as complete.
    pub destroyed: bool,
    /// Set when the run succeeds and memory was updated.
    pub memory_update: Option<CapabilityMemoryRecord>,
}

// ---------------------------------------------------------------------------
// Supervisor-side types — design-only in Phase 1 (manifests, permissions, limits)
// ---------------------------------------------------------------------------

/// Verification steps the supervisor must run before a tool may execute.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum VerificationKind {
    StaticAnalysis,
    DependencyScan,
    PolicyCheck,
    UnitTests,
    ResourceEstimate,
}

/// Fine-grained permission set attached to a generated tool manifest.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Permissions {
    #[serde(default)]
    pub network: bool,
    #[serde(default)]
    pub filesystem_write: bool,
    /// "none" | "sandbox/input_only" | an explicit allowlisted path
    pub filesystem_read: String,
    #[serde(default)]
    pub process_spawn: bool,
    #[serde(default)]
    pub env_access: bool,
}

/// Hard resource limits enforced by the sandbox runtime.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ResourceLimits {
    pub runtime_ms: u64,
    pub memory_mb: u64,
    pub stdout_bytes: u64,
    pub stderr_bytes: u64,
}

/// Full manifest created by the tool architect (Phase 2+).
/// In Phase 1 this is a data type only — no generation logic exists yet.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CapabilityManifest {
    pub manifest_version: u32,
    pub capability_id: String,
    pub problem_signature: String,
    pub tool_kind: String,
    pub input_contract: String,
    pub output_contract: String,
    pub permissions: Permissions,
    pub limits: ResourceLimits,
    pub verification_required: Vec<VerificationKind>,
    pub destroy_after_run: bool,
}

/// Capability memory entry — fingerprint stored after a run.
/// The binary is destroyed; only the pattern, constraints, and metrics survive.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CapabilityMemoryRecord {
    pub problem_signature: String,
    pub solution_pattern: String,
    pub input_shape: String,
    pub output_shape: String,
    pub constraints: CapabilityConstraints,
}

// ---------------------------------------------------------------------------
// Extraction adapter — used in harness.rs to wrap TelemetryResult
// ---------------------------------------------------------------------------

/// Wraps the model's full propose-stage output. The telemetry fields are at
/// the top level (flattened) so existing model responses without
/// capability_request still parse unchanged.
#[derive(Debug, Deserialize, Clone)]
pub struct ModelProposalOutput {
    #[serde(flatten)]
    pub telemetry: crate::types::TelemetryResult,
    #[serde(default)]
    pub capability_request: Option<CapabilityRequest>,
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn valid_request_json() -> &'static str {
        r#"{
            "kind": "capability_request",
            "capability": "stream_parse_logs",
            "input_contract": "UTF-8 log lines from stdin",
            "output_contract": "JSON array of matching events",
            "constraints": {
                "no_network": true,
                "read_only_input": true,
                "max_runtime_ms": 1000,
                "max_memory_mb": 64
            },
            "reason": "Existing text reasoning is inefficient for repeated regex parsing."
        }"#
    }

    #[test]
    fn capability_request_parses_from_valid_json() {
        let req: CapabilityRequest = serde_json::from_str(valid_request_json()).unwrap();
        assert_eq!(req.kind, "capability_request");
        assert_eq!(req.capability, "stream_parse_logs");
        assert!(req.constraints.no_network);
        assert_eq!(req.constraints.max_runtime_ms, 1000);
    }

    #[test]
    fn capability_request_validates_kind() {
        let mut req: CapabilityRequest = serde_json::from_str(valid_request_json()).unwrap();
        req.kind = "wrong_kind".into();
        assert!(req.validate().is_err());
    }

    #[test]
    fn capability_request_validates_empty_capability() {
        let mut req: CapabilityRequest = serde_json::from_str(valid_request_json()).unwrap();
        req.capability = "  ".into();
        assert!(req.validate().is_err());
    }

    #[test]
    fn capability_request_validates_empty_reason() {
        let mut req: CapabilityRequest = serde_json::from_str(valid_request_json()).unwrap();
        req.reason = String::new();
        assert!(req.validate().is_err());
    }

    #[test]
    fn capability_request_constraints_default_restrictive() {
        let json = r#"{
            "kind": "capability_request",
            "capability": "test",
            "input_contract": "x",
            "output_contract": "y",
            "reason": "z"
        }"#;
        let req: CapabilityRequest = serde_json::from_str(json).unwrap();
        assert!(
            req.constraints.no_network,
            "default must be no_network=true"
        );
        assert!(
            req.constraints.read_only_input,
            "default must be read_only=true"
        );
        assert_eq!(req.constraints.max_runtime_ms, 1000);
        assert_eq!(req.constraints.max_memory_mb, 64);
    }

    #[test]
    fn model_proposal_output_parses_telemetry_only() {
        let json = r#"{
            "affective_telemetry": {
                "primary_emotion": "neutral",
                "emotional_intensity": 0.1,
                "structural_tone": ["analytical"]
            },
            "intent_matrix": {
                "stated_objective": "test",
                "subtextual_motive": "test",
                "manipulation_risk": "low"
            },
            "cognitive_state": {
                "urgency_vector": 0.0,
                "coherence_rating": 0.95
            }
        }"#;
        let output: ModelProposalOutput = serde_json::from_str(json).unwrap();
        assert!(
            output.capability_request.is_none(),
            "capability_request must be absent when not emitted"
        );
        assert_eq!(output.telemetry.intent_matrix.manipulation_risk, "low");
    }

    #[test]
    fn model_proposal_output_parses_telemetry_with_capability_request() {
        let json = r#"{
            "affective_telemetry": {
                "primary_emotion": "neutral",
                "emotional_intensity": 0.1,
                "structural_tone": ["analytical"]
            },
            "intent_matrix": {
                "stated_objective": "parse 10GB log file",
                "subtextual_motive": "efficiency",
                "manipulation_risk": "low"
            },
            "cognitive_state": {
                "urgency_vector": 0.2,
                "coherence_rating": 0.95
            },
            "capability_request": {
                "kind": "capability_request",
                "capability": "stream_parse_logs",
                "input_contract": "UTF-8 log lines",
                "output_contract": "JSON events",
                "constraints": {
                    "no_network": true,
                    "read_only_input": true,
                    "max_runtime_ms": 2000,
                    "max_memory_mb": 128
                },
                "reason": "10GB file cannot be reasoned over line-by-line in a single context window."
            }
        }"#;
        let output: ModelProposalOutput = serde_json::from_str(json).unwrap();
        let req = output.capability_request.unwrap();
        assert_eq!(req.capability, "stream_parse_logs");
        assert_eq!(req.constraints.max_memory_mb, 128);
        assert!(req.validate().is_ok());
    }

    #[test]
    fn verification_kind_roundtrips() {
        let kinds = vec![
            VerificationKind::StaticAnalysis,
            VerificationKind::DependencyScan,
            VerificationKind::PolicyCheck,
            VerificationKind::UnitTests,
            VerificationKind::ResourceEstimate,
        ];
        for k in kinds {
            let s = serde_json::to_string(&k).unwrap();
            let back: VerificationKind = serde_json::from_str(&s).unwrap();
            assert_eq!(k, back);
        }
    }
}