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
//! Deterministic behavioral support probe over committed fixtures.
//!
//! This deliberately reports only operations it actually performs. Live
//! executable verification is a separate audit tier because it may require
//! credentials or spend quota.

use std::collections::BTreeMap;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use rusqlite::params;
use serde_json::{json, Value};
use supercode_harness::{
    harness_support_registry, DiscoveryQuery, HarnessCatalog, HarnessHomes, HarnessId,
    HarnessSessionService, Session, SessionFollower, SessionFormat,
};

const CLAUDE: &str = "claude_code_session.jsonl";
const CODEX: &str = "codex_session.jsonl";
const GEMINI: &str = "gemini_session.jsonl";
const PI: &str = "pi_session_live_corpus.jsonl";
const OPENCODE: &str = "opencode_fixture/opencode.db";
const GROK: &str = "grok_session/chat_history.jsonl";
const GOOSE: &str = "goose_session.json";

fn fixture_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")
}

fn fresh_dir() -> PathBuf {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("system clock")
        .as_nanos();
    let path = std::env::temp_dir().join(format!(
        "supercode-support-probe-{}-{nanos}",
        std::process::id()
    ));
    fs::create_dir_all(&path).expect("create probe directory");
    path
}

fn copy_fixture(root: &Path, relative: &str, target: &Path) -> PathBuf {
    let destination = target.join(Path::new(relative).file_name().unwrap());
    fs::copy(root.join(relative), &destination).expect("copy fixture");
    destination
}

fn create_goose_store(fixture: &Path, target: &Path) {
    let document: Value =
        serde_json::from_str(&fs::read_to_string(fixture).expect("read Goose fixture"))
            .expect("parse Goose fixture");
    let connection =
        rusqlite::Connection::open(target.join("sessions.db")).expect("create Goose fixture store");
    connection
        .execute_batch(
            "CREATE TABLE sessions (
            id TEXT PRIMARY KEY, name TEXT NOT NULL, working_dir TEXT NOT NULL,
            created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
            session_type TEXT NOT NULL, extension_data TEXT, goose_mode TEXT NOT NULL,
            provider_name TEXT, model_config_json TEXT, archived_at TEXT
         );
         CREATE TABLE messages (
            id INTEGER PRIMARY KEY, session_id TEXT NOT NULL, message_id TEXT,
            role TEXT NOT NULL, content_json TEXT NOT NULL,
            created_timestamp INTEGER NOT NULL, metadata_json TEXT
         );",
        )
        .expect("create Goose fixture schema");
    let id = document["id"].as_str().expect("Goose fixture id");
    connection
        .execute(
            "INSERT INTO sessions VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, NULL)",
            params![
                id,
                document["name"].as_str().unwrap_or("Goose fixture"),
                document["working_dir"].as_str().unwrap_or("/tmp"),
                document["created_at"]
                    .as_str()
                    .unwrap_or("2026-01-01 00:00:00"),
                document["updated_at"]
                    .as_str()
                    .unwrap_or("2026-01-01 00:00:00"),
                document["session_type"].as_str().unwrap_or("user"),
                document["extension_data"].to_string(),
                document["goose_mode"].as_str().unwrap_or("auto"),
                document["provider_name"].as_str(),
                document["model_config"].to_string(),
            ],
        )
        .expect("insert Goose fixture session");
    for (index, message) in document["conversation"]
        .as_array()
        .expect("Goose fixture conversation")
        .iter()
        .enumerate()
    {
        connection
            .execute(
                "INSERT INTO messages VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                params![
                    index as i64 + 1,
                    id,
                    message["id"].as_str(),
                    message["role"].as_str().unwrap_or("user"),
                    message["content"].to_string(),
                    message["created"].as_i64().unwrap_or(index as i64),
                    message["metadata"].to_string(),
                ],
            )
            .expect("insert Goose fixture message");
    }
}

fn event_kind(event: &supercode_harness::SessionWatchEvent) -> &'static str {
    match event {
        supercode_harness::SessionWatchEvent::SessionSnapshot { .. } => "session_snapshot",
        supercode_harness::SessionWatchEvent::MessagesAppended { .. } => "messages_appended",
        supercode_harness::SessionWatchEvent::WatchError { .. } => "watch_error",
    }
}

fn append_text(path: &Path, line: &str) {
    let mut file = OpenOptions::new()
        .append(true)
        .open(path)
        .expect("open append");
    file.write_all(line.as_bytes()).expect("append fixture");
    file.write_all(b"\n").expect("append newline");
    file.flush().expect("flush fixture");
}

