agengo 0.3.0

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
use crate::{
    adapter::{invoke_measured, Action},
    context,
    contract::{array_or_empty, criteria, owns, quality, string_or_empty, text},
    engine::{id, verify_reply, Engine},
    failure::DuplicatesFound,
    process::{run_with_limit, Repo},
};
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
use std::{
    collections::{BTreeMap, BTreeSet},
    path::Path,
    process::Command,
    time::Instant,
};
use tree_sitter::{Node, Parser};

const QUALITY_TASK: &str = "__quality__";

/// Summarize duplicate groups for people and agents.
pub fn describe(groups: &[Value]) -> String {
    let examples = groups
        .iter()
        .take(3)
        .map(|group| {
            array_or_empty(&group["locations"])
                .iter()
                .take(4)
                .map(|item| {
                    format!(
                        "{}:{} ({})",
                        string_or_empty(&item["path"]),
                        item["line"],
                        string_or_empty(&item["name"])
                    )
                })
                .collect::<Vec<_>>()
                .join(" = ")
        })
        .collect::<Vec<_>>()
        .join(". ");
    format!(
        "Found {} new or growing group(s) of duplicated Python functions. {examples}",
        groups.len()
    )
}

/// Run the duplicate audit between two commits and record it as an attempt.
///
/// In blocking mode a finding or an unparsable changed file is recorded as
/// `failed` and returned as an error. Otherwise it is recorded as `warning`
/// and the run continues.
pub fn duplicate_audit(
    engine: &Engine,
    base: &str,
    head: &str,
    ignore: &Value,
    task: Option<&str>,
    role: &str,
    block: bool,
) -> Result<()> {
    let attempt = id();
    let request = json!({"attempt_id":attempt,"base":base,"head":head,"ignore_paths":ignore,
        "plan_revision":engine.settings.revision,"mode":if block {"block"} else {"warn"}});
    engine.attempt(&attempt, task, role, &request)?;
    let started = Instant::now();
    let outcome = duplicates(engine.repo, base, head, ignore, engine.timeout());
    engine.store.record_duration(&attempt, started.elapsed())?;
    let problem = if block { "failed" } else { "warning" };
    match outcome {
        Ok(groups) if groups.is_empty() => engine.result(&attempt, "ok", &json!({"duplicates":[]})),
        Ok(groups) => {
            let error = describe(&groups);
            engine.result(
                &attempt,
                problem,
                &json!({"duplicates":groups,"error":error}),
            )?;
            if block {
                return Err(DuplicatesFound(error).into());
            }
            Ok(())
        }
        Err(error) => {
            engine.result(
                &attempt,
                problem,
                &json!({"duplicates":[],"error":format!("{error:#}")}),
            )?;
            if block {
                return Err(error);
            }
            Ok(())
        }
    }
}

pub fn verify(engine: &Engine, path: &Path, commit: &str) -> Result<()> {
    let policy = quality(&engine.plan)?;
    engine.checks(
        array_or_empty(&policy["checks"]),
        path,
        "quality_command",
        None,
    )?;
    let base = string_or_empty(&engine.run["base"]);
    let mode = string_or_empty(&policy["python_duplicates"]);
    if mode != "off" {
        duplicate_audit(
            engine,
            base,
            commit,
            &policy["ignore_paths"],
            None,
            "quality_duplicates",
            mode == "block",
        )?;
    }
    let task = json!({"id":QUALITY_TASK,"goal":"Review the integrated diff for reuse and quality.",
    "owns":engine.repo.changed(base,commit)?,"verify":[],"acceptance":[
        {"id":"AC-REUSE","text":"Reuse shared implementations and avoid duplicating behavior across the integrated changes."},
        {"id":"AC-INTEGRATION","text":"Inspect the combined changes for behavior regressions and gaps in acceptance checks."}
    ]});
    let packet = context::packet(engine.store, engine.id, &task)?;
    if policy["review"] == true || !array_or_empty(&packet["open_findings"]).is_empty() {
        review(engine, commit, &policy, task, packet)?;
    }
    Ok(())
}

