Skip to content

The agent that grows with you

refactor(agent/verify): tighten evidence classification, recipe builders, and runner phase bookkeeping

Teknium8873f7abc76d
diff --git a/agent/verification_evidence.py b/agent/verification_evidence.py
index ad043bde1fb..a73f0801fa0 100644
--- a/agent/verification_evidence.py
+++ b/agent/verification_evidence.py
@@ -316,8 +316,7 @@ def _is_under(token: str, base: str | Path | None) -> bool:
path = Path(token).expanduser()
if not path.is_absolute():
return False
- resolved = path.resolve()
- base_path = Path(base).expanduser().resolve()
+ resolved, base_path = path.resolve(), Path(base).expanduser().resolve()
return resolved == base_path or base_path in resolved.parents
except Exception:
return False
@@ -342,11 +341,9 @@ def _ad_hoc_script_args(tokens: list[str], root: str | Path | None) -> Optional[
if command in _INTERPRETERS:
# Skip interpreter flags; the first positional must be the script.
for idx, token in enumerate(candidate_tokens[1:], start=1):
- if token == "--":
- continue
if _is_temp_script_path(token, root):
return candidate_tokens[idx + 1:]
- if not token.startswith("-"):
+ if token != "--" and not token.startswith("-"):
return None
return None
@@ -443,19 +440,16 @@ def classify_verification_command(
verify_commands = list(facts.get("verifyCommands") or [])
match = _find_canonical_match(command, verify_commands, int(exit_code))
- is_ad_hoc = False
- if match is None:
- ad_hoc_args = None if verify_commands else _find_ad_hoc_match(command, facts.get("root"), int(exit_code))
- if ad_hoc_args is None:
+ if match is not None:
+ canonical, trailing_args = match
+ kind = _kind_for_command(canonical)
+ scope = "targeted" if any(map(_looks_like_target, trailing_args)) else "full"
+ else:
+ if verify_commands or _find_ad_hoc_match(command, facts.get("root"), int(exit_code)) is None:
return None
- is_ad_hoc = True
- match = ("ad-hoc verification script", ad_hoc_args)
-
- canonical, trailing_args = match
+ canonical, kind, scope = "ad-hoc verification script", "ad_hoc", "targeted"
return VerificationEvidence(
- command=command, canonical_command=canonical,
- kind="ad_hoc" if is_ad_hoc else _kind_for_command(canonical),
- scope="targeted" if is_ad_hoc or any(map(_looks_like_target, trailing_args)) else "full",
+ command=command, canonical_command=canonical, kind=kind, scope=scope,
status="passed" if int(exit_code) == 0 else "failed", exit_code=int(exit_code),
cwd=str(Path(cwd or ".").resolve()), root=_root_for(facts, cwd),
session_id=str(session_id or "default"), output_summary=_summarize_output(output),
@@ -493,8 +487,8 @@ def record_verify_run(
def _insert_evidence(evidence: VerificationEvidence) -> dict[str, Any]:
"""Insert a classified evidence row and repoint the workspace state."""
created_at = _utc_now()
+ e = evidence
with _DB_LOCK, _transaction() as conn:
- e = evidence
cur = conn.execute(
"INSERT INTO verification_events("
" created_at, session_id, cwd, root, command, canonical_command,"
@@ -514,12 +508,12 @@ def _insert_evidence(evidence: VerificationEvidence) -> dict[str, Any]:
" last_event_id = excluded.last_event_id,"
" last_edit_at = NULL,"
" changed_paths_json = '[]'",
- (evidence.session_id, evidence.root, event_id),
+ (e.session_id, e.root, event_id),
)
- _prune_old_events(conn, session_id=evidence.session_id, root=evidence.root)
+ _prune_old_events(conn, session_id=e.session_id, root=e.root)
conn.commit()
- return {"id": event_id, **evidence.__dict__, "created_at": created_at}
+ return {"id": event_id, **e.__dict__, "created_at": created_at}
def mark_workspace_edited(
@@ -540,9 +534,9 @@ def mark_workspace_edited(
"SELECT changed_paths_json FROM verification_state WHERE session_id = ? AND root = ?",
(sid, root),
).fetchone()
- existing = set(_load_changed_paths(row["changed_paths_json"])) if row is not None else set()
# Merge with what was already recorded, bounded to the last 200 paths.
- merged = sorted(existing | set(changed_paths))[-200:]
+ existing = _load_changed_paths(row["changed_paths_json"]) if row is not None else []
+ merged = sorted(set(existing) | set(changed_paths))[-200:]
conn.execute(
"INSERT INTO verification_state("
" session_id, root, last_event_id, last_edit_at, changed_paths_json"
diff --git a/agent/verify/recipes.py b/agent/verify/recipes.py
index 49a8b0c6dc0..d7f90440baa 100644
--- a/agent/verify/recipes.py
+++ b/agent/verify/recipes.py
@@ -63,19 +63,16 @@ class Recipe:
kind = "unknown"
start = raw.get("start") or raw.get("startCommand")
- start = start.strip() if isinstance(start, str) and start.strip() else None
-
port_raw = raw.get("port") or raw.get("startPort")
if isinstance(port_raw, str) and port_raw.strip().isdigit():
port_raw = int(port_raw.strip())
- port = port_raw if isinstance(port_raw, int) and 0 < port_raw < 65536 else None
-
readiness = raw.get("readinessPath") or raw.get("readiness_path") or "/"
- if not (isinstance(readiness, str) and readiness.startswith("/")):
- readiness = "/"
return cls(
- name=name.strip(), kind=kind.strip(), start=start, port=port, readiness_path=readiness,
+ name=name.strip(), kind=kind.strip(),
+ start=start.strip() if isinstance(start, str) and start.strip() else None,
+ port=port_raw if isinstance(port_raw, int) and 0 < port_raw < 65536 else None,
+ readiness_path=readiness if isinstance(readiness, str) and readiness.startswith("/") else "/",
bootstrap=_as_strings(raw.get("bootstrap") or raw.get("installCommands")),
build=_as_strings(raw.get("build") or raw.get("buildCommands")),
test=_as_strings(raw.get("test") or raw.get("testCommands")),
@@ -158,20 +155,15 @@ def _detect_node_recipe(root: Path, pkg: dict[str, Any]) -> Recipe:
("node", "Node.js app", None),
)
- start_script = next((s for s in ("dev", "start") if scripts.get(s)), None)
- start = port = None
- if start_script:
- start = _script_runner(package_manager, start_script)
- port = _infer_port_from_command(scripts[start_script]) or default_port
-
- def runners(names: tuple[str, ...]) -> list[str]:
+ def runners(*names: str) -> list[str]:
return _dedupe([_script_runner(package_manager, s) for s in names if scripts.get(s)])
+ start_script = next((s for s in ("dev", "start") if scripts.get(s)), None)
return Recipe(
- name=label, kind=kind, start=start, port=port,
+ name=label, kind=kind, start=runners(start_script)[0] if start_script else None,
+ port=(_infer_port_from_command(scripts[start_script]) or default_port) if start_script else None,
bootstrap=[_NODE_INSTALL.get(package_manager or "", "npm install")],
- build=runners(("build", "typecheck")),
- test=runners(("test", "check", "lint")),
+ build=runners("build", "typecheck"), test=runners("test", "check", "lint"),
evidence=_dedupe([
"Detected package.json",
f"Package manager: {package_manager}" if package_manager else None,
@@ -201,10 +193,8 @@ def _detect_python_recipe(root: Path) -> Recipe | None:
return Recipe(
name="Django app", kind="django", bootstrap=[install], test=["python manage.py test"],
start="python manage.py runserver 0.0.0.0:8000", port=8000,
- evidence=_dedupe([
- "Detected manage.py" if manage_py else "Detected Django dependency",
- "Detected pyproject.toml" if pyproject else None,
- ]),
+ evidence=["Detected manage.py" if manage_py else "Detected Django dependency"]
+ + (["Detected pyproject.toml"] if pyproject else []),
)
if "fastapi" in lower or "uvicorn" in lower:
app_module = (_first_existing(root, ("main.py", "app.py")) or "main.py").removesuffix(".py") + ":app"
@@ -247,10 +237,7 @@ def _detect_rust_recipe(root: Path) -> Recipe | None:
def _detect_java_recipe(root: Path) -> Recipe | None:
if (root / "pom.xml").exists():
- return Recipe(
- name="Maven project", kind="maven", build=["mvn package"], test=["mvn test"],
- evidence=["Detected pom.xml"],
- )
+ return Recipe(name="Maven project", kind="maven", build=["mvn package"], test=["mvn test"], evidence=["Detected pom.xml"])
if _first_existing(root, ("build.gradle", "build.gradle.kts")):
gradle = "./gradlew" if (root / "gradlew").exists() else "gradle"
return Recipe(
diff --git a/agent/verify/runner.py b/agent/verify/runner.py
index 63bf73ae977..bf2963e5f88 100644
--- a/agent/verify/runner.py
+++ b/agent/verify/runner.py
@@ -98,16 +98,13 @@ def _run_phase_command(
on_output: Callable[[str], None] | None = None,
) -> PhaseResult:
started = time.monotonic()
- timed_out = False
try:
proc = subprocess.run(command, cwd=str(root), timeout=timeout, **_SUBPROCESS_KW)
- output = proc.stdout or ""
- exit_code: int | None = proc.returncode
+ output, exit_code, timed_out = proc.stdout or "", proc.returncode, False
except subprocess.TimeoutExpired as exc:
raw = exc.output
output = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else (raw or "")
- exit_code = None
- timed_out = True
+ exit_code, timed_out = None, True
duration = time.monotonic() - started
if on_output and output:
on_output(output)