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.
atkit/tally.py ADDED
@@ -0,0 +1,40 @@
1
+ """What the calls did: for each program and each tool, its runs, how many failed, and their seconds."""
2
+
3
+ from collections import defaultdict
4
+
5
+ # With exit code 1 these found nothing. That is an answer and not a failure, so it is counted on its own.
6
+ SEARCHES = frozenset({"rg", "grep", "ag", "ack"})
7
+
8
+
9
+ class Tally:
10
+ """Counts calls as their events go by, so a long history is never held in memory."""
11
+
12
+ def __init__(self):
13
+ self.rows = defaultdict(lambda: {"runs": 0, "failed": 0, "nothing": 0, "seconds": 0.0})
14
+ self.open, self.task = {}, None
15
+
16
+ def add(self, event):
17
+ if event["task"] != self.task:
18
+ self.open, self.task = {}, event["task"] # a call that never ended goes with its task
19
+ if event["kind"] == "call_start":
20
+ self.open[event["id"]] = event
21
+ elif event["kind"] == "call_end" and event["id"] in self.open:
22
+ start = self.open.pop(event["id"])
23
+ row = self.rows[(str(start.get("type") or "call"), str(start.get("name") or "unnamed"))]
24
+ nothing = start.get("name") in SEARCHES and event.get("exit") == 1
25
+ row["runs"] += 1
26
+ row["nothing"] += nothing
27
+ row["failed"] += bool(event.get("failed")) and not nothing
28
+ row["seconds"] += (event["at"] - start["at"]).total_seconds()
29
+
30
+ def table(self):
31
+ """{(type, name): {"runs", "failed", "nothing", "seconds"}}, the most runs first."""
32
+ return dict(sorted(self.rows.items(), key=lambda item: (-item[1]["runs"], item[0])))
33
+
34
+
35
+ def calls(events):
36
+ """The table of every program and tool in a stream of events. The events of a task must come together."""
37
+ tally = Tally()
38
+ for event in events:
39
+ tally.add(event)
40
+ return tally.table()
atkit/writer.py ADDED
@@ -0,0 +1,72 @@
1
+ """Writes AtKit's events as an agent works, for a harness in Python. A harness in another language writes the same
2
+ lines itself: one JSON object on a line, one file for each task, with the format's name and version on the first."""
3
+
4
+ from datetime import datetime, timezone
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import re
9
+ import threading
10
+
11
+ from atkit.events import VERSION, checked, unfinished
12
+ from atkit.kept import prints, short
13
+
14
+ # ponytail: one lock for every file, so that two writers of one task in a process never mix their lines. Use one for
15
+ # each file when that slows a harness. Two processes must not write one task at the same time.
16
+ LOCK = threading.Lock()
17
+
18
+
19
+ class Writer:
20
+ """Writes the events of one task to its own file in a folder. Another writer of the same task, as after a restart,
21
+ goes on in the same file."""
22
+
23
+ def __init__(self, folder, task):
24
+ if not isinstance(task, str) or not task:
25
+ raise ValueError("a task needs its name")
26
+ self.task = task
27
+ # A task's name can hold a slash, or differ from another's by case alone, which some disks do not tell apart.
28
+ # So the file is named by a fingerprint of it, with its plain letters in front for a person to read.
29
+ self.path = Path(folder) / f"{re.sub(r'[^A-Za-z0-9_-]+', '-', task)[:40]}-{short(task)}.jsonl"
30
+
31
+ def write(self, kind, turn, at=None, **fields):
32
+ """Add one event, at this moment when no time is given. ValueError or TypeError, and nothing written, when it
33
+ is not an event AtKit can read."""
34
+ if "task" in fields:
35
+ raise ValueError("a writer writes the one task it was made for")
36
+ event = checked({"kind": kind, "task": self.task, "turn": turn, "at": datetime.now(timezone.utc) if at is None else at, **fields})
37
+ event["at"] = event["at"].astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
38
+ line = json.dumps(event, allow_nan=False) + "\n" # whole before the file is touched
39
+ with LOCK:
40
+ self.path.parent.mkdir(parents=True, exist_ok=True)
41
+ with self.path.open("ab+") as file:
42
+ ready(file)
43
+ file.write(line.encode())
44
+
45
+
46
+ def ready(file):
47
+ """Make a file ready for one more line: give a new one its first line, and mend the end of one whose last line has
48
+ no line feed. A line a crash cut short is taken off: it cannot be read, and the next would be joined to it."""
49
+ size = file.seek(0, os.SEEK_END)
50
+ if size:
51
+ file.seek(size - 1)
52
+ if file.read(1) != b"\n":
53
+ file.seek(0)
54
+ tail = file.read().rpartition(b"\n")[2]
55
+ if unfinished(tail):
56
+ size -= len(tail)
57
+ file.truncate(size)
58
+ else:
59
+ file.write(b"\n")
60
+ if not size:
61
+ file.write(json.dumps({"format": "atkit", "version": VERSION}).encode() + b"\n")
62
+
63
+
64
+ def wrote(changes):
65
+ """The fields of a `call_end` that changed files, from {path: (text before, text after)}. None stands for a file
66
+ that is not there. A path is absolute, or from the repository's root. The event holds the paths and the
67
+ fingerprints of the lines that came and went, and none of the text."""
68
+ fields = {"wrote": True, "files": list(changes), "added": {}, "removed": {}}
69
+ for path, (before, after) in changes.items():
70
+ old, new = prints(before or ""), prints(after or "")
71
+ fields["added"][path], fields["removed"][path] = sorted(new - old), sorted(old - new)
72
+ return fields