#!/usr/bin/env python3
"""Tally one council round from member reply files.
Usage:
tally.py [--state FILE] [--target N] [--cap N] [--skipped NAME]... [--no-save] REPLY...
REPLY is `name=path` or a path (the member name is then the file stem).
A reply whose first line starts with `skipped` (e.g. `skipped (limit)`,
`skipped (unavailable)`) counts as skipped, as does `--skipped NAME`. The score is the first line that
starts with score/overall/final/rating/verdict followed by `N/10`, or a line
that is only `N/10`. A reply without one is `no score`; a score is never
invented.
--state holds previous rounds as JSON. It is read if present, this round is
appended, and it is written back (unless --no-save). Prints the round table
in the SKILL.md report format, the average, the findings, and which stop
rule fires.
Stdlib only, Python 3.8+.
"""
import argparse
import json
import re
import sys
from pathlib import Path
SKIPPED = "skipped (limit)"
NO_SCORE = "no score"
TAGS = ("blocker", "should", "nit")
FRACTION = r"(\d{1,2}(?:\.\d+)?)\s*/\s*10(?![\d.]*\d)"
_MD = r"[\s#>*_`\-+]*"
_SEP = r"[\s:*_`=\-–—]*"
# A score only counts on a labeled line ("Score: 7/10", "**Final score** - 6/10")
# or a line that is only the fraction ("**7.5/10**"). A fraction inside a
# finding sentence is never a score.
LABELED_SCORE = re.compile(
r"^" + _MD + r"(?:score|overall|final|rating|verdict)\b"
+ r"(?:" + _SEP + r"(?:score|rating|verdict))?" + _SEP + r"(?<![\d.])" + FRACTION,
re.I,
)
BARE_SCORE = re.compile(r"^" + _MD + r"(?<![\d.])" + FRACTION + r"[\s*_`.]*$")
FINDING = re.compile(
r"^\s*(?:[-*+]|\d+[.)])?\s*(?:\*\*|__|\[|`)?\s*(blocker|should|nit)\s*(?:\*\*|__|\]|`)?\s*[:\-–—]?\s*(.*)$",
re.I,
)
LOCATION = re.compile(r"((?:[\w.@-]+/)*[\w@-][\w.@-]*\.[A-Za-z0-9]+):(\d+)")
def parse_reply(text):
"""Return {"score": float|None|SKIPPED, "findings": [...]} for one reply."""
stripped = text.strip()
first = stripped.splitlines()[0].strip() if stripped else ""
if first.lower().startswith("skipped"):
return {"score": first.lower() if "(" in first else SKIPPED, "findings": []}
score = None
lines = stripped.splitlines()
for line in lines:
m = LABELED_SCORE.match(line) or BARE_SCORE.match(line)
if m and 0 <= float(m.group(1)) <= 10:
score = float(m.group(1))
break
findings = []
for line in lines:
m = FINDING.match(line)
if not m:
continue
rest = m.group(2).strip()
loc = LOCATION.search(rest)
findings.append({
"tag": m.group(1).lower(),
"file": loc.group(1) if loc else None,
"line": int(loc.group(2)) if loc else None,
"text": rest,
})
return {"score": score, "findings": findings}
def numeric(score):
return isinstance(score, (int, float)) and not isinstance(score, bool)
def is_skipped(score):
return isinstance(score, str) and score.startswith("skipped")
def fmt_score(score):
if score is None:
return NO_SCORE
if is_skipped(score):
return score
return f"{score:g}/10"
def average(members):
vals = [m["score"] for m in members.values() if numeric(m["score"])]
return round(sum(vals) / len(vals), 2) if vals else None
def finding_keys(members):
return {
(f["tag"], f["file"], f["line"]) if f["file"]
else (f["tag"], None, " ".join(f["text"].lower().split()))
for m in members.values()
for f in m["findings"]
if f["tag"] != "nit"
}
def stop_rule(rounds, target, cap):
"""Return (rule, reason) for the first stop rule that fires, or (None, reason)."""
cur = rounds[-1]["members"]
active = {n: m for n, m in cur.items() if not is_skipped(m["score"])}
blockers = sum(f["tag"] == "blocker" for m in active.values() for f in m["findings"])
shoulds = sum(f["tag"] == "should" for m in active.values() for f in m["findings"])
scored = [m["score"] for m in active.values() if numeric(m["score"])]
if active and len(scored) == len(active) and all(s >= target for s in scored) and blockers == 0:
return "target met", f"every scoring member >= {target:g}/10, no open blocker"
if active and blockers == 0 and shoulds == 0:
return "only nits left", "no blocker or should across members"
if len(rounds) >= 2:
prev_avg, cur_avg = rounds[-2]["average"], rounds[-1]["average"]
if prev_avg is not None and cur_avg is not None and cur_avg - prev_avg < 0.5:
return "plateau", f"average {prev_avg:g} -> {cur_avg:g} (rose < 0.5)"
if len(rounds) >= 3:
stuck = finding_keys(cur) & finding_keys(rounds[-2]["members"]) & finding_keys(rounds[-3]["members"])
if stuck:
tag, f, l = sorted(stuck, key=str)[0]
where = f"at {f}:{l}" if f else f"'{l}'"
return "plateau", f"{tag} {where} survived two fix attempts"
if len(rounds) >= cap:
return "round cap", f"{len(rounds)} of {cap} rounds used"
return None, "no stop rule fired"
def render(rounds, rule, reason):
names = []
for r in rounds:
for n in r["members"]:
if n not in names:
names.append(n)
n_rounds = len(rounds)
status = f"stopped: {rule}" if rule else "continue"
out = ["## Council review", "", f"Rounds: {n_rounds} ({status})", ""]
out.append("| Delegate | " + " | ".join(f"Round {i + 1}" for i in range(n_rounds)) + " |")
out.append("| --- |" + " --- |" * n_rounds)
for n in names:
cells = [fmt_score(r["members"][n]["score"]) if n in r["members"] else "—" for r in rounds]
out.append(f"| {n} | " + " | ".join(cells) + " |")
avgs = [f"{r['average']:g}" if r["average"] is not None else "—" for r in rounds]
out.append("| Average | " + " | ".join(avgs) + " |")
out.append("")
cur = rounds[-1]["members"]
found = [(n, f) for n, m in cur.items() for f in m["findings"]]
found.sort(key=lambda nf: TAGS.index(nf[1]["tag"]))
counts = {t: sum(f["tag"] == t for _, f in found) for t in TAGS}
out.append(f"Round {n_rounds} findings: {counts['blocker']} blocker, {counts['should']} should, {counts['nit']} nit")
for n, f in found:
out.append(f"- **{f['tag']}** ({n}) {f['text']}")
out.append("")
out.append(f"Stop rule: {rule or 'none'} ({reason})")
return "\n".join(out)
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("replies", nargs="*", help="name=path or path")
ap.add_argument("--state", help="JSON with previous rounds; this round is appended")
ap.add_argument("--target", type=float, help="score target (default 8; setting it raises the cap to 5)")
ap.add_argument("--cap", type=int, help="round cap (default 3, or 5 with --target)")
ap.add_argument("--skipped", action="append", default=[], metavar="NAME", help="member skipped (limit)")
ap.add_argument("--no-save", action="store_true", help="do not write --state back")
args = ap.parse_args(argv)
state = {"rounds": []}
if args.state and Path(args.state).exists():
state = json.loads(Path(args.state).read_text())
if args.target is not None:
state["target"], state["target_set"] = args.target, True
if args.cap:
state["cap_override"] = args.cap
target = state.get("target", 8.0)
cap = state.get("cap_override") or (5 if state.get("target_set") else 3)
members = {}
for spec in args.replies:
name, sep, path = spec.partition("=")
if not sep:
name, path = Path(spec).stem, spec
p = Path(path)
if not p.exists():
ap.error(f"reply file not found: {path}")
members[name] = parse_reply(p.read_text(encoding="utf-8", errors="replace"))
for name in args.skipped:
members[name] = {"score": SKIPPED, "findings": []}
if not members:
ap.error("no replies given")
state["rounds"].append({"members": members, "average": average(members)})
rule, reason = stop_rule(state["rounds"], target, cap)
print(render(state["rounds"], rule, reason))
if args.state and not args.no_save:
Path(args.state).write_text(json.dumps(state, indent=2) + "\n")
return 0
if __name__ == "__main__":
sys.exit(main())