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__";
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()
)
}
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"]);
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()
};
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());
}
}
}
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());
}
"attribute" | "subscript" => {}
_ => {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
bind_pattern(child, source, bound);
}
}
}
}
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") {
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(')');
}
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"
);
}
}