agent-test-kit 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_test_kit-0.0.1.dist-info/METADATA +72 -0
- agent_test_kit-0.0.1.dist-info/RECORD +18 -0
- agent_test_kit-0.0.1.dist-info/WHEEL +5 -0
- agent_test_kit-0.0.1.dist-info/entry_points.txt +2 -0
- agent_test_kit-0.0.1.dist-info/licenses/LICENSE +202 -0
- agent_test_kit-0.0.1.dist-info/top_level.txt +1 -0
- atkit/__init__.py +9 -0
- atkit/claude_code.py +283 -0
- atkit/cli.py +133 -0
- atkit/events.py +121 -0
- atkit/kept.py +424 -0
- atkit/label.html +249 -0
- atkit/labels.py +49 -0
- atkit/out.py +56 -0
- atkit/page.py +191 -0
- atkit/stages.py +82 -0
- atkit/tally.py +40 -0
- atkit/writer.py +72 -0
atkit/cli.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""The atkit command. `atkit report FOLDER` labels every result the agent called ready and counts the labels. With no
|
|
2
|
+
folder it reads the agent's own session logs, so the first report needs no setup. Where the events name the stages
|
|
3
|
+
of the work, the report also says which work is moving and which is stuck, and where they name none it works the
|
|
4
|
+
stages out from the repository. `--out` saves the same report as JSON files, for a host that draws its own pages. `atkit ui` opens AtKit's page on this
|
|
5
|
+
machine, where a person checks those labels against their own."""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
from collections import Counter
|
|
9
|
+
from datetime import datetime, timedelta, timezone
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from atkit import claude_code, events, kept, out, page, stages, tally
|
|
14
|
+
|
|
15
|
+
LABELS = ("kept", "not kept", "not clear")
|
|
16
|
+
MOST = 12 # the programs and tools shown, the most runs first, and the stuck work shown, the longest stuck first
|
|
17
|
+
DAYS = 14 # how far back the agent's own logs are read when no folder is named
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def report(results, others=None, called=None, standing=(), now=None):
|
|
21
|
+
"""The report as text: the counts, the kept share with its range, one line for every result, the work by where it
|
|
22
|
+
stands (`standing`, a list of Progress, the longest in its stage first), the calls by program and tool, and the
|
|
23
|
+
events of kinds AtKit does not read, as {kind: count}."""
|
|
24
|
+
counts = Counter(result.label for result in results)
|
|
25
|
+
lines = ["AtKit report", "", f"{'Results the agent called ready':<34}{len(results):>5}"]
|
|
26
|
+
implied = sum(result.implied for result in results)
|
|
27
|
+
if implied:
|
|
28
|
+
lines.append(f" {'implied, with no claim logged':<32}{implied:>5}")
|
|
29
|
+
for name, count in (("commit found by its files", sum(result.found for result in results)),
|
|
30
|
+
("rewritten later in the task", sum(result.signals["again"] == "rewritten" for result in results)),
|
|
31
|
+
("same files changed again", sum(result.signals["again"] == "changed again" for result in results))):
|
|
32
|
+
if count:
|
|
33
|
+
lines.append(f" {name:<32}{count:>5}")
|
|
34
|
+
lines += [f" {name:<32}{counts[name]:>5}" for name in LABELS]
|
|
35
|
+
value, low, high = kept.share(results)
|
|
36
|
+
if value is not None:
|
|
37
|
+
spread = f"({low:.0f} to {high:.0f})" if low is not None else "(too few or too alike for a range)"
|
|
38
|
+
# The share counts decided results only, so it is said beside it how few of all the results those are.
|
|
39
|
+
decided = counts["kept"] + counts["not kept"]
|
|
40
|
+
lines.append(f" {'kept share':<32}{value:>4.0f}% {spread}, of the {decided} decided out of {len(results)}")
|
|
41
|
+
if results:
|
|
42
|
+
rows = [("Task", "Label", "Check", "Tests", "Files", "Repository", "Follow-up")]
|
|
43
|
+
rows += [(one.task, one.label, one.signals["check"], one.signals["tests"], one.signals["again"], one.signals["merged"], one.signals["follow_up"]) for one in results]
|
|
44
|
+
widths = [max(len(row[column]) for row in rows) for column in range(len(rows[0]))]
|
|
45
|
+
lines += [""] + [" ".join(cell.ljust(width) for cell, width in zip(row, widths)).rstrip() for row in rows]
|
|
46
|
+
if standing:
|
|
47
|
+
states = Counter(one.state for one in standing)
|
|
48
|
+
lines += ["", f"{'Work by its stage':<34}{len(standing):>5}"] + [f" {name:<32}{states[name]:>5}" for name in ("moving", "stuck", "done")]
|
|
49
|
+
value, low, high = stages.stuck_share(standing)
|
|
50
|
+
if value is not None:
|
|
51
|
+
spread = f"({low:.0f} to {high:.0f})" if low is not None else "(too few or too alike for a range)"
|
|
52
|
+
lines.append(f" {'stuck share':<32}{value:>4.0f}% {spread}, of the {states['moving'] + states['stuck']} not done")
|
|
53
|
+
stuck = [one for one in standing if one.state == "stuck"]
|
|
54
|
+
if stuck:
|
|
55
|
+
now = now or datetime.now(timezone.utc)
|
|
56
|
+
rows = [("Stuck work", "Stage", "Days there")] + [(one.task, one.stage, str((now - one.since).days)) for one in stuck[:MOST]]
|
|
57
|
+
widths = [max(len(row[column]) for row in rows) for column in range(len(rows[0]))]
|
|
58
|
+
lines += [""] + [" ".join([row[0].ljust(widths[0]), row[1].ljust(widths[1]), row[2].rjust(widths[2])]) for row in rows]
|
|
59
|
+
if len(stuck) > MOST:
|
|
60
|
+
lines.append(f"({len(stuck) - MOST} more pieces of stuck work not shown)")
|
|
61
|
+
if called:
|
|
62
|
+
rows = [("Calls", "Runs", "Failed", "Found nothing", "Seconds")]
|
|
63
|
+
rows += [(f"{kind} {name}", str(row["runs"]), str(row["failed"]), str(row["nothing"]), f"{row['seconds']:.0f}") for (kind, name), row in list(called.items())[:MOST]]
|
|
64
|
+
widths = [max(len(row[column]) for row in rows) for column in range(len(rows[0]))]
|
|
65
|
+
lines += [""] + [" ".join([row[0].ljust(widths[0])] + [cell.rjust(width) for cell, width in zip(row[1:], widths[1:])]) for row in rows]
|
|
66
|
+
if len(called) > MOST:
|
|
67
|
+
lines.append(f"({len(called) - MOST} more programs and tools not shown)")
|
|
68
|
+
if others:
|
|
69
|
+
lines += ["", "Events of kinds AtKit does not read: " + ", ".join(f"{kind} {count}" for kind, count in sorted(others.items()))]
|
|
70
|
+
return "\n".join(lines)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def main(argv=None):
|
|
74
|
+
parser = argparse.ArgumentParser(prog="atkit", description="An agent test kit: test coding agents on the work they really did.")
|
|
75
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
76
|
+
shared = argparse.ArgumentParser(add_help=False)
|
|
77
|
+
# ponytail: one reader so far. Pick among readers here once there is a second.
|
|
78
|
+
shared.add_argument("events", type=Path, nargs="?", help="A folder of event files (default: Claude Code's own session logs)")
|
|
79
|
+
shared.add_argument("--days", type=int, default=DAYS, help=f"With no folder: the sessions changed in the last so many days (default: {DAYS})")
|
|
80
|
+
shared.add_argument("--repo", type=Path, help="The repository of results whose calls name no file; without one two signals are not known")
|
|
81
|
+
shared.add_argument("--main", help="The branch a result has to reach (default: the repository's own default branch)")
|
|
82
|
+
reporting = commands.add_parser("report", parents=[shared], help="Label every result the agent called ready, and count the labels")
|
|
83
|
+
reporting.add_argument("--stuck", type=float, default=stages.STUCK.days, help="The days in one stage after which work counts as stuck (default: %(default)s)")
|
|
84
|
+
reporting.add_argument("--out", type=Path, help="A folder to save the report in too, as JSON files for another program to read")
|
|
85
|
+
paging = commands.add_parser("ui", parents=[shared], help="Open AtKit's page on this machine, to check its labels against your own")
|
|
86
|
+
paging.add_argument("--labels", type=Path, default=page.FILE, help="Where the sample and your answers are kept (default: %(default)s)")
|
|
87
|
+
paging.add_argument("--port", type=int, default=0, help="The port on this machine to serve the page on (default: a free one)")
|
|
88
|
+
args = parser.parse_args(argv)
|
|
89
|
+
if not args.events and not claude_code.HOME.is_dir():
|
|
90
|
+
parser.error(f"there are no Claude Code logs in {claude_code.HOME}. For another agent, name the folder of its events: atkit {args.command} FOLDER")
|
|
91
|
+
others, called, moving = Counter(), tally.Tally(), stages.Stages()
|
|
92
|
+
|
|
93
|
+
def counted(stream):
|
|
94
|
+
"""The same events, with the calls and the kinds AtKit does not read counted on the way past."""
|
|
95
|
+
for event in stream:
|
|
96
|
+
if event["kind"] not in events.KINDS:
|
|
97
|
+
others[event["kind"]] += 1
|
|
98
|
+
called.add(event)
|
|
99
|
+
moving.add(event)
|
|
100
|
+
yield event
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
if args.command == "report" and args.out:
|
|
104
|
+
args.out.mkdir(parents=True, exist_ok=True) # a folder that cannot be made is said before the long reading
|
|
105
|
+
# Events go by one task at a time and only the results are kept, so a long history does not fill memory.
|
|
106
|
+
source = events.read(args.events) if args.events else claude_code.read(days=args.days)
|
|
107
|
+
if not args.events:
|
|
108
|
+
print(f"Reading the last {'day' if args.days == 1 else f'{args.days} days'} of Claude Code's logs. This can take several minutes, and a smaller --days takes less.",
|
|
109
|
+
file=sys.stderr, flush=True)
|
|
110
|
+
elif args.command == "ui":
|
|
111
|
+
print("Reading the results, which can take a few minutes on a long history.", file=sys.stderr)
|
|
112
|
+
results = list(kept.results(counted(source), args.repo, args.main))
|
|
113
|
+
if args.command == "ui":
|
|
114
|
+
# What was said around a result is in the agent's log alone; a folder of events holds none of it.
|
|
115
|
+
page.serve(page.Check(results, args.labels, None if args.events else claude_code.said), args.port)
|
|
116
|
+
else:
|
|
117
|
+
# A task whose harness names its stages is one piece of work. For any other, each result is one, and its
|
|
118
|
+
# stage is worked out from the repository.
|
|
119
|
+
after, now = timedelta(days=args.stuck), datetime.now(timezone.utc) # one moment for the text and the files
|
|
120
|
+
unnamed = [one for one in results if one.task not in moving.last]
|
|
121
|
+
standing = sorted([*moving.progress(now, after), *stages.standing(unnamed, now, after)], key=lambda one: (one.since, one.task))
|
|
122
|
+
if args.out:
|
|
123
|
+
out.save(args.out, out.tables(results, standing, called.table(), others, now))
|
|
124
|
+
# A task's name can hold what the terminal cannot show, and that must not stop the report.
|
|
125
|
+
shown = sys.stdout.encoding or "utf-8"
|
|
126
|
+
print(report(results, others, called.table(), standing, now).encode(shown, "replace").decode(shown))
|
|
127
|
+
except (ValueError, OSError) as wrong:
|
|
128
|
+
parser.error(str(wrong))
|
|
129
|
+
return 0
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if __name__ == "__main__":
|
|
133
|
+
raise SystemExit(main())
|
atkit/events.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""The event format: one JSON object on one line, one file for each task. The first line of a file names the format's
|
|
2
|
+
version. Every other line is an event with a `kind`, a `task`, a `turn` and `at`, its time in UTC."""
|
|
3
|
+
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
VERSION = 1
|
|
10
|
+
# The kinds AtKit reads. Agents differ, so a harness may write kinds of its own: they pass through the reader untouched,
|
|
11
|
+
# and the report counts them, so a misspelled kind shows up as a count and is not read as nothing having happened.
|
|
12
|
+
KINDS = frozenset({"turn_start", "turn_end", "message", "call_start", "call_end", "ask", "answer", "usage", "result", "stage"})
|
|
13
|
+
COMMON = ("kind", "task", "turn", "at")
|
|
14
|
+
COMMIT = re.compile(r"[0-9a-fA-F]{7,64}")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def read(folder):
|
|
18
|
+
"""The events of every .jsonl file under a folder, as dicts with `at` as a datetime. They come one file at a time,
|
|
19
|
+
each file's in the order of their times, so memory holds one task and never the whole history. ValueError names the
|
|
20
|
+
file and the line of anything that is not an event of this format; it is raised when that line is reached. A last
|
|
21
|
+
line that is still being written is left out, because a harness may be adding to a file while it is read."""
|
|
22
|
+
folder = Path(folder)
|
|
23
|
+
if not folder.is_dir():
|
|
24
|
+
raise ValueError(f"{folder} is not a folder")
|
|
25
|
+
return stream(folder)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def stream(folder):
|
|
29
|
+
seen = set() # task names only: a task in two files would be judged as two half tasks
|
|
30
|
+
for path in sorted(folder.rglob("*.jsonl")):
|
|
31
|
+
own = []
|
|
32
|
+
with path.open("rb") as lines: # as bytes: the last line can end in the middle of a character
|
|
33
|
+
first = True
|
|
34
|
+
for number, line in enumerate(lines, 1):
|
|
35
|
+
if not line.strip() or unfinished(line):
|
|
36
|
+
continue
|
|
37
|
+
try:
|
|
38
|
+
value = parsed(line)
|
|
39
|
+
if first:
|
|
40
|
+
first = False
|
|
41
|
+
if value.get("format") != "atkit" or value.get("version") != VERSION:
|
|
42
|
+
raise ValueError(f'the first line must be {{"format": "atkit", "version": {VERSION}}}')
|
|
43
|
+
continue
|
|
44
|
+
event = checked(value)
|
|
45
|
+
if own and event["task"] != own[0]["task"]:
|
|
46
|
+
raise ValueError(f"a file holds one task, and this one holds {own[0]['task']!r} and {event['task']!r}")
|
|
47
|
+
own.append(event)
|
|
48
|
+
except ValueError as wrong:
|
|
49
|
+
raise ValueError(f"{path}:{number}: {wrong}") from None
|
|
50
|
+
if not own:
|
|
51
|
+
continue
|
|
52
|
+
if own[0]["task"] in seen:
|
|
53
|
+
raise ValueError(f"{path}: task {own[0]['task']!r} is in another file too")
|
|
54
|
+
seen.add(own[0]["task"])
|
|
55
|
+
own.sort(key=lambda event: event["at"]) # a stable sort: events of one moment keep their file order
|
|
56
|
+
yield from own
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def unfinished(line):
|
|
60
|
+
"""Whether a line, as bytes, is still being written or was cut short: it has no line feed yet, as only a file's last
|
|
61
|
+
line can, and it is not complete JSON."""
|
|
62
|
+
if line.endswith(b"\n"):
|
|
63
|
+
return False
|
|
64
|
+
try:
|
|
65
|
+
json.loads(line)
|
|
66
|
+
except ValueError:
|
|
67
|
+
return True
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def parsed(line):
|
|
72
|
+
try:
|
|
73
|
+
value = json.loads(line)
|
|
74
|
+
except ValueError:
|
|
75
|
+
raise ValueError("not JSON") from None
|
|
76
|
+
if not isinstance(value, dict):
|
|
77
|
+
raise ValueError("not a JSON object")
|
|
78
|
+
return value
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def checked(event):
|
|
82
|
+
"""The event with `at` as a datetime, or ValueError saying what keeps it from being one."""
|
|
83
|
+
missing = [name for name in COMMON if name not in event]
|
|
84
|
+
if missing:
|
|
85
|
+
raise ValueError(f"missing {', '.join(missing)}")
|
|
86
|
+
if not isinstance(event["kind"], str):
|
|
87
|
+
raise ValueError(f"kind is not a name: {event['kind']!r}")
|
|
88
|
+
if not isinstance(event["task"], str) or not event["task"]:
|
|
89
|
+
raise ValueError(f"task is not a name: {event['task']!r}")
|
|
90
|
+
if not isinstance(event["turn"], int) or isinstance(event["turn"], bool):
|
|
91
|
+
raise ValueError(f"turn is not a whole number: {event['turn']!r}")
|
|
92
|
+
for name in ("type", "name"):
|
|
93
|
+
if event["kind"] == "call_start" and not isinstance(event.get(name), (str, type(None))):
|
|
94
|
+
raise ValueError(f"a call's {name} is not a name: {event[name]!r}")
|
|
95
|
+
# A name is saved and shown, so it must not be a command line. The message does not repeat it, for it may hold a secret.
|
|
96
|
+
if event["kind"] == "call_start" and event.get("type") == "command" and re.search(r"[\s/\\]", event.get("name") or ""):
|
|
97
|
+
raise ValueError("a command's name is its program alone, with no path and no arguments")
|
|
98
|
+
if event["kind"] in ("call_start", "call_end") and not isinstance(event.get("id"), str):
|
|
99
|
+
raise ValueError("a call needs an id, to pair its start with its end")
|
|
100
|
+
if event["kind"] == "stage" and not (isinstance(event.get("stage"), str) and event["stage"]):
|
|
101
|
+
raise ValueError("a stage needs its name")
|
|
102
|
+
if event["kind"] == "stage" and event.get("done") not in (None, True, False):
|
|
103
|
+
raise ValueError(f"done is true or false: {event['done']!r}")
|
|
104
|
+
files = event.get("files")
|
|
105
|
+
if files is not None and not (isinstance(files, list) and all(isinstance(path, str) for path in files)):
|
|
106
|
+
raise ValueError("files is not a list of paths")
|
|
107
|
+
for name in ("added", "removed"):
|
|
108
|
+
lines = event.get(name)
|
|
109
|
+
if lines is not None and not (isinstance(lines, dict) and all(isinstance(found, list) and all(isinstance(one, str) for one in found) for found in lines.values())):
|
|
110
|
+
raise ValueError(f"{name} is not a table of line fingerprints by file")
|
|
111
|
+
# The commit is handed to git as an argument, where anything but a commit's name could be read as an option.
|
|
112
|
+
if event["kind"] == "result" and event.get("commit") is not None and not (isinstance(event["commit"], str) and COMMIT.fullmatch(event["commit"])):
|
|
113
|
+
raise ValueError(f"commit is not a commit's name: {event['commit']!r}")
|
|
114
|
+
try:
|
|
115
|
+
at = datetime.fromisoformat(str(event["at"]))
|
|
116
|
+
except ValueError:
|
|
117
|
+
raise ValueError(f"at is not a time: {event['at']!r}") from None
|
|
118
|
+
if at.tzinfo is None:
|
|
119
|
+
# Times without a zone from two machines cannot be put in order.
|
|
120
|
+
raise ValueError("at has no time zone; write it in UTC, ending in Z")
|
|
121
|
+
return {**event, "at": at}
|