fn review(
    engine: &Engine,
    commit: &str,
    policy: &Value,
    task: Value,
    mut packet: Value,
) -> Result<()> {
    let attempt = id();
    let path = engine.workspace("quality-review", &attempt);
    packet["decisions"] =
        context::packet(engine.store, engine.id, &json!({"id":null,"acceptance":[]}))?["decisions"]
            .clone();
    packet["verified_commands"] = json!(array_or_empty(&engine.plan["final_verify"])
        .iter()
        .chain(array_or_empty(&policy["checks"]))
        .collect::<Vec<_>>());
    packet["work_packages"] = json!(array_or_empty(&engine.plan["tasks"]).iter().map(|task|
        Ok(json!({"id":task["id"],"goal":task["goal"],"owns":task["owns"],"acceptance":criteria(task)?})))
        .collect::<Result<Vec<Value>>>()?);
    let request = json!({"schema_version":1,"message_id":attempt,"attempt_id":attempt,"run_id":engine.id,
        "plan_revision":engine.settings.revision,"role":"review","review_scope":"integrated",
        "project_goal":engine.plan["goal"],"base":engine.run["base"],"head":commit,"integration_sha":commit,
        "worktree":path,"feedback":null,"decisions":[],"task":task,"context":packet});
    engine.attempt(&attempt, None, "quality_review", &request)?;
    let mut report = json!({});
    let mut changes = (Vec::new(), Vec::new());
    let started = Instant::now();
    let mut usage = None;
    let outcome = (|| -> Result<()> {
        engine.repo.worktree(&path, commit, None)?;
        let invocation = invoke_measured(
            engine.settings.agent.as_deref(),
            &request,
            &path,
            engine.timeout(),
            &engine.profile,
        );
        usage = invocation.usage;
        let result = invocation.reply?;
        report["review"] = result.clone();
        verify_reply(&request, &result)?;
        let status = text(&result["status"], "integrated review status")?;
        let summary = text(&result["summary"], "integrated review summary")?;
        if result["head"] != commit || engine.repo.clean_head(&path, &BTreeSet::new())? != commit {
            bail!("integrated review must attest the delivery commit in a clean worktree");
        }
        if status == "blocked" {
            if result["blocker"]["kind"] == "action" {
                return Err(Action {
                    message: summary.into(),
                    recommendation: text(&result["blocker"]["recommendation"], "review action")?
                        .into(),
                    reason: text(&result["blocker"]["reason"], "review action reason")?.into(),
                }
                .into());
            }
            bail!("The whole-branch review is blocked. {summary}");
        }
        if !matches!(status, "pass" | "changes_requested") {
            bail!("invalid integrated review verdict");
        }
        let (findings, resolutions) = context::changes(&request, &result)?;
        if status == "changes_requested" {
            let remaining = array_or_empty(&request["context"]["open_findings"])
                .iter()
                .filter(|item| {
                    !resolutions.iter().any(|resolved| {
                        resolved["status"] == "resolved" && resolved["id"] == item["id"]
                    })
                })
                .chain(&findings)
                .collect::<Vec<_>>();
            if remaining.is_empty() {
                bail!("integrated review changes_requested requires concrete findings");
            }
            let examples = remaining
                .iter()
                .take(3)
                .map(|item| {
                    format!(
                        "{} — {}",
                        string_or_empty(&item["location"]),
                        string_or_empty(&item["required_outcome"])
                    )
                })
                .collect::<Vec<_>>()
                .join(". ");
            let error = format!(
                "The whole-branch review requested changes for {} finding(s). {examples}",
                remaining.len()
            );
            report["findings"] = json!(findings);
            report["finding_resolutions"] = json!(resolutions);
            changes = (findings, resolutions);
            bail!("{error}");
        }
        report["findings"] = json!(findings);
        report["finding_resolutions"] = json!(resolutions);
        changes = (findings, resolutions);
        Ok(())
    })();
    let elapsed = started.elapsed();
    engine.discard(&path);
    if let Err(error) = &outcome {
        report["error"] = json!(error.to_string());
    }
    engine.store.atomic(|| {
        engine.store.record_duration(&attempt, elapsed)?;
        engine.store.record_usage(&attempt, usage.as_ref())?;
        context::save(engine.store, &request, changes.0, changes.1)?;
        engine.result(
            &attempt,
            if outcome.is_ok() { "ok" } else { "failed" },
            &report,
        )
    })?;
    outcome
}

fn python_tree(repo: &Repo, commit: &str, ignore: &Value) -> Result<BTreeMap<String, String>> {
    let output = repo.git(&["ls-tree", "-rz", commit])?;
    Ok(output
        .split('\0')
        .filter_map(|entry| {
            let (meta, path) = entry.split_once('\t')?;
            let mut meta = meta.split(' ');
            let mode = meta.next()?;
            let kind = meta.next()?;
            let sha = meta.next()?;
            (kind == "blob"
                && matches!(mode, "100644" | "100755")
                && path.ends_with(".py")
                && !owns(path, ignore))
            .then(|| (path.to_owned(), sha.to_owned()))
        })
        .collect())
}

