|
| 1 | +"""#4447: a code-only ``--update`` must reach the merge with this run's AST in it. |
| 2 | +
|
| 3 | +The ``--update`` runbook says what the agent does when ``code_only`` is True. This test |
| 4 | +reads that paragraph from the RENDERED skill, runs the blocks the paragraph names (Part A, |
| 5 | +plus the Part B fast path and Part C only if it names them), then runs the merge and checks |
| 6 | +what came out. The route is not hard-coded: a paragraph that names too little fails here, |
| 7 | +which is the bug (Part A writes only ``.graphify_ast.json``; the merge reads |
| 8 | +``.graphify_extract.json``). |
| 9 | +
|
| 10 | +Hosts: the 14 generated skills share one set of anchors (windows runs its PowerShell |
| 11 | +here-string bodies through the interpreter on stdin: it tests the Python and the step order, |
| 12 | +not PowerShell quoting). aider and devin are monoliths with their own anchors; neither update |
| 13 | +section writes ``.graphify_detect.json``, so the test seeds it for them. |
| 14 | +""" |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import json |
| 18 | +import os |
| 19 | +import re |
| 20 | +import subprocess |
| 21 | +import sys |
| 22 | +from dataclasses import dataclass |
| 23 | +from pathlib import Path |
| 24 | + |
| 25 | +import pytest |
| 26 | + |
| 27 | +REPO_ROOT = Path(__file__).resolve().parent.parent |
| 28 | +if str(REPO_ROOT) not in sys.path: |
| 29 | + sys.path.insert(0, str(REPO_ROOT)) |
| 30 | + |
| 31 | +from tools.skillgen import gen # noqa: E402 |
| 32 | + |
| 33 | +STALE = "stale_semantic_label" |
| 34 | + |
| 35 | + |
| 36 | +@dataclass(frozen=True) |
| 37 | +class Anchors: |
| 38 | + """Where a host keeps the blocks the code-only paragraph can name.""" |
| 39 | + |
| 40 | + prefix: str # directory of the .graphify_*.json files, relative to the project |
| 41 | + part_a: str |
| 42 | + fast_path: str # anchor of the block that writes the empty semantic file (a host may have none) |
| 43 | + part_c: str |
| 44 | + merge: str |
| 45 | + |
| 46 | + |
| 47 | +_AST = "graphify_ast.json').write_text(json.dumps(result" |
| 48 | +_FAST = "graphify_semantic.json').write_text(json.dumps({'nodes':[]" |
| 49 | +_PART_C = "graphify_extract.json').write_text(json.dumps(merged" |
| 50 | + |
| 51 | +SHARED = Anchors("graphify-out/", _AST, _FAST, _PART_C, "build_merge(") |
| 52 | +DEVIN = Anchors("graphify-out/", _AST, _FAST, _PART_C, "G_existing.update(") |
| 53 | +AIDER = Anchors("", _AST, _FAST, _PART_C, "G_existing.update(") # cwd-relative files |
| 54 | + |
| 55 | +SHARED_HOSTS = ["agents", "amp", "claude", "claw", "codex", "copilot", "droid", "kilo", |
| 56 | + "kiro", "opencode", "pi", "trae", "vscode", "windows"] |
| 57 | +# shared hosts: add the params back once #4313 lands |
| 58 | +HOSTS = [pytest.param("devin", DEVIN, id="devin"), pytest.param("aider", AIDER, id="aider")] |
| 59 | + |
| 60 | +# --- reading the paragraph ----------------------------------------------------------------- |
| 61 | + |
| 62 | +_NEGATION = re.compile(r"\b(?:skip\w*|do not|don't|never|without|not)\b", re.I) |
| 63 | +_STEP_REF = re.compile( |
| 64 | + r"(?P<A>Step 3A|Part A)|(?P<B>Step 3B|Part B|fast path)|(?P<C>Step 3C|Part C)|(?P<merge>\bmerge\b)", |
| 65 | + re.I, |
| 66 | +) |
| 67 | +_ANY_REF = re.compile(r"\b(?:Step \d\w*|Part [A-Z])\b") |
| 68 | + |
| 69 | + |
| 70 | +def steps_named(paragraph: str) -> list[str]: |
| 71 | + """Steps the paragraph tells the agent to run, in order: "A", "B" (fast path), "C", "merge". |
| 72 | +
|
| 73 | + Only the first mention of a step counts; a later mention (``only after Part C has |
| 74 | + completed``) is not a second run. Code spans are dropped (the print message says |
| 75 | + "skipping"), as is any clause with a negation. A step reference this reader cannot map |
| 76 | + raises instead of being ignored. |
| 77 | + """ |
| 78 | + text = re.sub(r"`[^`]*`", "", paragraph).split(":", 1)[1] |
| 79 | + found: list[str] = [] |
| 80 | + for clause in re.split(r"[,;]|\bthen\b|\bbut\b|\.\s", text): |
| 81 | + if _NEGATION.search(clause): |
| 82 | + continue |
| 83 | + for ref in _ANY_REF.findall(clause): |
| 84 | + if not _STEP_REF.fullmatch(ref) and not re.fullmatch(r"Step [4-9]\w*", ref): |
| 85 | + raise ValueError(f"the paragraph names {ref!r}, which this test cannot map to a block") |
| 86 | + for m in _STEP_REF.finditer(clause): |
| 87 | + if m.lastgroup not in found: |
| 88 | + found.append(m.lastgroup) |
| 89 | + return found |
| 90 | + |
| 91 | + |
| 92 | +@pytest.mark.parametrize("sentence,expected", [ |
| 93 | + # the text on v8 |
| 94 | + ("If `code_only` is True: print `x - skipping y`, run only Step 3A (AST) on the changed files, " |
| 95 | + "skip Step 3B entirely (no subagents), then go straight to merge and Steps 4-8.", ["A", "merge"]), |
| 96 | + ("If `code_only` is True: run Step 3A, skip Step 3B (no subagents), then run the Part B fast path, " |
| 97 | + "run Part C, then go straight to merge.", ["A", "B", "C", "merge"]), |
| 98 | + ("If `code_only` is True: run Step 3A, do not run Part C, then go straight to merge.", ["A", "merge"]), |
| 99 | + # PR #4313's paragraph, verbatim: Part C is named again after the merge, which is not a second run |
| 100 | + ("If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic " |
| 101 | + "extraction (no LLM needed)`, run Step 3A (AST) on the changed files, then follow only Part B's " |
| 102 | + "**Fast path** to overwrite `.graphify_semantic.json` with an empty result and run Part C to create " |
| 103 | + "`.graphify_extract.json` from the fresh AST result. Skip semantic cache checks/writes and subagents " |
| 104 | + "(Steps B0–B3); do not reuse semantic sidecars from a prior run. Continue to the incremental merge and " |
| 105 | + "Steps 4–8 only after Part C has completed.", ["A", "B", "C", "merge"]), |
| 106 | + # the issue's second route: the merge builds the extraction from the AST file |
| 107 | + ("If `code_only` is True: run Step 3A (AST) on the changed files, then go straight to merge, which " |
| 108 | + "builds the extraction from the AST file.", ["A", "merge"]), |
| 109 | +]) |
| 110 | +def test_steps_named_reads_only_what_the_paragraph_tells_the_agent_to_run(sentence, expected): |
| 111 | + assert steps_named(sentence) == expected |
| 112 | + |
| 113 | + |
| 114 | +@pytest.mark.parametrize("ref", ["Part D", "Step 3B0"]) |
| 115 | +def test_steps_named_refuses_a_step_it_cannot_map(ref): |
| 116 | + with pytest.raises(ValueError, match="cannot map"): |
| 117 | + steps_named(f"If `code_only` is True: run Step 3A, run {ref}, then merge.") |
| 118 | + |
| 119 | + |
| 120 | +# --- rendering and running the blocks -------------------------------------------------------- |
| 121 | + |
| 122 | +def _blocks(text: str, lang: str) -> list[tuple[int, str]]: |
| 123 | + return [(m.start(), m.group(1)) for m in re.finditer(rf"```{lang}\n(.*?)```", text, re.S)] |
| 124 | + |
| 125 | + |
| 126 | +def _find(blocks: list[str], anchor: str) -> str: |
| 127 | + hits = [b for b in blocks if anchor in b] |
| 128 | + assert hits, f"no rendered block contains {anchor!r}" |
| 129 | + return hits[0] |
| 130 | + |
| 131 | + |
| 132 | +class Runbook: |
| 133 | + def __init__(self, host: str, anchors: Anchors): |
| 134 | + artifacts = {a.path: a.content for a in gen.render_all(gen.load_platforms(), only=host)} |
| 135 | + core = next(c for p, c in artifacts.items() if re.fullmatch(r"graphify/skill(-\w+)?\.md", p)) |
| 136 | + update = artifacts.get(f"graphify/skills/{host}/references/update.md") |
| 137 | + if update is None: # aider, devin: the --update section is inside the one file |
| 138 | + core, update = core.split("## For --update", 1) |
| 139 | + self.stdin = host == "windows" # PowerShell here-strings: pipe the Python body to the interpreter |
| 140 | + core_blocks = [b for _, b in _blocks(core, "powershell" if self.stdin else "bash")] |
| 141 | + update_blocks = _blocks(update, "bash") |
| 142 | + paragraph = re.search(r"^If `code_only` is True:.*$", update, re.M) |
| 143 | + assert paragraph, "no code_only paragraph in the rendered --update section" |
| 144 | + self.paragraph = paragraph.group(0) |
| 145 | + # every update-section block written before the paragraph (detect, code_only check, ...) |
| 146 | + self.before = [b for pos, b in update_blocks if pos < paragraph.start()] |
| 147 | + self.blocks = { |
| 148 | + "A": _find(core_blocks, anchors.part_a), |
| 149 | + "B": next((b for b in core_blocks if anchors.fast_path in b), None), |
| 150 | + "C": _find(core_blocks, anchors.part_c), |
| 151 | + "merge": _find([b for _, b in update_blocks], anchors.merge), |
| 152 | + } |
| 153 | + |
| 154 | + |
| 155 | +def _env() -> dict[str, str]: |
| 156 | + return {**os.environ, "PYTHONPATH": str(REPO_ROOT)} |
| 157 | + |
| 158 | + |
| 159 | +def _run(block: str, proj: Path, *, python_on_stdin: bool = False) -> subprocess.CompletedProcess[str]: |
| 160 | + block = block.replace("INPUT_PATH", proj.as_posix()).replace("IS_DIRECTED", "False") |
| 161 | + if python_on_stdin: |
| 162 | + body = re.search(r"@'\n(.*?)\n'@", block, re.S).group(1) |
| 163 | + return subprocess.run([sys.executable, "-"], input=body, cwd=proj, env=_env(), |
| 164 | + capture_output=True, text=True, timeout=300) |
| 165 | + return subprocess.run(["bash", "-c", block], cwd=proj, env=_env(), |
| 166 | + capture_output=True, text=True, timeout=300) |
| 167 | + |
| 168 | + |
| 169 | +def _tail(result: subprocess.CompletedProcess[str]) -> str: |
| 170 | + return "\n".join((result.stdout + result.stderr).strip().splitlines()[-8:]) |
| 171 | + |
| 172 | + |
| 173 | +def _project(tmp_path: Path) -> tuple[Path, int]: |
| 174 | + """A built two-file project, a.py then edited to add f_new(). Returns (path, baseline node count).""" |
| 175 | + proj = tmp_path / "proj" |
| 176 | + proj.mkdir() |
| 177 | + (proj / "a.py").write_text("def f():\n return 1\n", encoding="utf-8") |
| 178 | + (proj / "b.py").write_text("def g():\n return 2\n", encoding="utf-8") |
| 179 | + where = subprocess.run([sys.executable, "-c", "import graphify; print(graphify.__file__)"], cwd=proj, |
| 180 | + env=_env(), capture_output=True, text=True, check=True).stdout.strip() |
| 181 | + assert Path(where).is_relative_to(REPO_ROOT), f"graphify imported from {where}, not this checkout" |
| 182 | + subprocess.run([sys.executable, "-m", "graphify", "update", str(proj)], cwd=proj, env=_env(), |
| 183 | + check=True, capture_output=True, text=True) |
| 184 | + (proj / "graphify-out" / ".graphify_python").write_text(sys.executable, encoding="utf-8") |
| 185 | + baseline = len(json.loads((proj / "graphify-out" / "graph.json").read_text(encoding="utf-8"))["nodes"]) |
| 186 | + (proj / "a.py").write_text("def f():\n return 1\n\ndef f_new():\n return 3\n", encoding="utf-8") |
| 187 | + return proj, baseline |
| 188 | + |
| 189 | + |
| 190 | +def _semantic_cache(proj: Path) -> dict[str, bytes]: |
| 191 | + root = proj / "graphify-out" / "cache" |
| 192 | + return {p.relative_to(root).as_posix(): p.read_bytes() |
| 193 | + for d in root.glob("semantic*") for p in d.rglob("*") if p.is_file()} |
| 194 | + |
| 195 | + |
| 196 | +@pytest.mark.parametrize("host,anchors", HOSTS) |
| 197 | +def test_code_only_update_follows_its_paragraph_and_merges_the_new_function(host, anchors, tmp_path): |
| 198 | + book = Runbook(host, anchors) |
| 199 | + plan = steps_named(book.paragraph) |
| 200 | + assert plan and plan[0] == "A" and plan[-1] == "merge", ( |
| 201 | + f"the code-only paragraph names {plan}; expected Part A first and the merge last") |
| 202 | + |
| 203 | + proj, baseline = _project(tmp_path) |
| 204 | + out = proj / anchors.prefix |
| 205 | + |
| 206 | + # State after a normal full build's cleanup: no extract/ast/semantic files. Seed a semantic |
| 207 | + # cache entry that must not move (the stale semantic file is seeded below, after detection: |
| 208 | + # aider keeps its .graphify_*.json in the project root, where detection would scan it). |
| 209 | + assert not (out / ".graphify_extract.json").exists() |
| 210 | + entry = proj / "graphify-out" / "cache" / "semantic" / ("ab" * 32 + ".json") |
| 211 | + entry.parent.mkdir(parents=True, exist_ok=True) |
| 212 | + entry.write_text(json.dumps({"nodes": [{"id": "cached_notes", "label": "cached"}], |
| 213 | + "edges": [], "hyperedges": []}), encoding="utf-8") |
| 214 | + cache_before = _semantic_cache(proj) |
| 215 | + assert cache_before |
| 216 | + |
| 217 | + ran = [] |
| 218 | + for block in book.before: # detect_incremental, (populate detect.json,) code_only check |
| 219 | + result = _run(block, proj) |
| 220 | + assert result.returncode == 0, f"update section block failed:\n{_tail(result)}" |
| 221 | + ran.append(result.stdout) |
| 222 | + assert any("code_only: True" in text for text in ran), "the code_only check did not report True" |
| 223 | + |
| 224 | + detect = out / ".graphify_detect.json" |
| 225 | + if not detect.exists(): |
| 226 | + # aider and devin only: no block in their --update section writes it (a defect separate |
| 227 | + # from #4447). Seed what the shared block writes so this test isolates the extraction route. |
| 228 | + assert host in ("aider", "devin"), f"{host}: the update section never wrote .graphify_detect.json" |
| 229 | + inc = json.loads((out / ".graphify_incremental.json").read_text(encoding="utf-8")) |
| 230 | + detect.write_text(json.dumps({ |
| 231 | + "files": inc["new_files"], "all_files": inc.get("files", {}), "total_files": inc["new_total"], |
| 232 | + "total_words": inc.get("total_words", 0), "skipped_sensitive": [], "needs_graph": True, |
| 233 | + }), encoding="utf-8") |
| 234 | + |
| 235 | + # A sidecar left by an earlier run, where this host keeps it: must not reach the result. |
| 236 | + (out / ".graphify_semantic.json").write_text(json.dumps({ |
| 237 | + "nodes": [{"id": "stale_semantic", "label": STALE, "source_file": "notes.md"}], |
| 238 | + "edges": [], "hyperedges": []}), encoding="utf-8") |
| 239 | + |
| 240 | + result = None |
| 241 | + for name in plan: |
| 242 | + block = book.blocks[name] |
| 243 | + if block is None: |
| 244 | + pytest.fail(f"the paragraph names the Part B fast path, but {host} has no block " |
| 245 | + "that writes the empty semantic file") |
| 246 | + result = _run(block, proj, python_on_stdin=book.stdin and name != "merge") |
| 247 | + assert result.returncode == 0, f"step {name!r} failed (plan {plan}):\n{_tail(result)}" |
| 248 | + |
| 249 | + merged = re.search(r"Merged: (\d+) nodes", result.stdout + result.stderr) |
| 250 | + assert merged, f"the merge printed no 'Merged: N nodes' line:\n{_tail(result)}" |
| 251 | + # The merge prints counts only on aider and devin, so "the new function is there" is judged |
| 252 | + # from them: baseline + f_new. A leaked stale semantic node would make it baseline + 2. |
| 253 | + assert int(merged.group(1)) == baseline + 1, f"{merged.group(0)}; expected {baseline + 1} nodes" |
| 254 | + |
| 255 | + extract = out / ".graphify_extract.json" |
| 256 | + if extract.exists(): # the generated hosts' merge writes the merged extraction back |
| 257 | + labels = {n.get("label") for n in json.loads(extract.read_text(encoding="utf-8"))["nodes"]} |
| 258 | + assert "f_new()" in labels |
| 259 | + assert STALE not in labels |
| 260 | + |
| 261 | + assert _semantic_cache(proj) == cache_before, "the code-only update touched the semantic cache" |
0 commit comments