From 911e1d81b11220a98eef5ac9caf5ab33aeb183aa Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 21:30:48 -0700 Subject: [PATCH] Fix the review's faults: only good outcomes set speed; damaged history files skipped; stale starts cleared; judge input bounds and redaction; --better wording Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- sisi/models.py | 43 +++++++++++------------ sisi/retro.py | 34 +++++++----------- sisi/store.py | 14 +++++++- tests/test_core.py | 86 +++++++++++++++++++++++++++++++++++++++++++++- 5 files changed, 131 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index b631e4d..021f806 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ its limits are. | `sisi pick routine\|ordinary\|hard [--review-of WORKER] [--not WORKER]` | The wheel gives one worker; a review goes to a different maker | | `sisi retro` | Print what happened in this piece of work, to set against the objective | | `sisi retro --gap … --cause … --improve … --term T [--scope user]` | Record the gap and the term of the objective it fell short on; the improvement is a rule at once | -| `sisi retro --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded, not a rule) | +| `sisi retro --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded with the retro; it becomes a rule only if it recurs, when the rules are organized) | | `sisi retro --later …` | The work is not finished yet | | `sisi learn [--project] "…"` | The person's own words become a rule at once | | `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them; undo the last change | diff --git a/sisi/models.py b/sisi/models.py index 5f7ae53..30d4c25 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -2,7 +2,7 @@ A research worker writes it, the lead reads it to route, and `sisi judge` adds how each delegation went so the next research knows. The table is plain text a person can read and correct.""" -import json, os, re, time +import json, math, os, re, time from . import rules, store RESEARCH = """You are a worker. Do this task yourself; do not delegate it further. @@ -123,7 +123,9 @@ def claim(s, text): for name in s.get("picked") or []: if any(re.search(r"(? 0: - out.setdefault(short(o["worker"]), []).append(o["minutes"]) - except (ValueError, KeyError, TypeError): - pass + for o in store.records("outcomes.jsonl"): + if o.get("verdict") == "good" and type(o.get("minutes")) is int and 0 < o["minutes"] <= 10000 and isinstance(o.get("worker"), str): + out.setdefault(short(o["worker"]), []).append(o["minutes"]) return {w: v[-10:] for w, v in out.items()} @@ -222,13 +220,10 @@ def pick(args, cwd=None, rand=None): def outcomes(n): out = [] - for line in store.read(store.data("outcomes.jsonl")).splitlines()[-n:]: - try: - o = json.loads(line) + for o in store.records("outcomes.jsonl")[-n:]: + if all(type(o.get(k)) is str for k in ("ts", "worker", "verdict", "why")): out.append("%s %s %s %s%s" % (o["ts"][:10], o["worker"], o["verdict"], "(%d min) " % o["minutes"] if type(o.get("minutes")) is int else "", o["why"])) - except (ValueError, KeyError): - pass return out @@ -259,27 +254,29 @@ def research_record(answer_file): def judge(args, cwd=None): """`sisi judge WORKER good|bad "" [--minutes N]`: how a delegation went, and how long it took (from the pick's start in this session unless --minutes says).""" + from . import retro # not at the top: hooks import this module and must stay quick minutes = None if "--minutes" in args: i = args.index("--minutes") v, args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:] - minutes = int(v) if re.fullmatch(r"[1-9]\d*", v) else 0 - if len(args) != 3 or args[1] not in ("good", "bad") or len(args[2].split()) < 3 or minutes == 0: + minutes = int(v) if re.fullmatch(r"[1-9]\d{0,3}|10000", v) else 0 + if len(args) != 3 or not args[0].strip() or args[1] not in ("good", "bad") or len(args[2].split()) < 3 or minutes == 0: print('usage: sisi judge WORKER good|bad "" [--minutes N]') return 1 sid = store.current_session(cwd) if sid: with store.session(sid) as s: - starts = s.get("starts", {}).get(short(args[0])) - if starts: - began = starts.pop(0) - minutes = minutes or max(1, int((time.time() - began) / 60)) + starts = s["starts"].get(short(args[0])) if isinstance(s.get("starts"), dict) else None + if isinstance(starts, list) and starts: + began = starts.pop(0) # a start in the future or not a number is dropped and times nothing + if type(began) in (int, float) and math.isfinite(began) and began <= time.time(): + minutes = minutes or max(1, int((time.time() - began) / 60)) log = store.data("outcomes.jsonl") store.append(log, json.dumps(dict({"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "worker": args[0], "verdict": args[1], - "why": " ".join(args[2].split()), "project": os.path.basename(store.project_root(cwd))}, + "why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd))}, **{"minutes": minutes} if minutes else {}), sort_keys=True)) store.commit("delegation judged", log) - print("recorded.") + print("recorded: %d min." % minutes if minutes else "recorded, not timed.") return 0 diff --git a/sisi/retro.py b/sisi/retro.py index e70dd5c..1a38f87 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -19,7 +19,7 @@ USAGE = """Record one of these: sisi retro --no-gap "" --term TERM \\ --better "" TERM is where the work fell short, or could most have scored better: %s. - A piece of work can always be done better; the better is recorded, not made a rule. + A piece of work can always be done better; the better is recorded with the retro, and becomes a rule only if it recurs, when the rules are organized. sisi retro --later "\"""" % "; ".join("%s = %s" % kv for kv in TERMS.items()) @@ -39,7 +39,7 @@ def counts(state, cwd): def facts(state, cwd): n, dirty = counts(state, cwd), store.git(["status", "--porcelain"], cwd)[1].splitlines() d = show(state["done"]) if state.get("done") else ["(no done recorded)"] - named = fell(_records()[-10:]) + named = fell(store.records("retro.jsonl")[-10:]) out = ["time (measured): %d minutes since %s" % (n["minutes"], "the last retro" if state.get("retro_at") else "the session began"), "cost (measured): you made %d tool call(s) yourself and %d delegation(s); workers used: %s" % ( n["direct"], n["delegations"], ", ".join(state.get("workers_since") or []) or "none")] @@ -58,17 +58,6 @@ def show(d): + ["next: " + d["next"]]) -def _records(): - out = [] - for line in store.read(store.data("retro.jsonl")).splitlines(): - try: - if isinstance(json.loads(line), dict): - out.append(json.loads(line)) - except ValueError: - pass - return out - - def fell(group): """How many of these records named each term, e.g. "time 4, attention 2" (old records carry none).""" return ", ".join("%s %d" % (k, n) for k in TERMS for n in [sum(r.get("term") == k for r in group)] if n) @@ -76,18 +65,19 @@ def fell(group): def trend(): """The measured trend, by term, over the records that carry numbers: the last 10 pieces of work and the 10 before.""" - records = _records() + records = store.records("retro.jsonl") units = [r for r in records if isinstance(r.get("unit"), dict)] + num = lambda x, k: x[k] if type(x.get(k)) in (int, float) else 0 median = lambda v: (lambda s: (s[(len(s) - 1) // 2] + s[len(s) // 2]) / 2.0)(sorted(v)) out = [] for label, group in (("last", units[-10:]), ("before", units[-20:-10])): if group: u = [r["unit"] for r in group] out.append(" %s %d: time median %g min; cost median %g calls; attention median %g messages; evidence %d checks failed" % ( - label, len(group), median([x.get("minutes", 0) for x in u]), - median([x.get("direct", 0) + x.get("delegations", 0) for x in u]), median([x.get("messages", 0) for x in u]), - sum(x.get("checks_fail", 0) for x in u))) - out.append(" fell short on: %s" % (fell(records[-10:]) or "nothing named yet")) + label, len(group), median([num(x, "minutes") for x in u]), + median([num(x, "direct") + num(x, "delegations") for x in u]), median([num(x, "messages") for x in u]), + sum(num(x, "checks_fail") for x in u))) + out.append(" fell short or could do better on: %s" % (fell(records[-10:]) or "nothing named yet")) return ["measured (pieces of work with numbers):"] + out if len(units) >= 2 else [] @@ -118,7 +108,7 @@ def record(s, cwd, opt): store.commit("retro recorded", log) s["snapshot"], s["changed"], s["retro_at"] = store.snapshot(cwd), False, now for key in ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", "done", "paused", - "fails_since", "picked"): + "fails_since", "picked", "starts"): s.pop(key, None) @@ -158,7 +148,7 @@ def done(args, cwd=None): def _options(args): opt, i = {}, 0 while i < len(args): - if args[i] in FLAGS and i + 1 < len(args): + if args[i] in FLAGS and i + 1 < len(args) and args[i][2:] not in opt: opt[args[i][2:]] = clean(args[i + 1]) i += 2 else: @@ -183,7 +173,7 @@ def run(args, cwd=None): else "later" if set(opt) == {"later"} and _words(opt, "later", 3) else "no-gap" if set(opt) == {"no-gap"} and _words(opt, "no-gap", 5) else "gap" if set(opt) == {"gap", "cause", "improve"} and all(_words(opt, k, 4) for k in opt) else None) - if kind is None or len(opt.get("improve", "")) > 400 or (kind == "later" and (term or better)) or (kind != "no-gap" and better): + if kind is None or len(opt.get("improve", "")) > 400 or len(better or "") > 400 or (kind == "later" and (term or better)) or (kind != "no-gap" and better): print("sisi retro: that is not a retro yet (each part needs a real sentence; an improvement is at most " "400 characters).\n" + USAGE) return 1 @@ -192,7 +182,7 @@ def run(args, cwd=None): return 1 if kind == "no-gap" and len((better or "").split()) < 5: print("sisi retro: a piece of work can always be done better. Add --better \"\"; it is recorded, not made a rule." % term) + "scored better on %s, 5+ words>\"; it is recorded, and becomes a rule only if it recurs." % term) return 1 opt.update({"term": term} if kind == "gap" else {"term": term, "better": clean(better)} if kind == "no-gap" else {}) if sid: diff --git a/sisi/store.py b/sisi/store.py index db7a02b..21f671b 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -39,12 +39,24 @@ def data(*parts): def read(path, default=""): try: - with open(path, encoding="utf-8") as f: + with open(path, encoding="utf-8", errors="replace") as f: return f.read() except OSError: return default +def records(name): + """The JSON objects in a data file, one per line; a damaged or non-object line is skipped.""" + out = [] + for line in read(data(name)).splitlines(): + try: + o = json.loads(line) + except (ValueError, RecursionError): + continue + out += [o] if isinstance(o, dict) else [] + return out + + def write(path, text): os.makedirs(os.path.dirname(path), exist_ok=True) tmp = "%s.%d.tmp" % (path, os.getpid()) diff --git a/tests/test_core.py b/tests/test_core.py index 2c672f7..4414d22 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -441,6 +441,90 @@ class Core(unittest.TestCase): self.assertEqual(judge()[0], 0) self.assertEqual(self.outcomes()[-1]["minutes"], 1) + def jsonl(self, name, *lines): + os.makedirs(self.data, exist_ok=True) + with open(os.path.join(self.data, name), "wb") as f: + f.write(b"\n".join(l if isinstance(l, bytes) else l.encode() for l in lines) + b"\n") + + def outcome(self, worker, verdict, minutes): + return json.dumps({"ts": "2026-11-20T10:00:00", "worker": worker, "verdict": verdict, "minutes": minutes, "why": "did it fine"}) + + def test_only_good_outcomes_set_a_workers_speed(self): + self.jsonl("outcomes.jsonl", *[self.outcome("flaky", "bad", 1)] * 10 + [self.outcome("steady", "good", 15)] * 10) + r = subprocess.run([sys.executable, "-B", "-c", "from sisi import models; print(models.speeds())"], cwd=REPO, + env=self.env, capture_output=True, text=True) + self.assertEqual(r.stdout.strip(), str({"steady": [15] * 10})) + + def test_damaged_history_files_break_no_command(self): + self.table(FIXTURE) + junk = [b"\xff\xfe", b"null", b"[]", b'{"unit": {"minutes": null}}', b'{"unit": {"minutes": null}}', b'{"ts": 5}', + b'{"ts": 5, "worker": "x", "verdict": "good", "why": "a b c", "minutes": null}'] + self.jsonl("outcomes.jsonl", *junk) + self.jsonl("retro.jsonl", *junk) + for args in (("pick", "hard"), ("models",), ("models", "research"), ("retro",)): + rc, out, err = self.sisi(*args, sid="s1") + self.assertEqual((rc, err), (0, ""), args) + + def test_a_stale_or_odd_start_never_times_a_judgement(self): + self.table(WORKERS) + self.hook("tick") + self.hook("prompt", prompt="go") + self.done() + judge = lambda *a: self.sisi("judge", "sonnet", "good", "did the job in one pass", *a, sid="s1") + delegate = lambda: (self.sisi("pick", "hard", sid="s1")[0], self.tool("Agent", tool_input={"model": "sonnet"})[0]) + + def start(value): + with open(os.path.join(self.tmp, "state", "core-sessions", "s1.json"), "r+") as f: + st = json.load(f) + st["starts"] = value + f.seek(0), f.truncate(), json.dump(st, f) + self.assertEqual(delegate(), (0, 0)) + start({"sonnet": [time.time() + 3600]}) # a start in the future + rc, out, _ = judge() + self.assertEqual((rc, out.strip()), (0, "recorded, not timed.")) + self.assertNotIn("minutes", self.outcomes()[-1]) + self.assertEqual(self.state()["starts"]["sonnet"], []) + start({"sonnet": [time.time() - 600]}) + self.assertEqual(judge()[1].strip(), "recorded: 10 min.") + for wrong in ([], "x", 5): # starts of the wrong type + self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0) + start(wrong) + self.assertEqual(self.tool("Agent", tool_input={"model": "sonnet"})[0], 0) # the pick is still spent + self.assertEqual(self.state()["picked"], []) + start(wrong) + self.assertEqual(judge()[1].strip(), "recorded, not timed.") + self.assertEqual(delegate(), (0, 0)) # a retro ends the stored starts + self.assertIn("starts", self.state()) + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export change", sid="s1")[0], 0) + self.assertNotIn("starts", self.state()) + self.assertEqual(judge()[1].strip(), "recorded, not timed.") # no stale start left to time it + + def test_judge_and_retro_refuse_odd_input(self): + judge = lambda *a: self.sisi("judge", *a, sid="s1") + self.assertEqual(judge("sonnet", "good", "did the job in one pass", "--minutes", "10000")[0], 0) + self.assertEqual(self.outcomes()[-1]["minutes"], 10000) + for bad in ("10001", "1" * 400): + self.assertEqual(judge("sonnet", "good", "did the job in one pass", "--minutes", bad)[0], 1, bad) + self.assertEqual(judge("", "good", "did the job in one pass")[0], 1) + self.assertEqual(judge(" ", "good", "did the job in one pass")[0], 1) + self.assertEqual(len(self.outcomes()), 1) + self.assertEqual(judge("sonnet", "bad", "leaked token=abc123secretvalue in its answer")[0], 0) + self.assertNotIn("abc123secretvalue", self.read(self.data, "outcomes.jsonl")) + long = "word " * 90 + self.assertEqual(self.sisi("retro", "--no-gap", "the export kept every row", "--term", "time", "--better", long)[0], 1) + for flag, other in (("--term", "time"), ("--better", "start the first build in the same turn"), ("--no-gap", "the export kept every row")): + args = ["--no-gap", "the export kept every row", "--term", "time", "--better", "start the first build in the same turn"] + rc, out, _ = self.sisi("retro", *args, flag, other) + self.assertEqual((rc, "Record one of these" in out), (1, True), flag) + rc, out, _ = self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export change", "--gap", "again the rows were dropped quietly") + self.assertEqual(rc, 1) + self.assertEqual(self.sisi("retro", "--no-gap", "the export kept every row", *NG)[0], 0) + self.assertEqual(self.sisi("retro", "--no-gap", "the export kept every row", *NG)[0], 0) + out = self.sisi("retro")[1] + self.assertIn("fell short or could do better on: time 2", out) + self.assertNotIn("recorded, not made a rule", self.sisi("retro")[1]) + self.assertIn("becomes a rule only if it recurs", self.sisi("retro")[1]) + def test_the_wheel_favours_the_faster_worker(self): sys.path.insert(0, REPO) from sisi import models @@ -539,7 +623,7 @@ class Core(unittest.TestCase): self.write(log, self.read(log) + "\n".join(rec(m, n, f, g) for m, n, f, g in ((20, 4, 1, True), (30, 6, 0, False), (40, 8, 2, True))) + "\n") out = self.sisi("retro", sid="s1")[1] self.assertRegex(out, r"time median 25 min.*cost median 2 calls.*attention median 5 messages.*evidence 3 checks failed") - self.assertIn("fell short on: time 2, attention 2", out) + self.assertIn("fell short or could do better on: time 2, attention 2", out) self.assertIn("learning (measured): last 10 pieces of work named: time 2, attention 2", out) def test_the_new_objective_is_the_one_the_retro_reads(self):