#[derive(Clone)]
struct Function {
    fingerprint: String,
    name: String,
    line: usize,
}

fn duplicates(
    repo: &Repo,
    base: &str,
    head: &str,
    ignore: &Value,
    timeout: u64,
) -> Result<Vec<Value>> {
    let before = python_tree(repo, base, ignore)?;
    let after = python_tree(repo, head, ignore)?;
    if before == after {
        return Ok(Vec::new());
    }
    let names: BTreeMap<_, _> = before
        .iter()
        .chain(&after)
        .map(|(path, sha)| (sha.as_str(), path.as_str()))
        .collect();
    let changed: BTreeSet<_> = after
        .iter()
        .filter(|(path, sha)| before.get(*path) != Some(*sha))
        .map(|(_, sha)| sha.as_str())
        .collect();
    let mut parser = Parser::new();
    parser.set_language(&tree_sitter_python::LANGUAGE.into())?;
    let mut parsed = BTreeMap::new();
    let input = names
        .keys()
        .map(|sha| format!("{sha}\n"))
        .collect::<String>();
    let mut command = Command::new("git");
    command
        .current_dir(&repo.root)
        .args(["cat-file", "--batch"]);
    // Blob data needs a larger allowance than terminal output.
    let output = run_with_limit(
        &mut command,
        Some(input.as_bytes()),
        Some(timeout),
        128 * 1024 * 1024,
    )?;
    if !output.status.success() {
        bail!("cannot load Git blobs for duplicate review");
    }
    let mut data = output.stdout.as_slice();
    for (sha, path) in names {
        let end = data
            .iter()
            .position(|byte| *byte == b'\n')
            .context("truncated Git blob header")?;
        let header: Vec<_> = std::str::from_utf8(&data[..end])?.split(' ').collect();
        if header.len() != 3 || header[0] != sha || header[1] != "blob" {
            bail!("unexpected Git blob response for {sha}");
        }
        let len = header[2].parse::<usize>()?;
        data = &data[end + 1..];
        let source = data.get(..len).context("truncated Git blob response")?;
        if data.get(len) != Some(&b'\n') {
            bail!("truncated Git blob response for {sha}");
        }
        let tree = parser
            .parse(source, None)
            .context("could not parse Python source")?;
        if tree.root_node().has_error() {
            if changed.contains(sha) {
                bail!("could not parse {path} for Python duplicate review");
            }
        } else {
            let mut functions = Vec::new();
            collect(tree.root_node(), source, &mut functions);
            parsed.insert(sha, functions);
        }
        data = &data[len + 1..];
    }
    let mut baseline = BTreeMap::<&str, usize>::new();
    for sha in before.values() {
        if let Some(functions) = parsed.get(sha.as_str()) {
            for function in functions {
                *baseline.entry(&function.fingerprint).or_default() += 1;
            }
        }
    }
    let mut groups = BTreeMap::<&str, Vec<Value>>::new();
    for (path, sha) in &after {
        if let Some(functions) = parsed.get(sha.as_str()) {
            for function in functions {
                groups
                    .entry(&function.fingerprint)
                    .or_default()
                    .push(json!({"path":path,"line":function.line,"name":function.name}));
            }
        }
    }
    Ok(groups
        .into_iter()
        .filter_map(|(key, locations)| {
            let count = baseline.get(key).copied().unwrap_or(0);
            (locations.len() > count.max(1))
                .then(|| json!({"baseline_count":count,"locations":locations}))
        })
        .collect())
}