fn mutate_jsonl(harness: &str, path: &Path) {
    match harness {
        HarnessId::CLAUDE_CODE => append_text(
            path,
            r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"support probe append"}]},"uuid":"support-probe-a","parentUuid":"support-probe-u","sessionId":"support-probe"}"#,
        ),
        HarnessId::CODEX => append_text(
            path,
            r#"{"timestamp":"2099-01-01T00:00:00Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"support probe append"}],"phase":"final_answer"}}"#,
        ),
        HarnessId::PI => append_text(
            path,
            r#"{"type":"message","id":"support-probe-message","parentId":"dda32458","timestamp":"2099-01-01T00:00:00Z","message":{"role":"user","content":"support probe append","timestamp":4070908800000}}"#,
        ),
        HarnessId::GROK => append_text(
            path,
            r#"{"type":"assistant","content":"support probe append","tool_calls":[],"model_id":"grok-code-fixture"}"#,
        ),
        HarnessId::GEMINI => append_text(
            path,
            r#"{"id":"gemini-support-probe","timestamp":"2099-01-01T00:00:00.000Z","type":"gemini","content":"support probe append","model":"gemini-2.5-pro"}"#,
        ),
        HarnessId::GOOSE => {
            let mut document: Value =
                serde_json::from_str(&fs::read_to_string(path).expect("read Goose fixture"))
                    .expect("parse Goose fixture");
            let conversation = document["conversation"]
                .as_array_mut()
                .expect("Goose conversation");
            conversation.push(json!({
                "id": "support-probe-goose",
                "role": "assistant",
                "created": 4070908800_i64,
                "content": [{"type": "text", "text": "support probe append"}],
                "metadata": {"userVisible": true, "agentVisible": true}
            }));
            document["message_count"] = Value::from(conversation.len());
            fs::write(path, serde_json::to_string_pretty(&document).unwrap())
                .expect("rewrite Goose fixture");
        }
        _ => unreachable!(),
    }
}

fn mutate_opencode(path: &Path) {
    let connection = rusqlite::Connection::open(path).expect("open copied OpenCode fixture");
    let session_id = "ses_fixtureAAAAAAAAAAAAAAA1";
    let message_id = "msg_supportProbe000000001";
    connection
        .execute(
            "INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?1, ?2, ?3, ?3, ?4)",
            params![
                message_id,
                session_id,
                4_070_908_800_000_i64,
                r#"{"role":"user","time":{"created":4070908800000},"agent":"build"}"#
            ],
        )
        .expect("insert OpenCode message");
    connection
        .execute(
            "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?1, ?2, ?3, ?4, ?4, ?5)",
            params![
                "prt_supportProbe000000001",
                message_id,
                session_id,
                4_070_908_800_000_i64,
                r#"{"type":"text","text":"support probe append"}"#
            ],
        )
        .expect("insert OpenCode part");
    connection
        .execute(
            "UPDATE session SET time_updated = ?1 WHERE id = ?2",
            params![4_070_908_800_000_i64, session_id],
        )
        .expect("update OpenCode session");
}

fn format_name(format: SessionFormat) -> &'static str {
    match format {
        SessionFormat::ClaudeCode => HarnessId::CLAUDE_CODE,
        SessionFormat::Codex => HarnessId::CODEX,
        SessionFormat::OpenCode => HarnessId::OPENCODE,
        SessionFormat::Pi => HarnessId::PI,
        SessionFormat::Grok => HarnessId::GROK,
        SessionFormat::Gemini => HarnessId::GEMINI,
        SessionFormat::Goose => HarnessId::GOOSE,
    }
}

fn fixture_probe(harness: &str, path: &Path, format: SessionFormat) -> Value {
    let loaded = match Session::load(path) {
        Ok(session) => session,
        Err(error) => return json!({"load": {"status": "failed", "error": error.to_string()}}),
    };
    let mut translations = BTreeMap::new();
    for target in [
        SessionFormat::ClaudeCode,
        SessionFormat::Codex,
        SessionFormat::OpenCode,
        SessionFormat::Pi,
        SessionFormat::Grok,
        SessionFormat::Gemini,
        SessionFormat::Goose,
    ] {
        let outcome = loaded.to_jsonl(target).and_then(|encoded| {
            Session::load_str(&encoded, target).map(|reloaded| (encoded, reloaded))
        });
        translations.insert(
            format_name(target),
            match outcome {
                Ok((encoded, reloaded)) => json!({
                    "status": "exercised",
                    "bytes": encoded.len(),
                    "source_messages": loaded.messages.len(),
                    "reloaded_messages": reloaded.messages.len(),
                    "message_count_preserved": loaded.messages.len() == reloaded.messages.len(),
                }),
                Err(error) => json!({"status": "failed", "error": error.to_string()}),
            },
        );
    }

    let mut follower = SessionFollower::open(path, None).expect("fixture follower opens");
    let initial = follower
        .poll()
        .expect("initial poll")
        .expect("initial event");
    if harness == HarnessId::OPENCODE {
        mutate_opencode(path);
    } else {
        mutate_jsonl(harness, path);
    }
    let mutation = follower.poll().expect("mutation poll");

    json!({
        "load": {
            "status": "verified",
            "source": format_name(format),
            "messages": loaded.messages.len(),
        },
        "follow": {
            "status": if mutation.is_some() { "verified" } else { "failed" },
            "initial_event": event_kind(&initial),
            "mutation_event": mutation.as_ref().map(event_kind),
        },
        "translations": translations,
    })
}

