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/label.html ADDED
@@ -0,0 +1,249 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>AtKit: check the labels</title>
7
+ <style nonce="{{nonce}}">
8
+ :root {
9
+ color-scheme: light dark;
10
+ --ink: #1d1d1b; --soft: #66665f; --line: #dcdbd4; --paper: #f8f7f3; --card: #ffffff; --accent: #275d4f; --on-accent: #ffffff; --mark: #8a4b12;
11
+ }
12
+ @media (prefers-color-scheme: dark) {
13
+ :root { --ink: #eceae4; --soft: #a5a49c; --line: #3b3b37; --paper: #161614; --card: #1f1f1c; --accent: #8fcab5; --on-accent: #0f211b; --mark: #e0a96b; }
14
+ }
15
+ * { box-sizing: border-box; }
16
+ body { margin: 0; background: var(--paper); color: var(--ink); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
17
+ main { max-width: 46rem; margin: 0 auto; padding: 2.5rem 1.25rem 4rem; }
18
+ header { display: flex; align-items: baseline; justify-content: space-between; gap: 1rem; margin-bottom: 1.5rem; }
19
+ h1 { font-size: 1.35rem; font-weight: 600; margin: 0; }
20
+ h2 { font-size: 1.05rem; font-weight: 600; margin: 2rem 0 0.5rem; }
21
+ p { margin: 0 0 0.75rem; }
22
+ .soft { color: var(--soft); }
23
+ .small { font-size: 0.875rem; }
24
+ .card { background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 1.1rem 1.25rem; }
25
+ dl { margin: 0; }
26
+ dt { color: var(--soft); font-size: 0.8rem; letter-spacing: 0.02em; margin-top: 0.9rem; }
27
+ dt:first-child { margin-top: 0; }
28
+ dd { margin: 0.15rem 0 0; overflow-wrap: anywhere; white-space: pre-wrap; }
29
+ .names { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.875rem; }
30
+ .ask { margin: 1.5rem 0 0.75rem; }
31
+ .answers { display: flex; flex-wrap: wrap; gap: 0.6rem; align-items: center; }
32
+ button { font: inherit; color: var(--ink); background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 0.55rem 0.95rem; cursor: pointer; }
33
+ button:hover { border-color: var(--soft); }
34
+ button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
35
+ button[aria-pressed="true"], button.main { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
36
+ button.plain { border-color: transparent; background: none; color: var(--soft); padding-inline: 0.4rem; }
37
+ button:disabled { opacity: 0.45; cursor: default; }
38
+ kbd { font: 0.75rem ui-monospace, SFMono-Regular, Menlo, monospace; opacity: 0.7; margin-left: 0.4rem; }
39
+ table { border-collapse: collapse; width: 100%; font-size: 0.9rem; }
40
+ th, td { text-align: left; padding: 0.4rem 0.6rem 0.4rem 0; border-bottom: 1px solid var(--line); vertical-align: top; }
41
+ th { color: var(--soft); font-weight: 500; }
42
+ td.count, th.count { text-align: right; font-variant-numeric: tabular-nums; }
43
+ .differs { color: var(--mark); }
44
+ .card:focus { outline: none; }
45
+ ul { list-style: none; margin: 0; padding: 0; }
46
+ li { padding: 0.6rem 0; border-bottom: 1px solid var(--line); }
47
+ li p { margin: 0; overflow-wrap: anywhere; }
48
+ .verdict { font-size: 1.2rem; margin-bottom: 0.4rem; }
49
+ [hidden] { display: none !important; }
50
+ </style>
51
+ </head>
52
+ <body>
53
+ <main>
54
+ <header>
55
+ <h1>Check the labels</h1>
56
+ <span class="soft small" id="progress" aria-live="polite"></span>
57
+ </header>
58
+
59
+ <section id="loading"><p class="soft">Loading the sample.</p></section>
60
+
61
+ <section id="failed" hidden>
62
+ <p>The page could not reach AtKit. It may have been stopped.</p>
63
+ <p class="soft small" id="why"></p>
64
+ </section>
65
+
66
+ <section id="empty" hidden><p id="none"></p></section>
67
+
68
+ <section id="label" hidden>
69
+ <p class="soft">AtKit says of each piece of your agent's work whether it was kept or not, by a rule. Here is a sample of that work. Say what you think of each piece, and at the end AtKit shows how often its rule agrees with you.</p>
70
+ <p class="soft small" id="gone" hidden></p>
71
+ <div class="card" id="card" tabindex="-1">
72
+ <dl>
73
+ <dt>When and where</dt><dd id="when"></dd>
74
+ <dt id="files-name">Files it changed</dt><dd id="files" class="names"></dd>
75
+ <dt id="began-name">The task began with</dt><dd id="began"></dd>
76
+ <dt id="asked-name">You asked</dt><dd id="asked"></dd>
77
+ <dt id="answered-name">The agent said at the end</dt><dd id="answered"></dd>
78
+ <dt id="next-name">You said next</dt><dd id="next"></dd>
79
+ </dl>
80
+ </div>
81
+ <p class="ask">Was this work kept? <span class="soft">Kept means what the agent left stayed as it was. Not kept means it had to be fixed, redone or thrown away.</span></p>
82
+ <div class="answers">
83
+ <button type="button" data-label="kept">Kept<kbd>K</kbd></button>
84
+ <button type="button" data-label="not kept">Not kept<kbd>N</kbd></button>
85
+ <button type="button" data-label="not clear">Cannot tell<kbd>U</kbd></button>
86
+ <button type="button" class="plain" id="back">Back</button>
87
+ </div>
88
+ <p class="soft small ask">AtKit's own label is hidden until you have answered them all. Each answer is saved at once, so you can stop and come back.</p>
89
+ </section>
90
+
91
+ <section id="done" hidden>
92
+ <p class="verdict" id="verdict"></p>
93
+ <p id="evidence"></p>
94
+ <p class="soft small" id="note"></p>
95
+ <h2>Every pair of labels</h2>
96
+ <table id="pairs"></table>
97
+ <h2>Each result</h2>
98
+ <ul id="each"></ul>
99
+ <p class="ask"><button type="button" class="main" id="stop">Done</button></p>
100
+ </section>
101
+
102
+ <section id="closed" hidden><p>AtKit's page has stopped. You can close this tab.</p></section>
103
+ </main>
104
+ <script nonce="{{nonce}}">
105
+ const base = location.pathname.replace(/\/$/, "");
106
+ const $ = (id) => document.getElementById(id);
107
+ const LABELS = ["kept", "not kept", "not clear"];
108
+ const KEYS = {k: "kept", n: "not kept", u: "not clear"};
109
+ const VERDICTS = {
110
+ "match": "AtKit's labels match yours.",
111
+ "do not match": "AtKit's labels do not match yours.",
112
+ "not clear": "It is not clear yet whether AtKit's labels match yours.",
113
+ "not known": "Not known: there is no result that both you and AtKit decided.",
114
+ };
115
+ let items = [], given = {}, at = 0, busy = false;
116
+
117
+ function show(name) {
118
+ for (const section of document.querySelectorAll("main > section")) section.hidden = section.id !== name;
119
+ }
120
+
121
+ async function call(name, body) {
122
+ const options = body === undefined ? {} : {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body)};
123
+ const response = await fetch(`${base}/${name}`, options);
124
+ if (response.status === 409) return null;
125
+ if (!response.ok) throw new Error(`${name} answered ${response.status}`);
126
+ return response.json();
127
+ }
128
+
129
+ function fail(error) {
130
+ $("why").textContent = String(error && error.message || error);
131
+ $("progress").textContent = "";
132
+ show("failed");
133
+ }
134
+
135
+ function field(name, text) {
136
+ $(name).textContent = text || "";
137
+ $(name).hidden = $(`${name}-name`).hidden = !text;
138
+ }
139
+
140
+ function draw() {
141
+ const item = items[at];
142
+ $("progress").textContent = `${at + 1} of ${items.length}`;
143
+ $("when").textContent = item.repo ? `${item.when}, in ${item.repo}` : item.when;
144
+ field("files", item.files.join(", ") + (item.more ? ` and ${item.more} more` : ""));
145
+ field("began", item.began);
146
+ field("asked", item.asked);
147
+ field("answered", item.answered);
148
+ field("next", item.next);
149
+ for (const button of document.querySelectorAll("[data-label]")) button.setAttribute("aria-pressed", String(given[item.key] === button.dataset.label));
150
+ $("back").disabled = at === 0;
151
+ show("label");
152
+ // The button just pressed must not look like the answer to the next result, nor take the next Enter for one.
153
+ $("card").focus({preventScroll: true});
154
+ }
155
+
156
+ async function answer(label) {
157
+ if (busy || $("label").hidden) return;
158
+ busy = true;
159
+ try {
160
+ const item = items[at];
161
+ await call("answer", {key: item.key, label});
162
+ given[item.key] = label;
163
+ // On to the next result that has no answer yet, looking past the end and round to the start.
164
+ const left = items.map((_, index) => (at + 1 + index) % items.length).find((index) => !(items[index].key in given));
165
+ if (left === undefined) await finish();
166
+ else { at = left; draw(); }
167
+ } catch (error) { fail(error); } finally { busy = false; }
168
+ }
169
+
170
+ function row(table, cells, head) {
171
+ const line = table.insertRow();
172
+ cells.forEach((cell, index) => {
173
+ const made = line.appendChild(document.createElement(head ? "th" : "td"));
174
+ made.textContent = cell;
175
+ if (index > 0) made.className = "count";
176
+ });
177
+ }
178
+
179
+ function line(parent, text, kind) {
180
+ const made = parent.appendChild(document.createElement("p"));
181
+ made.textContent = text;
182
+ if (kind) made.className = kind;
183
+ }
184
+
185
+ async function finish() {
186
+ const result = await call("result");
187
+ if (!result) { at = items.findIndex((item) => !(item.key in given)); return draw(); }
188
+ $("progress").textContent = `${items.length} of ${items.length}`;
189
+ $("verdict").textContent = VERDICTS[result.decision];
190
+ const whole = (value) => Math.round(value);
191
+ const range = result.low === null ? "too few for a range" : `${whole(result.low)} to ${whole(result.high)}`;
192
+ $("evidence").textContent = result.share === null ? "" :
193
+ `You and AtKit agree on ${whole(result.share)}% (${range}) of the ${result.decided} results that both of you decided. The bar is ${result.bar}%.`;
194
+ $("note").textContent = "The range says where the share could lie had other work been sampled. A result that you or AtKit could not decide is left out of the share.";
195
+ const count = (mine, theirs) => (result.pairs.find((pair) => pair[0] === mine && pair[1] === theirs) || [0, 0, 0])[2];
196
+ const pairs = $("pairs");
197
+ pairs.replaceChildren();
198
+ row(pairs, ["AtKit's label", ...LABELS.map((label) => `You: ${label}`)], true);
199
+ for (const mine of [...LABELS, "gone"]) {
200
+ // AtKit draws only results it decided. The other two rows show up when a rule has changed since, or a result is gone.
201
+ if (!["kept", "not kept"].includes(mine) && !LABELS.some((theirs) => count(mine, theirs))) continue;
202
+ row(pairs, [mine === "gone" ? "not read now" : mine, ...LABELS.map((theirs) => count(mine, theirs))]);
203
+ }
204
+ const each = $("each");
205
+ each.replaceChildren();
206
+ for (const item of result.items) {
207
+ const differs = item.mine !== item.theirs && item.mine !== "not clear" && item.theirs !== "not clear";
208
+ const entry = each.appendChild(document.createElement("li"));
209
+ line(entry, `${item.when}: ${item.files.join(", ")}${item.more ? ` and ${item.more} more` : ""}`, "names");
210
+ line(entry, `You: ${item.theirs}. AtKit: ${item.mine}${differs ? ", which differs." : "."}`, differs ? "differs" : "");
211
+ line(entry, `AtKit's signs: check ${item.signals.check}, tests ${item.signals.tests}, ${item.signals.again}, ${item.signals.merged}.`, "soft small");
212
+ }
213
+ show("done");
214
+ }
215
+
216
+ async function start() {
217
+ try {
218
+ const sample = await call("items");
219
+ items = sample.items;
220
+ given = sample.given;
221
+ if (!items.length) {
222
+ $("none").textContent = sample.gone
223
+ ? "The results of this sample are not among those AtKit read this time. Read as far back as when the sample was drawn, or name another labels file to draw a new one."
224
+ : "AtKit decided no result, so there is none to check.";
225
+ return show("empty");
226
+ }
227
+ if (sample.gone) {
228
+ $("gone").textContent = `${sample.gone} results of the sample are not among those read this time, and are left out.`;
229
+ $("gone").hidden = false;
230
+ }
231
+ at = items.findIndex((item) => !(item.key in given));
232
+ if (at < 0) return await finish();
233
+ draw();
234
+ } catch (error) { fail(error); }
235
+ }
236
+
237
+ for (const button of document.querySelectorAll("[data-label]")) button.addEventListener("click", () => answer(button.dataset.label));
238
+ $("back").addEventListener("click", () => { if (at > 0) { at -= 1; draw(); } });
239
+ $("stop").addEventListener("click", async () => { try { await call("stop", {}); } catch (error) { /* it has stopped already */ } $("progress").textContent = ""; show("closed"); });
240
+ document.addEventListener("keydown", (event) => {
241
+ if (event.metaKey || event.ctrlKey || event.altKey || $("label").hidden) return;
242
+ const label = KEYS[event.key.toLowerCase()];
243
+ if (label) answer(label);
244
+ else if (event.key === "ArrowLeft") $("back").click();
245
+ });
246
+ start();
247
+ </script>
248
+ </body>
249
+ </html>
atkit/labels.py ADDED
@@ -0,0 +1,49 @@
1
+ """A check of AtKit's own labels against a person's. A host asks for a sample of results, shows each one to a person
2
+ in a screen of its own without AtKit's label, and hands the person's labels back to learn how often the two agree.
3
+ AtKit asks no question itself and keeps no answer: where the answers are kept is the host's business. A host keeps each
4
+ one under the result's `key`, so a rule can change and be scored again without labelling again."""
5
+
6
+ from collections import Counter, defaultdict
7
+ import random
8
+
9
+ from atkit.kept import ranged
10
+
11
+ SIZE, SEED = 30, 1 # a fixed seed, so the same results always give the same sample
12
+ DECIDED = ("kept", "not kept")
13
+ GIVEN = (*DECIDED, "not clear") # what a person may answer
14
+
15
+
16
+ def sample(results, size=SIZE, seed=SEED):
17
+ """The results for a person to label: half from those AtKit calls kept and half from those it says did not, in
18
+ a mixed order, so the person cannot tell AtKit's label from where a result stands. A side with too few is made up
19
+ from the other. Results AtKit could not decide are left out: there is no label of its own to check. A host shows
20
+ a result without its label, its signals and its commit."""
21
+ rng = random.Random(seed)
22
+ sides = [sorted((one for one in results if one.label == name), key=lambda one: one.key) for name in DECIDED]
23
+ for side in sides:
24
+ rng.shuffle(side)
25
+ half = size // 2
26
+ rest = sides[0][half:] + sides[1][half:]
27
+ rng.shuffle(rest)
28
+ picked = sides[0][:half] + sides[1][:half]
29
+ picked += rest[:size - len(picked)]
30
+ rng.shuffle(picked)
31
+ return picked
32
+
33
+
34
+ def agreement(results, given):
35
+ """AtKit's labels against a person's, `given` as {a result's key: the person's label}. Returns (share, low, high,
36
+ pairs): the share in percent of the results both decided on which the two agree, with its range drawn by task as
37
+ `share` draws it, and a count for each (AtKit's label, the person's label). A label given to a result that is not
38
+ among those read is counted under "gone". ValueError for a label that is none of the three."""
39
+ by_key = {one.key: one for one in results}
40
+ pairs, tasks = Counter(), defaultdict(lambda: [0, 0])
41
+ for key, theirs in given.items():
42
+ if theirs not in GIVEN:
43
+ raise ValueError(f"{theirs!r} is not a label: give one of {', '.join(GIVEN)}")
44
+ one = by_key.get(key)
45
+ pairs[(one.label if one else "gone", theirs)] += 1
46
+ if one and one.label in DECIDED and theirs in DECIDED:
47
+ tasks[one.task][0] += one.label == theirs
48
+ tasks[one.task][1] += 1
49
+ return (*ranged(list(tasks.values())), pairs)
atkit/out.py ADDED
@@ -0,0 +1,56 @@
1
+ """The report as data, for a host that draws its own pages: four tables, each saved as one JSON file. They hold names,
2
+ counts and times, and no path. A number that is not known is None and never zero."""
3
+
4
+ from collections import Counter
5
+ from datetime import datetime, timezone
6
+ import json
7
+ from pathlib import Path
8
+
9
+ from atkit import kept, stages
10
+
11
+ FORMAT, VERSION = "atkit-report", 1
12
+ SIGNALS = ("check", "tests", "again", "merged", "follow_up")
13
+
14
+
15
+ def utc(at):
16
+ return at.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
17
+
18
+
19
+ def ranged(numbers, out_of):
20
+ """A share in percent with its range and what it is a share of."""
21
+ return {**{name: None if number is None else round(number, 1) for name, number in zip(("value", "low", "high"), numbers)}, "out_of": out_of}
22
+
23
+
24
+ def tables(results, standing=(), called=None, others=None, now=None):
25
+ """The four tables by name. `standing` is a list of Progress, `called` the table of `calls`, and `others` the
26
+ events of kinds AtKit does not read, as {kind: count}."""
27
+ labels, states = Counter(one.label for one in results), Counter(one.state for one in standing)
28
+ summary = {"results": {"all": len(results), "implied": sum(one.implied for one in results), "commit_found": sum(one.found for one in results),
29
+ "kept": labels["kept"], "not_kept": labels["not kept"], "not_clear": labels["not clear"]},
30
+ "kept_share": ranged(kept.share(results), labels["kept"] + labels["not kept"]),
31
+ "work": {state: states[state] for state in ("moving", "stuck", "done")},
32
+ "stuck_share": ranged(stages.stuck_share(standing), states["moving"] + states["stuck"]),
33
+ "kinds_not_read": dict(sorted((others or {}).items()))}
34
+ rows = {"results": [{"key": one.key, "task": one.task, "turn": one.turn, "at": utc(one.at), "label": one.label, "implied": one.implied, "commit": one.commit,
35
+ "commit_found": one.found, "signals": {name: one.signals.get(name) for name in SIGNALS}} for one in results],
36
+ "work": [{"task": one.task, "stage": one.stage, "since": utc(one.since), "state": one.state} for one in standing],
37
+ "calls": [{"type": kind, "name": name, "runs": row["runs"], "failed": row["failed"], "found_nothing": row["nothing"], "seconds": round(row["seconds"], 1)}
38
+ for (kind, name), row in (called or {}).items()]}
39
+ made = utc(now or datetime.now(timezone.utc)) # the same in all four, so a reader can tell that they belong together
40
+ contents = {"summary": summary, **{name: {"rows": found} for name, found in rows.items()}}
41
+ return {name: {"format": FORMAT, "version": VERSION, "table": name, "made": made, **content} for name, content in contents.items()}
42
+
43
+
44
+ def save(folder, made):
45
+ """Save every table as a JSON file of its name, an empty one too, so that none is left from an older run."""
46
+ for name, table in made.items():
47
+ replace(Path(folder) / f"{name}.json", table)
48
+
49
+
50
+ def replace(path, value):
51
+ """Save a value as JSON, replacing the file in one step, so that no reader finds half of it and a stop in the
52
+ middle loses nothing. ponytail: two runs into one folder at the same time can take each other's new file."""
53
+ path.parent.mkdir(parents=True, exist_ok=True)
54
+ fresh = path.with_name(path.name + ".new")
55
+ fresh.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n", encoding="utf-8")
56
+ fresh.replace(path)
atkit/page.py ADDED
@@ -0,0 +1,191 @@
1
+ """AtKit's local page, served to this machine only. Its first screen checks AtKit's labels against a person's own: it
2
+ shows a sample of results without AtKit's label, keeps the person's answers in a file, and ends in how often the two
3
+ agree. The page is one host of the two functions in `labels`, as any other application can be."""
4
+
5
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6
+ from importlib import resources
7
+ import json
8
+ from pathlib import Path
9
+ import secrets
10
+ import threading
11
+ import webbrowser
12
+
13
+ from atkit import labels
14
+ from atkit.out import replace
15
+
16
+ FILE = Path.home() / ".atkit" / "labels.json"
17
+ BAR = 80 # the agreement, in percent, at which AtKit's labels count as matching a person's
18
+ NAMED = 6 # the files named for a result
19
+ MOST = 10_000 # the bytes the page may send in one answer
20
+ SIGNALS = ("check", "tests", "again", "merged")
21
+
22
+
23
+ def load(path):
24
+ """The sample drawn and the answers given so far, as {"drawn": [keys], "labels": {key: label}}. A file that is not
25
+ there yet gives an empty one; ValueError for a file in another shape."""
26
+ try:
27
+ saved = json.loads(Path(path).read_text(encoding="utf-8"))
28
+ except FileNotFoundError:
29
+ return {"drawn": [], "labels": {}}
30
+ except ValueError:
31
+ raise ValueError(f"{path} is not a labels file") from None
32
+ if not (isinstance(saved, dict) and isinstance(saved.get("drawn"), list) and isinstance(saved.get("labels"), dict)
33
+ and all(label in labels.GIVEN for label in saved["labels"].values())):
34
+ raise ValueError(f"{path} is not a labels file")
35
+ return saved
36
+
37
+
38
+ def decision(share, low, high):
39
+ """What the check says of AtKit's labels. They match a person's when the whole range lies at the bar or over it,
40
+ they do not when the whole range lies under it, and otherwise it is not clear."""
41
+ if share is None:
42
+ return "not known" # no result that both decided
43
+ if low is None:
44
+ return "not clear" # too few tasks for a range
45
+ return "match" if low >= BAR else "do not match" if high < BAR else "not clear"
46
+
47
+
48
+ class Check:
49
+ """The check of AtKit's labels by hand. The sample is drawn once and saved in a file with the person's answers, so the
50
+ person can stop and go on later, and a rule can change and be scored again without labelling again. The file holds
51
+ each result's task, its time and the answer: no path and no text."""
52
+
53
+ def __init__(self, results, path=FILE, said=None, size=labels.SIZE):
54
+ self.results, self.path, self.lock = list(results), Path(path), threading.Lock()
55
+ self.saved = load(self.path)
56
+ if not self.saved["drawn"]:
57
+ self.saved["drawn"] = [one.key for one in labels.sample(self.results, size)]
58
+ if self.saved["drawn"]:
59
+ replace(self.path, self.saved)
60
+ by_key = {one.key: one for one in self.results}
61
+ # A result of the sample that is not among those read now cannot be shown: it is counted, and left out.
62
+ self.shown = [by_key[key] for key in self.saved["drawn"] if key in by_key]
63
+ # What was said around a result is read once, from the agent's log, and saved in memory alone.
64
+ self.said = {one.key: tuple(said(one.task, one.turn)) if said else () for one in self.shown}
65
+
66
+ def told(self, one):
67
+ """What a person is told of a result whoever made what of it: when it was, where, and the names of its files."""
68
+ names = sorted({Path(name).name for name in one.files})
69
+ return {"key": one.key, "when": f"{one.at.astimezone():%Y-%m-%d %H:%M}", "repo": Path(one.repo).name if one.repo else None,
70
+ "files": names[:NAMED], "more": max(0, len(names) - NAMED)}
71
+
72
+ def items(self):
73
+ """The results to label and the answers given so far. Nothing AtKit made of a result is here: not its label,
74
+ its signals or its commit."""
75
+ asked = [{**self.told(one), **dict(zip(("asked", "answered", "next", "began"), self.said[one.key]))} for one in self.shown]
76
+ given = {one.key: self.saved["labels"][one.key] for one in self.shown if one.key in self.saved["labels"]}
77
+ return {"items": asked, "given": given, "gone": len(self.saved["drawn"]) - len(self.shown)}
78
+
79
+ def answer(self, key, label):
80
+ """Keep one answer, and say how many results are left. ValueError for a result that is not shown or a label
81
+ that is none of the three."""
82
+ if label not in labels.GIVEN or key not in self.said:
83
+ raise ValueError("not an answer to a result of this sample")
84
+ with self.lock:
85
+ self.saved["labels"][key] = label
86
+ replace(self.path, self.saved)
87
+ return sum(one.key not in self.saved["labels"] for one in self.shown)
88
+
89
+ def result(self):
90
+ """How the person's labels compare with AtKit's. None while a result shown has no answer, so that nothing AtKit
91
+ made of a result is seen while there is still one to label."""
92
+ given = self.saved["labels"]
93
+ if any(one.key not in given for one in self.shown):
94
+ return None
95
+ share, low, high, pairs = labels.agreement(self.results, given)
96
+ decided = sum(count for (mine, theirs), count in pairs.items() if mine in labels.DECIDED and theirs in labels.DECIDED)
97
+ if share in (0, 100) and low is None and decided:
98
+ # Answers that all agree, or all differ, leave nothing to draw again. The rule of three bounds such a
99
+ # share: with n alike, the other kind is under 3 in n. ponytail: it counts results and not tasks.
100
+ edge = min(100, 300 / decided)
101
+ low, high = (100 - edge, 100) if share == 100 else (0, edge)
102
+ return {"share": share, "low": low, "high": high, "decided": decided, "bar": BAR, "decision": decision(share, low, high),
103
+ "pairs": [[mine, theirs, count] for (mine, theirs), count in sorted(pairs.items())],
104
+ "items": [{**self.told(one), "mine": one.label, "theirs": given[one.key], "signals": {name: one.signals.get(name) for name in SIGNALS}} for one in self.shown]}
105
+
106
+
107
+ class Handler(BaseHTTPRequestHandler):
108
+ server_version = "AtKit"
109
+
110
+ def log_message(self, *arguments):
111
+ """Nothing is logged: the address asked for holds the page's secret."""
112
+
113
+ def reply(self, status, body=None, kind="application/json", **headers):
114
+ body = body if isinstance(body, bytes) else json.dumps(body).encode()
115
+ self.send_response(status)
116
+ for name, value in {"Content-Type": kind, "Content-Length": len(body), "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
117
+ "Referrer-Policy": "no-referrer", **headers}.items():
118
+ self.send_header(name, str(value))
119
+ self.end_headers()
120
+ self.wfile.write(body)
121
+
122
+ def asked(self):
123
+ """The name asked for under the page's secret address, after refusing anything else. Another site open in the
124
+ browser can reach this port: it does not know the secret, and a name it points here is not this machine's."""
125
+ if self.headers.get("Host") not in self.server.hosts:
126
+ return self.reply(403, {"error": "this page is served to this machine only"})
127
+ parts = self.path.partition("?")[0].split("/")
128
+ if len(parts) != 3 or not secrets.compare_digest(parts[1].encode(), self.server.token.encode()):
129
+ return self.reply(404, {"error": "not found"})
130
+ return parts[2]
131
+
132
+ def do_GET(self):
133
+ name, check = self.asked(), self.server.check
134
+ if name == "":
135
+ nonce = secrets.token_urlsafe(16)
136
+ policy = f"default-src 'none'; script-src 'nonce-{nonce}'; style-src 'nonce-{nonce}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
137
+ self.reply(200, self.server.html.replace("{{nonce}}", nonce).encode(), "text/html; charset=utf-8", **{"Content-Security-Policy": policy})
138
+ elif name == "items":
139
+ self.reply(200, check.items())
140
+ elif name == "result":
141
+ result = check.result()
142
+ self.reply(200 if result else 409, result or {"error": "there are results left to label"})
143
+ elif name is not None:
144
+ self.reply(404, {"error": "not found"})
145
+
146
+ def do_POST(self):
147
+ name = self.asked()
148
+ if name is None:
149
+ return
150
+ # A page of another site cannot send this kind of body here without the browser asking this server first.
151
+ if self.headers.get("Content-Type") != "application/json":
152
+ return self.reply(415, {"error": "send JSON"})
153
+ size = int(self.headers.get("Content-Length") or 0) if (self.headers.get("Content-Length") or "0").isdigit() else MOST + 1
154
+ if size > MOST:
155
+ return self.reply(413, {"error": "too long"})
156
+ try:
157
+ sent = json.loads(self.rfile.read(size) or b"{}")
158
+ if name == "answer":
159
+ return self.reply(200, {"left": self.server.check.answer(sent["key"], sent["label"])})
160
+ except (ValueError, KeyError, TypeError):
161
+ return self.reply(400, {"error": "not an answer"})
162
+ if name == "stop":
163
+ self.reply(200, {})
164
+ # From another thread: this one is serving the request that asks for the stop.
165
+ return threading.Thread(target=self.server.shutdown, daemon=True).start()
166
+ self.reply(404, {"error": "not found"})
167
+
168
+
169
+ def server(check, port=0):
170
+ """A server of the page on this machine alone, at an address that holds a secret; its `url` is where it is."""
171
+ httpd = ThreadingHTTPServer(("127.0.0.1", port), Handler)
172
+ httpd.daemon_threads = True
173
+ httpd.check, httpd.token = check, secrets.token_urlsafe(16)
174
+ httpd.html = resources.files("atkit").joinpath("label.html").read_text(encoding="utf-8")
175
+ httpd.hosts = {f"{name}:{httpd.server_port}" for name in ("127.0.0.1", "localhost")}
176
+ httpd.url = f"http://127.0.0.1:{httpd.server_port}/{httpd.token}/"
177
+ return httpd
178
+
179
+
180
+ def serve(check, port=0, browser=True):
181
+ """Serve the page and open it, until the page says it is done or Ctrl-C is pressed."""
182
+ httpd = server(check, port)
183
+ print(f"AtKit's page is open at {httpd.url}\nIt is served to this machine only, and stops when you press Done on it or Ctrl-C here.", flush=True)
184
+ if browser:
185
+ webbrowser.open(httpd.url)
186
+ try:
187
+ httpd.serve_forever()
188
+ except KeyboardInterrupt:
189
+ pass
190
+ finally:
191
+ httpd.server_close()
atkit/stages.py ADDED
@@ -0,0 +1,82 @@
1
+ """Is the work moving, or is it stuck? Work passes through stages on its way, such as working, review, approved and
2
+ merged, and a harness writes a `stage` event each time the work enters one. The last of them says where a task's work
3
+ stands: done when that stage is its end, moving when it got there lately, and stuck when nothing has moved it since.
4
+ Where a harness names no stage, three are worked out from the repository: not committed, committed and merged."""
5
+
6
+ from dataclasses import dataclass
7
+ from datetime import datetime, timedelta, timezone
8
+
9
+ from atkit.kept import committed, ranged
10
+
11
+ STUCK = timedelta(days=2) # how long work may stay in one stage before it counts as stuck
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Progress:
16
+ """Where one task's work stands: the stage it is in, when it got there, and whether it is moving, stuck or done."""
17
+
18
+ task: str
19
+ stage: str
20
+ since: datetime
21
+ state: str
22
+
23
+
24
+ class Stages:
25
+ """Keeps the last stage of each task as its events go by, so a long history is never held in memory."""
26
+
27
+ def __init__(self):
28
+ self.last = {}
29
+
30
+ def add(self, event):
31
+ if event["kind"] == "stage" and (event["task"] not in self.last or event["at"] >= self.last[event["task"]]["at"]):
32
+ self.last[event["task"]] = event
33
+
34
+ def progress(self, now=None, after=STUCK):
35
+ """Every task that named a stage, the one longest in its stage first. A task that names none is not here:
36
+ where its work stands is not known."""
37
+ now = now or datetime.now(timezone.utc)
38
+ for event in sorted(self.last.values(), key=lambda event: (event["at"], event["task"])):
39
+ state = "done" if event.get("done") else "stuck" if now - event["at"] > after else "moving"
40
+ yield Progress(event["task"], event["stage"], event["at"], state)
41
+
42
+
43
+ def standing(results, now=None, after=STUCK):
44
+ """Where the work of results stands when no harness names its stages, worked out from the repository, one Progress
45
+ for each result: not committed, committed, or merged, which is its end. Only a result whose lines or files were
46
+ left alone, in a repository that is known, is work on its way. One that was rewritten, reworked or reverted is not,
47
+ and of one that names no file nothing can be said.
48
+ ponytail: a commit is looked for in the week after a result, so work committed later reads as not committed."""
49
+ now = now or datetime.now(timezone.utc)
50
+ found = []
51
+ for one in results:
52
+ landed = one.signals.get("merged")
53
+ if one.signals.get("again") != "left alone" or not one.repo or (one.commit and landed not in ("merged as it was", "not merged yet")):
54
+ continue
55
+ if not one.commit:
56
+ stage, since = "not committed", one.at
57
+ elif landed == "merged as it was":
58
+ stage, since = "merged", one.at
59
+ else:
60
+ stage, since = "committed", committed(one.repo, one.commit) or one.at
61
+ found.append(Progress(one.task, stage, since, "done" if stage == "merged" else "stuck" if now - since > after else "moving"))
62
+ return sorted(found, key=lambda one: (one.since, one.task))
63
+
64
+
65
+ def stuck_share(standing):
66
+ """The share of the work not done that is stuck, in percent, as (share, low, high). The pieces of work of one task
67
+ share its fate, so the range is drawn by task."""
68
+ by_task = {}
69
+ for one in standing:
70
+ if one.state != "done":
71
+ pair = by_task.setdefault(one.task, [0, 0])
72
+ pair[0] += one.state == "stuck"
73
+ pair[1] += 1
74
+ return ranged(list(by_task.values()))
75
+
76
+
77
+ def progress(events, now=None, after=STUCK):
78
+ """Where the work of every task in a stream of events stands, as a list of Progress."""
79
+ stages = Stages()
80
+ for event in events:
81
+ stages.add(event)
82
+ return list(stages.progress(now, after))