fn collect(node: Node<'_>, source: &[u8], found: &mut Vec<Function>) {
    if let ("function_definition", Some(name), Some(body)) = (
        node.kind(),
        node.child_by_field_name("name"),
        node.child_by_field_name("body"),
    ) {
        let mut cursor = body.walk();
        let mut statements: Vec<_> = body
            .named_children(&mut cursor)
            .filter(|node| node.kind() != "comment")
            .collect();
        if statements.first().is_some_and(|node| {
            node.kind() == "expression_statement"
                && node
                    .named_child(0)
                    .is_some_and(|child| matches!(child.kind(), "string" | "concatenated_string"))
        }) {
            statements.remove(0);
        }
        let boilerplate = statements.len() == 1 && trivial(statements[0], source)
            || statements.iter().all(|statement| field_store(*statement));
        if !statements.is_empty() && !boilerplate {
            let mut fingerprint = if node.child(0).is_some_and(|first| first.kind() == "async") {
                "async".to_string()
            } else {
                "sync".into()
            };
            // Local names are numbered by first use, so renaming a parameter
            // or a local variable does not hide a copied function.
            let mut bound = BTreeSet::new();
            if let Some(parameters) = node.child_by_field_name("parameters") {
                bind_parameters(parameters, source, &mut bound);
            }
            for statement in &statements {
                bind_targets_in(*statement, source, &mut bound);
            }
            let mut renamer = Renamer {
                bound,
                order: BTreeMap::new(),
            };
            for statement in statements {
                fingerprint_node(statement, source, &mut fingerprint, &mut renamer);
            }
            found.push(Function {
                fingerprint,
                name: String::from_utf8_lossy(&source[name.byte_range()]).into(),
                line: node.start_position().row + 1,
            });
        }
    }
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        collect(child, source, found);
    }
}

struct Renamer {
    bound: BTreeSet<Vec<u8>>,
    order: BTreeMap<Vec<u8>, usize>,
}

fn span<'s>(node: Node<'_>, source: &'s [u8]) -> &'s [u8] {
    &source[node.byte_range()]
}

fn bind_parameters(parameters: Node<'_>, source: &[u8], bound: &mut BTreeSet<Vec<u8>>) {
    let mut cursor = parameters.walk();
    for parameter in parameters.named_children(&mut cursor) {
        let name = match parameter.kind() {
            "identifier" => Some(parameter),
            "default_parameter" | "typed_default_parameter" => {
                parameter.child_by_field_name("name")
            }
            "typed_parameter" | "list_splat_pattern" | "dictionary_splat_pattern" => {
                let mut inner = parameter.walk();
                let found = parameter
                    .named_children(&mut inner)
                    .find(|child| child.kind() == "identifier");
                found
            }
            _ => None,
        };
        if let Some(name) = name.filter(|name| name.kind() == "identifier") {
            bound.insert(span(name, source).to_vec());
        }
    }
}

/// Collect names bound by assignment-like targets, without entering nested
/// scopes.
fn bind_targets_in(node: Node<'_>, source: &[u8], bound: &mut BTreeSet<Vec<u8>>) {
    if matches!(
        node.kind(),
        "function_definition" | "class_definition" | "lambda"
    ) {
        return;
    }
    let target = match node.kind() {
        "assignment" | "augmented_assignment" | "for_statement" | "for_in_clause" => {
            node.child_by_field_name("left")
        }
        "named_expression" => node.child_by_field_name("name"),
        "as_pattern" => node.child_by_field_name("alias"),
        _ => None,
    };
    if let Some(target) = target {
        bind_pattern(target, source, bound);
    }
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        bind_targets_in(child, source, bound);
    }
}

fn bind_pattern(node: Node<'_>, source: &[u8], bound: &mut BTreeSet<Vec<u8>>) {
    match node.kind() {
        "identifier" => {
            bound.insert(span(node, source).to_vec());
        }
        // `self.x = ...` and `items[0] = ...` bind no new local name.
        "attribute" | "subscript" => {}
        _ => {
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                bind_pattern(child, source, bound);
            }
        }
    }
}

/// `self.name = name` style statements that only copy values into fields.
fn field_store(statement: Node<'_>) -> bool {
    let Some(assignment) = statement
        .named_child(0)
        .filter(|_| statement.kind() == "expression_statement")
        .filter(|child| child.kind() == "assignment")
    else {
        return false;
    };
    let left = assignment.child_by_field_name("left");
    let right = assignment.child_by_field_name("right");
    left.is_some_and(|left| left.kind() == "attribute")
        && right.is_some_and(|right| {
            matches!(
                right.kind(),
                "identifier"
                    | "attribute"
                    | "string"
                    | "integer"
                    | "float"
                    | "true"
                    | "false"
                    | "none"
                    | "list"
                    | "dictionary"
                    | "tuple"
                    | "set"
            ) && (right.named_child_count() == 0 || matches!(right.kind(), "attribute" | "string"))
        })
}

