blyte 0.56.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
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
488
489
490
491
492
493
494
495
//! Scope checks for `blyte review`.
//!
//! Flags files changed that the task text never mentions, commit subjects
//! not matching what the task specified, host commands, outside reads, and
//! non-verified outcomes.

const IGNORED_LOCKFILES: &[&str] = &[
    "Cargo.lock",
    "uv.lock",
    "package-lock.json",
    "pnpm-lock.yaml",
    "yarn.lock",
    "poetry.lock",
];

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Checks {
    pub flags: Vec<String>,
}

/// Files changed by the run that the task text never mentions.
/// A file counts as mentioned when the task text contains its full repo-relative path,
/// or its file name (last path component), anywhere (code spans, prose, lists).
/// Ignored (never flagged): Cargo.lock, uv.lock, package-lock.json, pnpm-lock.yaml, yarn.lock, poetry.lock.
pub fn unmentioned_files(task: &str, changed: &[String]) -> Vec<String> {
    changed
        .iter()
        .filter(|path| {
            if path.is_empty() {
                return false;
            }
            let file_name = std::path::Path::new(path)
                .file_name()
                .and_then(|s| s.to_str())
                .unwrap_or(path.as_str());

            if IGNORED_LOCKFILES.contains(&file_name) || IGNORED_LOCKFILES.contains(&path.as_str())
            {
                return false;
            }

            let mentioned =
                task.contains(path.as_str()) || (!file_name.is_empty() && task.contains(file_name));
            !mentioned
        })
        .cloned()
        .collect()
}

/// Commit subjects (first lines) that do not appear verbatim in the task text.
/// Returns them in the order given. If the task text contains no line starting with
/// "commit" or "Commit" (case-insensitive word "commit" anywhere in a heading or line), return empty:
/// the task did not specify a message.
pub fn unexpected_subjects(task: &str, subjects: &[String]) -> Vec<String> {
    if !specifies_commit(task) {
        return Vec::new();
    }
    subjects
        .iter()
        .filter(|s| !task.contains(s.as_str()))
        .cloned()
        .collect()
}

fn specifies_commit(task: &str) -> bool {
    for line in task.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('#') && contains_word_commit(trimmed) {
            return true;
        }
        let stripped = trimmed.trim_start_matches(|c: char| {
            c.is_whitespace()
                || c == '*'
                || c == '-'
                || c == '_'
                || c == '>'
                || c == '`'
                || c == '#'
        });
        if stripped.to_lowercase().starts_with("commit")
            || stripped.to_lowercase().contains("commit message")
        {
            return true;
        }
    }
    false
}

fn contains_word_commit(s: &str) -> bool {
    s.to_lowercase()
        .split(|c: char| !c.is_alphanumeric())
        .any(|w| w == "commit" || w == "commits")
}

fn sanitize_flag(flag: String) -> String {
    let single_line = flag.lines().next().unwrap_or("").to_string();
    if single_line.chars().count() > 200 {
        single_line.chars().take(200).collect()
    } else {
        single_line
    }
}

const KNOWN_FILE_EXTENSIONS: &[&str] = &[
    "rs",
    "py",
    "pyi",
    "ts",
    "tsx",
    "js",
    "jsx",
    "mjs",
    "cjs",
    "go",
    "c",
    "h",
    "cc",
    "cpp",
    "cxx",
    "hpp",
    "hh",
    "java",
    "kt",
    "kts",
    "scala",
    "cs",
    "fs",
    "rb",
    "php",
    "swift",
    "m",
    "mm",
    "zig",
    "nim",
    "lua",
    "pl",
    "pm",
    "r",
    "jl",
    "ex",
    "exs",
    "erl",
    "hrl",
    "hs",
    "ml",
    "mli",
    "clj",
    "cljs",
    "el",
    "vim",
    "sh",
    "bash",
    "zsh",
    "fish",
    "ps1",
    "bat",
    "cmd",
    "sql",
    "toml",
    "yaml",
    "yml",
    "json",
    "jsonc",
    "json5",
    "xml",
    "html",
    "htm",
    "css",
    "scss",
    "sass",
    "less",
    "vue",
    "svelte",
    "astro",
    "md",
    "mdx",
    "rst",
    "txt",
    "adoc",
    "tex",
    "csv",
    "tsv",
    "ini",
    "cfg",
    "conf",
    "env",
    "properties",
    "lock",
    "mod",
    "sum",
    "proto",
    "thrift",
    "avsc",
    "graphql",
    "gql",
    "prisma",
    "tf",
    "tfvars",
    "hcl",
    "nix",
    "dhall",
    "star",
    "bzl",
    "cmake",
    "mk",
    "gradle",
    "sbt",
    "cabal",
    "gemspec",
    "podspec",
    "csproj",
    "fsproj",
    "sln",
    "plist",
    "svg",
    "png",
    "jpg",
    "jpeg",
    "gif",
    "ico",
    "webp",
    "woff",
    "woff2",
    "ttf",
    "eot",
    "wasm",
    "wat",
    "dockerfile",
];

