repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

test(snapshot): help, eval json, rpc sequence, trace pinned with insta

de91dcc15aca678bca0017aa8a792370dd092431

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (12)

+272 / −31 text lines

Diff layout

Cargo.lock

Modified

+37 / −0 text lines

370370source = "registry+https://github.com/rust-lang/crates.io-index"
371371checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
373[[package]]
374name = "console"
375version = "0.16.6"
376source = "registry+https://github.com/rust-lang/crates.io-index"
377checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3"
378dependencies = [
379 "encode_unicode",
380 "libc",
381 "windows-sys 0.61.2",
382]
373384[[package]]
374385name = "core_detect"
375386version = "1.0.0"
692703source = "registry+https://github.com/rust-lang/crates.io-index"
693704checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
706[[package]]
707name = "encode_unicode"
708version = "1.0.0"
709source = "registry+https://github.com/rust-lang/crates.io-index"
710checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
695712[[package]]
696713name = "encoding_rs"
697714version = "0.8.42"
11301147 "serde_core",
1150[[package]]
1151name = "insta"
1152version = "1.48.0"
1153source = "registry+https://github.com/rust-lang/crates.io-index"
1154checksum = "86f0f8fee8c926415c58d6ae43a08523a26faccb2323f5e6b644fe7dd4ef6b82"
1155dependencies = [
1156 "console",
1157 "once_cell",
1158 "similar",
1159 "tempfile",
11331162[[package]]
11341163name = "is_terminal_polyfill"
11351164version = "1.70.2"
18401869source = "registry+https://github.com/rust-lang/crates.io-index"
18411870checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
1872[[package]]
1873name = "similar"
1874version = "2.7.0"
1875source = "registry+https://github.com/rust-lang/crates.io-index"
1876checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"
18431878[[package]]
18441879name = "slab"
18451880version = "0.4.12"
18891924 "archunit",
18901925 "assert_cmd",
18911926 "clap",
1927 "insta",
18921928 "predicates",
18931929 "serde_json",
18941930 "smith",
19061942 "fs2",
19071943 "futures",
19081944 "ignore",
1945 "insta",
19091946 "nix",
19101947 "proptest",
19111948 "serde",

smith-cli/Cargo.toml

Modified

+1 / −0 text lines

2121archunit = { workspace = true }
2222assert_cmd = { workspace = true }
2323predicates = { workspace = true }
24insta = { workspace = true }
2425smith-core = { path = "../smith-core", version = "0.1.0" }

smith-cli/tests/e2e_eval.rs

Modified

+2 / −9 text lines

6262 assert!(output.status.success());
6363 let stdout = String::from_utf8(output.stdout).unwrap();
6464 assert_eq!(stdout.lines().count(), 1, "{stdout}");
65 let report: serde_json::Value = serde_json::from_str(&stdout).unwrap();
66 assert_eq!(
67 report,
68 serde_json::json!({
69 "text": MOCK_REPLY,
70 "reason": "EndTurn",
71 "cost": {"input_tokens": 0, "output_tokens": 0},
72 })
73 );
65 // The mock reply and its zero cost are fixed; the line is pinned byte for byte.
66 insta::assert_snapshot!("eval_mock_json", stdout);
7669#[test]

smith-cli/tests/e2e_help.rs

Added
new file mode 100644

+32 / −0 text lines

1//! Help text of the built `smith` binary, pinned as snapshots
2//! (`SMH-SPEC-SPEC0001`, Interface modes).
3//!
4//! Selection variables are removed: clap prints their current values in
5//! `[env: …]`, which would leak the caller's environment into the snapshot.
6
7use assert_cmd::Command;
8
9fn help(args: &[&str]) -> String {
10 let output = Command::cargo_bin("smith")
11 .unwrap()
12 .args(args)
13 .env_remove("SMITH_PROVIDER")
14 .env_remove("SMITH_MODEL")
15 .env_remove("SMITH_BASE_URL")
16 .env_remove("CLICOLOR_FORCE")
17 .output()
18 .unwrap();
19 assert!(output.status.success(), "{output:?}");
20 assert!(output.stderr.is_empty(), "{output:?}");
21 String::from_utf8(output.stdout).unwrap()
22}
24#[test]
25fn help_top_level() {
26 insta::assert_snapshot!(help(&["--help"]));
27}
29#[test]
30fn help_eval() {
31 insta::assert_snapshot!(help(&["eval", "--help"]));
32}

smith-cli/tests/e2e_rpc.rs

Modified

+23 / −22 text lines

1818struct Rpc {
1919 child: Child,
2020 stdin: Option<ChildStdin>,
21 /// Parsed stdout lines; `None` marks end of output.
22 lines: Receiver<Option<Value>>,
21 /// Raw stdout lines; `None` marks end of output.
22 lines: Receiver<Option<String>>,
23 /// Every line sent (`> `) and received (`< `), in order.
24 transcript: Vec<String>,
2527impl Rpc {
4749 let (sender, lines) = mpsc::channel();
4850 std::thread::spawn(move || {
4951 for line in BufReader::new(stdout).lines() {
50 let line = line.unwrap();
51 let value = serde_json::from_str(&line)
52 .unwrap_or_else(|error| panic!("stdout line is not JSON ({error}): {line}"));
53 if sender.send(Some(value)).is_err() {
52 if sender.send(Some(line.unwrap())).is_err() {
5453 return;
5554 }
5655 }
6160 child,
6261 stdin,
6362 lines,
63 transcript: Vec::new(),
6464 }
6565 }
6969 }
7171 fn send(&mut self, line: &str) {
72 self.transcript.push(format!("> {line}"));
7273 let stdin = self.stdin.as_mut().unwrap();
7374 stdin.write_all(line.as_bytes()).unwrap();
7475 stdin.write_all(b"\n").unwrap();
7576 stdin.flush().unwrap();
7677 }
78 fn next(&self) -> Value {
79 fn next(&mut self) -> Value {
7980 match self.lines.recv_timeout(DEADLINE) {
80 Ok(Some(value)) => value,
81 Ok(Some(line)) => {
82 let value = serde_json::from_str(&line)
83 .unwrap_or_else(|error| panic!("stdout line is not JSON ({error}): {line}"));
84 self.transcript.push(format!("< {line}"));
85 value
86 }
8187 Ok(None) => panic!("rpc output ended early"),
8288 Err(error) => panic!("no rpc line within {DEADLINE:?}: {error}"),
8389 }
8894 drop(self.stdin.take());
8995 match self.lines.recv_timeout(DEADLINE) {
9096 Ok(None) => {}
91 Ok(Some(value)) => panic!("unexpected rpc line after close: {value}"),
97 Ok(Some(line)) => panic!("unexpected rpc line after close: {line}"),
9298 Err(error) => panic!("rpc did not end output within {DEADLINE:?}: {error}"),
9399 }
94100 self.child.wait().unwrap()
260266 ],
261267 &[("OPENAI_API_KEY", "sk-e2e-fixture")],
262268 );
269 // Each step waits for its reply before the next; the provider holds its
270 // response until the abort is acknowledged, so the order is fixed.
263271 rpc.send(r#"{"id": 1, "method": "prompt", "params": {"input": "block"}}"#);
264 assert_eq!(rpc.next(), json!({"id": 1, "event": "start"}));
272 rpc.next();
265273 provider
266274 .received
267275 .recv_timeout(DEADLINE)
268276 .expect("provider request within the deadline");
270277 rpc.send(r#"{"id": 2, "method": "abort"}"#);
271 assert_eq!(rpc.next(), json!({"id": 2, "aborting": true}));
278 rpc.next();
272279 provider.release.send(()).unwrap();
274 let end = rpc.next();
275 assert_eq!(end["id"], 1);
276 assert_eq!(end["event"], "end");
277 assert_eq!(end["error"]["code"], "TURN_FAILED");
278 assert_eq!(end["error"]["message"], "operation cancelled");
279 assert!(end.get("text").is_none(), "{end}");
280 rpc.next();
281281 // `wait` answers once the aborted turn has settled; `status` then agrees.
282282 rpc.send(r#"{"id": 3, "method": "wait"}"#);
283 assert_eq!(rpc.next(), json!({"id": 3, "settled": true}));
283 rpc.next();
284284 rpc.send(r#"{"id": 4, "method": "status"}"#);
285 assert_eq!(rpc.next(), json!({"id": 4, "settled": true}));
285 rpc.next();
286 insta::assert_snapshot!("rpc_prompt_then_abort_then_wait", rpc.transcript.join("\n"));
286287 assert!(rpc.close().success());

smith-cli/tests/snapshots/e2e_eval__eval_mock_json.snap

Added
new file mode 100644

+5 / −0 text lines

1---
2source: smith-cli/tests/e2e_eval.rs
3expression: stdout
4---
5{"text":"mock provider: no model configured","reason":"EndTurn","cost":{"input_tokens":0,"output_tokens":0}}

smith-cli/tests/snapshots/e2e_help__help_eval.snap

Added
new file mode 100644

+41 / −0 text lines

1---
2source: smith-cli/tests/e2e_help.rs
3expression: "help(&[\"eval\", \"--help\"])"
4---
5Run one prompt without the TUI
6
7Usage: smith eval [OPTIONS] <PROMPT>
8
9Arguments:
10 <PROMPT>
11 The prompt to run
13Options:
14 --json
15 Print the structured outcome as JSON
17 --mock
18 Use the scripted mock provider instead of a real endpoint
20 --provider <PROVIDER>
21 Provider kind; required for real endpoints
23 Possible values:
24 - openai: OpenAI-compatible endpoints
25 - anthropic: Anthropic Messages API
26 - google: Google Gemini API
27
28 [env: SMITH_PROVIDER=]
30 --model <MODEL>
31 Model id; required for real endpoints
32
33 [env: SMITH_MODEL=]
35 --base-url <BASE_URL>
36 Endpoint base URL override
37
38 [env: SMITH_BASE_URL=]
40 -h, --help
41 Print help (see a summary with '-h')

smith-cli/tests/snapshots/e2e_help__help_top_level.snap

Added
new file mode 100644

+17 / −0 text lines

1---
2source: smith-cli/tests/e2e_help.rs
3expression: "help(&[\"--help\"])"
4---
5Smith, a fast coding-agent runtime
6
7Usage: smith <COMMAND>
8
9Commands:
10 auth Manage stored provider credentials
11 eval Run one prompt without the TUI
12 rpc Serve LF-delimited JSON-RPC on standard input and output
13 help Print this message or the help of the given subcommand(s)
15Options:
16 -h, --help Print help
17 -V, --version Print version

smith-cli/tests/snapshots/e2e_rpc__rpc_prompt_then_abort_then_wait.snap

Added
new file mode 100644

+13 / −0 text lines

1---
2source: smith-cli/tests/e2e_rpc.rs
3expression: "rpc.transcript.join(\"\\n\")"
4---
5> {"id": 1, "method": "prompt", "params": {"input": "block"}}
6< {"id":1,"event":"start"}
7> {"id": 2, "method": "abort"}
8< {"id":2,"aborting":true}
9< {"id":1,"event":"end","error":{"code":"TURN_FAILED","message":"operation cancelled"}}
10> {"id": 3, "method": "wait"}
11< {"id":3,"settled":true}
12> {"id": 4, "method": "status"}
13< {"id":4,"settled":true}

smith-core/Cargo.toml

Modified

+1 / −0 text lines

2222[dev-dependencies]
2323smith-alloc = { path = "../smith-alloc", version = "0.1.0" }
2424proptest = { workspace = true }
25insta = { workspace = true }

smith-core/tests/snapshots/trace_snapshot__trace_of_message_tool_round_trip_and_compaction.snap

Added
new file mode 100644

+13 / −0 text lines

1---
2source: smith-core/tests/trace_snapshot.rs
3expression: redacted_trace(&session)
4---
5{"timestamp_ms":0,"session_id":"<session>","kind":"SessionCreated","event_ref":"branch:<branch>"}
6{"timestamp_ms":"<timestamp>","session_id":"<session>","kind":"MessageStreamed","event_ref":"message:<message-0>"}
7{"timestamp_ms":"<timestamp>","session_id":"<session>","kind":"ToolCallEmitted","event_ref":"call:00000000-0000-0000-0000-000000000001"}
8{"timestamp_ms":"<timestamp>","session_id":"<session>","kind":"ToolResultReceived","event_ref":"result:00000000-0000-0000-0000-000000000001:ok"}
9{"timestamp_ms":"<timestamp>","session_id":"<session>","kind":"ToolCallEmitted","event_ref":"call:00000000-0000-0000-0000-000000000002"}
10{"timestamp_ms":"<timestamp>","session_id":"<session>","kind":"ToolResultReceived","event_ref":"result:00000000-0000-0000-0000-000000000002:failed"}
11{"timestamp_ms":"<timestamp>","session_id":"<session>","kind":"MessageStreamed","event_ref":"message:<message-5>"}
12{"timestamp_ms":"<timestamp>","session_id":"<session>","kind":"Compaction","event_ref":"meta:compaction:<entry-6>"}
13{"timestamp_ms":"<timestamp>","session_id":"<session>","kind":"EntryAdded","event_ref":"meta:<entry-7>"}

smith-core/tests/trace_snapshot.rs

Added
new file mode 100644

+87 / −0 text lines

1//! The trace of a small session, pinned as a snapshot (`SMH-SPEC-SPEC0001`,
2//! Sessions).
3//!
4//! Session, branch, entry, and message ids and entry timestamps differ every
5//! run; they are redacted to placeholders before snapshotting. Call ids are
6//! chosen by the test and stay literal.
7
8use serde_json::Value;
9use smith::id::ToolCallId;
10use smith::message::{Message, Role};
11use smith_core::session::{COMPACTION_KIND, EntryContent, EntryKind, Session};
12use smith_core::trace::build_trace;
14/// One JSON line per record, with every run-specific value replaced.
15fn redacted_trace(session: &Session) -> String {
16 let branch = session.active_branch();
17 let mut placeholders = vec![
18 (session.id().to_string(), "<session>".to_string()),
19 (branch.id().to_string(), "<branch>".to_string()),
20 ];
21 for (index, entry) in branch.entries().iter().enumerate() {
22 placeholders.push((entry.id.to_string(), format!("<entry-{index}>")));
23 if let EntryKind::Message { id, .. } = entry.kind {
24 placeholders.push((id.to_string(), format!("<message-{index}>")));
25 }
26 }
27 let redact = |text: &str| {
28 placeholders
29 .iter()
30 .fold(text.to_string(), |text, (id, placeholder)| {
31 text.replace(id, placeholder)
32 })
33 };
34 build_trace(session)
35 .iter()
36 .map(|record| {
37 let mut line = serde_json::to_value(record).unwrap();
38 if line["timestamp_ms"] != 0 {
39 line["timestamp_ms"] = Value::from("<timestamp>");
40 }
41 redact(&line.to_string())
42 })
43 .collect::<Vec<_>>()
44 .join("\n")
45}
47#[test]
48fn trace_of_message_tool_round_trip_and_compaction() {
49 let call = ToolCallId::from_u128(1);
50 let failed_call = ToolCallId::from_u128(2);
51 let mut session = Session::new();
52 for content in [
53 EntryContent::Message(Message::with_text(Role::User, "list files")),
54 EntryContent::ToolCall {
55 name: "ls".to_string(),
56 input: serde_json::json!({"path": "."}),
57 call_id: call,
58 },
59 EntryContent::ToolResult {
60 ok: true,
61 output: "a.txt".to_string(),
62 call_id: call,
63 },
64 EntryContent::ToolCall {
65 name: "read".to_string(),
66 input: serde_json::json!({"path": "missing.txt"}),
67 call_id: failed_call,
68 },
69 EntryContent::ToolResult {
70 ok: false,
71 output: "not found".to_string(),
72 call_id: failed_call,
73 },
74 EntryContent::Message(Message::with_text(Role::Assistant, "a.txt")),
75 EntryContent::Meta {
76 kind: COMPACTION_KIND.to_string(),
77 detail: serde_json::json!({}),
78 },
79 EntryContent::Meta {
80 kind: "branch".to_string(),
81 detail: serde_json::json!({}),
82 },
83 ] {
84 session.append(&content).unwrap();
85 }
86 insta::assert_snapshot!(redacted_trace(&session));
87}