File size: 6,909 Bytes
9368cc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Standalone tests for the agentic tool layer: confinement, reads, edits."""
import sys, tempfile, shutil, os
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "examples" / "llama-eval"))
from agentic_eval import Workspace, ToolBox  # noqa: E402

fails = []
def check(name, cond, detail=""):
    print(f"  {'PASS' if cond else 'FAIL'}  {name}" + (f"   [{detail}]" if not cond else ""))
    if not cond:
        fails.append(name)

root = Path(tempfile.mkdtemp(prefix="toolbox-"))
try:
    (root / "pkg").mkdir()
    (root / "pkg" / "calc.py").write_text(
        "\n".join(f"line{i}" for i in range(1, 31)) + "\n")
    (root / "pkg" / "dup.py").write_text("x = 1\ny = 1\nz = 2\n")
    (root / "README.md").write_text("readme\n")

    ws = Workspace(root)
    tb = ToolBox(ws, linter=lambda t: f"lint({t})")

    # -- confinement ---------------------------------------------------
    for name, path in [("relative ..", "../../../etc/passwd"),
                       ("absolute", "/etc/passwd"),
                       ("nested ..", "pkg/../../../../etc/passwd")]:
        out = tb.dispatch("read_file", {"path": path})
        check(f"confine: {name} rejected", out.startswith("Error:") and "outside" in out, out[:80])

    os.symlink("/etc", root / "sneaky")
    out = tb.dispatch("read_file", {"path": "sneaky/passwd"})
    check("confine: symlink escape rejected", out.startswith("Error:") and "outside" in out, out[:80])
    out = tb.dispatch("write_file", {"path": "../escaped.txt", "content": "x"})
    check("confine: write escape rejected", out.startswith("Error:"), out[:80])
    check("confine: attempts counted", ws.escape_attempts == 5, str(ws.escape_attempts))

    # -- read ----------------------------------------------------------
    out = tb.dispatch("read_file", {"path": "pkg/calc.py"})
    check("read: line numbers present", "\n 1\tline1" in out or out.splitlines()[1].startswith(" 1\t"), out[:60])
    check("read: reports total", "30 lines total" in out, out[:60])

    out = tb.dispatch("read_file", {"path": "pkg/calc.py", "start_line": 5, "end_line": 7})
    body = [l for l in out.splitlines() if "\t" in l]
    check("read: narrowing honours range", len(body) == 3 and body[0].strip().startswith("5\tline5"), str(body))

    out = tb.dispatch("read_file", {"path": "pkg/calc.py", "start_line": 99})
    check("read: past EOF is an error", out.startswith("Error:") and "only 30 lines" in out, out[:80])
    out = tb.dispatch("read_file", {"path": "nope.py"})
    check("read: missing file is an error", out.startswith("Error:"), out[:80])

    # -- search --------------------------------------------------------
    out = tb.dispatch("search", {"pattern": r"line1\d"})
    check("search: finds matches", out.count("\n") >= 9 and "pkg/calc.py:10" in out, out[:80])
    out = tb.dispatch("search", {"pattern": "zzz"})
    check("search: no matches reported", out.startswith("No matches"), out[:80])
    out = tb.dispatch("search", {"pattern": "["})
    check("search: bad regex is an error", out.startswith("Error:"), out[:80])
    out = tb.dispatch("search", {"pattern": "readme", "glob": "*.py"})
    check("search: glob filters", out.startswith("No matches"), out[:80])

    # -- edit_lines ----------------------------------------------------
    out = tb.dispatch("edit_lines", {"path": "pkg/calc.py", "start_line": 1,
                                     "end_line": 2, "new_text": "FIRST"})
    txt = (root / "pkg" / "calc.py").read_text().splitlines()
    check("edit_lines: replaces range", txt[0] == "FIRST" and txt[1] == "line3", str(txt[:3]))
    check("edit_lines: warns of shift", "shifted" in out, out[:90])

    out = tb.dispatch("edit_lines", {"path": "pkg/calc.py", "start_line": 500,
                                     "end_line": 501, "new_text": "x"})
    check("edit_lines: out of range rejected", out.startswith("Error:"), out[:80])
    out = tb.dispatch("edit_lines", {"path": "pkg/calc.py", "start_line": 5,
                                     "end_line": 2, "new_text": "x"})
    check("edit_lines: inverted range rejected", out.startswith("Error:"), out[:80])

    n_before = len((root / "pkg" / "calc.py").read_text().splitlines())
    tb.dispatch("edit_lines", {"path": "pkg/calc.py", "start_line": 3,
                               "end_line": 3, "new_text": ""})
    n_after = len((root / "pkg" / "calc.py").read_text().splitlines())
    check("edit_lines: empty text deletes", n_after == n_before - 1, f"{n_before}->{n_after}")

    # -- edit_replace --------------------------------------------------
    out = tb.dispatch("edit_replace", {"path": "pkg/dup.py", "old_text": "= 1",
                                       "new_text": "= 9"})
    check("edit_replace: ambiguous rejected", out.startswith("Error:") and "2 times" in out, out[:100])
    check("edit_replace: ambiguous did not write", (root / "pkg" / "dup.py").read_text() == "x = 1\ny = 1\nz = 2\n")

    out = tb.dispatch("edit_replace", {"path": "pkg/dup.py", "old_text": "= 1",
                                       "new_text": "= 9", "replace_all": True})
    check("edit_replace: replace_all works", (root / "pkg" / "dup.py").read_text() == "x = 9\ny = 9\nz = 2\n")

    out = tb.dispatch("edit_replace", {"path": "pkg/dup.py", "old_text": "absent",
                                       "new_text": "x"})
    check("edit_replace: missing text rejected", out.startswith("Error:") and "not found" in out, out[:80])

    out = tb.dispatch("edit_replace", {"path": "pkg/dup.py", "old_text": "z = 2",
                                       "new_text": "z = 3"})
    check("edit_replace: unique match applies", "Replaced 1" in out and "z = 3" in (root / "pkg" / "dup.py").read_text())

    # -- write / lint / finish ----------------------------------------
    out = tb.dispatch("write_file", {"path": "pkg/new.py", "content": "n = 1\n"})
    check("write_file: creates", "Created" in out and (root / "pkg" / "new.py").exists(), out[:60])
    out = tb.dispatch("write_file", {"path": "pkg/new.py", "content": "n = 2\n"})
    check("write_file: overwrites", "Overwrote" in out, out[:60])

    check("lint: delegates", tb.dispatch("lint", {}) == "lint(None)")
    out = tb.dispatch("unknown_tool", {})
    check("dispatch: unknown tool is an error", out.startswith("Error: unknown tool"), out[:60])
    out = tb.dispatch("edit_lines", {"path": "pkg/dup.py"})
    check("dispatch: missing arg is an error", out.startswith("Error: missing required argument"), out[:80])

    tb.dispatch("finish", {"summary": "done"})
    check("finish: sets state", tb.finished and tb.finish_summary == "done")
    check("counters: errors tracked", tb.errors >= 12, str(tb.errors))
finally:
    shutil.rmtree(root, ignore_errors=True)

print(f"\n{'ALL PASS' if not fails else 'FAILURES: ' + ', '.join(fails)}")
sys.exit(1 if fails else 0)