Something went wrong. Try again.
Play: parse coding-agent trajectories into phase trees (shift-reduce), measure what collapsing non-speech saves
Something went wrong. Try again.
traj-trees parse.py
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167"""Parse SWE-agent trajectories into trees with a tiny rule-based shift-reduce pass.
Tree: Task > Phase* > Step* (a Step = thought [speech] + action + observation)Phases: reproduce | locate | edit | verify | fix-loop(edit/verify iterations) | cleanup | submit | talk
The step classifier is plain rules here; the Holanarchy idea is to swap it for ajev-like (small model, option logprobs) later and compare against these labels."""import re, sys, json, collectionsimport pandas as pd
LOCATE = {"open", "search_dir", "search_file", "find_file", "find", "find.", "grep", "ls", "goto", "scroll_down", "scroll_up", "next_match", "cat", "pwd", "cd", "cd.."}RUN = {"python", "pytest", "bash", "flake8", "sh", "tox", "make", "node", "npm"}
CODE = re.compile(r"```\n?(.*?)```", re.S)OPEN_FILE = re.compile(r"\(Open file: ([^)]*)\)")
def split_ai(text): """-> (thought, command)""" blocks = CODE.findall(text) if not blocks: return text.strip(), "" cmd = blocks[-1].strip() thought = text[: text.rfind("```" + blocks[-1]) if ("```" + blocks[-1]) in text else len(text)] thought = CODE.sub("", text).strip() return thought, cmd
def is_repro(path): return bool(path) and re.search(r"(reproduce|repro|test_issue|bug)\w*\.(py|sh)", path) is not None
def raw_label(cmd, open_file): if not cmd: return "talk" head = cmd.split()[0] if head == "submit": return "submit" if head == "rm": return "cleanup" if head == "create": target = cmd.split()[1] if len(cmd.split()) > 1 else "" return "reproduce" if is_repro(target) else "edit" if head == "edit": return "reproduce" if is_repro(open_file) else "edit" if head in LOCATE: return "locate" # anything else that executes something: the repo's own CLI, python, tests... return "run"
def steps_of(traj): msgs = [m for m in traj if m["role"] in ("ai", "user")] # first user message is the issue issue = msgs[0]["text"] if msgs and msgs[0]["role"] == "user" else "" steps, open_file = [], None i = 1 while i < len(msgs): m = msgs[i] if m["role"] != "ai": i += 1 continue thought, cmd = split_ai(m["text"]) obs = msgs[i + 1]["text"] if i + 1 < len(msgs) and msgs[i + 1]["role"] == "user" else "" lab = raw_label(cmd, open_file) mo = OPEN_FILE.search(obs or "") if mo and mo.group(1) not in ("n/a", ""): open_file = mo.group(1) steps.append(dict(thought=thought, cmd=cmd, obs=obs, label=lab)) i += 2 return issue, steps
def contextual(steps): """Shift pass: decide what each 'run' means from what came before it.""" edited = False for s in steps: if s["label"] == "edit": edited = True if s["label"] == "run": s["label"] = "verify" if edited else "reproduce" return steps
def reduce(steps): """Reduce pass 1: runs of equal labels -> phases. Pass 2: (edit verify)+ -> fix-loop.""" phases = [] for s in steps: if phases and phases[-1]["label"] == s["label"]: phases[-1]["steps"].append(s) else: phases.append(dict(label=s["label"], steps=[s])) out, i = [], 0 while i < len(phases): j = i while j + 1 < len(phases) and phases[j]["label"] == "edit" and phases[j + 1]["label"] == "verify": j += 2 iters = (j - i) // 2 if iters >= 2: # at least two edit->verify rounds out.append(dict(label="fix-loop", iterations=iters, children=phases[i:j])) i = j else: out.append(phases[i]) i += 1 return out
def sig(tree): abbrev = dict(reproduce="R", locate="L", edit="E", verify="V", submit="S", cleanup="C", talk="T") s = [] for p in tree: s.append(f"F{p['iterations']}" if p["label"] == "fix-loop" else abbrev[p["label"]]) return "".join(s)
def render(issue, tree, width=90): def step_line(st): t = (st["thought"].splitlines() or [""])[0][:width] return f" - [{st['cmd'].splitlines()[0][:40] if st['cmd'] else '(no action)'}] {t}" lines = ["Task: " + (issue.split("ISSUE:")[-1].strip().splitlines() or [""])[0][:width]] for p in tree: if p["label"] == "fix-loop": lines.append(f" fix-loop x{p['iterations']}") for c in p["children"]: lines.append(f" {c['label']} ({len(c['steps'])})") lines += [" " + step_line(st) for st in c["steps"]] else: lines.append(f" {p['label']} ({len(p['steps'])})") lines += [step_line(st) for st in p["steps"]] return "\n".join(lines)
def sizes(steps, tree): full = sum(len(s["thought"]) + len(s["cmd"]) + len(s["obs"]) for s in steps) # collapse non-speech: keep thoughts + one-line command, drop observations speech = sum(len(s["thought"]) + len((s["cmd"].splitlines() or [""])[0]) + 12 for s in steps) # phase-level: keep only the first thought of each phase (as its label/gist) def phase_nodes(t): for p in t: if p["label"] == "fix-loop": yield from phase_nodes(p["children"]) else: yield p phase = sum(len(p["steps"][0]["thought"]) + 20 for p in phase_nodes(tree)) return full, speech, phase
if __name__ == "__main__": df = pd.read_parquet(sys.argv[1]) n = int(sys.argv[2]) if len(sys.argv) > 2 else len(df) rows = [] for _, r in df.head(n).iterrows(): issue, steps = steps_of(r.trajectory) if not steps: continue tree = reduce(contextual(steps)) full, speech, phase = sizes(steps, tree) rows.append(dict(id=r.instance_id, model=r.model_name, resolved=bool(r.target), nsteps=len(steps), nphases=len(tree), sig=sig(tree), loops=sum(p.get("iterations", 0) for p in tree), full=full, speech=speech, phase=phase)) pd.DataFrame(rows).to_csv("trees.csv", index=False) print(len(rows), "trajectories -> trees.csv")