const KNOWN_EXTENSIONLESS_FILES: &[&str] = &[
    "Makefile",
    "Dockerfile",
    "Containerfile",
    "Justfile",
    "Procfile",
    "Gemfile",
    "Rakefile",
    "Brewfile",
    "Vagrantfile",
    "LICENSE",
    "CHANGELOG",
    "README",
    "OWNERS",
    "CODEOWNERS",
    "BUILD",
    "WORKSPACE",
];

fn looks_like_file_reference(raw: &str) -> bool {
    let token = raw
        .trim_start_matches(|c: char| {
            matches!(
                c,
                '`' | '\'' | '"' | '(' | '[' | '{' | '<' | '*' | ',' | ';' | ':'
            )
        })
        .trim_end_matches(|c: char| {
            matches!(
                c,
                '`' | '\'' | '"' | ')' | ']' | '}' | '>' | '*' | ',' | ';' | ':' | '.' | '!' | '?'
            )
        });
    if token.is_empty()
        || token.starts_with("http://")
        || token.starts_with("https://")
        || token.contains("://")
    {
        return false;
    }

    let last_segment = token.rsplit('/').next().unwrap_or(token);
    if last_segment.is_empty() {
        return false;
    }
    if KNOWN_EXTENSIONLESS_FILES.contains(&last_segment) {
        return true;
    }

    if let Some((stem, ext)) = last_segment.rsplit_once('.') {
        let valid_stem = !stem.is_empty()
            && stem
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'));
        if !valid_stem || ext.is_empty() {
            return false;
        }
        let lower_ext = ext.to_ascii_lowercase();
        if KNOWN_FILE_EXTENSIONS.contains(&lower_ext.as_str()) {
            return true;
        }
        if token.contains('/')
            && ext.len() <= 6
            && ext.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
            && ext.chars().all(|c| c.is_ascii_alphanumeric())
        {
            return true;
        }
    }

    false
}

/// Returns whether the task text names any file or file path.
pub fn task_names_files(task: &str) -> bool {
    task.split_whitespace().any(looks_like_file_reference)
}

fn is_unnamed_files_flag(flag: &str) -> bool {
    flag.starts_with("files not named in the task")
}

/// Returns whether a verified run should receive a fresh model review.
pub fn should_run_model_review(
    flags: &[String],
    task_text: Option<&str>,
    risky_matches: &[String],
) -> bool {
    if !risky_matches.is_empty() {
        return true;
    }
    let names_files = task_text.is_some_and(task_names_files);
    flags
        .iter()
        .any(|f| names_files || !is_unnamed_files_flag(f))
}

