itok 0.3.2

context-cost estimator: token and window budgets for files and changes
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
//! Process-boundary smoke only. Everything else -- every verb, flag,
//! error path, and the permutation properties -- is unit- and
//! property-tested against `itok::cli::run` in cli.rs, at lib cost. These
//! three prove the one thing a lib test cannot: that `main` wires
//! `run`'s Output to the actual streams and the real process exit code.

#![allow(clippy::unwrap_used, clippy::panic)]

use assert_cmd::Command;
use predicates::prelude::*;

fn itok() -> Command {
    Command::cargo_bin("itok").unwrap()
}

#[test]
fn stdout_and_exit_zero_on_success() {
    itok()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains("itok"));
}

#[test]
fn stderr_and_exit_two_on_usage_error() {
    itok()
        .arg("bogus")
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("unknown"));
}

#[test]
fn estimate_reports_to_stdout() {
    itok()
        .args(["estimate", "SPEC.md"])
        .assert()
        .success()
        .stdout(predicate::str::contains("itok"));
}

// V11 at the process boundary: `--model` on doctor. An unknown model is a
// hard failure (exit 2), and a listed model resolves its encoding and
// labels the report -- proving `main` wires the resolver and its error.
#[test]
fn doctor_unknown_model_exits_two() {
    itok()
        .args(["doctor", "--model", "gpt-4o", "SPEC.md"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("unknown model"));
}

#[cfg(feature = "bpe")]
#[test]
fn doctor_honors_a_listed_model() {
    let dir =
        std::env::temp_dir().join(format!("itok-t7-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join(".context-models"), "gpt-4o o200k\n").unwrap();
    std::fs::write(dir.join("f.txt"), "hello world\n").unwrap();
    itok()
        .args(["doctor", "--model", "gpt-4o", "f.txt"])
        .current_dir(&dir)
        .assert()
        .success()
        .stdout(predicate::str::contains("(o200k)"));
}

// V18: a `--model` with a window column gives doctor a fit-line with no
// `--window` flag; an explicit `--window` overrides the table's window.
#[cfg(feature = "bpe")]
#[test]
fn doctor_model_window_gives_the_fit_line() {
    let dir = std::env::temp_dir()
        .join(format!("itok-t14-fit-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join(".context-models"), "qwen o200k 256k\n").unwrap();
    std::fs::write(dir.join("f.txt"), "hello world\n").unwrap();
    itok()
        .args(["doctor", "--model", "qwen", "f.txt"])
        .current_dir(&dir)
        .assert()
        .success()
        // The fit-line prints the resolved window, not the "pass --window"
        // prompt, because the model row supplied it.
        .stdout(
            predicate::str::contains("256000")
                .and(predicate::str::contains("pass --window").not()),
        );
}

#[cfg(feature = "bpe")]
#[test]
fn explicit_window_overrides_the_model_window() {
    let dir = std::env::temp_dir()
        .join(format!("itok-t14-override-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join(".context-models"), "qwen o200k 256k\n").unwrap();
    std::fs::write(dir.join("f.txt"), "hello world\n").unwrap();
    itok()
        .args(["doctor", "--model", "qwen", "--window", "1M", "f.txt"])
        .current_dir(&dir)
        .assert()
        .success()
        // Explicit --window wins: 1M, not the table's 256k (V18).
        .stdout(
            predicate::str::contains("1000000")
                .and(predicate::str::contains("256000").not()),
        );
}

// V20: `fit` selects the subset that fits and emits a bare, pipeable path
// list; --window is required, so its absence is a usage error.
#[test]
fn fit_emits_a_pipeable_path_list() {
    itok()
        .args(["fit", "--window", "100M", "Cargo.toml"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("Cargo.toml")
                .and(predicate::str::contains("itok").not()),
        );
}

#[test]
fn fit_without_a_window_is_a_usage_error() {
    itok()
        .args(["fit", "Cargo.toml"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("--window"));
}

// `cap` is the only verb fed by a STREAM, so it is the only one whose
// wiring a lib test cannot reach: `run` takes its input as a closure, and
// only `main` binds that closure to the process's real stdin (V49).
#[test]
fn cap_filters_real_stdin_and_announces_the_cut() {
    itok()
        .args(["cap", "2"])
        .write_stdin("aaaaaaa\nbbbbbbb\nccccccc\n")
        .assert()
        .success()
        .stdout(
            predicate::str::starts_with("aaaaaaa\n")
                .and(predicate::str::contains("ccccccc").not())
                .and(predicate::str::contains(
                    "resume: line 2 (byte offset 8)",
                )),
        );
}

// V38: the ollama network backend is CASSETTE-REPLAYED here -- a local
// stub serves the recorded responses (tests/fixtures/ollama.json, standard
// vcr-cassette format) so the full path (cli -> estcmd/discover -> ureq ->
// parse -> render) is exercised offline and deterministically, no server.
// Gated on the feature so it runs in the `--features ollama` CI axis.
#[cfg(feature = "ollama")]
mod ollama_cassette {
    use super::*;
    use std::io::{Read, Write};
    use std::net::{TcpListener, TcpStream};
    use std::thread;
    use vcr_cassette::Cassette;

    const CASSETTE: &str = include_str!("fixtures/ollama.json");
    const DIR: &str = env!("CARGO_MANIFEST_DIR");

    /// Spawn a replay server that serves each recorded response keyed by
    /// request path, over a random localhost port. Returns `host:port` for
    /// `OLLAMA_HOST`. The thread serves until the test process ends.
    fn replay() -> String {
        let cassette: Cassette = serde_json::from_str(CASSETTE).unwrap();
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let host = listener.local_addr().unwrap().to_string();
        thread::spawn(move || {
            for stream in listener.incoming().flatten() {
                serve(stream, &cassette);
            }
        });
        host
    }

    fn serve(mut stream: TcpStream, cassette: &Cassette) {
        let req = read_request(&stream);
        let body = response_for(cassette, &request_path(&req));
        let out = format!(
            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\
             Content-Type: application/json\r\nConnection: close\r\n\r\n{body}",
            body.len()
        );
        let _ = stream.write_all(out.as_bytes());
        let _ = stream.flush();
    }

    /// The whole request -- headers AND body -- before we reply.
    ///
    /// TCP is a STREAM: one `read` returns what has ARRIVED, not a request.
    /// The single POST (`/api/generate`) can land its body in a second
    /// segment, and replying after one read drops the socket mid-write, so
    /// the client sees `Invalid argument (os error 22)`. Serial runs happen
    /// to fit one segment; parallel ones do not (B5). Drain to
    /// `Content-Length`, then answer.
    fn read_request(stream: &TcpStream) -> String {
        let mut peek = stream.try_clone().unwrap();
        let mut buf = Vec::new();
        let mut chunk = [0u8; 1024];
        while !is_complete(&buf) {
            let n = peek.read(&mut chunk).unwrap_or(0);
            if n == 0 {
                break;
            }
            buf.extend_from_slice(chunk.get(..n).unwrap_or(&[]));
        }
        String::from_utf8_lossy(&buf).into_owned()
    }

    /// True once the buffer holds the header block plus a full body.
    fn is_complete(buf: &[u8]) -> bool {
        let text = String::from_utf8_lossy(buf);
        let Some(end) = text.find("\r\n\r\n").map(|i| i.saturating_add(4))
        else {
            return false;
        };
        text.len().saturating_sub(end) >= content_length(&text)
    }

    /// `Content-Length` from the header block; 0 when absent (a GET).
    fn content_length(head: &str) -> usize {
        head.lines()
            .filter(|l| l.to_ascii_lowercase().starts_with("content-length:"))
            .find_map(|l| l.split(':').nth(1))
            .and_then(|v| v.trim().parse().ok())
            .unwrap_or(0)
    }

    /// The path from the request line (`GET /api/tags HTTP/1.1`).
    fn request_path(req: &str) -> String {
        req.split_whitespace().nth(1).unwrap_or("").to_owned()
    }

    /// The recorded response body whose request path matches, else empty.
    fn response_for(cassette: &Cassette, path: &str) -> String {
        cassette
            .http_interactions
            .iter()
            .find(|i| i.request.uri.path() == path)
            .map(|i| i.response.body.string.clone())
            .unwrap_or_default()
    }

    #[test]
    fn estimate_ollama_replays_the_exact_count() {
        // The cassette's /api/generate returns prompt_eval_count=42, tagged
        // the exact tier (V22) -- deterministic, offline.
        let host = replay();
        itok()
            .args(["estimate", "--ollama", "Cargo.toml"])
            .env("OLLAMA_HOST", &host)
            .current_dir(DIR)
            .assert()
            .success()
            // T79: the label NAMES the tokenizer that produced the count,
            // so a number from an unintended endpoint is visible (V101).
            // `(exact)` alone used to render identically for every model
            // on every host.
            .stdout(
                predicate::str::contains("42 itok").and(
                    predicate::str::contains("exact via qwen3-coder:30b@"),
                ),
            );
    }

    #[test]
    fn doctor_ollama_fleet_unions_the_models() {
        // V24: two hosts, each serving qwen3-coder:30b, union to one model.
        let fleet = format!("{},{}", replay(), replay());
        itok()
            .arg("doctor")
            .arg("--ollama")
            .arg(&fleet)
            .current_dir(DIR)
            .assert()
            .success()
            .stdout(
                predicate::str::contains("qwen3-coder:30b")
                    .and(predicate::str::contains("262144")),
            );
    }

    #[test]
    fn doctor_ollama_replays_the_enumerate() {
        // /api/tags -> qwen3-coder:30b, /api/show -> window 262144 (V22).
        let host = replay();
        itok()
            .args(["doctor", "--ollama"])
            .env("OLLAMA_HOST", &host)
            .current_dir(DIR)
            .assert()
            .success()
            .stdout(
                predicate::str::contains("qwen3-coder:30b")
                    .and(predicate::str::contains("262144")),
            );
    }

    /// V9: json keeps `method` as the bare tier a parser matches on, and
    /// carries the endpoint as its OWN field -- folding it into `method`
    /// would break every consumer testing for `"exact"`.
    #[test]
    fn estimate_ollama_json_keeps_method_and_adds_endpoint() {
        let host = replay();
        itok()
            .args(["estimate", "--ollama", "--format", "json", "Cargo.toml"])
            .env("OLLAMA_HOST", &host)
            .current_dir(DIR)
            .assert()
            .success()
            .stdout(predicate::str::contains("\"method\":\"exact\"").and(
                predicate::str::contains("\"endpoint\":\"qwen3-coder:30b@"),
            ));
    }

    /// V6 on a discovered set: a family prefix narrows to the one model
    /// the fleet serves. The cassette serves only `qwen3-coder:30b`, so
    /// `qwen3` is unambiguous and must resolve rather than 404.
    #[test]
    fn doctor_ollama_narrows_by_a_model_prefix() {
        let host = replay();
        itok()
            .args(["doctor", "--ollama", "--model", "qwen3"])
            .env("OLLAMA_HOST", &host)
            .current_dir(DIR)
            .assert()
            .success()
            .stdout(predicate::str::contains("qwen3-coder:30b"));
    }

    /// T85: a comma-list renders the fleet view -- a shared `context:` header
    /// over one row per element. The cassette serves one model, so both
    /// elements resolve to it, which is the shape that proves the LIST path
    /// ran rather than the single-model one.
    #[test]
    fn doctor_ollama_accepts_a_model_list() {
        let host = replay();
        itok()
            .args(["doctor", "--ollama", "--model", "qwen3,qwen3-coder"])
            .env("OLLAMA_HOST", &host)
            .current_dir(DIR)
            .assert()
            .success()
            .stdout(
                predicate::str::contains("context:")
                    .and(predicate::str::contains("qwen3-coder:30b")),
            );
    }

    /// T85's teeth: one unresolvable element fails the WHOLE call. A partial
    /// list reading as a complete one is B11b's failure (V44).
    #[test]
    fn a_model_list_is_all_or_nothing() {
        let host = replay();
        itok()
            .args(["doctor", "--ollama", "--model", "qwen3,no-such-model"])
            .env("OLLAMA_HOST", &host)
            .current_dir(DIR)
            .assert()
            .code(2)
            .stderr(predicate::str::contains("no-such-model"));
    }

    /// V71: an unserved name is a USAGE error that NAMES what is served.
    /// The fleet answered, so exit 7 (network) would be a lie -- and a CI
    /// retry loop would spin on what is really a typo.
    #[test]
    fn an_unserved_model_names_the_alternatives() {
        let host = replay();
        itok()
            .args(["doctor", "--ollama", "--model", "no-such-model"])
            .env("OLLAMA_HOST", &host)
            .current_dir(DIR)
            .assert()
            .code(2)
            .stderr(
                predicate::str::contains("no fleet host serves")
                    .and(predicate::str::contains("qwen3-coder:30b")),
            );
    }

    // The LIVE check (V38): never in the gate. Run by hand against a real
    // host: `OLLAMA_HOST=box:11434 cargo test -p itok --features ollama -- \
    // --ignored`.
    #[test]
    #[ignore = "hits a real ollama host; run with --ignored + OLLAMA_HOST"]
    fn live_ollama_smoke() {
        itok()
            .args(["estimate", "--ollama", "README.md"])
            .current_dir(DIR)
            .assert()
            .success()
            .stdout(predicate::str::contains("(exact)"));
    }
}