From 33427c0394e27399c13f0558cd5b98588c98eab7 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 14:34:16 -0700 Subject: [PATCH] Items 6, 7, 8, 10: rule-add/rule-replace with shortens, every problem reported at once, merge and specific reject, a self-contained brief of at most 6000 characters and 8 learnings, apply summary in 15 lines, status --learning, lessons ID. done / next: docs, repeat runs, rehearsal Co-Authored-By: Claude Sonnet 5.5 --- sisi/cycle.py | 233 ++++++++++++++++++-------- sisi/learning.py | 5 +- tests/test_cycle_hardening.py | 297 ++++++++++++++++++++++++++++++++++ tests/test_learning_loop.py | 4 +- 4 files changed, 465 insertions(+), 74 deletions(-) diff --git a/sisi/cycle.py b/sisi/cycle.py index 49380cf..2f0fafa 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -1,39 +1,37 @@ """The learning cycle: proposed learnings become mechanisms in the user store. -Due by a counter (no scheduler). A worker writes a cycle file; `sisi cycle apply FILE` -treats it as untrusted input, validates and plans everything before writing anything, -replays command checks against the originating unit's commits in a temporary worktree -(one replay implementation: evaluate.validate_command), refuses protected rules, parks -consequential changes for the owner (`sisi approve`), and commits each change to the user -store so revert is exact. What cannot be replayed is `unvalidated` and always reported as -such; nothing is labelled `validated` without a validation run that passed. +Due by a counter (no scheduler): learnings a cycle can act on (`proposed`, not tool changes, not +waiting for the owner). `sisi cycle` prints a brief a small agent can act on alone: the file format +with an example per action, every enumerated value, what each kind of action does, and at most +eight learnings with statement, origin and whether commits are recorded, in at most 6000 +characters. The agent writes a cycle file. `sisi cycle check FILE` runs nothing and lists every +problem at once; `sisi cycle apply FILE` treats the file as untrusted input, validates and plans +everything before writing anything, replays command checks (one replay implementation: +evaluate.validate_command) only between the two commits the learning's own record holds, in an +exported copy of each tree with no history and a reduced environment, refuses protected rules, +parks consequential changes for the owner (`sisi approve`, which needs the word typed at the +terminal), and commits each change to the user store so revert is exact. What cannot be replayed is +`unvalidated` and always reported as such; nothing is labelled `validated` without a validation run +that passed. What a mechanism reaches is decided here from the learning, never from the cycle file: a mechanism is written with the learning's id and the scope the learning has *earned* (learning.earned_scope: its origin project, unless it was seen in two units in two projects or is an owner statement made at user scope). A scope or `every_project` flag in the file is only a request for more; a request for more than the learning has earned, any enforced command that -is not proven in its origin project, any risk pattern that lowers a profile, any replacement or -disabling of a rule, and any rule or library entry from a learning confined to one project -wait for the owner. Readers filter by project; nothing reads a flag the cycle author wrote. +is not proven in its origin project, any risk pattern that lowers a profile, any whole-rule +replacement or disabling of a rule, any sentence added to a rule or library entry from a learning +confined to one project, and any mechanism for a project that no longer exists wait for the owner. +Readers filter by project; nothing reads a flag the cycle author wrote. -Cycle file (JSON): - {"base": "", "actions": [ - {"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", - "cmd": "...", "expect": {"exit": 0}, "before": "", "after": ""}, - {"action": "promote", "learning": "L-0002", "mechanism_kind": "contract-requirement", - "when": "csv import", "require_kind": "property"}, - {"action": "promote", "learning": "L-0003", "mechanism_kind": "rule-text", - "rule_id": "new-rule", "rule_text": "## Title {#new-rule}\\n\\n... Why: ..."}, - {"action": "promote", "learning": "L-0004", "mechanism_kind": "library", - "library_kind": "recipe"|"verifier", "entry_text": "..."}, - {"action": "promote", "learning": "L-0005", "mechanism_kind": "risk", - "pattern": "src/auth/**", "profile": "critical"}, - {"action": "promote", "learning": "L-0006", "mechanism_kind": "routing", - "kind": "impl", "difficulty": 2, "prefer": "worker-x"}, - {"action": "promote", "learning": "L-0007", "mechanism_kind": "benchmark", - "name": "csv-import", "case": {"...": "..."}}, - {"action": "revise"|"revert"|"reject", "learning": "L-0008", "why": "..."}]} +A learning waiting for the owner is `pending-approval`; a change to sisi itself is `backlog` (it +goes out with `sisi promote --export`). Neither is in a brief or counts towards "due". + +Actions (the brief carries a filled example of each): promote with mechanism_kind +command-check, contract-requirement (`when` is a risk profile or a path glob), rule-add (one or +two sentences before a rule's Why, naming what it shortens), rule-replace (the whole rule, always +the owner's), library, risk, routing, benchmark; reject (a specific reason), merge (into another +learning), revise, revert; disable-rule. Mechanism data files (user store overlay); every entry carries learning, scope, project: enforced.json {"checks": [{"type": "command"|"contract-requirement", "learning": id, ...}]} @@ -222,28 +220,109 @@ def due_notice(session=None): return "\n".join(lines) +BRIEF_MAX_LEARNINGS = 8 +BRIEF_MAX_CHARS = 6000 +STATEMENT_MAX = 600 # a longer statement is cut, with the command that shows it whole + +FORMAT = """Write one JSON file, then run `sisi cycle check FILE` (runs nothing; lists every problem at once) and +`sisi cycle apply FILE`. Never run `sisi approve`: only the owner decides what waits. +{"base": "@BASE@", "actions": [ one action per learning below; leave a learning out to leave it ]} +Actions (L-0000 stands for an id listed below): + {"action":"promote","learning":"L-0000","mechanism_kind":"command-check","cmd":"grep -q fixed f.txt","expect":{"exit":0}} + {"action":"promote","learning":"L-0000","mechanism_kind":"contract-requirement","when":"src/auth/**","require_kind":"parsing"} + {"action":"promote","learning":"L-0000","mechanism_kind":"rule-add","rule_id":"deliver-fast","add":"One or two sentences.","shortens":"nothing: "} + {"action":"promote","learning":"L-0000","mechanism_kind":"rule-replace","rule_id":"deliver-fast","rule_text":"## Title {#deliver-fast}\\n\\nBody.\\n\\nWhy: ...","shortens":"..."} + {"action":"promote","learning":"L-0000","mechanism_kind":"library","library_kind":"recipe","entry_text":"---\\nid: x\\n---\\n..."} + {"action":"promote","learning":"L-0000","mechanism_kind":"risk","pattern":"src/auth/**","profile":"critical"} + {"action":"promote","learning":"L-0000","mechanism_kind":"routing","kind":"impl","difficulty":2,"prefer":"worker-x"} + {"action":"promote","learning":"L-0000","mechanism_kind":"benchmark","name":"csv-import","case":{...}} + {"action":"reject","learning":"L-0000","why":"names the evidence: the retry loop in sync.py was already removed"} + {"action":"merge","learning":"L-0000","into":"L-9999","why":"same cause"} {"action":"revise"|"revert","learning":"L-0000","why":"..."} +Values: mechanism_kind @KINDS@; risk profile @PROFILES@; require_kind @REQKINDS@; + library_kind recipe|verifier; difficulty 1|2|3; when = a risk profile (that or higher) or a path glob. +A command check: cmd must name a path the fix changed; apply replays it in a copy of the tree without .git, between the + commits recorded for the learning (never ones you write): it must fail at the start and pass at the end. No commits: it waits. +Takes effect at once: reject, merge, revise, revert; risk (not lowering), routing, benchmark, contract-requirement; a replayed + command check; rule-add and library only from a learning seen in 2 units in 2 projects. +Held for the owner: rule-replace, disable-rule, rule-add or library from a one-project learning, a command check that was not + replayed, risk that lowers a profile, scope beyond what was earned, a project gone from disk. +Refused (whole file, every reason listed): protected rules (@PROTECTED@), a vacuous or failed replay, a generic reject reason, + a learning acted on twice or already waiting, a rule with a change waiting, a rulebook over @BUDGET@, a flagged learning left out. +Rules you may change (id): @RULES@. Rulebook now @SIZE@. Adding to it means naming what it shortens, or "nothing: ". +""" + + +def _learning_block(r): + pr = r.get("proposed") or {} + prov = r.get("provenance") or [] + units = len({p.get("unit") for p in prov}) + projects = len({p.get("project") for p in prov}) + stmt = " ".join(str(pr.get("description") or r.get("title") or "").split()) + if len(stmt) > STATEMENT_MAX: + stmt = stmt[:STATEMENT_MAX].rstrip() + " ... (`sisi lessons %s` shows it whole)" % r["id"] + commits = "yes" if L.replay_commits(r) else "no" + lines = ["- %s [%s; earned scope %s; seen in %d unit(s), %d project(s)]" % ( + r["id"], pr.get("mechanism") or "policy", L.earned_scope(r), units, projects), + " statement: %s" % stmt, + " origin: %s, unit %s, commits recorded: %s" % (os.path.basename(str(r.get("origin_project") or "").rstrip("/")) or "?", + r.get("source_unit") or "?", commits)] + if r.get("expected_effect"): + lines.append(" expected effect: %s" % " ".join(str(r["expected_effect"]).split())[:160]) + return "\n".join(lines) + + +def _rank(rows): + """The most recurrent first, then the oldest; flagged learnings (which the cycle must act on) lead.""" + def key(r): + prov = r.get("provenance") or [] + return (0 if r.get("flagged_not_working") else 1, -len({p.get("unit") for p in prov}), str(r.get("created") or ""), + r["id"]) + return sorted(rows, key=key) + + +def format_text(base): + from . import risk, contract as _contract + rules = overlay.effective()[1] + prot = protected_rules() + ids = ", ".join(r["id"] for r in rules if r["id"] not in prot) + lines, chars = _book_size() + return (FORMAT.replace("@BASE@", base).replace("@KINDS@", "|".join(MECHANISM_KINDS)) + .replace("@PROFILES@", "|".join(risk.PROFILES)).replace("@REQKINDS@", "|".join(_contract.KINDS)) + .replace("@PROTECTED@", ", ".join(sorted(p for p in prot if p in {r["id"] for r in rules}))) + .replace("@BUDGET@", "%d lines/%d characters" % (overlay.MAX_LINES, overlay.MAX_CHARS)) + .replace("@RULES@", ids).replace("@SIZE@", "%d lines/%d characters" % (lines, chars))) + + def brief_text(): + """The whole brief for a cheap agent working alone: the file format with one example per action, + every enumerated value, what happens to each kind of action, and at most BRIEF_MAX_LEARNINGS + learnings (flagged first, then the most recurrent, then the oldest), each with its statement, + origin project, source unit and whether commits are recorded, in at most BRIEF_MAX_CHARS.""" rows = L.load_learnings() changed = L.monitor(rows) if changed: L.save_learnings(rows, "monitoring: %d learning(s) now monitored" % len(changed), touched=changed, via="cycle") - lines = ["Learning cycle brief. Base: %s" % L.store_base(rows), "", - "Write one cycle file (JSON, format in `sisi cycle help`) turning proposed " - "learnings into mechanisms. Prefer an executable mechanism over rule text. " - "A command check is replayed against its unit's commits and must fail before " - "the fix and pass after (the repository must be trusted and the command must exist " - "at both commits). A mechanism reaches only the scope its learning has earned; " - "anything wider, any command that is not proven, any replaced or disabled rule " - "waits for the owner. Protected rules (canon/protected.json) cannot be touched.", ""] - for r in proposed(rows): - lines.append("- %s [%s] %s (earned scope: %s)\n change: %s\n expect: %s validate: %s" - % (r["id"], r.get("proposed", {}).get("mechanism"), r.get("title"), L.earned_scope(r), - r.get("proposed", {}).get("description"), r.get("expected_effect"), - (r.get("validation") or {}).get("method"))) - for r in L.flagged(rows): - lines.append("- %s FLAGGED NOT WORKING (%d recurrences since promotion): this cycle " - "must revise or revert it." % (r["id"], r.get("recurrences_after_promotion", 0))) - return "\n".join(lines) + "\n" + base = L.store_base(rows) + flagged = {r["id"] for r in L.flagged(rows)} + todo = _rank([r for r in proposed(rows) if r["id"] not in flagged] + L.flagged(rows)) + text = "Learning cycle brief.\n" + format_text(base) + blocks, left = [], 0 + for r in todo[:BRIEF_MAX_LEARNINGS]: + if r["id"] in flagged: + blk = "- %s FLAGGED NOT WORKING (%d recurrences since promotion): act on it with revise or revert." % ( + r["id"], r.get("recurrences_after_promotion", 0)) + else: + blk = _learning_block(r) + if len(text) + sum(len(b) + 1 for b in blocks) + len(blk) + 120 > BRIEF_MAX_CHARS and r["id"] not in flagged: + left += 1 + continue + blocks.append(blk) + left += max(0, len(todo) - BRIEF_MAX_LEARNINGS) + out = text + "Learnings (%d of %d; the most recurrent first, then the oldest):\n" % (len(blocks), len(todo)) \ + + ("\n".join(blocks) if blocks else "(none a cycle can act on)") + "\n" + if left: + out += "%d more wait for the next cycle.\n" % left + return out # ---- replay validation (one implementation: evaluate.validate_command) ----------------- @@ -1175,40 +1254,52 @@ def cmd_approve(argv): return 2 -HELP = """sisi cycle: turn proposed learnings into mechanisms. JSON cycle file: - {"base": "", "actions": [ ... ]} -promote actions, by mechanism_kind: - command-check {learning, cmd, expect?, before?, after?} replayed in the origin project's trusted - repository: it must exist at both commits, fail before and pass after - contract-requirement {learning, when, require_kind, max_rung?} - rule-text {learning, rule_id, rule_text} (protected rules refused) - library {learning, library_kind: recipe|verifier, entry_text, entry_id?, replacing?} - risk {learning, pattern, profile} -> overlay/risk-adjustments.json - routing {learning, kind, difficulty?, prefer|avoid} -> overlay/routing-adjustments.json - benchmark {learning, name, case:{...}} -> overlay/benchmarks/.json -other actions: {action: revise|revert|reject, learning, why}; {action: disable-rule, rule_id} -Every mechanism is written with its learning's id and the scope that learning has earned (its origin -project unless it was seen in two units in two projects, or is an owner statement); a scope or -every_project flag only asks for more. These wait for the owner (`sisi approve`, in a terminal): -more scope than earned, a command not proven by replay, a risk pattern that lowers a profile, a -replaced or disabled rule, a rule or library entry from a learning confined to one project. -A cycle that ignores a flagged learning is refused. `sisi cycle revert` undoes only that cycle's changes. -""" +APPLY_LINES = 15 # what `apply` prints at most + + +def _capped(lines, n=APPLY_LINES): + return lines if len(lines) <= n else lines[:n - 1] + ["... and %d more line(s)" % (len(lines) - n + 1)] + + +def _summary(cid, lines): + """What took effect, what waits and what was refused, in at most APPLY_LINES lines.""" + wait = [x for x in lines if "waits for the owner" in x] + took = [x for x in lines if x not in wait] + head = "%s applied: %d took effect, %d wait for the owner, 0 refused" % (cid, len(took), len(wait)) + body = ["took effect: " + x for x in took] + ["waits: " + x.split(": `sisi approve`")[0] for x in wait] + if wait: + body.append("the owner decides: `sisi approve` lists each in full, then `sisi approve ID --yes|--no`") + return [head] + _capped(body, APPLY_LINES - 1) + + +def _check_summary(plan): + cmds = sum(1 for p in plan if p["kind"] == "promote" and p["action"].get("mechanism_kind") == "command-check") + wait = sum(1 for p in plan if p["pending"] and not (p["kind"] == "promote" + and p["action"].get("mechanism_kind") == "command-check")) + lines = ["valid: %d action(s); %d apply at once, %d wait for the owner%s" % ( + len(plan), len(plan) - wait - cmds, wait, + ", %d command check(s) are replayed only by `apply`, which decides whether each takes effect or waits" % cmds + if cmds else "")] + for p in plan: + if p["pending"] and p["reasons"] and not (p["kind"] == "promote" + and p["action"].get("mechanism_kind") == "command-check"): + lines.append("waits: %s: %s" % (p["rec"]["id"] if p["rec"] else p["action"].get("rule_id"), + "; ".join(p["reasons"]))) + return _capped(lines) def cmd_cycle(args): if args and args[0] == "help": - sys.stdout.write(HELP) + sys.stdout.write(format_text("")) return 0 if args and args[0] == "apply" and len(args) > 1: try: cid, lines = apply_file(args[1]) except (CycleError, OSError, documents.DocumentError, overlay.OverlayError) as e: - print("sisi cycle: %s" % e, file=sys.stderr) + msg = str(e).splitlines() + print("\n".join(_capped(["sisi cycle: " + msg[0]] + msg[1:])), file=sys.stderr) return 2 - print("%s applied:" % cid) - for x in lines: - print("- " + x) + print("\n".join(_summary(cid, lines))) return 0 if args and args[0] == "check" and len(args) > 1: try: @@ -1216,10 +1307,10 @@ def cmd_cycle(args): doc = json.load(f) plan = validate_doc(doc, L.load_learnings(), run=False) except (CycleError, OSError, ValueError, documents.DocumentError, overlay.OverlayError) as e: - print("sisi cycle: %s" % e, file=sys.stderr) + msg = str(e).splitlines() + print("\n".join(_capped(["sisi cycle: " + msg[0]] + msg[1:])), file=sys.stderr) return 2 - wait = sum(1 for p in plan if p["pending"]) - print("valid: %d action(s) apply at once, %d wait for the owner" % (len(plan) - wait, wait)) + print("\n".join(_check_summary(plan))) return 0 if args and args[0] == "revert": try: diff --git a/sisi/learning.py b/sisi/learning.py index 6dd6a19..beebd68 100644 --- a/sisi/learning.py +++ b/sisi/learning.py @@ -39,7 +39,10 @@ GENERIC_WORDS = set(( "went go goes gone smooth smoothly expected nicely perfect perfectly success successful successfully " "finished complete completed happened happen hitch hitches without notable remarkable report reported " "particular special specific cause causes reason reasons known unknown clear obvious say said " - "passed pass green").split()) + "passed pass green " + # a verdict with no reason ("not useful", "wrong idea") says nothing about what is wrong + "useful useless unneeded unnecessary needed relevant irrelevant important valuable worthwhile pointless " + "redundant wrong incorrect invalid idea ideas").split()) class LearningError(Exception): diff --git a/tests/test_cycle_hardening.py b/tests/test_cycle_hardening.py index 6960f13..9c7abd8 100644 --- a/tests/test_cycle_hardening.py +++ b/tests/test_cycle_hardening.py @@ -548,3 +548,300 @@ class Duplicates(Base): r = self.apply([{"action": "disable-rule", "rule_id": "deliver-fast"}], base=L.store_base()) self.assertIn("already has a change", r.stderr) self.assertEqual(len(self.pending()), 1) + + +class Rules(Base): + """R-11.5-10, R-11.5-11, R-11.7-2 (item 6): rule text is an addition by default.""" + + def add(self, lid, rid="deliver-fast", text="Hand the owner a first useful result early, then refine it.", + shortens="nothing: every sentence of the rule is needed", **kw): + a = {"action": "promote", "learning": lid, "mechanism_kind": "rule-add", "rule_id": rid, "add": text} + if shortens is not None: + a["shortens"] = shortens + a.update(kw) + return a + + def test_rule_add_goes_before_why_waits_for_a_one_project_learning_and_prints_the_size(self): + from sisi import overlay + _contract(self) + self.git_init() + self.retro(*PROMOTE[1:]) + r = self.apply([self.add("L-0001", text="Name the first useful result in the plan. Hand it over early.")]) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(len(self.pending()), 1) + self.assertEqual(self.pending()[0]["action"]["mechanism_kind"], "rule-add") + self.assertNotIn("Name the first useful", overlay.render()) + listing = self.sisi("approve").stdout + self.assertIn("Name the first useful result in the plan.", listing) + self.assertIn("what it shortens: nothing", listing) + with terminal(): + r = self.sisi("approve", "P-0001", "--yes") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertRegex(r.stdout, r"the loaded rulebook went from \d+ to \d+ lines, \d+ to \d+ characters") + body = overlay.render().split("{#deliver-fast}", 1)[1].split("{#orchestrate}", 1)[0] + self.assertLess(body.index("Hand it over early."), body.index("Why:")) + self.assertIn("Never buy speed with a weaker check or a smaller result. Name the first", body) # same paragraph + + def test_the_applied_message_prints_the_size_before_and_after(self): + """Item 6: an applied rule-add (a learning that earned its scope) says what it cost the loaded rulebook.""" + _contract(self) + self.retro(*PROMOTE[1:]) + self.earn("L-0001") + r = self.apply([self.add("L-0001")], base=L.store_base()) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertRegex(r.stdout, r"went from \d+ to \d+ lines, \d+ to \d+ characters") + self.assertEqual(self.pending(), []) + + def test_twenty_sentences_are_refused_and_so_is_an_add_that_names_nothing_it_shortens(self): + """Item 6 abuse case: 20 sentences in one add; twenty adds that say nothing about what they shorten.""" + _contract(self) + self.retro(*PROMOTE[1:]) + twenty = " ".join("Sentence number %d says something about delivering." % i for i in range(20)) + r = self.apply([self.add("L-0001", text=twenty)]) + self.assertEqual(r.returncode, 2) + self.assertIn("one or two plain sentences", r.stderr) + ids = ["L-0001"] + [self.another(n) for n in range(1, 20)] + rules = ["deliver-fast", "orchestrate", "size-by-risk", "own-the-outcome"] + acts = [self.add(lid, rid=rules[n % 4], shortens=None) for n, lid in enumerate(ids)] + r = self.apply(acts, base=L.store_base()) + self.assertEqual(r.returncode, 2) + self.assertIn("20 problem(s)", r.stderr) # all of them are reported, and the output stays short + self.assertLessEqual(len(r.stderr.splitlines()), 15) + self.assertGreaterEqual(r.stderr.count("needs \"shortens\""), 10) + self.assertFalse(self.exists("overlay/rules")) # nothing was applied + # a shortens that names no rule and does not say nothing is refused too + r = self.apply([self.add("L-0001", shortens="some other thing entirely")]) + self.assertIn("must name an existing rule id", r.stderr) + + def test_the_rulebook_budget_still_holds_and_is_reported_with_the_other_problems(self): + _contract(self) + self.retro(*PROMOTE[1:]) + big = "## Huge {#huge-rule}\n\n" + "\n".join("line %d of the rule" % i for i in range(400)) + "\n\nWhy: no.\n" + r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace", + "rule_id": "huge-rule", "rule_text": big}]) + self.assertEqual(r.returncode, 2) + self.assertIn("needs \"shortens\"", r.stderr) # both problems of the one action are not hidden: first found + r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace", + "rule_id": "huge-rule", "rule_text": big, "shortens": "nothing: it is all new"}]) + self.assertIn("breaks the rulebook budget", r.stderr) + + def test_protected_rules_and_unknown_rules_are_refused_for_rule_add(self): + """R-11.7-2: protected under its id and under a retired id; the existing tests keep the rest.""" + _contract(self) + self.retro(*PROMOTE[1:]) + r = self.apply([self.add("L-0001", rid="verify-enough")]) + self.assertIn("protected", r.stderr) + r = self.apply([self.add("L-0001", rid="no-such-rule")]) + self.assertIn("no rule 'no-such-rule'", r.stderr) + + def test_rule_text_is_gone_with_a_message_that_says_what_to_use(self): + _contract(self) + self.retro(*PROMOTE[1:]) + r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", + "rule_id": "deliver-fast", "rule_text": "## X {#deliver-fast}\n\nA.\n\nWhy: b.\n"}]) + self.assertIn("use rule-add", r.stderr) + + +class Check(Base): + """R-11.5-6, R-16-7 (items 7 and 10): check lists every problem at once, each with how to fix it.""" + + def test_one_check_lists_every_problem(self): + _contract(self) + self.git_init() + ids = [self.another(n) for n in range(6)] + rows = self.rows() + rows[5]["flagged_not_working"] = True + L.save_learnings(rows, "t", touched=rows, via="test") + acts = [ + {"action": "reject", "learning": ids[0], "why": "not useful"}, + {"action": "promote", "learning": ids[1], "mechanism_kind": "rule-add", "rule_id": "deliver-fast", + "add": "Hand the owner a first useful result early."}, + {"action": "promote", "learning": ids[2], "mechanism_kind": "contract-requirement", + "when": "csv import", "require_kind": "parsing"}, + {"action": "promote", "learning": "L-0099", "mechanism_kind": "risk", "pattern": "x", "profile": "critical"}, + {"action": "promote", "learning": ids[3], "mechanism_kind": "command-check", "cmd": "echo ok"}, + {"action": "frobnicate", "learning": ids[4]}, + ] + p = self.cycle_file(acts, base="stale") + r = self.sisi("cycle", "check", p) + self.assertEqual(r.returncode, 2) + self.assertIn("7 problem(s)", r.stderr) + for fragment in ("stale or missing \"base\"", "generic", "needs \"shortens\"", "not something the code evaluates", + "no learning 'L-0099'", "unknown action 'frobnicate'", "flagged-not-working"): + self.assertIn(fragment, r.stderr) + self.assertLessEqual(len(r.stderr.splitlines()), 15) + # each problem says how to fix it; fix them all and the next check passes + acts = [{"action": "reject", "learning": ids[0], "why": "the importer fix removed the %s row loss" % "alpha"}, + {"action": "promote", "learning": ids[1], "mechanism_kind": "rule-add", "rule_id": "deliver-fast", + "add": "Hand the owner a first useful result early.", "shortens": "nothing: every sentence is needed"}, + {"action": "promote", "learning": ids[2], "mechanism_kind": "contract-requirement", + "when": "data/*.csv", "require_kind": "parsing"}, + {"action": "revert", "learning": ids[5], "why": "recurred twice since promotion"}] + r = self.sisi("cycle", "check", self.cycle_file(acts)) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("valid: 4 action(s)", r.stdout) + + def test_a_reject_with_a_generic_reason_is_refused_and_a_specific_one_is_not(self): + _contract(self) + self.retro(*PROMOTE[1:]) + r = self.apply([{"action": "reject", "learning": "L-0001", "why": "not useful"}]) + self.assertEqual(r.returncode, 2) + self.assertIn("generic", r.stderr) + self.assertEqual(self.rows()[0]["status"], "proposed") + r = self.apply([{"action": "reject", "learning": "L-0001", + "why": "f.txt is generated now, so a content check on it cannot fail"}]) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(self.rows()[0]["status"], "rejected") + + def test_merge_into_another_learning(self): + _contract(self) + self.retro(*PROMOTE[1:]) + self.retro("--new", *PROMOTE[1:]) # the same words again, as its own learning: L-0002 + self.assertEqual(len(self.rows()), 2) + r = self.apply([{"action": "merge", "learning": "L-0002", "into": "L-0001", "why": "same finding"}]) + self.assertEqual(r.returncode, 0, r.stderr) + rows = {x["id"]: x for x in self.rows()} + self.assertEqual((rows["L-0002"]["status"], rows["L-0002"]["merged_into"]), ("merged", "L-0001")) + self.assertEqual(rows["L-0001"]["status"], "proposed") + self.assertEqual(rows["L-0001"]["history"][-1]["learning"], "L-0002") + # into itself, into a learning that is gone, into one that shares nothing: refused + other = self.another(5) + for into, frag in (("L-0001", "different learning"), ("L-0099", "different learning"), (other, "share too little")): + r = self.apply([{"action": "merge", "learning": "L-0001", "into": into}], base=L.store_base()) + self.assertEqual(r.returncode, 2) + self.assertIn(frag, r.stderr) + self.assertEqual(self.apply([{"action": "merge", "learning": other, "into": "L-0002"}], + base=L.store_base()).returncode, 2) # into a merged (ended) learning + + def test_apply_prints_what_took_effect_what_waits_and_what_was_refused_in_fifteen_lines(self): + self.git_init() + _contract(self) + ids = [self.another(n) for n in range(20)] + acts = [] + for n, lid in enumerate(ids): + if n % 2: + acts.append({"action": "promote", "learning": lid, "mechanism_kind": "command-check", "cmd": "make x%d" % n}) + else: + acts.append({"action": "reject", "learning": lid, "why": "the %s importer path was deleted last week" % lid}) + r = self.apply(acts) + self.assertEqual(r.returncode, 0, r.stderr) + lines = r.stdout.splitlines() + self.assertLessEqual(len(lines), 15) + self.assertRegex(lines[0], r"cycle-0001 applied: 10 took effect, 10 wait for the owner, 0 refused") + self.assertIn("... and", r.stdout) + + def test_status_learning_prints_only_the_learning_report_and_lessons_shows_one(self): + _contract(self) + self.retro(*PROMOTE[1:]) + r = self.sisi("status", "--learning") + self.assertEqual(r.returncode, 0) + self.assertTrue(r.stdout.startswith("Learning loop"), r.stdout[:80]) + self.assertNotIn("closed work units yet", r.stdout) + self.assertNotIn("recent units", r.stdout) + self.assertIn("by status: proposed 1", r.stdout) + one = self.sisi("lessons", "L-0001") + self.assertEqual(one.returncode, 0) + self.assertEqual(json.loads(one.stdout)["id"], "L-0001") + self.assertEqual(self.sisi("lessons", "L-0042").returncode, 2) + self.assertEqual(self.sisi("lessons", "show", "L-0001").stdout, one.stdout) + + +class Brief(Base): + """R-11.1-14, R-11.5-4, R-16-10 (item 8): a small model can act on the brief alone.""" + + def many(self, n, long=False): + _contract(self) + words = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa quebec romeo sierra tango".split() + for i in range(n): + w = words[i % 20] + str(i) + change = "make the %s importer reject every row with a negative amount, and say in the summary which row it rejected" % w + if long: + change += ", " + "and keep a count of every rejected row by reason in the run summary " * 12 + r = self.retro("--new", "--finding", "the %s importer accepted a negative amount in row %d" % (w, i), + "--cause", "no check covered the %s amount column" % w, "--impact", "correctness", + "--disposition", "promote", "--change", change, "--mechanism", "verification", + "--expect", "negative amounts in %s are caught" % w, "--validate", "run the %s importer on a bad file" % w) + self.assertEqual(r.returncode, 0, r.stderr) + + def test_the_brief_is_small_complete_and_limited_to_eight_learnings(self): + self.many(30, long=True) + text = self.sisi("cycle").stdout + self.assertLessEqual(len(text), 6000, len(text)) + listed = [l for l in text.splitlines() if l.startswith("- L-")] + self.assertLessEqual(len(listed), 8) + self.assertGreaterEqual(len(listed), 2) + self.assertIn("more wait for the next cycle", text) + self.assertNotIn("sisi cycle help", text) + for needle in ("command-check", "contract-requirement", "rule-add", "rule-replace", "library", "risk", "routing", + "benchmark", "reject", "merge", "revise", "revert", + "trivial|isolated|logic|integration|data|critical|release", "general|concurrency", + "Takes effect at once", "Held for the owner", "Refused", "recipe|verifier"): + self.assertIn(needle, text) + self.assertNotRegex(text, r"(?m)^\s*(expect|validate):\s*$") + self.assertNotIn("None", text) + + def test_each_learning_has_its_full_statement_origin_unit_and_commit_flag(self): + self.many(3) + rows = self.rows() + rows[1]["source_unit"] = rows[2]["source_unit"] = "another-unit" + L.save_learnings(rows, "t", touched=rows, via="test") + self.archive_unit("a" * 40, "b" * 40, uid=self.rows()[0]["source_unit"]) + text = self.sisi("cycle").stdout + blocks = text.split("\n- L-")[1:] + self.assertEqual(len(blocks), 3) + r0 = self.rows()[0] + full = r0["proposed"]["description"] + self.assertGreater(len(full), 95) # the old brief cut at 95 + self.assertIn(full, text) + self.assertIn("origin: proj, unit %s, commits recorded: yes" % r0["source_unit"], text) + self.assertIn("commits recorded: no", text) + self.assertIn("expected effect: negative amounts", text) + + def test_the_most_recurrent_come_first_then_the_oldest_and_flagged_always_appear(self): + self.many(12) + rows = self.rows() + by = {r["id"]: r for r in rows} + for n in (9, 10): # L-0010 and L-0011 recurred in two more units + by["L-%04d" % (n + 1)]["provenance"] += [{"unit": "x%d" % k, "project": "p", "kind": "recurrence"} for k in (1, 2)] + rows[11]["flagged_not_working"] = True + L.save_learnings(rows, "t", touched=rows, via="test") + text = self.sisi("cycle").stdout + order = [l.split()[1] for l in text.splitlines() if l.startswith("- L-")] + self.assertEqual(order[0], "L-0012") # flagged leads + self.assertEqual(order[1:3], ["L-0010", "L-0011"]) # most recurrent + self.assertEqual(order[3:6], ["L-0001", "L-0002", "L-0003"]) # then the oldest + self.assertIn("FLAGGED NOT WORKING", text) + + def test_every_example_in_the_brief_is_valid_json_and_names_a_known_kind(self): + from sisi import cycle + text = cycle.format_text("b") + n = 0 + for line in text.splitlines(): + if not line.startswith(" {"): + continue + for part in line.replace(" {", "\n{").splitlines(): + part = part.strip().replace('"revise"|"revert"', '"revise"').replace("{...}", "{}") + d = json.loads(part) + self.assertIn(d["action"], ("promote", "reject", "merge", "revise")) + if d["action"] == "promote": + self.assertIn(d["mechanism_kind"], cycle.MECHANISM_KINDS) + n += 1 + self.assertEqual(n, 11) + + def test_a_cheap_agent_can_write_the_file_from_the_brief_alone(self): + """The examples, filled in with the ids from the brief, check clean.""" + self.git_init() + self.many(4) + text = self.sisi("cycle").stdout + ids = [l.split()[1] for l in text.splitlines() if l.startswith("- L-")] + base_value = text.split('{"base": "', 1)[1].split('"', 1)[0] + acts = [{"action": "promote", "learning": ids[0], "mechanism_kind": "risk", "pattern": "importers/**", "profile": "critical"}, + {"action": "reject", "learning": ids[1], "why": "the importers directory was deleted in the last release"}, + {"action": "promote", "learning": ids[2], "mechanism_kind": "contract-requirement", + "when": "importers/**", "require_kind": "parsing"}] + p = os.path.join(self.tmp, "c.json") + with open(p, "w") as f: + json.dump({"base": base_value, "actions": acts}, f) + r = self.sisi("cycle", "check", p) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0) diff --git a/tests/test_learning_loop.py b/tests/test_learning_loop.py index 3cfe3b7..7e0fc4b 100644 --- a/tests/test_learning_loop.py +++ b/tests/test_learning_loop.py @@ -120,7 +120,7 @@ class Base(SisiCase): "--mechanism", "verification", "--expect", "the %s case is caught" % word, "--validate", "run the %s fixture" % word) self.assertEqual(r.returncode, 0, r.stderr) - return "L-%04d" % (n + 1) + return self.rows()[-1]["id"] def set_config(self, cfg): os.makedirs(self.data, exist_ok=True) @@ -763,7 +763,7 @@ class Mechanisms(Base): bad = [{"action": "promote", "learning": "L-0002", "mechanism_kind": "risk", "pattern": "y/**", "profile": "logic"}] self.assertNotEqual(self.apply(bad).returncode, 0) - good = [{"action": "reject", "learning": "L-0001", "why": "wrong idea"}] + good = [{"action": "reject", "learning": "L-0001", "why": "the f.txt content check was replaced by a type check"}] self.assertEqual(self.apply(good).returncode, 0) self.assertEqual(self.rows()[0]["status"], "rejected")