/// Build the flags list. Each flag is one line of at most 200 characters.
pub fn build(
    task: Option<&str>,
    changed: &[String],
    subjects: &[String],
    host_cmds: usize,
    outside_reads: usize,
    outcome: Option<&str>,
) -> Checks {
    let mut flags = Vec::new();

    if task.is_none() {
        flags.push("task file not found: scope not checked".to_string());
    }

    if let Some(outc) = outcome {
        if outc != "verified" {
            flags.push(format!("outcome {outc}: review in depth"));
        }
    }

    if changed.is_empty() {
        flags.push("no files changed".to_string());
    }

    if let Some(t) = task {
        let unmentioned = unmentioned_files(t, changed);
        if !unmentioned.is_empty() {
            let msg = if unmentioned.len() <= 10 {
                format!("files not named in the task: {}", unmentioned.join(", "))
            } else {
                let first_10 = &unmentioned[..10];
                let more = unmentioned.len() - 10;
                format!(
                    "files not named in the task: {}, … (+{more} more)",
                    first_10.join(", ")
                )
            };
            flags.push(msg);
        }

        let unexpected = unexpected_subjects(t, subjects);
        for subj in unexpected {
            flags.push(format!("commit message not in the task: {subj}"));
        }
    }

    if host_cmds > 0 {
        flags.push(format!("{host_cmds} host command(s): see == host commands"));
    }

    if outside_reads > 0 {
        flags.push(format!(
            "{outside_reads} read(s) outside the repository: see == reads outside the repository"
        ));
    }

    let flags = flags.into_iter().map(sanitize_flag).collect();
    Checks { flags }
}

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

    #[test]
    fn test_unmentioned_files() {
        let task = "Mentions `src/a.rs` by path and `b.rs` by name only";
        let changed = vec![
            "src/a.rs".to_string(),
            "src/x/b.rs".to_string(),
            "src/c.rs".to_string(),
            "Cargo.lock".to_string(),
        ];
        assert_eq!(unmentioned_files(task, &changed), vec!["src/c.rs"]);
    }

    #[test]
    fn test_unexpected_subjects() {
        let task = "Commit message: `feat: add x`";
        let subjects = vec!["feat: add x".to_string(), "fix: y".to_string()];
        assert_eq!(unexpected_subjects(task, &subjects), vec!["fix: y"]);
    }

    #[test]
    fn test_unexpected_subjects_no_commit() {
        let task = "Just implement the feature and run the tests.";
        let subjects = vec!["feat: add x".to_string(), "fix: y".to_string()];
        assert!(unexpected_subjects(task, &subjects).is_empty());
    }

    #[test]
    fn test_build_none_task() {
        let checks = build(None, &[], &[], 0, 0, None);
        assert_eq!(
            checks.flags.first().map(|s| s.as_str()),
            Some("task file not found: scope not checked")
        );
    }

    #[test]
    fn test_build_outcome_gate_failed() {
        let checks = build(
            Some("mentions a.rs"),
            &["a.rs".to_string()],
            &[],
            0,
            0,
            Some("gate_failed"),
        );
        assert!(checks
            .flags
            .contains(&"outcome gate_failed: review in depth".to_string()));
    }

    #[test]
    fn test_build_12_unmentioned_files() {
        let changed: Vec<String> = (0..12).map(|i| format!("f{i}.rs")).collect();
        let checks = build(Some("mentions none of them"), &changed, &[], 0, 0, None);
        assert_eq!(checks.flags.len(), 1);
        let flag = &checks.flags[0];
        for i in 0..10 {
            assert!(flag.contains(&format!("f{i}.rs")));
        }
        assert!(!flag.contains("f10.rs"));
        assert!(!flag.contains("f11.rs"));
        assert!(flag.contains("(+2 more)"));
    }

    #[test]
    fn test_build_clean() {
        let task = "Files: `src/a.rs`\nCommit message: `feat: x`";
        let changed = vec!["src/a.rs".to_string()];
        let subjects = vec!["feat: x".to_string()];
        let checks = build(Some(task), &changed, &subjects, 0, 0, Some("verified"));
        assert!(checks.flags.is_empty());
    }

    #[test]
    fn test_build_host_cmds() {
        let checks = build(Some(""), &[], &[], 2, 0, None);
        assert!(checks
            .flags
            .contains(&"2 host command(s): see == host commands".to_string()));
    }

    #[test]
    fn test_ignored_lockfiles() {
        let task = "no files mentioned";
        let changed = vec![
            "Cargo.lock".to_string(),
            "uv.lock".to_string(),
            "package-lock.json".to_string(),
            "pnpm-lock.yaml".to_string(),
            "yarn.lock".to_string(),
            "poetry.lock".to_string(),
        ];
        assert!(unmentioned_files(task, &changed).is_empty());
    }

    #[test]
    fn test_build_outside_reads() {
        let checks = build(Some(""), &[], &[], 0, 3, None);
        assert!(checks.flags.contains(
            &"3 read(s) outside the repository: see == reads outside the repository".to_string()
        ));
    }
}