fn trivial(node: Node<'_>, source: &[u8]) -> bool {
    let simple = |value: Node<'_>| {
        matches!(
            value.kind(),
            "string"
                | "concatenated_string"
                | "integer"
                | "float"
                | "true"
                | "false"
                | "none"
                | "ellipsis"
        )
    };
    match node.kind() {
        "pass_statement" => true,
        "expression_statement" => node.named_child(0).is_some_and(simple),
        "return_statement" => node.named_child(0).is_none_or(|value| {
            simple(value) || matches!(value.kind(), "identifier" | "attribute")
        }),
        "raise_statement" => node.named_child(0).is_some_and(|value| {
            let exception = value.child_by_field_name("function").unwrap_or(value);
            &source[exception.byte_range()] == b"NotImplementedError"
        }),
        _ => false,
    }
}

fn fingerprint_node(node: Node<'_>, source: &[u8], output: &mut String, renamer: &mut Renamer) {
    if node.kind() == "comment" {
        return;
    }
    if node.kind() == "parenthesized_expression" && node.named_child_count() == 1 {
        if let Some(inner) = node.named_child(0) {
            fingerprint_node(inner, source, output, renamer);
            return;
        }
    }
    output.push('(');
    output.push_str(node.kind());
    if node.child_count() == 0 && node.is_named() {
        output.push(' ');
        let token = span(node, source);
        if matches!(node.kind(), "string_start" | "string_end") {
            // Quote style changes the token spelling, while prefixes and literal content carry semantics.
            let normalized: Vec<_> = token
                .iter()
                .map(|byte| if *byte == b'\'' { b'"' } else { *byte })
                .collect();
            output.push_str(&format!("{normalized:?}"));
        } else if node.kind() == "identifier" && is_local_use(node) && renamer.bound.contains(token)
        {
            let next = renamer.order.len();
            let index = *renamer.order.entry(token.to_vec()).or_insert(next);
            output.push_str(&format!("${index}"));
        } else {
            output.push_str(&format!("{token:?}"));
        }
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        fingerprint_node(child, source, output, renamer);
    }
    output.push(')');
}

/// Field names after a dot and keyword-argument names are part of the API,
/// not local variables, even when spelled like one.
fn is_local_use(node: Node<'_>) -> bool {
    let Some(parent) = node.parent() else {
        return true;
    };
    let field = |name| parent.child_by_field_name(name) == Some(node);
    !((parent.kind() == "attribute" && field("attribute"))
        || (parent.kind() == "keyword_argument" && field("name")))
}

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

    fn functions(source: &str) -> Vec<Function> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_python::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();
        let mut found = Vec::new();
        collect(tree.root_node(), source.as_bytes(), &mut found);
        found
    }

    fn same(left: &str, right: &str) -> bool {
        let (left, right) = (functions(left), functions(right));
        assert_eq!(
            (left.len(), right.len()),
            (1, 1),
            "each sample has one checked function"
        );
        left[0].fingerprint == right[0].fingerprint
    }

    #[test]
    fn renamed_locals_and_parameters_still_match() {
        assert!(same(
            "def a(value):\n    cleaned = value.strip()\n    return cleaned.lower()\n",
            "def b(text):\n    out = text.strip()\n    return out.lower()\n",
        ));
    }

    #[test]
    fn different_calls_attributes_and_keywords_differ() {
        assert!(!same(
            "def a(x):\n    return load(x)\n",
            "def b(x):\n    return save(x)\n"
        ));
        assert!(!same(
            "def a(self):\n    return self.w * 2\n",
            "def b(self):\n    return self.h * 2\n"
        ));
        assert!(!same(
            "def a(x):\n    return f(x, mode=x)\n",
            "def b(x):\n    return f(x, kind=x)\n"
        ));
    }

    #[test]
    fn field_store_boilerplate_is_ignored() {
        let source = "class A:\n    def __init__(self, name, size=1):\n        self.name = name\n        self.size = size\n        self.items = []\n";
        assert!(functions(source).is_empty());
    }

    #[test]
    fn nested_scopes_keep_their_own_names() {
        let left =
            functions("def a(x):\n    def inner(y):\n        return y + 1\n    return inner(x)\n");
        let right =
            functions("def b(x):\n    def inner(y):\n        return y + 2\n    return inner(x)\n");
        assert_eq!((left.len(), right.len()), (2, 2));
        assert_ne!(
            left[0].fingerprint, right[0].fingerprint,
            "outer bodies differ"
        );
        assert_ne!(
            left[1].fingerprint, right[1].fingerprint,
            "inner bodies differ"
        );
    }
}