Merge t3/close-rebuild-seam-gaps: grouped help carries workers note/only; routing adjustments, notes, limits, host-native and with_commit all kept. done / next: fix 1 (rule map)
This commit is contained in:
commit
6cff3a0667
42 files changed
+777
-420
No files matched your search
+2
-2
@@ -126,8 +126,8 @@ def human(id, rung=5, kind="general"):
|
||||
|
||||
|
||||
def contract(checks, invariants=()):
|
||||
return {"id": "t", "goal": "g", "checks": list(checks), "invariants": list(invariants),
|
||||
"assumptions": [], "questions": []}
|
||||
return {"id": "t", "goal": "g", "risk": {"profile": "isolated"}, "checks": list(checks),
|
||||
"invariants": list(invariants), "assumptions": [], "questions": []}
|
||||
|
||||
|
||||
def skip_timing_if_busy(case):
|
||||
|
||||
@@ -4,6 +4,39 @@ from sisi import contract as C
|
||||
|
||||
|
||||
class ContractTests(SisiCase):
|
||||
def test_the_contract_must_state_its_risk_profile(self):
|
||||
"""R-5.3-1: `risk.profile` is the agent's own judgement and is required; init writes the floor as its start."""
|
||||
good = contract([check("a", "true")])
|
||||
for name, risk in (("missing", None), ("empty object", {}), ("unknown", {"profile": "huge"})):
|
||||
with self.subTest(name):
|
||||
c = dict(good)
|
||||
c.pop("risk")
|
||||
if risk is not None:
|
||||
c["risk"] = risk
|
||||
errs = C.validate(c)
|
||||
self.assertTrue(any("risk" in e and "sisi risk" in e and "integration" in e and "release" in e
|
||||
for e in errs), errs)
|
||||
self.assertEqual(C.validate(good), [])
|
||||
self.git_init()
|
||||
self.assertEqual(self.sisi("contract", "init").returncode, 0)
|
||||
c = C.load(os.path.join(self.proj, ".sisi", "contract.json"))
|
||||
self.assertIn(c["risk"]["profile"], C.RISK_PROFILES)
|
||||
with open(os.path.join(self.proj, "migrations_001.sql"), "w") as f:
|
||||
f.write("alter table t add column c int;\n")
|
||||
os.remove(os.path.join(self.proj, ".sisi", "contract.json"))
|
||||
self.assertEqual(self.sisi("contract", "init").returncode, 0)
|
||||
floor = self.sisi("risk", "--json")
|
||||
import json as _j
|
||||
self.assertEqual(C.load(os.path.join(self.proj, ".sisi", "contract.json"))["risk"]["profile"],
|
||||
_j.loads(floor.stdout)["floor"])
|
||||
self.assertNotEqual(_j.loads(floor.stdout)["floor"], "trivial")
|
||||
c = C.load(os.path.join(self.proj, ".sisi", "contract.json"))
|
||||
c["risk"] = {}
|
||||
C.save(os.path.join(self.proj, ".sisi", "contract.json"), c)
|
||||
r = self.sisi("contract", "check")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("risk.profile", r.stdout)
|
||||
|
||||
def test_skeleton_is_valid_but_fails(self):
|
||||
c = C.skeleton("goal")
|
||||
self.assertEqual(C.validate(c), [])
|
||||
|
||||
+1
-1
@@ -132,7 +132,7 @@ class EndToEnd(SisiCase):
|
||||
"covers": "the migration is deleted"}]
|
||||
c["invariants"] = [{"id": "readme", "claim": "the readme stays", "cmd": "test -f README.md", "expect": {"exit": 0}}]
|
||||
c["requirements"] = [{"id": "r1", "kind": "explicit", "text": "a users table exists", "decision": "now"}]
|
||||
c["risk"] = {"blast_radius": "one new table; nothing reads it yet", "rollback": "drop the table"}
|
||||
c["risk"] = {"profile": "data", "blast_radius": "one new table; nothing reads it yet", "rollback": "drop the table"}
|
||||
c["approach"] = {"chosen": "a plain SQL migration", "why": "the project already uses them",
|
||||
"alternatives": ["an ORM auto-migration: hides the schema"]}
|
||||
self.agent_writes(os.path.join(".sisi", "contract.json"), json.dumps(c))
|
||||
|
||||
+22
-2
@@ -25,7 +25,7 @@ def full(**over):
|
||||
[dict(check("keeps", "test -f README.md"), covers="the readme is deleted")])
|
||||
c.update(id="t", goal="make the feature work",
|
||||
requirements=[{"id": "r1", "kind": "explicit", "text": "ok.txt exists when the feature is done", "decision": "now"}],
|
||||
risk={"blast_radius": "only the feature file; nothing else reads it", "rollback": "git revert the commit"},
|
||||
risk={"profile": "isolated", "blast_radius": "only the feature file; nothing else reads it", "rollback": "git revert the commit"},
|
||||
approach={"chosen": "write the file directly", "why": "the simplest thing that works",
|
||||
"alternatives": ["generate it from a template: more moving parts"]},
|
||||
started=store.now(), status="open", pauses=[], deviations=[])
|
||||
@@ -174,6 +174,16 @@ class RequirementTests(GateBase):
|
||||
self.assertIn("sisi contract init", miss[0][1])
|
||||
self.assertEqual(assure.missing("isolated", contract([check("a", "false")]), self.proj), [])
|
||||
|
||||
def test_a_contract_without_a_risk_profile_is_missing_one_in_the_gates_list(self):
|
||||
"""R-5.3-1: the declared profile is on the "what is missing" list, once, with the field that supplies it."""
|
||||
c = full()
|
||||
c["risk"] = {"blast_radius": "x" * 20, "rollback": "git revert"}
|
||||
miss = assure.missing("isolated", c, self.proj, errors=C.validate(c))
|
||||
self.assertEqual(len(miss), 1, miss)
|
||||
self.assertIn("risk profile", miss[0][0])
|
||||
self.assertIn('"profile"', miss[0][1])
|
||||
self.assertEqual(assure.missing("isolated", full(), self.proj, errors=C.validate(full())), [])
|
||||
|
||||
def test_logic_needs_covers_on_every_check(self):
|
||||
"""R-5.3-6."""
|
||||
c = contract([check("a", "false"), dict(check("b", "false"), covers="the parser drops a line")])
|
||||
@@ -185,7 +195,7 @@ class RequirementTests(GateBase):
|
||||
|
||||
def test_integration_needs_invariants_requirements_a_risk_note_and_an_approach(self):
|
||||
"""R-5.3-7: each missing piece is named, with the field that supplies it."""
|
||||
c = full(invariants=[], requirements=[], risk={}, approach=None)
|
||||
c = full(invariants=[], requirements=[], risk={"profile": "isolated"}, approach=None)
|
||||
text = " | ".join("%s -> %s" % m for m in assure.missing("integration", c, self.proj))
|
||||
for field in ('"invariants"', '"requirements"', '"risk"', '"approach"'):
|
||||
self.assertIn(field, text)
|
||||
@@ -518,6 +528,16 @@ class FlowTests(GateBase):
|
||||
self.assertEqual(a, "block")
|
||||
self.assertIn("bad", msg)
|
||||
|
||||
def test_the_send_back_shows_the_failing_test_not_only_the_end_of_the_output(self):
|
||||
"""R-5.6-1, R-5.6-4: the failure printed 300 lines above the end of the output is in the gate's message."""
|
||||
cmd = ("echo 'FAIL: test_needle (mod.T.test_needle)'; echo 'AssertionError: needle missing'; "
|
||||
"for i in $(seq 1 300); do echo \"summary $i\"; done; exit 1")
|
||||
self.write_contract(contract([check("t", cmd)]) | {"risk": {"profile": "isolated"}})
|
||||
a, msg = self.call()
|
||||
self.assertEqual(a, "block")
|
||||
self.assertIn("FAIL: test_needle (mod.T.test_needle)", msg)
|
||||
self.assertIn("AssertionError: needle missing", msg)
|
||||
|
||||
def test_a_check_over_the_budget_is_reported_not_passed(self):
|
||||
"""R-15-5: a check that cannot finish in time is not-run, never passed."""
|
||||
with open(os.path.join(self.tmp, "cfg"), "w"):
|
||||
|
||||
@@ -542,6 +542,34 @@ class Mechanisms(Base):
|
||||
self.assertEqual(len(cycle.routing_adjustments(self.proj)), 1)
|
||||
self.assertEqual(cycle.routing_adjustments(self.other_project()), [])
|
||||
|
||||
def test_a_promoted_routing_adjustment_changes_sisi_route_for_its_project_only(self):
|
||||
"""R-11.1-7, R-7.1-1: the reader of routing-adjustments.json is `sisi route`: a cycle's avoid entry
|
||||
moves the choice in its own project, names its learning in --explain, and leaves another project alone."""
|
||||
bindir = os.path.join(self.tmp, "bin")
|
||||
os.makedirs(bindir)
|
||||
tool = os.path.join(bindir, "muse")
|
||||
with open(tool, "w") as f:
|
||||
f.write('#!/bin/sh\nif [ "$1 $2" = "exec --list-models" ]; then echo beta-1; echo beta-2; fi\nexit 0\n')
|
||||
os.chmod(tool, 0o755)
|
||||
env = {"PATH": bindir}
|
||||
for m, price in (("beta-1", "1"), ("beta-2", "2")):
|
||||
r = self.sisi("workers", "fact", "muse/" + m, "--price", price, "--source", "fixture", env=env)
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
other = self.other_project()
|
||||
route = ("route", "--kind", "impl", "--difficulty", "2", "--explain")
|
||||
before, before_other = self.sisi(*route, env=env), self.sisi(*route, cwd=other, env=env)
|
||||
self.assertEqual(before.stdout.splitlines()[0], "muse/beta-1", before.stdout)
|
||||
self.assertEqual(before_other.stdout, before.stdout)
|
||||
self.propose()
|
||||
self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "routing",
|
||||
"kind": "impl", "avoid": "beta-1"}]).returncode, 0)
|
||||
after, after_other = self.sisi(*route, env=env), self.sisi(*route, cwd=other, env=env)
|
||||
self.assertEqual(after.stdout.splitlines()[0], "muse/beta-2", after.stdout)
|
||||
self.assertIn("learning L-0001", after.stdout)
|
||||
self.assertEqual(after_other.stdout, before_other.stdout)
|
||||
unrelated = self.sisi("route", "--kind", "review", "--difficulty", "2", env=env)
|
||||
self.assertEqual(unrelated.stdout.splitlines()[0], "muse/beta-1")
|
||||
|
||||
def test_earned_scope_widens_what_a_cycle_may_apply(self):
|
||||
"""R-11.6-2: once a learning has earned scope (two units, two projects) its risk adjustment
|
||||
reaches both projects and a rule it motivates needs no approval for reach alone."""
|
||||
@@ -929,6 +957,21 @@ class Store(Base):
|
||||
self.assertIn("prefer short plain reports", r.stdout)
|
||||
self.assertEqual(len(L.owner_statements()), 1)
|
||||
|
||||
def test_learn_says_what_it_stored_and_how_to_take_it_back(self):
|
||||
"""R-12-1: the receipt shows the stored text (secrets scrubbed), id, scope and a withdraw command that works."""
|
||||
out = self.sisi("learn", "--scope", "project", "prefer short plain reports, password=hunter2hunter2").stdout
|
||||
row = self.rows()[0]
|
||||
self.assertIn(row["id"], out)
|
||||
self.assertIn("scope: project", out)
|
||||
self.assertIn(row["observation"]["evidence"], out)
|
||||
self.assertNotIn("hunter2", out)
|
||||
cmd = [l for l in out.splitlines() if "sisi learn --withdraw" in l][0].split("sisi learn ", 1)[1]
|
||||
self.assertIn("--withdraw %s " % row["id"], cmd)
|
||||
import shlex
|
||||
r = self.sisi("learn", *shlex.split(cmd.replace("<why it was recorded by mistake>", "test")))
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(L.owner_statements(), [])
|
||||
|
||||
def test_learn_records_whether_the_owner_typed_it(self):
|
||||
"""A statement quoted from a human-typed message of the session transcript is `typed by the
|
||||
owner`; a relayed one, or none to check, is `relayed by an agent`. Never blocked."""
|
||||
@@ -976,7 +1019,7 @@ class Store(Base):
|
||||
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
bad = []
|
||||
for n in sorted(os.listdir(os.path.join(root, "sisi"))):
|
||||
if not n.endswith(".py") or n == "gate.py": # gate.py's retro.lessons_block is the live gate seam
|
||||
if not n.endswith(".py"):
|
||||
continue
|
||||
with open(os.path.join(root, "sisi", n)) as f:
|
||||
for i, line in enumerate(f, 1):
|
||||
@@ -985,6 +1028,23 @@ class Store(Base):
|
||||
bad.append("%s:%d" % (n, i))
|
||||
self.assertEqual(bad, [])
|
||||
|
||||
def test_no_guarded_seams_between_modules_that_always_exist(self):
|
||||
"""Item 4: no `except ImportError` or `hasattr(module, ...)` probe stands in for a module of this
|
||||
package, and nothing names a removed seam. The one platform probe (fcntl, absent on Windows, in pdata) stays."""
|
||||
import re
|
||||
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
bad = []
|
||||
for n in sorted(os.listdir(os.path.join(root, "sisi"))):
|
||||
if not n.endswith(".py"):
|
||||
continue
|
||||
with open(os.path.join(root, "sisi", n)) as f:
|
||||
for i, line in enumerate(f, 1):
|
||||
if n != "pdata.py" and re.search(r"except \(?ImportError|hasattr\((delivery|unit|gate|retro|learning|cycle)\b", line):
|
||||
bad.append("%s:%d" % (n, i))
|
||||
if re.search(r"retro\.(TEMPLATE|satisfied|lessons_block)|ensure_imported", line):
|
||||
bad.append("%s:%d" % (n, i))
|
||||
self.assertEqual(bad, [])
|
||||
|
||||
def test_no_resource_warnings_from_the_learning_commands(self):
|
||||
"""Item 13: file handles are closed; every learning command runs clean under -W always."""
|
||||
_contract(self)
|
||||
|
||||
@@ -80,6 +80,67 @@ class BriefTests(OrchCase):
|
||||
self.assertIn("Acceptance", r.stdout)
|
||||
self.assertIn("Files you may change", r.stdout)
|
||||
|
||||
def brief_with(self, **parts):
|
||||
"""valid_brief() with the text of some parts replaced; keys are the heading words."""
|
||||
text = valid_brief()
|
||||
heads = {"acceptance": "Acceptance", "verification": "Verification", "outcome": "Outcome and scope",
|
||||
"deliverables": "Deliverables and report format"}
|
||||
for key, body in parts.items():
|
||||
h = heads[key]
|
||||
start = text.index("## " + h)
|
||||
end = text.find("\n\n##", start)
|
||||
end = len(text) if end < 0 else end
|
||||
text = text[:start] + "## %s\n%s" % (h, body) + text[end:]
|
||||
return text
|
||||
|
||||
def advice(self, text):
|
||||
p = os.path.join(self.proj, "b.md")
|
||||
open(p, "w").write(text)
|
||||
r = self.sisi("delegate", "check", p, env=self.env())
|
||||
self.assertEqual(r.returncode, 0, r.stdout) # advice never blocks
|
||||
self.assertLessEqual(len(r.stdout.splitlines()), 20)
|
||||
return r.stdout
|
||||
|
||||
def test_brief_template_carries_what_the_rebuild_learned(self):
|
||||
"""R-7.5-1: the template's guidance names the six cases, and an unfilled template is still unfilled."""
|
||||
t = self.sisi("delegate", "brief", env=self.env()).stdout
|
||||
for phrase in ("a number with the command that measures it", "name that reader", "different worker",
|
||||
"held-out", "abuse cases", "forge the field that marks trust", "unrelated reason",
|
||||
"30 times", "in parallel", "done / next"):
|
||||
self.assertIn(phrase, t)
|
||||
p = os.path.join(self.proj, "t.md")
|
||||
open(p, "w").write(t)
|
||||
r = self.sisi("delegate", "check", p, env=self.env())
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertNotIn("advice", r.stdout) # the template's own guidance is not the author's words
|
||||
|
||||
def test_check_flags_each_case_and_stays_quiet_on_a_clean_brief(self):
|
||||
"""R-7.5-1, abuse: each flag has a brief that trips it and a near-identical one that does not."""
|
||||
self.assertNotIn("advice", self.advice(valid_brief()))
|
||||
cases = {
|
||||
"acceptance": (dict(acceptance="Keep the report short and fast."), "Acceptance says"),
|
||||
"gate": (dict(outcome="Add an approval gate for deploys."), "abuse cases"),
|
||||
"tests": (dict(verification="Write tests for the parser."), "repeat run"),
|
||||
"reader": (dict(outcome="Write the index file for other modules to read."), "no reader is named"),
|
||||
"labels": (dict(outcome="Build a matcher and a labelled set of examples."), "different worker"),
|
||||
"commits": (dict(deliverables="1. the parser\n2. the writer"), "commit per item"),
|
||||
}
|
||||
for name, (parts, flag) in cases.items():
|
||||
with self.subTest(name):
|
||||
self.assertIn(flag, self.advice(self.brief_with(**parts)))
|
||||
fixed = {
|
||||
"acceptance": dict(acceptance="The report is under 40 lines (`wc -l report.md`) and the check runs in 5 s."),
|
||||
"gate": dict(outcome="Add an approval gate for deploys.", verification="Abuse cases: omit the trigger field."),
|
||||
"tests": dict(verification="Write tests; run the new module 30 times in parallel."),
|
||||
"reader": dict(outcome="Write the index for other modules to read; the reader is `sisi/search.py`."),
|
||||
"labels": dict(outcome="Build a matcher; the labelled set comes from a different worker."),
|
||||
"commits": dict(deliverables="1. the parser\n2. the writer\nCommit after each item with a done / next note."),
|
||||
}
|
||||
for name, parts in fixed.items():
|
||||
with self.subTest("fixed " + name):
|
||||
self.assertNotIn("advice", self.advice(self.brief_with(**parts)))
|
||||
self.assertLessEqual(len(self.advice(self.brief_with(**{k: v for c in cases.values() for k, v in c[0].items()})).splitlines()), 20)
|
||||
|
||||
def test_check_passes_a_full_brief(self):
|
||||
p = os.path.join(self.proj, "full.md")
|
||||
open(p, "w").write(valid_brief())
|
||||
|
||||
@@ -103,6 +103,54 @@ class PublishableTree(unittest.TestCase):
|
||||
self.assertFalse(os.path.exists(os.path.join(REPO, "docs", "superpowers")))
|
||||
|
||||
|
||||
class HelpIsGrouped(SisiCase):
|
||||
"""`sisi help` is for its readers: four headings, one line per command, short enough to read at a glance."""
|
||||
|
||||
HEADINGS = ["For the person", "For the agent at work", "Hooks (the tools call these)", "Maintaining sisi"]
|
||||
|
||||
def dispatched(self):
|
||||
"""Every command name the dispatcher in cli.main compares `cmd` to, plus the data-layer subcommands."""
|
||||
import ast, argparse
|
||||
from sisi import cli, learn_cli
|
||||
tree = ast.parse(open(cli.__file__, encoding="utf-8").read())
|
||||
main = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "main")
|
||||
found = set()
|
||||
for n in ast.walk(main):
|
||||
if isinstance(n, ast.Compare) and isinstance(n.left, ast.Name) and n.left.id == "cmd":
|
||||
for c in n.comparators:
|
||||
for k in (c.elts if isinstance(c, ast.Tuple) else [c]):
|
||||
if isinstance(k, ast.Constant) and isinstance(k.value, str) and not k.value.startswith("-"):
|
||||
found.add(k.value)
|
||||
ap = argparse.ArgumentParser()
|
||||
sub = ap.add_subparsers()
|
||||
learn_cli.register(sub)
|
||||
return found | set(sub.choices)
|
||||
|
||||
def test_the_whole_help_fits_60_lines_of_110_characters_under_four_headings(self):
|
||||
out = self.sisi("help").stdout
|
||||
lines = out.splitlines()
|
||||
self.assertLessEqual(len(lines), 60)
|
||||
self.assertLessEqual(max(map(len, lines)), 110)
|
||||
at = [lines.index(h) for h in self.HEADINGS]
|
||||
self.assertEqual(at, sorted(at))
|
||||
|
||||
def test_every_command_the_dispatcher_accepts_is_listed_once_and_nothing_else(self):
|
||||
from sisi import helptext
|
||||
listed = helptext.names()
|
||||
self.assertEqual(len(listed), len(set(listed)), "a command is listed twice")
|
||||
self.assertEqual(set(listed), self.dispatched())
|
||||
text = self.sisi("help").stdout
|
||||
for name in listed:
|
||||
self.assertTrue(re.search(r"(^ sisi |\| |, )%s\b" % re.escape(name), text, re.M), name)
|
||||
|
||||
def test_the_long_explanation_is_one_help_away(self):
|
||||
a, b = self.sisi("help", "retro"), self.sisi("retro", "--help")
|
||||
self.assertEqual((a.returncode, b.returncode), (0, 0))
|
||||
self.assertEqual(a.stdout, b.stdout)
|
||||
self.assertIn("--disposition promote|record|drop", a.stdout)
|
||||
self.assertEqual(self.sisi("help", "nonesuch").returncode, 64)
|
||||
|
||||
|
||||
NOT_BUILT = {"build", "inbox"} # designed in docs/design.md, named in the README as not built
|
||||
|
||||
|
||||
|
||||
+2
-1
@@ -515,8 +515,9 @@ class StatusTests(UnitCase):
|
||||
helptext = self.sisi("help").stdout
|
||||
for gone in ("sisi time", "sisi scoreboard", "sisi improve", "sisi backlog"):
|
||||
self.assertNotIn(gone, helptext)
|
||||
for kept in ("sisi unit close", "sisi unit pause", "sisi unit show", "sisi status"):
|
||||
for kept in ("sisi unit close|pause|show|list", "sisi status"):
|
||||
self.assertIn(kept, helptext)
|
||||
self.assertIn("sisi unit pause", self.sisi("help", "unit").stdout)
|
||||
for cmd in ("time", "scoreboard"):
|
||||
self.assertNotEqual(self.sisi(cmd).returncode, 0, cmd)
|
||||
|
||||
|
||||
@@ -264,7 +264,7 @@ class NothingUnrunIsEverPassedTests(SisiCase):
|
||||
if wc:
|
||||
x["when_changed"] = wc
|
||||
return x
|
||||
c = {"id": "t", "goal": "g", "assumptions": [], "questions": [], "invariants": [],
|
||||
c = {"id": "t", "goal": "g", "risk": {"profile": "isolated"}, "assumptions": [], "questions": [], "invariants": [],
|
||||
"checks": [mk("a", "f_a", None, True), mk("b", "f_b", ["f_b*"], True),
|
||||
mk("c", "f_c", ["nothing/**"], True), mk("d", "f_d", None, False)]}
|
||||
self.write_contract(c, d)
|
||||
|
||||
+34
-1
@@ -301,9 +301,42 @@ class LintCrossCheckTests(LibCase):
|
||||
self.assertIn("warning(s)", r.stdout)
|
||||
|
||||
|
||||
class RepeatUnderLoadTests(SisiCase):
|
||||
"""R-5.6-1: the library has an entry for repeating a test under parallel load, its command works with the
|
||||
standard library alone, and the two recipes say what this rebuild learned."""
|
||||
|
||||
def test_the_entry_is_in_the_library_and_its_command_separates_stable_from_order_dependent_tests(self):
|
||||
import subprocess
|
||||
r = self.sisi("verifiers", "show", "repeat-under-parallel-load")
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertIn("xargs -P 8", r.stdout)
|
||||
d = os.path.join(self.tmp, "rp")
|
||||
os.makedirs(d)
|
||||
with open(os.path.join(d, "test_mod.py"), "w") as f:
|
||||
f.write("import os, time, unittest\n"
|
||||
"class Stable(unittest.TestCase):\n def test_ok(self):\n self.assertEqual(1 + 1, 2)\n"
|
||||
"class Shared(unittest.TestCase):\n def test_shared_path(self):\n"
|
||||
" p = os.path.join(os.path.dirname(__file__), 'shared.txt')\n"
|
||||
" open(p, 'w').write(str(os.getpid())); time.sleep(0.05)\n"
|
||||
" self.assertEqual(open(p).read(), str(os.getpid()))\n")
|
||||
cmd = "seq 30 | xargs -P 8 -I{} python3 -m unittest -q test_mod.%s"
|
||||
run = lambda name: subprocess.run(cmd % name, shell=True, cwd=d, capture_output=True).returncode
|
||||
self.assertEqual(run("Stable"), 0)
|
||||
self.assertNotEqual(run("Shared"), 0)
|
||||
|
||||
def test_the_recipes_name_the_first_increment_and_the_scored_heuristic(self):
|
||||
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
for name in ("feature", "new-product"):
|
||||
text = open(os.path.join(root, "done", name + ".md"), encoding="utf-8").read()
|
||||
self.assertIn("first usable increment", text, name)
|
||||
self.assertIn("labelled as an estimate", text, name)
|
||||
self.assertIn("labels a different worker wrote", text, name)
|
||||
self.assertIn("repeat-under-parallel-load", text, name)
|
||||
|
||||
|
||||
class CoreMdTests(SisiCase):
|
||||
def test_help_lists_new_commands(self):
|
||||
out = self.sisi("help").stdout
|
||||
out = self.sisi("help").stdout + self.sisi("help", "verifiers").stdout + self.sisi("help", "done").stdout
|
||||
for w in ("verifiers show", "verifiers for", "verifiers doctor | lint", "sisi done", "done for"):
|
||||
self.assertIn(w, out)
|
||||
|
||||
|
||||
@@ -2,6 +2,64 @@ import json, unittest
|
||||
from support import *
|
||||
|
||||
|
||||
class EvidenceTests(SisiCase):
|
||||
"""R-5.6-1, R-5.6-4: a failed check keeps the lines that identify the failure, not only the tail of its output."""
|
||||
|
||||
NOISE = "for i in $(seq 1 300); do echo \"summary noise $i\"; done"
|
||||
|
||||
def test_a_failure_300_lines_above_the_end_is_in_the_stored_result_and_the_report(self):
|
||||
cmd = "echo 'FAIL: test_alpha (mod.T.test_alpha)'; echo 'AssertionError: 1 != 2'; %s; exit 1" % self.NOISE
|
||||
r = self.sisi("verify") if self.write_contract(contract([check("t", cmd)])) is None else None
|
||||
self.assertEqual(r.returncode, 1)
|
||||
row = [x for x in self.results() if x["check"] == "t"][0]
|
||||
self.assertEqual(row["status"], "failed")
|
||||
self.assertIn("FAIL: test_alpha (mod.T.test_alpha)", row["evidence"])
|
||||
self.assertIn("AssertionError: 1 != 2", row["evidence"])
|
||||
self.assertLess(len(row["evidence"]), 3100)
|
||||
shown = r.stdout[r.stdout.index("FAILED:"):]
|
||||
self.assertIn("test_alpha", shown)
|
||||
self.assertLess(shown.index("test_alpha"), shown.index("summary noise 300"))
|
||||
|
||||
def test_each_known_runner_keeps_its_failing_test_names(self):
|
||||
from sisi import verify as V
|
||||
outputs = {
|
||||
"unittest": ("FAIL: test_a (m.T.test_a)\n----\nTraceback\nAssertionError: x\n" + "ok\n" * 200 + "FAILED (failures=1)", "test_a (m.T.test_a)"),
|
||||
"pytest": ("_____ test_b _____\nE assert 1 == 2\n" + "x\n" * 200 + "FAILED tests/t.py::test_b - assert 1 == 2", "tests/t.py::test_b"),
|
||||
"cargo": ("test tests::c ... FAILED\n---- tests::c stdout ----\nthread 'tests::c' panicked at src/l.rs:1:1:\n" + "x\n" * 200 + "test result: FAILED", "tests::c"),
|
||||
"go": ("--- FAIL: TestD (0.00s)\n d_test.go:9: want 1 got 2\n" + "x\n" * 200 + "FAIL\tpkg", "TestD"),
|
||||
"jest": (" ● suite › case e\n Expected: 1\n Received: 2\n" + "x\n" * 200 + "Tests: 1 failed", "case e"),
|
||||
}
|
||||
for name, (text, want) in outputs.items():
|
||||
with self.subTest(name):
|
||||
ev = V.evidence(text)
|
||||
self.assertIn(want, ev)
|
||||
self.assertNotIn("\nx\nx\nx", ev)
|
||||
|
||||
def test_unknown_output_keeps_the_first_and_last_30_lines_bounded_and_scrubbed(self):
|
||||
from sisi import verify as V
|
||||
text = "\n".join(["line %d" % i for i in range(1, 401)] + ["password=hunter2hunter2"])
|
||||
ev = V.evidence(text)
|
||||
self.assertIn("line 1\n", ev + "\n")
|
||||
self.assertIn("line 30\n", ev + "\n")
|
||||
self.assertNotIn("line 31\n", ev + "\n")
|
||||
self.assertIn("line 400", ev)
|
||||
self.assertNotIn("hunter2", ev)
|
||||
self.assertLessEqual(len(V.evidence("y" * 100000)), V.EVIDENCE_CHARS)
|
||||
|
||||
def test_a_timeout_keeps_what_it_had_printed(self):
|
||||
c = contract([check("slow", "echo 'FAIL: test_slow (m.T.test_slow)'; sleep 5", timeout_s=0.5)])
|
||||
self.write_contract(c)
|
||||
self.sisi("verify")
|
||||
row = [x for x in self.results() if x["check"] == "slow"][0]
|
||||
self.assertEqual(row["status"], "not-run")
|
||||
self.assertIn("test_slow", row["evidence"])
|
||||
|
||||
def test_a_passing_check_stores_no_evidence(self):
|
||||
self.write_contract(contract([check("ok", "echo fine; test -d .")]))
|
||||
self.sisi("verify")
|
||||
self.assertEqual([x["evidence"] for x in self.results() if x["check"] == "ok"], [""])
|
||||
|
||||
|
||||
class VerifyTests(SisiCase):
|
||||
def run_verify(self, c, *extra):
|
||||
self.write_contract(c)
|
||||
|
||||
+32
-1
@@ -19,6 +19,37 @@ def snapshot(root):
|
||||
return snap
|
||||
|
||||
|
||||
def remove_hooks(obj):
|
||||
"""Test oracle: strip our hook groups from a settings object (the product removes them structurally)."""
|
||||
changed = False
|
||||
hooks = obj.get("hooks")
|
||||
if not isinstance(hooks, dict):
|
||||
return False
|
||||
for ev, sub in (("SessionStart", "tick"), ("UserPromptSubmit", "prompt"), ("Stop", "gate"), ("SubagentStop", "gate"),
|
||||
("PreToolUse", "watch"), ("PostToolUse", "watch")):
|
||||
groups = hooks.get(ev)
|
||||
if not isinstance(groups, list):
|
||||
continue
|
||||
keep, ev_changed = [], False
|
||||
for g in groups:
|
||||
hs = g.get("hooks") if isinstance(g, dict) else None
|
||||
if isinstance(hs, list) and any(wiring._is_ours(h, sub) for h in hs):
|
||||
changed = ev_changed = True
|
||||
rest = [h for h in hs if not wiring._is_ours(h, sub)]
|
||||
if rest:
|
||||
g = dict(g, hooks=rest)
|
||||
else:
|
||||
continue
|
||||
keep.append(g)
|
||||
if keep:
|
||||
hooks[ev] = keep
|
||||
elif ev_changed:
|
||||
del hooks[ev]
|
||||
if changed and not hooks:
|
||||
del obj["hooks"]
|
||||
return changed
|
||||
|
||||
|
||||
class WiringBase(SisiCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
@@ -127,7 +158,7 @@ class WiringPropertyTests(WiringBase):
|
||||
if st is not None and st.strip():
|
||||
orig = json.loads(st)
|
||||
now = json.loads(self.path(".claude/settings.json") and open(self.path(".claude/settings.json"), "rb").read())
|
||||
wiring.remove_hooks(now)
|
||||
remove_hooks(now)
|
||||
|
||||
def norm(d): # empty hook lists/objects may legitimately disappear in the structural path
|
||||
h = d.get("hooks")
|
||||
|
||||
@@ -88,37 +88,6 @@ class DiscoveryTests(WorkerCase):
|
||||
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())
|
||||
|
||||
Reference in new issue
Block a user