Universal lessons with project handover; whole-document edits; worker discovery and routing
ci / tests (macos-latest, python 3.10) (push) Canceled after 0s
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.10) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s

Lessons and statements carry a required scope; project items leave the shared
store for a per-project handover pile filed into that project's own docs.
Every learning round ends with a whole-document edit with traced lessons.
sisi workers / route / delegate discover tools, choose the most affordable
adequate worker and record results in the personal store; the host tool's own
subagents come first, the command-line runner is the fallback.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 08:59:21 -07:00
1 parent dad13062a1
commit ba84772acf
33 files changed
+4623 -125

No files matched your search

+26 -3
View File
@@ -52,8 +52,29 @@ class ShortCase(LibCase):
def cycle_doc(self, notes=None, **parts):
doc = {"version": 1, "base": cycle.base_version(), "summary": "test cycle"}
if notes is not None:
notes = list(notes)
have = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-scope"}
for e in list(notes):
if isinstance(e, dict) and isinstance(e.get("lesson"), int) and e["lesson"] not in have:
notes.append({"lesson": e["lesson"], "action": "set-scope", "scope": "everywhere"})
have.add(e["lesson"])
doc["notes"] = notes
doc.update(parts)
# A cycle file must also answer for every document the brief lists for whole-document
# review: mark them reviewed here (tests of rewriting itself live in test_documents).
try:
from sisi import documents as _docs
_con = retro.connect()
try:
_have = {e.get("doc") for e in doc.get("documents") or [] if isinstance(e, dict)}
_rev = [{"doc": d["doc"], "action": "reviewed", "reason": "test helper: structure left as it is"}
for d in _docs.required_documents(_con) if d["doc"] not in _have]
finally:
_con.close()
if _rev:
doc["documents"] = list(doc.get("documents") or []) + _rev
except Exception:
pass
p = os.path.join(self.tmp, "cycle.json")
with open(p, "w") as f:
json.dump(doc, f)
@@ -165,7 +186,7 @@ class DigestTests(ShortCase):
self.assertLess(out.index("## asking questions"), out.index("## Not yet summarized"))
self.assertIn("Use a readiness probe, not a sleep.", out)
self.assertIn("in the rulebook", out)
self.assertIn("attached to fuzz work", out)
self.assertIn("attached to Fuzz work", out)
self.assertIn("loose note", out)
self.assertIn("change to sisi itself, not built yet", out)
self.assertIn("seen 3 times", out)
@@ -190,7 +211,7 @@ class DigestTests(ShortCase):
def test_digest_shows_what_you_said_first(self):
self.seed_digest()
self.assertEqual(self.sisi("learn", "Always", "show", "the", "options.").returncode, 0)
self.assertEqual(self.sisi("learn", "--scope", "everywhere", "Always", "show", "the", "options.").returncode, 0)
out = self.sisi("lessons", "digest").stdout
self.assertIn("## What you said", out)
self.assertIn("Always show the options.", out)
@@ -292,7 +313,9 @@ class BulletTests(ShortCase):
# restore base: the previous cycle changed the lesson, so clear via a fresh cycle file
doc2 = {"version": 1, "base": cycle.base_version(), "summary": "second",
"notes": [{"lesson": lid, "action": "set-short",
"short": "Prefer probes over sleeps.", "topic": "testing"}]}
"short": "Prefer probes over sleeps.", "topic": "testing"}],
"documents": [{"doc": "recipe:parser-or-codec", "action": "reviewed",
"reason": "this round only rewrites the short line"}]}
p2 = self.cycle_path(doc2)
r = self.sisi("cycle", "apply", p2)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+289
View File
@@ -0,0 +1,289 @@
"""Whole-document edits in a learning round: folded lessons become part of the document's own
text, every lesson stays traceable to the exact fragment that carries it, structure is checked
mechanically, and a stale personal copy is listed for re-merge instead of silently kept."""
import json, os, unittest
from support import *
from sisi import cycle, documents, overlay, paths, retro
from test_verifiers import LibCase, vfile, dfile
WHEN = "parser, codec, parse, decode, round trip, fuzzing, tabular data"
RECIPE_BODY = """## Done means
- The parser accepts every valid input in the corpus.
- Invalid input is refused with a clear error.
## Checks
- Round trip: `proptest` (many-inputs), rung 2.
## Common false finishes
- Only the examples in the report were tried.
"""
REWRITE = """---
id: parser-or-codec
title: Parser or codec work
applies_to: parsing work
---
## Done means
- The parser accepts every valid input in the corpus.
- Invalid input is refused with a clear error.
- Seed the corpus from the golden files before fuzzing.
- Try truncated input at every length.
## Checks
- Round trip: `proptest` (many-inputs), rung 2.
## Common false finishes
- Only the examples in the report were tried.
"""
class DocCase(LibCase):
def setUp(self):
super().setUp()
self.put("prove/fuzz.md", vfile("fuzz"))
self.put("many-inputs/proptest.md", vfile("proptest", "many-inputs", 2))
self.put("parser-or-codec.md",
dfile("parser-or-codec", title="Parser or codec work", applies="parsing work",
body="\n" + RECIPE_BODY), self.ddir)
self.notes = os.path.join(self.data, "notes")
def mk(self, change, **kw):
f = dict(aim="verified", change_kind="recipe", target="parser-or-codec",
moment="the parser accepted a truncated file in the nightly job",
cause="no truncated-input case existed", change=change, when=WHEN,
scope="everywhere", short="Seed the corpus from golden files.", topic="parsing")
f.update(kw)
con = retro.connect()
try:
lid = retro.new_lesson(con, f, self.proj, None)
con.commit()
return lid
finally:
con.close()
def cycle_file(self, **parts):
doc = {"version": 1, "base": cycle.base_version(), "summary": "document round"}
doc.update(parts)
p = os.path.join(self.tmp, "cycle.json")
with open(p, "w") as fh:
json.dump(doc, fh)
return p
def tree_bytes(self):
out = {}
for root in (paths.overlay_dir(), paths.notes_dir()):
for dp, dns, fns in os.walk(root):
for n in fns:
p = os.path.join(dp, n)
with open(p, "rb") as fh:
out[p] = fh.read()
return out
class BriefAndCheckTests(DocCase):
def test_brief_lists_recipe_with_field_notes_in_full(self):
a = self.mk("Seed the corpus from the golden files before fuzzing parsers")
b = self.mk("Try truncated input at every length when testing a parser",
short="Try truncated input at every length.")
brief = cycle.brief_text()
self.assertIn("recipe:parser-or-codec", brief)
self.assertIn("whole-document", brief.lower())
self.assertIn("Seed the corpus from the golden files", brief) # the folded lesson, universal part
self.assertIn("one instruction per bullet", brief.lower()) # the editorial standard
self.assertIn(RECIPE_BODY.splitlines()[1], brief) # the document's current text
def test_check_refuses_a_file_that_skips_a_listed_document(self):
self.mk("Seed the corpus from the golden files before fuzzing parsers")
r = self.sisi("cycle", "check", self.cycle_file())
self.assertEqual(r.returncode, 1)
self.assertIn("recipe:parser-or-codec", r.stdout)
self.assertIn("documents", r.stdout)
def test_reviewed_entry_satisfies_the_round(self):
self.mk("Seed the corpus from the golden files before fuzzing parsers")
p = self.cycle_file(documents=[{"doc": "recipe:parser-or-codec", "action": "reviewed",
"reason": "two short sections, one instruction per bullet, nothing duplicated"}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 0, r.stdout)
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
# still shown as a field note until a rewrite integrates it
self.assertIn("Seed the corpus", retro.notes_for("parser-or-codec"))
class RewriteTests(DocCase):
def _two_lessons(self):
a = self.mk("Seed the corpus from the golden files before fuzzing parsers")
b = self.mk("Try truncated input at every length when testing a parser",
short="Try truncated input at every length.")
return a, b
def test_rewrite_integrates_lessons_and_traces_them(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout)
out = self.sisi("done", "parser-or-codec").stdout
self.assertIn("Seed the corpus from the golden files before fuzzing.", out)
self.assertNotIn("Field notes from earlier agents", out) # integrated, not appended
self.assertEqual(retro.notes_for("parser-or-codec"), "")
show = self.sisi("lessons", "show", str(a)).stdout
self.assertIn("recipe:parser-or-codec", show)
self.assertIn("Seed the corpus from the golden files before fuzzing.", show)
traced = self.sisi("done", "parser-or-codec", "--trace").stdout
self.assertIn("#%d" % a, traced)
self.assertIn("Seed the corpus", traced)
def test_rewrite_missing_one_fragment_is_refused(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("lesson #%d" % b, r.stdout)
def test_fragment_must_occur_in_the_new_text(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "This sentence is nowhere in the document."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("fragment", r.stdout)
def test_dated_journal_bullet_is_refused(self):
a, b = self._two_lessons()
bad = REWRITE + "- 2024-01-02: an old note (aim: verified; seen 1 times; lesson %d)\n" % a
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": bad,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("dated", r.stdout.lower())
def test_lint_failing_recipe_is_refused(self):
a, b = self._two_lessons()
bad = REWRITE.replace("## Checks", "## Things")
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": bad,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
def test_revert_restores_documents_and_notes_byte_for_byte(self):
a, b = self._two_lessons()
before = self.tree_bytes()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
self.assertNotEqual(self.tree_bytes(), before)
self.assertEqual(self.sisi("cycle", "revert").returncode, 0)
self.assertEqual(self.tree_bytes(), before)
def test_product_change_lists_the_document_for_remerge(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
self.assertNotIn("needs a re-merge", cycle.brief_text())
prod = os.path.join(self.ddir, "parser-or-codec.md")
with open(prod) as fh:
text = fh.read()
with open(prod, "w") as fh:
fh.write(text.replace("Invalid input is refused", "Bad input is refused"))
brief = cycle.brief_text()
self.assertIn("Document recipe:parser-or-codec", brief)
self.assertIn("needs a re-merge", brief)
class RulebookTests(DocCase):
def test_rule_order_applies_and_numbers_follow_it(self):
_pre, rules = overlay.effective()
ids = [r["id"] for r in rules]
new_order = [ids[1], ids[0]] + ids[2:]
p = self.cycle_file(rule_order=new_order)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout)
_pre2, rules2 = overlay.effective()
self.assertEqual([x["id"] for x in rules2], new_order)
out = self.sisi("rule", "1").stdout
self.assertIn("{#%s}" % new_order[0], out)
self.assertEqual(self.sisi("cycle", "revert").returncode, 0)
_pre3, rules3 = overlay.effective()
self.assertEqual([x["id"] for x in rules3], ids)
def _rulebook_text(self, drop=None, extra=None):
pre, rules = overlay.effective()
parts = [pre] if pre.strip() else []
for r in rules:
if r["id"] == drop:
continue
body = r["body"] + (("\n\n" + extra) if extra and r["id"] == "know-done" else "")
parts.append("## %s {#%s}\n\n%s" % (r["title"], r["id"], body))
return "\n\n".join(parts) + "\n"
def test_rulebook_rewrite_traces_a_rule_lesson(self):
lid = self.mk("Name the check that decides done before starting the work",
change_kind="rule", target=None, short="Name the deciding check first.")
p = self.cycle_file(notes=[{"lesson": lid, "action": "fold-into-rule", "into": "know-done"}])
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
frag = "Name the check that decides done before starting."
bad = self.cycle_file(documents=[{"doc": "rulebook", "action": "rewrite",
"text": self._rulebook_text(drop="deliver-quickly", extra=frag),
"shortens": "know-done: tightened while integrating",
"trace": [{"lesson": lid, "fragment": frag}]}])
r = self.sisi("cycle", "check", bad)
self.assertEqual(r.returncode, 1)
self.assertIn("deliver-quickly", r.stdout)
good = self.cycle_file(documents=[{"doc": "rulebook", "action": "rewrite",
"text": self._rulebook_text(extra=frag),
"shortens": "know-done: tightened while integrating",
"trace": [{"lesson": lid, "fragment": frag}]}])
r = self.sisi("cycle", "apply", good)
self.assertEqual(r.returncode, 0, r.stdout)
out = self.sisi("rule", "know-done").stdout
self.assertIn(frag, out)
self.assertIn("carried in rulebook", out)
self.assertIn("lives : in rulebook", self.sisi("lessons", "show", str(lid)).stdout)
self.assertEqual(self.sisi("cycle", "revert").returncode, 0)
self.assertNotIn(frag, self.sisi("rule", "know-done").stdout)
def test_rule_order_must_name_every_rule_once(self):
_pre, rules = overlay.effective()
p = self.cycle_file(rule_order=[rules[0]["id"]])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("rule_order", r.stdout)
class StructureTests(unittest.TestCase):
def test_existing_library_passes_the_structure_checks(self):
bad = []
for kind, root in (("recipe", os.path.join(REPO, "done")),
("verifier", os.path.join(REPO, "verifiers"))):
for dp, dns, fns in os.walk(root):
for n in sorted(fns):
if not n.endswith(".md"):
continue
p = os.path.join(dp, n)
with open(p, encoding="utf-8") as fh:
text = fh.read()
for prob in documents.structure_problems(kind, text, n[:-3]):
bad.append("%s: %s" % (p, prob))
self.assertEqual(bad, [])
if __name__ == "__main__":
unittest.main()
+29
View File
@@ -258,6 +258,35 @@ class ByteExactTests(SafetyBase):
self.assertEqual(open(p, "rb").read(), edited)
class OldGeneratedTests(SafetyBase):
OLD_PI = (b"// sisi:generated by `sisi install` -- runs `sisi tick` at session start and `sisi gate` before the session settles. Remove with `sisi uninstall`.\n"
b"import { execFile } from \"node:child_process\";\nconst OLD = true;\n")
def test_old_pi_extension_updated_by_install_and_dry_run(self):
os.makedirs(self.path(".pi", "agent", "extensions"))
p = self.path(".pi/agent/extensions/sisi.ts")
self.put(".pi/agent/extensions/sisi.ts", self.OLD_PI)
r = self.sisi("install", "--dry-run")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn("is not ours", r.stdout)
self.assertEqual(open(p, "rb").read(), self.OLD_PI) # dry run changes nothing
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertNotEqual(open(p, "rb").read(), self.OLD_PI)
self.assertIn(b"sisi:generated", open(p, "rb").read().split(b"\n", 1)[0])
wiring.uninstall()
self.assertFalse(os.path.exists(p))
def test_old_marker_only_in_body_still_refused(self):
os.makedirs(self.path(".pi", "agent", "extensions"))
mine = b"// my extension\nexport const X = 'sisi:generated';\n"
self.put(".pi/agent/extensions/sisi.ts", mine)
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertEqual(open(self.path(".pi/agent/extensions/sisi.ts"), "rb").read(), mine)
wiring.uninstall()
class FailOpenCommandTests(SafetyBase):
def test_hook_command_fails_open_without_launcher(self):
repo = os.path.join(self.tmp, "repo-copy")
+28 -7
View File
@@ -66,10 +66,13 @@ class LearningCase(LibCase):
con.close()
notes = list(doc.get("notes") or [])
covered = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-short"}
scoped = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-scope"}
exempt = {e.get("lesson") for e in notes if isinstance(e, dict)
and e.get("action") in ("retire", "withdraw", "merge")}
extra = []
for r in rows:
if r["id"] not in scoped and r["id"] not in exempt:
extra.append({"lesson": r["id"], "action": "set-scope", "scope": "everywhere"})
if r["id"] in covered or r["id"] in exempt:
continue
if (r.get("short") or "").strip() and (r.get("topic") or "").strip():
@@ -84,6 +87,21 @@ class LearningCase(LibCase):
doc["notes"] = notes + extra
except Exception:
pass
# A cycle file must also answer for every document the brief lists for whole-document
# review: mark them reviewed here (tests of rewriting itself live in test_documents).
try:
from sisi import documents as _docs
_con = retro.connect()
try:
_have = {e.get("doc") for e in doc.get("documents") or [] if isinstance(e, dict)}
_rev = [{"doc": d["doc"], "action": "reviewed", "reason": "test helper: structure left as it is"}
for d in _docs.required_documents(_con) if d["doc"] not in _have]
finally:
_con.close()
if _rev:
doc["documents"] = list(doc.get("documents") or []) + _rev
except Exception:
pass
p = os.path.join(self.tmp, "cycle.json")
with open(p, "w") as f:
json.dump(doc, f)
@@ -475,8 +493,9 @@ class CycleApplyTests(LearningCase):
b = self.mk(change="Session two lesson about widget caching", moment="s2 wait at step 2")
base = cycle.base_version() # both sessions read the same brief
_ss = lambda lid: {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}
doc1 = {"version": 1, "base": base, "summary": "one", "notes": [{"lesson": a, "action": "keep"}, _ss(a), _ss(b)]}
doc2 = {"version": 1, "base": base, "summary": "two", "notes": [{"lesson": b, "action": "keep"}, _ss(a), _ss(b)]}
_sc = lambda lid: {"lesson": lid, "action": "set-scope", "scope": "everywhere"}
doc1 = {"version": 1, "base": base, "summary": "one", "notes": [{"lesson": a, "action": "keep"}, _ss(a), _ss(b), _sc(a), _sc(b)]}
doc2 = {"version": 1, "base": base, "summary": "two", "notes": [{"lesson": b, "action": "keep"}, _ss(a), _ss(b), _sc(a), _sc(b)]}
paths_ = []
for i, d in enumerate((doc1, doc2)):
p = os.path.join(self.tmp, "two-%d.json" % i)
@@ -758,7 +777,7 @@ class MatchingCorpusTests(LearningCase):
self.assertEqual(wrong, [], "part one must stay empty for should-not requests")
def test_csv_lesson_reaches_the_next_agent_three_ways(self):
r = self.sisi("retro", "--new", "--aim", "verified",
r = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified",
"--moment", "The CSV importer test passed but 'python3 import.py big.csv' crashed on a quoted comma in row 4011",
"--cause", "the importer was only tested with three hand-written rows",
"--change-kind", "rule", "--when", CSV_WHEN,
@@ -827,13 +846,13 @@ class MatchingCorpusTests(LearningCase):
self.assertIn("#%d" % lid, out)
def test_unconfirmed_duplicate_sighting_is_recorded(self):
first = self.sisi("retro", "--new", "--aim", "verified",
first = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified",
"--moment", "the parser server waited 90 seconds in step 4 of the nightly job",
"--cause", "no readiness probe existed before the browser step",
"--change-kind", "rule", "--when", PARSER_WHEN, "--change", PARSER_CHANGE)
self.assertEqual(first.returncode, 0, first.stdout)
lid = int(first.stdout.split("lesson #")[1].split(",")[0])
dup = self.sisi("retro", "--aim", "verified",
dup = self.sisi("retro", "--scope", "everywhere", "--aim", "verified",
"--moment", "again the parser server waited 90 seconds in step 9 of the nightly job",
"--cause", "still no readiness probe before the browser step at all",
"--change-kind", "rule", "--when", PARSER_WHEN,
@@ -844,7 +863,7 @@ class MatchingCorpusTests(LearningCase):
self.assertEqual(retro.sightings_count(con, lid), 1)
con.close()
self.assertIn("1 unconfirmed sighting(s)", self.sisi("lessons", "show", str(lid)).stdout)
as_new = self.sisi("retro", "--new", "--aim", "verified",
as_new = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified",
"--moment", "again the parser server waited 90 seconds in step 9 of the nightly job",
"--cause", "still no readiness probe before the browser step at all",
"--change-kind", "rule", "--when", PARSER_WHEN,
@@ -968,7 +987,7 @@ class ImproveFromUseTests(LearningCase):
def test_sisi_improves_from_use_end_to_end(self):
"""The purpose itself: a lesson from session A reaches session B doing the same kind of work,
its showing is recorded, and recurrence after fresh showings strengthens it until a cycle is due."""
a = self.sisi("retro", "--new", "--aim", "verified",
a = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified",
"--moment", "The CSV importer test passed but 'python3 import.py big.csv' crashed on a quoted comma in row 4011",
"--cause", "the importer was only tested with three hand-written rows",
"--change-kind", "rule", "--when", CSV_WHEN,
@@ -1051,6 +1070,7 @@ class CycleGapTests(LearningCase):
doc = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"}])
# cycle_doc recomputes base; rebuild with the original base
d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"},
{"lesson": lid, "action": "set-scope", "scope": "everywhere"},
{"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]}
p = os.path.join(self.tmp, "g2.json")
with open(p, "w") as f:
@@ -1076,6 +1096,7 @@ class CycleGapTests(LearningCase):
base = cycle.base_version()
self.mk(change="Brand new parser lesson arriving mid cycle", moment="new wait at step 5")
d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"},
{"lesson": lid, "action": "set-scope", "scope": "everywhere"},
{"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]}
p = os.path.join(self.tmp, "g3.json")
with open(p, "w") as f:
+6 -6
View File
@@ -551,8 +551,8 @@ class ExportImportTests(PersonalCase):
def test_round_trip_is_lossless_for_committed_content(self):
self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta", "Body."))
self.ok("overlay", "replace-verifier", "shellcheck", "-", stdin=self.verifier_text("shellcheck", "Mine"))
self.ok("learn", "never", "ask", "twice")
self.ok("retro", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
self.ok("learn", "--scope", "everywhere", "never", "ask", "twice")
self.ok("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--change-kind", "rule",
"--when", "tests, pytest, failing first, regression, test quality, red green",
"--change", "write the failing test first and show it fail with `pytest -k new`")
@@ -588,7 +588,7 @@ class ExportImportTests(PersonalCase):
self.assertRegex(self.ok("verifiers", "--section", "safety").stdout, r"shellcheck .*Mine")
def test_import_sets_existing_data_aside_and_rebuilds_db_from_the_dump(self):
self.ok("retro", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
self.ok("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--change-kind", "rule",
"--when", "tests, pytest, failing first, regression, test quality, red green",
"--change", "write the failing test first and show it fail with `pytest -k new`")
@@ -632,7 +632,7 @@ def LessonRows():
class LessonDumpTests(PersonalCase):
RETRO = ["--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
RETRO = ["--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--change-kind", "rule",
"--when", "tests, pytest, failing first, regression, test quality, red green",
"--change", "write the failing test first and show it fail with `pytest -k new`"]
@@ -659,7 +659,7 @@ class LessonDumpTests(PersonalCase):
self.assertEqual(len(self.git_log()), n + 1)
def test_learn_and_note_are_personal_and_committed(self):
self.ok("learn", "Always", "use", "options")
self.ok("learn", "--scope", "everywhere", "Always", "use", "options")
self.assertIn("learn: Always use options", self.git_log()[0])
self.assertIn("learn-quarantine.jsonl", pdata.git("ls-files").stdout)
self.assertFalse(os.path.exists(os.path.join(self.state, "learn-quarantine.jsonl")))
@@ -738,7 +738,7 @@ class ProductIsReadOnlyTests(PersonalCase):
gate_in = json.dumps({"session_id": "s1", "cwd": self.proj, "stop_hook_active": False})
cmds = [("install",), ("doctor",), ("tick", "--tool", "t"), ("build-canon",), ("status",),
("overlay", "add-rule", "--id", "z", "-"), ("overlay", "diff"), ("overlay", "disable-rule", "z"),
("learn", "x"), ("lessons", "export"), ("verifiers", "show", "shellcheck"),
("learn", "--scope", "everywhere", "x"), ("lessons", "export"), ("verifiers", "show", "shellcheck"),
("contract", "init", "--goal", "g"), ("verify",), ("migrate",), ("update",),
("export", os.path.join(self.tmp, "e.tar.gz")), ("gate",), ("uninstall",)]
for c in cmds:
+56
View File
@@ -153,5 +153,61 @@ class LabelledMatchingTests(PromptCase):
self.assertIn("sisi done release", self.ctx("cut a new release and tag it"))
class RecipeFloorLabelledTests(SisiCase):
"""Long real-style multi-part requests and plain questions. Expected is a recipe id or None."""
CASES = [
("Please change the brand text everywhere it appears: the product is now called sisi is still improving in the help text, the README, the docs and the version banner, and update any tests that pin the old name; do not change behaviour, commands or file layout, just the words users see, and check nothing else still says the old name", None),
("Should lessons be universal, or can a lesson mention the project it came from?", None),
("Rename the exported brand string in the CLI help, the man page draft and the docs index to the new product name, keep every command name and flag exactly as it is, and make the tests that assert the old wording pass with the new wording", None),
("Fix the bug where the parser crashes on an empty file, a reported defect: reproduce it with a failing test first, find the cause in the tokeniser, fix only that, and run the whole suite to show nothing else changed", "bugfix"),
("Build a new command-line tool that runs from a shell with arguments and standard output, converting delimited files to JSON: flags for input and output, clear errors and exit codes for bad input, help text that matches behaviour, and tests for empty and huge inputs", "cli-tool"),
("Change the web settings page in the browser app to add a dark mode toggle, check the interface in a real browser at phone and desktop sizes, keep keyboard use working and do not move anything else on the page", "web-ui-change"),
("Upgrade the HTTP client library to the next major version, read its changelog for behaviour changes, pin it in the lockfile and make the whole suite pass from a clean checkout without weakening tests", "dependency-upgrade"),
("Performance work on the export job: make it faster and lighter on resource use, take a measured baseline first on the same inputs, speed up the hot loop, show identical outputs afterwards and report before and after latency timings with a spread", "performance-work"),
("Migrate the stored records to the new schema: every record in a realistic copy must survive, counts must match before and after by an independent check, old files must still load and running it twice must be safe", "data-migration"),
("Fix the security vulnerability where user input reaches the shell command, an injection weakness: reproduce it with an attack-shaped exploit test, fix the root cause everywhere the pattern occurs and keep legitimate behaviour unchanged", "security-fix"),
("Add an MCP server that AI agents call to search the catalogue: each tool needs a clear name and description, validated inputs, small structured outputs, and real agent tasks to prove agents pick the right tool", "agent-tool-surface"),
("Write the release: tag the version, make the manifest, tag and changelog agree, build the package from a clean checkout and check a fresh machine can install and upgrade it", "release"),
("Refactoring the billing module: change the structure of the code to remove the duplicated rounding logic without changing what it does, capture the current outputs and public interface first, compare afterwards and show performance did not get worse", "refactor"),
("Change the build configuration and CI workflow so the tests run on every push, run it in the real CI system, and show the new step fails when it should and secrets are not in the logs", "config-or-infra-change"),
]
QUESTIONS = [
"Should lessons always be universal, or can they name a project?",
"Why did the last learning round get refused as stale?",
"What does the recipe for releasing actually require in full?",
"Can a lesson mention a file name and still apply everywhere?",
"How does request-time delivery decide which recipe to hand over?",
"Is it better to fold this lesson into a rule or into an entry?",
"Whether we keep project facts with the project or in the general notes?",
"Do you think the backlog should have its own size limit?",
]
def test_labelled_requests(self):
from sisi import prompt as P
hits = false_matches = 0
for text, want in self.CASES:
got = P._best_recipe(text)
got_id = got["id"] if got else None
if got_id == want:
hits += 1
elif got_id is not None:
false_matches += 1
self.assertEqual(got_id, want, "%r -> %r (want %r)" % (text[:60], got_id, want))
self.assertGreaterEqual(len(self.CASES), 12)
def test_questions_get_nothing(self):
from sisi import prompt as P
for q in self.QUESTIONS:
self.assertEqual(P.build_context(q), "", q)
self.assertGreaterEqual(len(self.QUESTIONS), 8)
def test_reconstructed_failures(self):
from sisi import prompt as P
brand, question = self.CASES[0][0], self.CASES[1][0]
self.assertIsNone(P._best_recipe(brand))
self.assertNotEqual((P._best_recipe(question) or {}).get("id"), "bugfix")
self.assertEqual(P.build_context(question), "")
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -10,7 +10,7 @@ GOOD = dict(aim="verified",
change_kind="recipe",
change="Add the fuzz verifier to the Checks of the parser-or-codec recipe so parser work picks it by default",
when="parser, fuzzing, codec, hostile input, generated input, parsing",
target="parser-or-codec")
scope="everywhere", target="parser-or-codec")
def argv(f):
@@ -265,7 +265,7 @@ class SimilarityAndSameAsTests(RetroCase):
def test_dissimilar_lesson_accepted_directly(self):
self.retro()
other = dict(aim="speed", change_kind="tool", target="",
other = dict(aim="speed", change_kind="tool", target="", scope="everywhere",
moment="the screenshot comparison in `web-ui` waited 90 seconds on a dev server that never started",
cause="no readiness probe before the browser step",
when="browser, screenshot, dev server, port waiting, ui checks, startup",
+277
View File
@@ -0,0 +1,277 @@
import json, os, subprocess, unittest
from support import *
from sisi import retro, scope, store
WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file"
def retro_args(**kw):
f = dict(aim="verified", moment="the export broke in the acme-widgets repo when a field held a newline",
cause="rows were joined by hand in acme-widgets instead of with a quoting writer",
change_kind="rule",
change="Write delimited files with a quoting writer so embedded newlines survive",
when=WHEN, short="Use a quoting writer for delimited exports.", topic="data files")
f.update(kw)
out = []
for k, v in f.items():
out += ["--" + k.replace("_", "-"), v]
return out
# (text, kind, expected) expected True = universal passes, False = refused as naming this project
LABELLED = [
("Write delimited files with a quoting writer so embedded newlines survive", "rule", True),
("Check the README and CHANGELOG agree with the version before publishing", "rule", True),
("Update the changelog when behaviour changes and keep the readme example runnable", "rule", True),
("Run the whole test suite before saying work is done", "rule", True),
("Prefer a readiness probe over a fixed sleep when waiting for servers", "rule", True),
("Write the failing test first and watch it fail before fixing code", "rule", True),
("Keep functions small enough to test without a display or network", "rule", True),
("Never report success when every input record was skipped silently", "rule", True),
("Compare totals before and after any data migration with an independent count", "rule", True),
("Make error messages name the field that failed and what would be valid", "rule", True),
("In the acme-widgets project always quote fields by hand in the exporter", "rule", False),
("The acme-widgets exporter must join rows with its own quoting code", "rule", False),
("Fix export in widget_export.py by using a quoting writer there", "rule", False),
("Change src/widget_export.py to use a quoting writer for every row", "rule", False),
("See https://github.com/acme/acme-widgets for how exports should work here", "rule", False),
("In acme-widgets, release notes live in the changelog of that repository only", "rule", False),
("sisi should refuse lessons that name the project they came from", "tool", True),
("sisi must show the backlog separately from loose lesson headings", "tool", True),
("Agents should record a retro at the end of every piece of work", "rule", True),
("A parser should reject overlong input instead of allocating without bound", "rule", True),
("Use the acme-widgets keyboard layout with control on the left in every project", "rule", False),
("Keep the widget test fixture frozen at the acme-widgets sample rows", "rule", False),
("Always run tests with the licence and security notes updated for releases", "rule", True),
("Document every public function with its errors and limits in the readme", "rule", True),
]
class ScopeCase(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
subprocess.run(["git", "remote", "add", "origin", "https://github.com/acme/acme-widgets.git"], cwd=self.proj, check=True)
with open(os.path.join(self.proj, "widget_export.py"), "w") as f:
f.write("x=1\n")
os.makedirs(os.path.join(self.proj, "src"))
with open(os.path.join(self.proj, "src", "widget_export.py"), "w") as f:
f.write("x=1\n")
class ProjectIdTests(ScopeCase):
def test_remote_id_stable_across_clone_and_rename(self):
self.assertEqual(scope.project_id(self.proj), scope.normalized_remote("git" + chr(64) + "github.com:acme/acme-widgets.git"))
other = os.path.join(self.tmp, "renamed")
subprocess.run(["git", "clone", "-q", self.proj, other], check=True)
# clone from local path has local remote; set same remote
subprocess.run(["git", "remote", "set-url", "origin", "git" + chr(64) + "github.com:acme/acme-widgets"], cwd=other, check=True)
self.assertEqual(scope.project_id(other), scope.project_id(self.proj))
def test_path_fallback_without_remote(self):
d = os.path.join(self.tmp, "plainproj"); os.makedirs(d)
subprocess.run(["git", "init", "-q"], cwd=d, check=True)
self.assertEqual(scope.project_id(d), os.path.realpath(d))
class LabelledUniversalTests(ScopeCase):
def test_labelled_set(self):
hits = false_refusals = 0
for text, kind, want_pass in LABELLED:
reason = scope.universal_refusal([text], self.proj, kind=kind)
got_pass = reason is None
if got_pass and want_pass:
hits += 1
if not got_pass and want_pass:
false_refusals += 1
self.assertEqual(got_pass, want_pass, "%r kind=%s reason=%s" % (text, kind, reason))
self.assertGreaterEqual(len(LABELLED), 20)
def test_universal_change_with_project_moment_passes(self):
# amendment: moment/cause may name the project; only delivered parts are checked
for text in LABELLED[:4]:
self.assertIsNone(scope.universal_refusal([text], self.proj, kind="rule"))
r = self.sisi("retro", *retro_args(scope="everywhere"))
self.assertEqual(r.returncode, 0, r.stdout)
class RetroScopeTests(ScopeCase):
def test_missing_scope_refused_with_explanation(self):
r = self.sisi("retro", *retro_args())
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("everywhere", r.stdout); self.assertIn("project", r.stdout)
self.assertIn("general terms", r.stdout)
def test_everywhere_naming_project_refused(self):
r = self.sisi("retro", *retro_args(scope="everywhere",
change="In acme-widgets always use a quoting writer in the exporter for rows"))
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("rewrite", r.stdout.lower())
def test_project_scope_goes_to_handover_not_global(self):
r = self.sisi("retro", *retro_args(scope="project",
change="Use a quoting writer for delimited exports in this project",
short="Use a quoting writer here."))
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 0); con.close()
from sisi import handover
items = handover.for_project(scope.project_id(self.proj))
self.assertEqual(len(items), 1)
self.assertIn("acme-widgets", items[0]["moment"])
part1, part2 = retro.delivery("csv spreadsheet export delimited file")
self.assertFalse(part1 or part2)
self.assertIn("belong to this project", retro.tick_block(self.proj))
other = os.path.join(self.tmp, "otherproj"); os.makedirs(other)
self.assertNotIn("belong to this project", retro.tick_block(other))
out = self.sisi("handover").stdout
self.assertIn("Use a quoting writer for delimited exports in this project", out)
hid = items[0]["hid"]
bad = self.sisi("handover", "done", hid, "--where", "NOTES.md")
self.assertEqual(bad.returncode, 1, bad.stdout)
with open(os.path.join(self.proj, "NOTES.md"), "w") as f:
f.write("# design notes\n\nUse a quoting writer for delimited exports in this project.\n")
ok = self.sisi("handover", "done", hid, "--where", "NOTES.md")
self.assertEqual(ok.returncode, 0, ok.stdout)
self.assertEqual(handover.load_pile(), [])
self.assertIn("NOTES.md", open(handover.filed_path()).read())
def test_learn_missing_scope_and_project_learn(self):
r = self.sisi("learn", "always show options")
self.assertEqual(r.returncode, 2, (r.stdout, r.stderr))
r = self.sisi("learn", "--scope", "project", "use the left control key here")
self.assertEqual(r.returncode, 0, (r.stdout, r.stderr))
self.assertEqual(store.read("quarantine"), [])
from sisi import handover
items = handover.for_project(scope.project_id(self.proj))
self.assertEqual(items[-1]["text"], "use the left control key here")
r = self.sisi("learn", "--scope", "everywhere", "in acme-widgets always show options")
self.assertEqual(r.returncode, 2, (r.stdout, r.stderr))
def test_lessons_show_split(self):
r = self.sisi("retro", *retro_args(scope="everywhere"))
self.assertEqual(r.returncode, 0, r.stdout)
out = self.sisi("lessons", "show", "1").stdout
self.assertIn("Where this came from (historical example)", out)
self.assertLess(out.index("Write delimited files"), out.index("Where this came from"))
self.assertIn("acme-widgets", out.split("Where this came from (historical example)", 1)[1])
def test_digest_universal_first_then_project(self):
self.sisi("retro", *retro_args(scope="everywhere"))
self.sisi("retro", "--new", *retro_args(scope="project",
change="Use a quoting writer for delimited exports in this project",
short="Use a quoting writer here.", moment="another export broke at step 2 in this repo today"))
out = self.sisi("lessons", "digest").stdout
self.assertIn("Use a quoting writer for delimited exports.", out)
self.assertNotIn("Use a quoting writer here.", out)
self.assertIn("waiting to be filed", out)
self.assertIn("acme-widgets", out)
class StaleReadingTests(ScopeCase):
def test_reading_lessons_does_not_stale_cycle(self):
# folded lesson shown 20x via lessons show retires; cycle check must still pass
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="verified", change_kind="verifier", target=None,
moment="fuzz seeds missing at step 5 of the nightly run",
cause="the corpus was not seeded from golden files",
change="Seed the fuzz corpus from golden parser files before fuzzing",
when=WHEN, short="Seed fuzz corpus from golden files.", topic="testing"), self.proj, None)
con.execute("UPDATE lessons SET folded_into='fuzz', status='applied', effect='field-note' WHERE id=?", (lid,))
con.commit(); con.close()
from sisi import cycle
base = cycle.base_version()
for _ in range(20):
out = self.sisi("lessons", "show", str(lid))
self.assertEqual(out.returncode, 0, out.stdout)
con = retro.connect()
st = dict(con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone()); con.close()
self.assertEqual(st["status"], "applied") # retirement deferred while the round is open
doc = {"version": 1, "base": base, "summary": "keep",
"notes": [{"lesson": lid, "action": "set-short", "short": "Seed fuzz corpus from golden files.", "topic": "testing"},
{"lesson": lid, "action": "set-scope", "scope": "everywhere"}]}
p = os.path.join(self.tmp, "cyc.json")
with open(p, "w") as f: json.dump(doc, f)
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class DueAndBacklogTests(ScopeCase):
def test_tool_lessons_do_not_make_cycle_due_by_headings(self):
con = retro.connect()
for i in range(10):
retro.new_lesson(con, dict(aim="speed", change_kind="tool", target=None,
moment="tool wait %d at step 2 of the run" % i, cause="no cache existed for that step",
change="Make sisi cache transcript scans between gate decisions number %d and reuse them always" % i,
when=WHEN, short="Cache transcript scans.", topic="sisi itself"), self.proj, None)
con.commit(); con.close()
from sisi import cycle
st = cycle.due_state()
self.assertFalse(any("loose lesson headings" in r for r in st["reasons"]), st["reasons"])
out = self.sisi("backlog").stdout
self.assertIn("cap", out.lower())
def test_applied_tool_lesson_not_not_built_in_digest(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="speed", change_kind="tool", target=None,
moment="tool wait at step 2 of the run today", cause="no cache existed for that step",
change="Make sisi cache transcript scans between gate decisions and reuse them",
when=WHEN, short="Cache transcript scans.", topic="sisi itself"), self.proj, None)
con.commit(); con.close()
self.assertEqual(self.sisi("lessons", "set", str(lid), "--status", "applied").returncode, 0)
out = self.sisi("lessons", "digest").stdout
self.assertNotIn("not built yet", out)
self.assertIn("built", out)
self.assertNotIn("#%d" % lid, self.sisi("backlog").stdout)
class CycleScopeTests(ScopeCase):
def test_cycle_refuses_folding_project_lesson_into_entry(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="verified", change_kind="rule", target=None,
moment="export broke at step 2 in this repo", cause="rows joined by hand here",
change="Use a quoting writer for delimited exports in this project",
when=WHEN, short="Use a quoting writer here.", topic="data files"), self.proj, None)
con.execute("UPDATE lessons SET scope='project', project=? WHERE id=?", (scope.project_id(self.proj), lid))
con.commit(); con.close()
from sisi import cycle
doc = {"version": 1, "base": cycle.base_version(), "summary": "x",
"notes": [{"lesson": lid, "action": "fold-into-rule", "into": "know-done"},
{"lesson": lid, "action": "set-short", "short": "Use a quoting writer here.", "topic": "data files"}]}
p = os.path.join(self.tmp, "cyc2.json")
with open(p, "w") as f: json.dump(doc, f)
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn("project", r.stdout)
class CleanupRevertTests(ScopeCase):
def test_set_scope_project_moves_and_revert_restores(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="verified", change_kind="rule", target=None,
moment="export broke at step 2 in acme-widgets today", cause="rows joined by hand here",
change="Use a quoting writer for delimited exports in this project",
when=WHEN, short="Use a quoting writer here.", topic="data files"), self.proj, None)
con.commit(); con.close()
store.append("quarantine", store.stamp({"text": "use the left control key here"}))
from sisi import cycle
base = cycle.base_version()
brief = self.sisi("cycle", "--now").stdout
self.assertIn("Scope cleanup", brief)
self.assertIn(self.proj, brief)
doc = {"version": 1, "base": base, "summary": "cleanup",
"notes": [{"lesson": lid, "action": "set-scope", "scope": "project",
"project": scope.project_id(self.proj)}],
"learn": [{"text": "use the left control key here", "action": "set-scope",
"scope": "project", "project": scope.project_id(self.proj)}]}
p = os.path.join(self.tmp, "cleanup.json")
with open(p, "w") as f: json.dump(doc, f)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertIn("characters ->", r.stdout)
con = retro.connect()
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 0); con.close()
self.assertEqual(store.read("quarantine"), [])
from sisi import handover
self.assertEqual(len(handover.load_pile()), 2)
self.assertNotIn("Use a quoting writer here", self.sisi("lessons", "digest").stdout)
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 1); con.close()
self.assertEqual(len(store.read("quarantine")), 1)
self.assertEqual(handover.load_pile(), [])
if __name__ == "__main__":
unittest.main()
+3 -2
View File
@@ -83,8 +83,9 @@ class StoreTests(SisiCase):
def test_note_propose_learn_append_with_context(self):
for cmd, fn in (("note", "notes.jsonl"), ("propose", "proposals.jsonl"), ("learn", "learn-quarantine.jsonl")):
self.assertEqual(self.sisi(cmd, "first", "entry", env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0)
self.sisi(cmd, "second")
extra = ["--scope", "everywhere"] if cmd == "learn" else []
self.assertEqual(self.sisi(cmd, *(extra + ["first", "entry"]), env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0)
self.sisi(cmd, *(extra + ["second"]))
recs = self.read(fn)
self.assertEqual([r["text"] for r in recs], ["first entry", "second"])
self.assertEqual(recs[0]["cwd"], self.proj)
+269
View File
@@ -0,0 +1,269 @@
import json, os, random, stat, time, unittest
from support import *
FAKE_CODEX = """#!/bin/sh
case "$1 $2" in
"debug models") echo '{"models":[{"slug":"alpha-1"},{"slug":"alpha-contributor-x"}]}' ;;
"exec "*) echo '{"type":"error","error":{"type":"provider.go-limit","message":"monthly usage limit reached","status":429,"retryAfterMs":60000}}' ;;
*) echo 'codex help' ;;
esac
exit 0
"""
FAKE_MUSE = """#!/bin/sh
case "$1" in
exec)
if [ "$2" = "--list-models" ]; then echo "beta-1"; echo "beta-2"; exit 0; fi
echo "worker final report: done ok" ;;
usage) echo '{"allowance":{"tier":"flat plan","weekly":{"usedPercent":25},"window":{"usedPercent":10}}}' ;;
*) echo 'muse help' ;;
esac
exit 0
"""
FAKE_CURSOR = """#!/bin/sh
echo "Error: Authentication required. Run 'agent login' to sign in" >&2
exit 0
"""
FAKE_CLAUDE = """#!/bin/sh
echo "claude final report"
exit 0
"""
class WorkerCase(SisiCase):
def setUp(self):
super().setUp()
self.bindir = os.path.join(self.tmp, "bin")
os.makedirs(self.bindir)
for name, body in (("codex", FAKE_CODEX), ("muse", FAKE_MUSE), ("cursor-agent", FAKE_CURSOR),
("claude", FAKE_CLAUDE)):
p = os.path.join(self.bindir, name)
with open(p, "w") as f:
f.write(body)
os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR)
def env(self, **kw):
return dict(PATH=self.bindir, **kw)
def write_data(self, name, obj):
os.makedirs(self.data, exist_ok=True)
with open(os.path.join(self.data, name), "w") as f:
json.dump(obj, f)
def brief(self):
p = os.path.join(self.proj, "brief.md")
open(p, "w").write("You are a worker. Do the toy task and report back.\n")
return p
class DiscoveryTests(WorkerCase):
def test_workers_lists_tools_models_and_reasons(self):
r = self.sisi("workers", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("codex", r.stdout)
self.assertIn("alpha-1", r.stdout)
self.assertIn("beta-1", r.stdout)
self.assertIn("allowance left", r.stdout) # muse usage reported 75% weekly left
self.assertIn("cursor-agent", r.stdout)
self.assertIn("not logged in", r.stdout.lower())
self.assertIn("models learned by use", r.stdout) # tools with no listing command
def test_discovery_is_cached_in_personal_store(self):
self.sisi("workers", env=self.env())
cache = json.load(open(os.path.join(self.data, "workers.json")))
self.assertIn("checked", cache)
tools = {t["name"]: t for t in cache["tools"]}
self.assertIn("alpha-1", tools["codex"]["models"])
self.assertFalse(tools["cursor-agent"]["usable"])
class LedgerImportTests(WorkerCase):
def test_existing_ledger_imported_once_losslessly(self):
src = os.path.join(self.tmp, "orch-log.jsonl")
rows = [
{"kind": "attempt", "id": "abc123", "ts": 1700000000, "project": "p", "type": "impl",
"difficulty": 2, "worker": "beta-1", "outcome": "accepted", "check": "tests",
"minutes": 3, "tokens": None, "retry_of": None, "note": "keep me", "extra": [1, 2]},
{"kind": "attempt", "id": "def456", "ts": 1700000100, "project": "p", "type": "impl",
"difficulty": 2, "worker": "beta-1", "outcome": "rejected", "check": "read",
"minutes": 4, "tokens": 9, "retry_of": "abc123", "note": None},
{"kind": "amend", "id": "abc123", "ts": 1700000200, "note": "later wrong"},
]
with open(src, "w") as f:
for row in rows:
f.write(json.dumps(row) + "\n")
before = open(src).read()
r = self.sisi("workers", env=self.env(SISI_LEDGER=src))
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("imported 3 rows", r.stdout)
self.assertEqual(open(src).read(), before, "the original ledger must not be modified")
got = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
self.assertEqual(len(got), 3)
for want, have in zip(rows, got):
for k, v in want.items():
self.assertEqual(have.get(k), v, k)
# a second run imports nothing more
self.sisi("workers", env=self.env(SISI_LEDGER=src))
got2 = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
self.assertEqual(len(got2), 3)
class RouteTests(WorkerCase):
def test_route_explains_and_skips_contributor_and_logged_out(self):
r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn("contributor-x", r.stdout.splitlines()[0])
self.assertIn("contributor", r.stdout) # named as passed over
self.assertIn("cursor-agent", r.stdout)
def test_route_review_picks_another_maker(self):
r = self.sisi("route", "--kind", "review", "--difficulty", "1", "--review-of", "codex/alpha-1",
"--explain", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn("alpha", r.stdout.splitlines()[0])
class DelegateTests(WorkerCase):
def test_limit_with_success_exit_is_unavailability_and_retries_next(self):
r = self.sisi("delegate", "--kind", "impl", "--difficulty", "2", "--brief", self.brief(),
"--worker", "codex/alpha-1", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("worker final report: done ok", r.stdout) # fell through to muse
self.assertIn("sisi delegate judge", r.stdout)
avail = json.load(open(os.path.join(self.data, "worker-availability.json")))
self.assertTrue(any("alpha" in k or k == "codex" for k in avail), avail)
entries = list(avail.values())
self.assertEqual(entries[0]["reason"], "limit")
self.assertGreater(entries[0]["retry_at"], time.time())
# the limit failure is not recorded as bad work
recs = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
attempts = [x for x in recs if x.get("kind") == "attempt"]
self.assertEqual(attempts, [])
runs = [x for x in recs if x.get("kind") == "run"]
self.assertEqual(len(runs), 1)
self.assertTrue(os.path.isfile(runs[0]["transcript"]))
def test_unjudged_run_shows_then_judge_records_attempt(self):
r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(),
"--worker", "muse/beta-1", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
w = self.sisi("workers", env=self.env())
self.assertIn("waiting for a judgement", w.stdout)
recs = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
run = [x for x in recs if x.get("kind") == "run"][0]
j = self.sisi("delegate", "judge", run["id"], "--outcome", "accepted", "--check", "tests",
"--minutes", "2", env=self.env())
self.assertEqual(j.returncode, 0, j.stderr)
recs = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
attempts = [x for x in recs if x.get("kind") == "attempt"]
self.assertEqual(len(attempts), 1)
self.assertEqual(attempts[0]["type"], "read")
self.assertEqual(attempts[0]["check"], "tests")
w2 = self.sisi("workers", env=self.env())
self.assertNotIn("waiting for a judgement", w2.stdout)
def test_no_bypass_flag_is_passed(self):
marker = os.path.join(self.tmp, "argv.txt")
p = os.path.join(self.bindir, "muse")
open(p, "w").write("#!/bin/sh\necho \"$@\" > %s\ncase \"$1\" in exec) [ \"$2\" = \"--list-models\" ] && echo beta-1 && exit 0;; esac\necho ok-report\n" % marker)
os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR)
r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(),
"--worker", "muse/beta-1", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
argv = open(marker).read()
for bad in ("--yolo", "--disable-approval", "--disable-sandbox", "bypass", "dangerously"):
self.assertNotIn(bad, argv)
class SessionModelTests(WorkerCase):
def seed_strength(self, scores):
self.write_data("model-strength.json", {"models": {
m: {"score": s, "source": "test fixture", "date": "2000-01-01"} for m, s in scores.items()}})
self.write_data("workers.json", {"checked": time.time(), "tools": [
{"name": "muse", "usable": True, "models": ["beta-1", "beta-2"]},
{"name": "codex", "usable": True, "models": ["alpha-1"]}]})
def tick(self, payload):
return self.sisi("tick", stdin=json.dumps(payload))
def test_hookio_keeps_model(self):
from sisi import hookio
n = hookio.normalize("codex", {"session_id": "s", "cwd": "/w", "model": "alpha-1"})
self.assertEqual(n.get("model"), "alpha-1")
def test_tick_stores_model_and_strong_line(self):
self.seed_strength({"beta-1": 95, "alpha-1": 60})
r = self.tick({"session_id": "strong-1", "cwd": self.proj, "source": "startup", "model": "beta-1"})
self.assertEqual(r.returncode, 0, r.stderr)
rec = json.load(open(os.path.join(self.state, "sessions", "strong-1.json")))
self.assertEqual(rec.get("model"), "beta-1")
self.assertIn("sisi delegate", r.stdout)
self.assertIn("strongest", r.stdout)
def test_tick_weak_line_names_stronger(self):
self.seed_strength({"beta-1": 95, "alpha-1": 60})
r = self.tick({"session_id": "weak-1", "cwd": self.proj, "source": "startup", "model": "alpha-1"})
self.assertIn("do the work yourself", r.stdout)
self.assertIn("beta-1", r.stdout)
def test_tick_subagent_gets_no_delegation_line(self):
self.seed_strength({"beta-1": 95})
r = self.tick({"session_id": "sub-1", "cwd": self.proj, "source": "startup",
"model": "beta-1", "agent_id": "agent-7"})
self.assertNotIn("sisi delegate", r.stdout)
self.assertNotIn("do the work yourself", r.stdout)
def test_tick_unknown_strength_says_so(self):
r = self.tick({"session_id": "unk-1", "cwd": self.proj, "source": "startup", "model": "mystery-9"})
self.assertIn("unknown", r.stdout.lower())
class RoutingPropertyTests(unittest.TestCase):
def test_choice_invariants_over_generated_records(self):
from sisi import routing
rng = random.Random(20261123)
makers = ["alpha", "beta", "gamma"]
for _ in range(200 * ITERS):
cands, records, avail = [], [], {}
now = 1000000.0
for i in range(rng.randint(0, 7)):
maker = rng.choice(makers)
model = "%s-m%d%s" % (maker, i, "-contributor-z" if rng.random() < 0.15 else "")
w = "tool%d/%s" % (i, model)
cands.append({"worker": w, "tool": "tool%d" % i, "model": model, "maker": maker,
"plan": rng.choice(["flat", "per-use", None]),
"cost": rng.choice([None, 1.0, 5.0, 20.0]),
"allowance_pct_left": rng.choice([None, 0, 40, 90]),
"usable": True, "aliases": [w, model]})
if rng.random() < 0.3:
avail[w] = {"reason": "limit", "retry_at": now + 3600, "fails": 1}
for _ in range(rng.randint(0, 12)):
records.append({"kind": "attempt", "id": "r%d" % rng.randint(0, 10 ** 6),
"type": "impl", "difficulty": rng.choice([1, 2, 3]),
"worker": w, "outcome": rng.choice(["accepted", "rejected"]),
"check": "tests", "ts": now - 100})
author = rng.choice(cands)["worker"] if cands and rng.random() < 0.5 else None
a = routing.choose(cands, records, avail, "impl", rng.choice([1, 2, 3]),
review_of=author, now=now)
b = routing.choose(cands, records, avail, "impl", 2, review_of=author, now=now)
again = routing.choose(cands, records, avail, "impl", 2, review_of=author, now=now)
self.assertEqual((b["choice"] or {}).get("worker"), (again["choice"] or {}).get("worker"),
"choice must be deterministic for the same record")
if a["choice"] is None:
continue
w = a["choice"]["worker"]
self.assertNotIn("contributor", w)
self.assertNotIn(w, avail, "never picks an unavailable worker")
if author:
author_maker = next(c["maker"] for c in cands if c["worker"] == author)
others = [c for c in cands if c["maker"] != author_maker
and "contributor" not in c["worker"] and c["worker"] not in avail
and not (c["plan"] == "flat" and c["allowance_pct_left"] == 0)]
if others:
self.assertNotEqual(a["choice"]["maker"], author_maker)
if __name__ == "__main__":
unittest.main()