stampcheck 0.1.0__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.
stampcheck/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Check whether a human approval step still filters anything, or has become a rubber stamp."""
2
+ from .config import NAME, VERSION as __version__
3
+ from .record import record_review, review
4
+
5
+ __all__ = ["NAME", "record_review", "review", "__version__"]
stampcheck/alert.py ADDED
@@ -0,0 +1,46 @@
1
+ """Slack alert: posts only when something is RED or a drift finding is new since the last run."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from urllib.request import Request, urlopen
6
+
7
+ from .checks import AMBER, RED
8
+ from .config import NAME
9
+
10
+
11
+ def parse_target(spec: str) -> str:
12
+ """'slack:https://hooks.slack.com/...' -> the webhook URL. Raises ValueError otherwise."""
13
+ kind, _, url = spec.partition(":")
14
+ if kind != "slack" or not url.startswith("https://"):
15
+ raise ValueError(f"--alert must look like slack:https://hooks.slack.com/services/..., got {spec!r}")
16
+ return url
17
+
18
+
19
+ def _drifting(result: dict | None) -> set[tuple[str, str]]:
20
+ if not result:
21
+ return set()
22
+ return {(kind, name) for kind in ("steps", "reviewers") for name, item in result.get(kind, {}).items()
23
+ for f in item["findings"] if f["check"] == "drift" and f["verdict"] in (RED, AMBER)}
24
+
25
+
26
+ def should_alert(result: dict, previous: dict | None) -> bool:
27
+ return result["red"] or bool(_drifting(result) - _drifting(previous))
28
+
29
+
30
+ def message(result: dict, previous: dict | None, per_reviewer: bool, report: str) -> str:
31
+ new = _drifting(result) - _drifting(previous)
32
+ lines = [f"*{NAME}*: an approval review check needs a look (data up to {result['period']['to'][:10]})"]
33
+ for kind in ("steps", "reviewers") if per_reviewer else ("steps",):
34
+ for name, item in sorted(result[kind].items()):
35
+ hits = [f["message"] for f in item["findings"]
36
+ if f["verdict"] == RED or (f["check"] == "drift" and (kind, name) in new and f["verdict"] == AMBER)]
37
+ if hits:
38
+ lines.append(f"- {item['verdict']} {name}: {' '.join(hits)}")
39
+ lines.append(f"Report: {report}")
40
+ return "\n".join(lines)
41
+
42
+
43
+ def send(url: str, text: str) -> None:
44
+ req = Request(url, data=json.dumps({"text": text}).encode(), headers={"Content-Type": "application/json"})
45
+ with urlopen(req, timeout=10) as resp:
46
+ resp.read()
stampcheck/checks.py ADDED
@@ -0,0 +1,303 @@
1
+ """The checks. Each returns a finding: a verdict (GREEN / AMBER / RED / GREY) and one plain sentence."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from collections import Counter, defaultdict
6
+ from collections.abc import Callable
7
+ from datetime import datetime, time, timedelta, timezone
8
+ from statistics import median
9
+
10
+ from .config import DECIDED, NAME, VERSION
11
+
12
+ GREEN, AMBER, RED, GREY = "GREEN", "AMBER", "RED", "GREY"
13
+ RANK = {GREY: 0, GREEN: 1, AMBER: 2, RED: 3}
14
+ Z = 1.96 # 95% interval
15
+
16
+
17
+ def wilson_upper(k: int, n: int, z: float = Z) -> float:
18
+ """Upper end of the Wilson score interval for k events in n trials."""
19
+ if n == 0:
20
+ return 1.0
21
+ p = k / n
22
+ centre = p + z * z / (2 * n)
23
+ margin = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
24
+ return min(1.0, (centre + margin) / (1 + z * z / n))
25
+
26
+
27
+ def fmt_s(s: float | None) -> str:
28
+ if s is None:
29
+ return "n/a"
30
+ if s < 60:
31
+ return f"{s:.0f} s"
32
+ if s < 3600:
33
+ m, sec = divmod(round(s), 60)
34
+ return f"{m} min {sec} s" if sec else f"{m} min"
35
+ return f"{s / 3600:.1f} h"
36
+
37
+
38
+ def pct(x: float | None) -> str:
39
+ return "n/a" if x is None else f"{x:.0%}" if x >= 0.1 or x == 0 else f"{x:.1%}"
40
+
41
+
42
+ def stats(rows: list[dict]) -> dict:
43
+ """Disagreement and time-per-case figures for the cases a human actually decided."""
44
+ decided = [r for r in rows if r["decision"] in DECIDED]
45
+ n = len(decided)
46
+ k = sum(r["decision"] != r["recommended"] for r in decided)
47
+ times = [(r["decided_at"] - r["opened_at"]).total_seconds() for r in decided if r["opened_at"]]
48
+ waits = [(r["decided_at"] - r["notified_at"]).total_seconds() for r in decided
49
+ if r["notified_at"] and not r["opened_at"]]
50
+ return {"n": n, "disagree": k, "rate": k / n if n else None, "upper": wilson_upper(k, n),
51
+ "median_s": median(times) if times else None, "timed": len(times),
52
+ "median_from_notified_s": median(waits) if waits else None}
53
+
54
+
55
+ def signs(s: dict, th: dict) -> tuple[bool, bool] | None:
56
+ """(agrees almost always, decides fast), or None when there is not enough timed data."""
57
+ if s["n"] < th["min_cases"] or s["timed"] < th["min_cases"]:
58
+ return None
59
+ return s["upper"] < th["max_disagreement_upper"], s["median_s"] < th["max_median_seconds"]
60
+
61
+
62
+ def finding(check: str, verdict: str, message: str, **data) -> dict:
63
+ return {"check": check, "verdict": verdict, "message": message, "data": data}
64
+
65
+
66
+ def rubber_stamp(rows: list[dict], th: dict) -> dict:
67
+ s = stats(rows)
68
+ n, k, minc = s["n"], s["disagree"], th["min_cases"]
69
+ agreed = f"agreed with the system on {n - k} of {n} decided cases"
70
+ if n < minc:
71
+ return finding("rubber_stamp", GREY, f"Only {n} decided cases; at least {minc} are needed to judge.", **s)
72
+ if s["timed"] < minc:
73
+ why = "No opened_at recorded" if s["timed"] == 0 else f"Only {s['timed']} of {n} cases have opened_at"
74
+ msg = f"{why}: rubber-stamp check not possible. Use record_review to start logging it."
75
+ if s["upper"] < th["max_disagreement_upper"]:
76
+ msg += f" Worth a look anyway: {agreed}."
77
+ if s["median_from_notified_s"] is not None:
78
+ msg += (f" Time from notification ({fmt_s(s['median_from_notified_s'])}) includes queue wait,"
79
+ " so it can't tell reading from clicking.")
80
+ return finding("rubber_stamp", GREY, msg, **s)
81
+ agree, fast = signs(s, th)
82
+ med = fmt_s(s["median_s"])
83
+ if agree and fast:
84
+ return finding("rubber_stamp", RED, f"Looks like rubber-stamping: {agreed}, median {med} from opening "
85
+ "to decision.", **s)
86
+ if agree:
87
+ return finding("rubber_stamp", AMBER, f"One warning sign: {agreed}, but a median of {med} per case "
88
+ "suggests the cases are being read.", **s)
89
+ if fast:
90
+ return finding("rubber_stamp", AMBER, f"One warning sign: fast (median {med} per case), but still "
91
+ f"disagrees with the system on {pct(s['rate'])} of cases.", **s)
92
+ return finding("rubber_stamp", GREEN, f"Engaged: disagrees with the system on {pct(s['rate'])} of cases, "
93
+ f"median {med} per case.", **s)
94
+
95
+
96
+ def weeks(days: float) -> str:
97
+ return f"{days // 7:g} weeks" if days % 7 == 0 else f"{days:g} days"
98
+
99
+
100
+ def drift(rows: list[dict], th: dict, end: datetime) -> dict:
101
+ """Last drift_recent_days vs the drift_baseline_days before, both ending at `end`."""
102
+ recent_from = end - timedelta(days=th["drift_recent_days"])
103
+ base_from = recent_from - timedelta(days=th["drift_baseline_days"])
104
+ a = stats([r for r in rows if base_from <= r["decided_at"] < recent_from])
105
+ b = stats([r for r in rows if r["decided_at"] >= recent_from])
106
+ span = f"the last {weeks(th['drift_recent_days'])} vs the {weeks(th['drift_baseline_days'])} before"
107
+ minc = th["min_cases"]
108
+ if min(a["n"], b["n"]) < minc:
109
+ return finding("drift", GREY, f"Not enough cases to compare {span} ({b['n']} vs {a['n']}; "
110
+ f"need {minc} in each).", baseline=a, recent=b)
111
+ trends = []
112
+ if min(a["timed"], b["timed"]) >= minc and b["median_s"] <= a["median_s"] * (1 - th["drift_change"]):
113
+ trends.append(f"time per case went from {fmt_s(a['median_s'])} to {fmt_s(b['median_s'])}")
114
+ if b["upper"] < a["rate"]:
115
+ trends.append(f"disagreement fell from {pct(a['rate'])} to {pct(b['rate'])}")
116
+ trend = " and ".join(trends)
117
+ zone_a, zone_b = signs(a, th) == (True, True), signs(b, th) == (True, True)
118
+ if zone_b and not zone_a:
119
+ return finding("drift", RED, f"Drifted into the rubber-stamp zone: {trend or 'now agrees and decides fast'}"
120
+ f" ({span}).", baseline=a, recent=b)
121
+ if trend and not zone_b:
122
+ return finding("drift", AMBER, f"Trending toward rubber-stamping: {trend} ({span}), not in the "
123
+ "rubber-stamp zone yet.", baseline=a, recent=b)
124
+ if zone_a and zone_b:
125
+ return finding("drift", GREEN, "No change: already in the rubber-stamp zone in both periods.",
126
+ baseline=a, recent=b)
127
+ return finding("drift", GREEN, f"Stable: median {fmt_s(a['median_s'])} then {fmt_s(b['median_s'])} per case, "
128
+ f"disagreement {pct(a['rate'])} then {pct(b['rate'])} ({span}).",
129
+ baseline=a, recent=b)
130
+
131
+
132
+ def timeouts(rows: list[dict], th: dict) -> dict:
133
+ hits = sorted(r["decided_at"] for r in rows if r["decision"] == "timeout_approve")
134
+ total = sum(r["decision"].startswith("timeout") for r in rows)
135
+ if not hits:
136
+ msg = f"No timeouts ended in approval ({total} timed out, all rejected)." if total else "No timeouts."
137
+ return finding("timeouts", GREEN, msg, count=0, total=total)
138
+ when = f"between {hits[0]:%Y-%m-%d %H:%M} and {hits[-1]:%Y-%m-%d %H:%M} UTC" if len(hits) > 1 \
139
+ else f"at {hits[0]:%Y-%m-%d %H:%M} UTC"
140
+ return finding("timeouts", RED, f"{len(hits)} cases nobody reviewed before the deadline were approved "
141
+ f"anyway, {when}.", count=len(hits), total=total)
142
+
143
+
144
+ def duplicates(rows: list[dict], th: dict) -> dict:
145
+ if all(r["executed"] is None for r in rows):
146
+ return finding("duplicates", GREY, "No executed column: duplicate-execution check not possible.")
147
+ runs: Counter = Counter()
148
+ approved = set()
149
+ for r in rows:
150
+ runs[r["case_id"]] += r["executed"] or 0
151
+ if r["decision"] in ("approve", "timeout_approve"):
152
+ approved.add(r["case_id"])
153
+ dups = sorted(((c, n) for c, n in runs.items() if c in approved and n > 1), key=lambda x: (-x[1], x[0]))
154
+ if not dups:
155
+ return finding("duplicates", GREEN, "Every approval was executed at most once.", cases={})
156
+ names = ", ".join(f"case {c} ran {n} times" for c, n in dups[:3])
157
+ return finding("duplicates", RED, f"{len(dups)} approval{'s were' if len(dups) > 1 else ' was'} used for more "
158
+ f"than one action ({names}); often a retry or idempotency bug.",
159
+ cases=dict(dups))
160
+
161
+
162
+ def logging_quality(rows: list[dict], th: dict) -> dict:
163
+ if len(rows) < th["min_cases"]:
164
+ return finding("logging", GREY, f"Only {len(rows)} rows; too few to tell whether logging is hard-coded.",
165
+ suspicious=[])
166
+ issues, suspicious = [], []
167
+ for col in ("recommended", "decision"):
168
+ top = Counter(r[col] for r in rows).most_common(2)
169
+ share, second = top[0][1] / len(rows), top[1][1] if len(top) > 1 else 0
170
+ if share >= th["logging_dominant_share"] or second < th["logging_min_second_value"]:
171
+ suspicious.append(col)
172
+ issues.append(f"{col} is '{top[0][0]}' on {share:.1%} of rows (next value: {second} times)")
173
+ if not issues:
174
+ return finding("logging", GREEN, "The recommended and decision columns both vary.", suspicious=[])
175
+ return finding("logging", AMBER, f"Your logging may be hard-coded: {'; '.join(issues)}. Check it before "
176
+ "trusting the numbers built on it.", suspicious=suspicious)
177
+
178
+
179
+ def per_day(rows: list[dict]) -> float | None:
180
+ """Mean decided cases per reviewer per active day."""
181
+ days = Counter((r["reviewer"], r["decided_at"].date()) for r in rows
182
+ if r["reviewer"] and r["decision"] in DECIDED)
183
+ return sum(days.values()) / len(days) if days else None
184
+
185
+
186
+ def queue_load(rows: list[dict], th: dict) -> dict | None:
187
+ load = per_day(rows)
188
+ if load is None or load <= th["queue_max_per_day"]:
189
+ return None
190
+ return finding("queue", AMBER, f"Queue overload: ~{load:.0f} cases per reviewer per working day (limit "
191
+ f"{th['queue_max_per_day']:g}), which leaves little time to read each one.",
192
+ per_day=load)
193
+
194
+
195
+ def worst(findings: list[dict]) -> str:
196
+ return max((f["verdict"] for f in findings), key=RANK.get, default=GREY)
197
+
198
+
199
+ def weekly(rows: list[dict]) -> list[dict]:
200
+ by_week = group(rows, lambda r: (r["decided_at"].date() - timedelta(days=r["decided_at"].weekday())).isoformat())
201
+ return [{"week": w, **{k: s[k] for k in ("n", "rate", "median_s")}}
202
+ for w, s in ((w, stats(rs)) for w, rs in sorted(by_week.items()))]
203
+
204
+
205
+ def group(rows: list[dict], key: str | Callable) -> dict[str, list[dict]]:
206
+ out: dict = defaultdict(list)
207
+ for r in rows:
208
+ out[key(r) if callable(key) else r[key]].append(r)
209
+ return out
210
+
211
+
212
+ def _cap(findings: list[dict], why: str) -> None:
213
+ """Logging looks hard-coded: report RED rubber-stamp/drift findings as AMBER instead of trusting them."""
214
+ for f in findings:
215
+ if f["check"] in ("rubber_stamp", "drift") and f["verdict"] == RED:
216
+ f["verdict"], f["message"] = AMBER, f"{f['message']} (Not trusted: {why}.)"
217
+
218
+
219
+ def _attach_cause(findings: list[dict], queue: dict | None, who: str) -> None:
220
+ if queue:
221
+ for f in findings:
222
+ if f["check"] in ("rubber_stamp", "drift") and f["verdict"] in (RED, AMBER):
223
+ f["message"] += f" Likely cause: {who} handled ~{queue['data']['per_day']:.0f} cases per day."
224
+
225
+
226
+ def _summary(findings: list[dict], verdict: str) -> str:
227
+ if verdict == GREEN:
228
+ return "No problems found."
229
+ return " ".join(f["message"] for f in findings if f["verdict"] == verdict)
230
+
231
+
232
+ def run_all(rows: list[dict], th: dict, quality: dict | None = None) -> dict:
233
+ """Run every check per approval step and per reviewer. Returns a JSON-ready result."""
234
+ last = max(r["decided_at"] for r in rows)
235
+ end = datetime.combine(last.date() + timedelta(days=1), time.min, tzinfo=timezone.utc)
236
+ steps = group(rows, "category")
237
+ step_logging = {s: logging_quality(rs, th) for s, rs in steps.items()}
238
+ untrusted = {s for s, f in step_logging.items() if "recommended" in f["data"]["suspicious"]}
239
+
240
+ reviewers = {}
241
+ for name, rs in sorted(group([r for r in rows if r["reviewer"]], "reviewer").items()):
242
+ fs = [rubber_stamp(rs, th), drift(rs, th, end)]
243
+ queue = queue_load(rs, th)
244
+ _attach_cause(fs, queue, "this reviewer")
245
+ fs += [queue] if queue else []
246
+ their_steps = sorted({r["category"] for r in rs})
247
+ if untrusted & set(their_steps):
248
+ _cap(fs, "the system's recommendation barely varies in this step")
249
+ reviewers[name] = {"verdict": worst(fs), "steps": their_steps, "stats": stats(rs), "per_day": per_day(rs),
250
+ "findings": fs, "weekly": weekly(rs)}
251
+
252
+ out_steps = {}
253
+ for step, rs in sorted(steps.items()):
254
+ fs = [rubber_stamp(rs, th), drift(rs, th, end), timeouts(rs, th), duplicates(rs, th), step_logging[step]]
255
+ queue = queue_load(rs, th)
256
+ _attach_cause(fs, queue, "each reviewer")
257
+ fs += [queue] if queue else []
258
+ if step in untrusted:
259
+ _cap(fs, "the system's recommendation barely varies in this step")
260
+ names = sorted({r["reviewer"] for r in rs if r["reviewer"]})
261
+ if len(names) > 1: # with one reviewer the step-level findings already say it
262
+ fs.insert(0, _rollup([reviewers[n] for n in names]))
263
+ verdict = worst(fs)
264
+ out_steps[step] = {"verdict": verdict, "summary": _summary(fs, verdict), "stats": stats(rs),
265
+ "reviewers": len(names), "findings": fs, "weekly": weekly(rs)}
266
+
267
+ verdicts = [s["verdict"] for s in out_steps.values()] + [r["verdict"] for r in reviewers.values()]
268
+ return {"tool": NAME, "version": VERSION, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
269
+ "period": {"from": min(r["decided_at"] for r in rows).isoformat(), "to": last.isoformat()},
270
+ "thresholds": th, "quality": quality or {}, "not_possible": not_possible(rows),
271
+ "steps": out_steps, "reviewers": reviewers, "red": RED in verdicts}
272
+
273
+
274
+ def _rollup(revs: list[dict]) -> dict:
275
+ """Step-level line about its reviewers, without naming anyone."""
276
+ def count(check: str, verdict: str) -> int:
277
+ return sum(any(f["check"] == check and f["verdict"] == verdict for f in r["findings"]) for r in revs)
278
+
279
+ n, stamp, drifted = len(revs), count("rubber_stamp", RED), count("drift", RED)
280
+ of_n = f"of {n} reviewer{'s' if n != 1 else ''}"
281
+ parts = [f"{stamp} {of_n} match{'es' if stamp == 1 else ''} the rubber-stamp pattern"] if stamp else []
282
+ parts += [f"{drifted} {of_n} drifted into the rubber-stamp zone"] if drifted else []
283
+ if parts:
284
+ return finding("reviewers", RED, " and ".join(parts) + ".", red=stamp + drifted)
285
+ amber = sum(r["verdict"] == AMBER for r in revs)
286
+ if amber:
287
+ return finding("reviewers", AMBER, f"{amber} of {n} reviewers show one warning sign or a downward trend.")
288
+ if all(r["verdict"] == GREY for r in revs):
289
+ return finding("reviewers", GREY, f"Not enough data to judge any of the {n} reviewers yet.")
290
+ return finding("reviewers", GREEN, f"None of the {n} reviewers match the rubber-stamp pattern.")
291
+
292
+
293
+ def not_possible(rows: list[dict]) -> list[str]:
294
+ out = []
295
+ if all(r["opened_at"] is None for r in rows):
296
+ out.append("No opened_at column: rubber-stamp check not possible. Use record_review to start logging it.")
297
+ if all(r["reviewer"] is None for r in rows):
298
+ out.append("No reviewer column: per-reviewer checks and queue load not possible.")
299
+ if all(r["executed"] is None for r in rows):
300
+ out.append("No executed column: duplicate-execution check not possible.")
301
+ if all(r["category"] == "default" for r in rows):
302
+ out.append("No category column: all rows are treated as one approval step.")
303
+ return out
stampcheck/cli.py ADDED
@@ -0,0 +1,96 @@
1
+ """Command line: `stampcheck demo`, `stampcheck check`, `stampcheck init`. Exit 0 = no RED, 1 = RED, 2 = input error."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from . import alert, demo, report
10
+ from .checks import run_all
11
+ from .config import CONFIG_FILE, NAME, VERSION, ConfigError, init_text, load_config
12
+ from .record import write_rows
13
+ from .sources import InputError, load, pseudonymize
14
+
15
+
16
+ def check(source: str, out: str = ".", config: str | None = None, query: str | None = None,
17
+ alert_to: str | None = None, per_reviewer: bool = False, pseudonym: bool = False,
18
+ auto_config: bool = True) -> int:
19
+ try:
20
+ url = alert.parse_target(alert_to) if alert_to else None
21
+ cfg = load_config(config, auto=auto_config)
22
+ rows, quality = load(source, cfg, query)
23
+ except (ConfigError, InputError, ValueError) as e:
24
+ print(f"{NAME}: input error: {e}", file=sys.stderr)
25
+ return 2
26
+ if pseudonym:
27
+ pseudonymize(rows, cfg["pseudonymize_salt"])
28
+ quality["config"] = cfg["path"]
29
+ result = run_all(rows, cfg["thresholds"], quality)
30
+
31
+ out_dir = Path(out)
32
+ out_dir.mkdir(parents=True, exist_ok=True)
33
+ previous = None
34
+ if (out_dir / "result.json").is_file():
35
+ try:
36
+ previous = json.loads((out_dir / "result.json").read_text(encoding="utf-8"))
37
+ except (OSError, ValueError):
38
+ previous = None
39
+ report.write_json(result, out_dir / "result.json")
40
+ report.write_html(result, out_dir / "report.html")
41
+ print(report.terminal(result, out_dir))
42
+
43
+ if url and alert.should_alert(result, previous):
44
+ try:
45
+ alert.send(url, alert.message(result, previous, per_reviewer, str(out_dir / "report.html")))
46
+ print("Slack alert sent.")
47
+ except OSError as e: # urllib errors are OSErrors; a failed alert never changes the verdict
48
+ print(f"{NAME}: could not send the Slack alert: {e}", file=sys.stderr)
49
+ return 1 if result["red"] else 0
50
+
51
+
52
+ def main(argv: list[str] | None = None) -> int:
53
+ p = argparse.ArgumentParser(prog=NAME, description="Check whether your human approval step still does anything.")
54
+ p.add_argument("--version", action="version", version=f"{NAME} {VERSION}")
55
+ sub = p.add_subparsers(dest="cmd", required=True)
56
+
57
+ d = sub.add_parser("demo", help="run the check on a built-in example dataset")
58
+ d.add_argument("--out", default=".", help="folder for demo.db, report.html and result.json (default: .)")
59
+
60
+ c = sub.add_parser("check", help="check your own review data")
61
+ c.add_argument("--source", required=True, help="CSV/TSV, .jsonl, SQLite .db, or postgresql://... URL")
62
+ c.add_argument("--query", help="SQL to run (required for Postgres; default for SQLite: SELECT * FROM reviews)")
63
+ c.add_argument("--mapping", "--config", dest="config",
64
+ help=f"YAML or JSON file with thresholds and column/value mapping (default: ./{CONFIG_FILE})")
65
+ c.add_argument("--out", default=".", help="folder for report.html and result.json (default: .)")
66
+ c.add_argument("--alert", help="slack:<webhook-url>; posts only when something is RED or newly drifting")
67
+ c.add_argument("--per-reviewer", action="store_true", help="name individual reviewers in alerts")
68
+ c.add_argument("--pseudonymize", action="store_true", help="replace reviewer IDs with salted hashes")
69
+
70
+ i = sub.add_parser("init", help=f"write a commented example config ({CONFIG_FILE})")
71
+ i.add_argument("--path", default=CONFIG_FILE)
72
+ i.add_argument("--force", action="store_true", help="overwrite an existing file")
73
+
74
+ args = p.parse_args(argv)
75
+ if args.cmd == "demo":
76
+ out = Path(args.out)
77
+ out.mkdir(parents=True, exist_ok=True)
78
+ db = out / "demo.db"
79
+ db.unlink(missing_ok=True) # always rebuild the demo data from the fixed seed
80
+ write_rows(demo.generate(), db)
81
+ print(f"Demo: 8 weeks of synthetic data. An AI support agent recommends refunds and five fictional "
82
+ f"reviewers approve or reject them. Written to {db}\n")
83
+ return check(str(db), str(out), auto_config=False)
84
+ if args.cmd == "check":
85
+ return check(args.source, args.out, args.config, args.query, args.alert, args.per_reviewer, args.pseudonymize)
86
+ target = Path(args.path)
87
+ if target.exists() and not args.force:
88
+ print(f"{NAME}: {target} already exists; use --force to overwrite", file=sys.stderr)
89
+ return 2
90
+ target.write_text(init_text(), encoding="utf-8")
91
+ print(f"Wrote {target}. Edit it, then run: {NAME} check --source <your data>")
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
stampcheck/config.py ADDED
@@ -0,0 +1,208 @@
1
+ """Tool name, data model constants, default thresholds, and config-file loading (YAML or JSON)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import secrets
6
+ from pathlib import Path
7
+
8
+ NAME = "stampcheck" # rename the tool here (also rename the package folder and pyproject.toml)
9
+ VERSION = "0.1.0"
10
+ CONFIG_FILE = f"{NAME}.yaml"
11
+ DB_FILE = f"{NAME}.db"
12
+ ENV_PATH = f"{NAME.upper()}_PATH"
13
+
14
+ FIELDS = ("case_id", "recommended", "decision", "reviewer", "opened_at", "decided_at",
15
+ "notified_at", "category", "executed")
16
+ RECOMMENDATIONS = ("approve", "reject")
17
+ DECISIONS = ("approve", "reject", "escalate", "timeout_approve", "timeout_reject")
18
+ DECIDED = ("approve", "reject", "escalate") # a human actually decided; timeouts are not decisions
19
+
20
+ THRESHOLDS: dict[str, float] = {
21
+ "min_cases": 30,
22
+ "max_disagreement_upper": 0.05,
23
+ "max_median_seconds": 30,
24
+ "drift_recent_days": 14,
25
+ "drift_baseline_days": 28,
26
+ "drift_change": 0.5,
27
+ "logging_dominant_share": 0.99,
28
+ "logging_min_second_value": 5,
29
+ "queue_max_per_day": 200,
30
+ }
31
+ KEYS = {"thresholds", "columns", "values", "timezone", "csv_delimiter", "pseudonymize_salt"}
32
+
33
+
34
+ class ConfigError(Exception):
35
+ """A bad config or mapping file. The message is shown to the user (exit code 2)."""
36
+
37
+
38
+ def load_config(path: str | None = None, auto: bool = True) -> dict:
39
+ """Defaults merged with `path`, or with ./stampcheck.yaml if it exists and `auto` is set."""
40
+ cfg: dict = {"thresholds": dict(THRESHOLDS), "columns": {}, "values": {}, "timezone": "UTC",
41
+ "csv_delimiter": None, "pseudonymize_salt": NAME, "path": None}
42
+ if path is None:
43
+ if not (auto and Path(CONFIG_FILE).is_file()):
44
+ return cfg
45
+ path = CONFIG_FILE
46
+ p = Path(path)
47
+ if not p.is_file():
48
+ raise ConfigError(f"config file not found: {path}")
49
+ data = _parse(p)
50
+ if unknown := set(data) - KEYS:
51
+ raise ConfigError(f"{p}: unknown keys {sorted(unknown)}; allowed: {sorted(KEYS)}")
52
+ for k, v in (data.get("thresholds") or {}).items():
53
+ if k not in THRESHOLDS:
54
+ raise ConfigError(f"{p}: unknown threshold {k!r}; allowed: {sorted(THRESHOLDS)}")
55
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
56
+ raise ConfigError(f"{p}: threshold {k} must be a number, got {v!r}")
57
+ cfg["thresholds"][k] = v
58
+ for f, col in (data.get("columns") or {}).items():
59
+ if f not in FIELDS:
60
+ raise ConfigError(f"{p}: unknown field {f!r} under columns; allowed: {', '.join(FIELDS)}")
61
+ cfg["columns"][f] = None if col in (None, {}) else str(col)
62
+ allowed = {"recommended": RECOMMENDATIONS, "decision": DECISIONS}
63
+ for f, mapping in (data.get("values") or {}).items():
64
+ if f not in allowed:
65
+ raise ConfigError(f"{p}: values can be mapped for recommended and decision, not {f!r}")
66
+ cfg["values"][f] = {}
67
+ for raw, canon in (mapping or {}).items():
68
+ if str(canon).strip().lower() not in allowed[f]:
69
+ raise ConfigError(f"{p}: {f} value {raw!r} maps to {canon!r}; must be one of {', '.join(allowed[f])}")
70
+ cfg["values"][f][str(raw).strip().lower()] = str(canon).strip().lower()
71
+ for k in ("timezone", "csv_delimiter", "pseudonymize_salt"):
72
+ if data.get(k) not in (None, {}):
73
+ cfg[k] = str(data[k])
74
+ cfg["path"] = str(p)
75
+ return cfg
76
+
77
+
78
+ def _parse(p: Path) -> dict:
79
+ text = p.read_text(encoding="utf-8")
80
+ try:
81
+ if p.suffix.lower() == ".json":
82
+ data = json.loads(text)
83
+ else:
84
+ try:
85
+ import yaml
86
+ except ImportError:
87
+ data = mini_yaml(text)
88
+ else:
89
+ data = yaml.safe_load(text)
90
+ except ConfigError:
91
+ raise
92
+ except Exception as e: # any parser error becomes a readable input error
93
+ raise ConfigError(f"could not read {p}: {e}") from None
94
+ if data is None:
95
+ return {}
96
+ if not isinstance(data, dict):
97
+ raise ConfigError(f"{p}: expected key: value pairs at the top level")
98
+ return data
99
+
100
+
101
+ def mini_yaml(text: str) -> dict:
102
+ """The YAML subset our config uses (nested mappings of scalars), so PyYAML stays optional."""
103
+ root: dict = {}
104
+ stack: list[tuple[int, dict]] = [(-1, root)]
105
+ for n, raw in enumerate(text.splitlines(), 1):
106
+ line = _strip_comment(raw)
107
+ if not line.strip():
108
+ continue
109
+ indent = len(line) - len(line.lstrip(" "))
110
+ key, rest = _split_key(line.strip(), n)
111
+ while indent <= stack[-1][0]:
112
+ stack.pop()
113
+ parent = stack[-1][1]
114
+ if rest.strip():
115
+ parent[key] = _scalar(rest)
116
+ else:
117
+ parent[key] = {}
118
+ stack.append((indent, parent[key]))
119
+ return root
120
+
121
+
122
+ def _strip_comment(line: str) -> str:
123
+ quote = None
124
+ for i, ch in enumerate(line):
125
+ if quote:
126
+ quote = None if ch == quote else quote
127
+ elif ch in "'\"":
128
+ quote = ch
129
+ elif ch == "#" and (i == 0 or line[i - 1].isspace()):
130
+ return line[:i].rstrip()
131
+ return line.rstrip()
132
+
133
+
134
+ def _split_key(s: str, n: int) -> tuple[str, str]:
135
+ if s[0] in "'\"" and (end := s.find(s[0], 1)) > 0 and s[end + 1:end + 2] == ":":
136
+ return s[1:end], s[end + 2:]
137
+ if ": " in s:
138
+ key, rest = s.split(": ", 1)
139
+ return key.strip(), rest
140
+ if s.endswith(":"):
141
+ return s[:-1].strip(), ""
142
+ raise ConfigError(f"line {n}: expected 'key: value', got {s!r}")
143
+
144
+
145
+ def _scalar(s: str):
146
+ s = s.strip()
147
+ if len(s) >= 2 and s[0] == s[-1] and s[0] in "'\"":
148
+ return s[1:-1]
149
+ if s.lower() in ("null", "~"):
150
+ return None
151
+ if s.lower() in ("true", "false"):
152
+ return s.lower() == "true"
153
+ for cast in (int, float):
154
+ try:
155
+ return cast(s)
156
+ except ValueError:
157
+ pass
158
+ return s
159
+
160
+
161
+ INIT_TEMPLATE = """\
162
+ # {name} config, written by `{name} init`. Every key is optional.
163
+ # `{name} check` reads ./{config} automatically, or pass --config FILE (alias: --mapping).
164
+
165
+ # Thresholds. All of them are printed in every report.
166
+ thresholds:
167
+ min_cases: 30 # decided cases needed before a reviewer or step is judged
168
+ max_disagreement_upper: 0.05 # sign 1: 95% upper bound on the disagreement rate is below this
169
+ max_median_seconds: 30 # sign 2: median time from opened_at to decided_at is below this
170
+ drift_recent_days: 14 # drift compares the most recent N days...
171
+ drift_baseline_days: 28 # ...with the N days before that
172
+ drift_change: 0.5 # time per case falling by 50% or more counts as a trend
173
+ logging_dominant_share: 0.99 # one value on 99%+ of rows looks hard-coded
174
+ logging_min_second_value: 5 # so does a second value seen fewer than 5 times
175
+ queue_max_per_day: 200 # decided cases per reviewer per working day
176
+
177
+ # Which column in your data holds each field. Columns with common names are found automatically,
178
+ # and the check prints the mapping it used. Set a field to null if your data does not have it.
179
+ columns:
180
+ # case_id: ticket_id
181
+ # recommended: ai_suggestion # what the system proposed
182
+ # decision: final_status # what the human did
183
+ # reviewer: handled_by
184
+ # opened_at: first_opened_at # when the reviewer opened the case: the important one
185
+ # decided_at: closed_at
186
+ # notified_at: queued_at
187
+ # category: refund_band # approval step or category; each one gets its own verdict
188
+ # executed: times_executed # how many times the approved action actually ran
189
+
190
+ # Your values -> canonical values. Recognised without mapping: approve, approved, accept, accepted,
191
+ # reject, rejected, deny, denied, decline, declined, escalate, escalated, timeout_approve, timeout_reject.
192
+ # Any other value is listed in the output and its rows are skipped until you map it here.
193
+ values:
194
+ recommended:
195
+ # "REFUND": approve
196
+ # "NO_REFUND": reject
197
+ decision:
198
+ # "AUTO_APPROVED_SLA": timeout_approve # nobody reviewed it before the deadline, approved anyway
199
+ # "AUTO_REJECTED_SLA": timeout_reject
200
+
201
+ timezone: UTC # applied to timestamps that have no offset
202
+ csv_delimiter: null # detected automatically; set ";" or "tab" to force it
203
+ pseudonymize_salt: "{salt}" # used by --pseudonymize; keep it stable so hashes match across runs
204
+ """
205
+
206
+
207
+ def init_text() -> str:
208
+ return INIT_TEMPLATE.format(name=NAME, config=CONFIG_FILE, salt=secrets.token_hex(8))