fn main() {
    let registry = harness_support_registry();
    let mut service = HarnessSessionService::new();
    let service_response = service.handle(json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "harness.v1.support.report",
        "params": {},
    }));
    let service_ids = service_response["result"]["harnesses"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|entry| entry["id"].as_str())
        .collect::<Vec<_>>();
    let registry_ids = registry
        .harnesses
        .iter()
        .map(|entry| entry.id.as_str().to_owned())
        .collect::<Vec<_>>();
    let root = fixture_root();
    let temp = fresh_dir();
    let claude_dir = temp.join("claude");
    let codex_dir = temp.join("codex");
    let pi_dir = temp.join("pi");
    let opencode_dir = temp.join("opencode");
    let grok_dir = temp.join("grok");
    let gemini_dir = temp.join("gemini");
    let gemini_chats_dir = gemini_dir.join("tmp/support-probe/chats");
    let goose_dir = temp.join("goose");
    let grok_session_dir = grok_dir
        .join("%2Ftmp%2Fsupport-probe-grok")
        .join("support-probe-grok-session");
    for directory in [
        &claude_dir,
        &codex_dir,
        &pi_dir,
        &opencode_dir,
        &grok_session_dir,
        &gemini_chats_dir,
        &goose_dir,
    ] {
        fs::create_dir_all(directory).expect("create harness fixture directory");
    }
    let goose_fixture = copy_fixture(&root, GOOSE, &goose_dir);
    create_goose_store(&goose_fixture, &goose_dir);
    let paths = BTreeMap::from([
        (
            HarnessId::CLAUDE_CODE,
            copy_fixture(&root, CLAUDE, &claude_dir),
        ),
        (HarnessId::CODEX, copy_fixture(&root, CODEX, &codex_dir)),
        (HarnessId::PI, copy_fixture(&root, PI, &pi_dir)),
        (
            HarnessId::OPENCODE,
            copy_fixture(&root, OPENCODE, &opencode_dir),
        ),
        (
            HarnessId::GROK,
            copy_fixture(&root, GROK, &grok_session_dir),
        ),
        (
            HarnessId::GEMINI,
            copy_fixture(&root, GEMINI, &gemini_chats_dir),
        ),
        (HarnessId::GOOSE, goose_fixture),
    ]);
    let homes = HarnessHomes {
        claude_code: claude_dir,
        codex: codex_dir,
        gemini: gemini_dir,
        grok: grok_dir,
        goose: goose_dir,
        opencode: opencode_dir,
        pi: pi_dir,
        supercode: root.join("supercode"),
    };
    let discovered = HarnessCatalog::new()
        .discover(&DiscoveryQuery {
            homes,
            ..DiscoveryQuery::default()
        })
        .expect("fixture discovery");
    let mut discovered_by_harness = BTreeMap::<String, usize>::new();
    for descriptor in discovered {
        *discovered_by_harness
            .entry(descriptor.locator.harness.0)
            .or_default() += 1;
    }

    let formats = BTreeMap::from([
        (HarnessId::CLAUDE_CODE, SessionFormat::ClaudeCode),
        (HarnessId::CODEX, SessionFormat::Codex),
        (HarnessId::OPENCODE, SessionFormat::OpenCode),
        (HarnessId::PI, SessionFormat::Pi),
        (HarnessId::GROK, SessionFormat::Grok),
        (HarnessId::GEMINI, SessionFormat::Gemini),
        (HarnessId::GOOSE, SessionFormat::Goose),
    ]);
    let mut harnesses = serde_json::Map::new();
    for descriptor in registry.harnesses {
        let id = descriptor.id.0.clone();
        let fixture = match (paths.get(id.as_str()), formats.get(id.as_str())) {
            (Some(path), Some(format)) => fixture_probe(&id, path, *format),
            _ => json!({
                "load": {"status": "gap", "reason": "no committed native fixture"},
                "follow": {"status": "gap", "reason": "no native persistence implementation"},
                "translations": {},
            }),
        };
        harnesses.insert(
            id.clone(),
            json!({
                "registry": descriptor,
                "discovery": {
                    "status": if discovered_by_harness.get(&id).copied().unwrap_or(0) > 0 {
                        "verified"
                    } else {
                        "failed"
                    },
                    "sessions": discovered_by_harness.get(&id).copied().unwrap_or(0),
                },
                "fixture": fixture,
            }),
        );
    }

    println!(
        "{}",
        serde_json::to_string_pretty(&json!({
            "schema": "supercode.behavioral-support-probe.v1",
            "scope": "committed-fixtures",
            "live_executables_contacted": false,
            "surfaces": {
                "core": {"status": "verified", "operation": "harness_support_registry"},
                "service": {
                    "status": if service_ids == registry_ids { "verified" } else { "failed" },
                    "operation": "harness.v1.support.report",
                    "harnesses": service_ids,
                },
            },
            "harnesses": harnesses,
        }))
        .expect("serialize support probe")
    );
    fs::remove_dir_all(temp).ok();
}