Risk profiles and relevance: sisi risk, the design section retired, hooks print only what a session can act on, recipes matched by structured tags, a recipe for features

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 11:09:26 -07:00
commit 8f36c5b527
25 files changed
+1434 -857

No files matched your search

-276
View File
@@ -1,276 +0,0 @@
"""Live principles (`sisi learn`/`sisi oracle`), the contract design section, `sisi design`,
the gate's design send-back, and request-time design delivery."""
import json, os, subprocess, unittest
from support import *
PRINCIPLES = [
"drop into any user's environment and use what is already there",
"mechanisms over good intentions: check it, do not just advise it",
"never set up scheduled jobs or timers for me",
]
def good_design(principles=PRINCIPLES, **over):
d = {
"implies": ["The tool must work in an environment sisi did not choose, so discovery of what "
"the host already provides comes before building any replacement for it."],
"provided": [{"what": "git is already used for change measurement in this repository",
"evidence": "command:git"},
{"what": "the README documents the existing command surface to build on",
"evidence": "file:README.md"}],
"alternatives": [
{"name": "shell out to each tool's command line",
"cost": "one driver per tool, each with its own quoting and login handling",
"risk": "breaks wherever a tool has no usable command line or changes its flags"},
{"name": "build a new agent host of our own",
"cost": "months of work duplicating sessions, auth and tool wiring from scratch",
"risk": "nobody's existing setup carries over, so adoption starts from zero"},
],
"chosen": {"name": "use the host tool's own subagent mechanism",
"why": "It drops into the user's existing environment instead of rebuilding what "
"the host already provides, which is what the owner asked for."},
"objections": [{"principle": p, "applicable": True,
"objection": "You are rebuilding something the environment already gives me.",
"answer": "The design calls the host mechanism and builds only the missing adapter."}
if i < 2 else
{"principle": p, "applicable": False,
"reason": "Nothing in this design runs on a schedule; every step is triggered by use."}
for i, p in enumerate(principles)],
"challenge": {"by": "a subagent on a different model, briefed as the owner",
"recorded_at": "2026-01-01T00:00:00Z",
"objections": ["You never checked what the host already provides before designing drivers."],
"changes": ["Made the host subagent mechanism the main path; command lines are the fallback."]},
}
d.update(over)
return d
class PrinciplesCase(SisiCase):
def learn_all(self):
for p in PRINCIPLES:
r = self.sisi("learn", "--scope", "user", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class LivePrinciplesTests(PrinciplesCase):
def test_learn_takes_effect_at_once_without_quarantine_wording(self):
r = self.sisi("learn", "--scope", "user", PRINCIPLES[0])
self.assertEqual(r.returncode, 0, r.stdout)
self.assertNotIn("quarantin", (r.stdout + r.stderr).lower())
out = self.sisi("oracle").stdout
self.assertIn(PRINCIPLES[0], out)
def test_oracle_prints_one_principle_per_statement_with_quote_and_date(self):
self.learn_all()
out = self.sisi("oracle").stdout
for p in PRINCIPLES:
self.assertIn(p, out)
self.assertIn('"%s"' % p, out)
self.assertIn("Standing principles", out)
def test_quarantine_file_is_migrated_losslessly(self):
os.makedirs(self.data, exist_ok=True)
rec = {"ts": "2025-01-02T03:04:05Z", "cwd": self.proj, "tool": None, "session": None,
"text": "always show options with a recommendation", "scope": "user"}
with open(os.path.join(self.data, "learn-quarantine.jsonl"), "w") as f:
f.write(json.dumps(rec) + "\n")
out = self.sisi("oracle").stdout
self.assertIn("always show options with a recommendation", out)
self.assertIn("2025-01-02", out)
self.assertTrue(os.path.exists(os.path.join(self.data, "learn.jsonl")))
self.assertFalse(os.path.exists(os.path.join(self.data, "learn-quarantine.jsonl")))
rows = [json.loads(l) for l in open(os.path.join(self.data, "learn.jsonl"))]
self.assertEqual(rows[0]["text"], rec["text"])
self.assertEqual(rows[0]["ts"], rec["ts"])
def test_learn_statement_may_name_sisi_itself(self):
# the project folder is named proj in the fixture; use a folder named sisi
d = os.path.join(self.tmp, "sisi")
os.makedirs(d)
subprocess.run(["git", "init", "-q"], cwd=d, check=True)
r = self.sisi("learn", "--scope", "user",
"sisi should anticipate what I need from what I already said", cwd=d)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class DesignValidationTests(PrinciplesCase):
def errs(self, design):
from sisi import design as D
return D.validate_design({"goal": "g", "design": design}, cwd=REPO)
def test_good_design_passes(self):
self.learn_all()
self.assertEqual(self.errs(good_design()), [])
def test_missing_design_is_an_error(self):
from sisi import design as D
self.assertTrue(D.validate_design({"goal": "g"}, cwd=REPO))
def test_labelled_good_and_filler_sets(self):
"""At least 12 good and 12 filler design sections: every good one passes, every filler fails."""
self.learn_all()
base = good_design()
def variant(**kw):
d = json.loads(json.dumps(base))
d.update(kw)
return d
goods = [base]
for i in range(11):
d = json.loads(json.dumps(base))
d["implies"] = ["Implication %d: the result must keep working when the host, the model "
"and the project layout all change around it over time." % i]
d["provided"] = [{"what": "python3 runs the whole tool and its checks already",
"evidence": "command:python3"},
{"what": "the licence file fixes the terms this ships under",
"evidence": "file:LICENSE"}]
d["alternatives"][0]["name"] = "bespoke driver number %d" % i
d["challenge"]["by"] = "independent reviewer %d on a different model" % i
goods.append(d)
fillers = [
variant(implies=["As requested."]),
variant(implies=[]),
variant(provided=[{"what": "existing tools", "evidence": "command:no-such-command-xyz"}]),
variant(provided=["stuff that exists somewhere in general terms"]),
variant(provided=[]),
variant(alternatives=[base["alternatives"][0]]),
variant(alternatives=[dict(base["alternatives"][0], name="use the host tool's own subagent mechanism"),
base["alternatives"][1]]),
variant(alternatives=[dict(base["alternatives"][0], cost="low", risk="low"),
dict(base["alternatives"][1], cost="low", risk="low")]),
variant(chosen={"name": "use the host tool's own subagent mechanism", "why": "best"}),
variant(objections=[{"principle": PRINCIPLES[0], "applicable": True,
"objection": "x", "answer": "y"}]),
variant(objections=[dict(o, applicable=False, reason="n/a") if o.get("applicable") else o
for o in base["objections"]]),
variant(challenge={"by": "self", "recorded_at": "2026-01-01T00:00:00Z",
"objections": ["none"], "changes": []}),
variant(challenge={"by": "a subagent on a different model", "recorded_at": "2026-01-01T00:00:00Z",
"objections": [], "changes": ["changed things in response to the review"]}),
]
good_pass = sum(1 for d in goods if not self.errs(d))
filler_fail = sum(1 for d in fillers if self.errs(d))
self.assertGreaterEqual(len(goods), 12)
self.assertGreaterEqual(len(fillers), 12)
self.assertEqual((good_pass, filler_fail), (len(goods), len(fillers)),
"good %d/%d pass, filler %d/%d refused" % (good_pass, len(goods), filler_fail, len(fillers)))
class DesignCommandTests(PrinciplesCase):
def test_sisi_design_prints_principles_and_questions(self):
self.learn_all()
r = self.sisi("design")
self.assertEqual(r.returncode, 0, r.stderr)
for p in PRINCIPLES:
self.assertIn(p, r.stdout)
for key in ("implies", "provided", "alternatives", "chosen", "objections", "challenge"):
self.assertIn(key, r.stdout)
def test_contract_init_prints_principles_and_design_skeleton(self):
self.learn_all()
r = self.sisi("contract", "init", "--goal", "build the orchestrator")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn(PRINCIPLES[0], r.stdout)
c = json.load(open(os.path.join(self.proj, ".sisi", "contract.json")))
self.assertIn("design", c)
for key in ("implies", "provided", "alternatives", "chosen", "objections", "challenge"):
self.assertIn(key, c["design"])
class DesignGateTests(PrinciplesCase):
def gate(self, payload):
return self.sisi("gate", stdin=json.dumps(payload))
def large_contract_project(self, design=None):
self.git_init()
c = contract([check("a", "true")])
if design is not None:
c["design"] = design
self.write_contract(c)
with open(os.path.join(self.proj, "big.txt"), "w") as f:
f.write("line\n" * 80)
return {"session_id": "gate-design-1", "cwd": self.proj, "stop_hook_active": False}
def test_large_change_without_design_is_sent_back_then_never_traps(self):
self.learn_all()
payload = self.large_contract_project()
msgs = []
for _ in range(5):
r = self.gate(payload)
out = r.stdout.strip()
if not out:
break
d = json.loads(out)
msgs.append(d)
if d.get("decision") != "block":
break
self.assertTrue(any("design" in (m.get("reason") or "") for m in msgs), msgs)
# never traps: within the send-back budget the turn is let through
self.assertLessEqual(len([m for m in msgs if m.get("decision") == "block"]), 3)
def test_large_change_with_good_design_is_not_sent_back_for_design(self):
self.learn_all()
payload = self.large_contract_project(design=good_design())
r = self.gate(payload)
self.assertNotIn("design section is missing", r.stdout)
def test_small_change_needs_no_design(self):
self.git_init()
self.write_contract(contract([check("a", "true")]))
with open(os.path.join(self.proj, "small.txt"), "w") as f:
f.write("one line\n")
r = self.gate({"session_id": "gate-design-small", "cwd": self.proj})
self.assertNotIn("design", r.stdout)
class PromptDesignTests(PrinciplesCase):
def test_design_work_gets_principles_and_instruction(self):
self.learn_all()
from sisi import prompt as P
ctx = P.build_context("Build an automatic orchestrator that delegates work to other agents "
"across the tools installed here, with routing and judged outcomes")
self.assertIn(PRINCIPLES[0], ctx)
self.assertIn("design", ctx.lower())
self.assertLessEqual(len(ctx), P.MAX_CHARS)
def test_questions_and_small_edits_get_no_design_block(self):
self.learn_all()
from sisi import prompt as P
for q in ("Should the orchestrator use subagents or command lines?",
"rename the helper that formats the orchestrator headings in the docs",
"fix the typo in the orchestrator help text on the second line"):
self.assertNotIn(PRINCIPLES[0], P.build_context(q), q)
def test_labelled_design_requests(self):
self.learn_all()
from sisi import prompt as P
should = [
"Build an automatic orchestrator that delegates work to other agents across tools",
"Design and implement a new storage layer for session records with migration",
"Create a command that discovers installed agent tools and routes work between them",
"Implement a plugin system so other tools can add their own checks to the gate",
]
should_not = [
"Why does the orchestrator choose that worker for this kind of work?",
"rename the local variable in the routing helper to something clearer",
"fix the off-by-one in the pagination control of the list view",
"What does the design section of a contract actually require in full?",
]
hits = sum(1 for t in should if "design section" in P.build_context(t))
false = sum(1 for t in should_not if "design section" in P.build_context(t))
self.assertEqual((hits, false), (len(should), 0),
"design hits %d/%d, false %d/%d" % (hits, len(should), false, len(should_not)))
class RuleDesignTests(SisiCase):
def test_first_rule_is_choose_the_approach_with_real_enforcement(self):
r = self.sisi("rule", "1")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("choose-the-approach", r.stdout)
self.assertIn("Why:", r.stdout)
from sisi import rulecmd
self.assertIn("design", rulecmd.enforcement_for("choose-the-approach"))
self.assertNotIn("not enforced", rulecmd.enforcement_for("choose-the-approach"))
if __name__ == "__main__":
unittest.main()
+82
View File
@@ -0,0 +1,82 @@
"""Session start and prompt hooks after the rework (R-17-3, R-12-12, target section 11)."""
import json, os, unittest
from support import *
class TickCleanTests(SisiCase):
def payload(self, **kw):
return json.dumps(dict({"session_id": "s1", "cwd": self.proj,
"hook_event_name": "SessionStart", "source": "startup"}, **kw))
def test_clean_home_prints_nothing(self):
"""R-17-3: in a clean home with nothing to act on, session start is silent."""
self.git_init()
self.sisi("install")
r = self.sisi("tick", stdin=self.payload())
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout, "")
def test_broken_wiring_still_prints_one_line(self):
"""R-17-2: broken wiring is actionable, so it is the one line printed."""
os.makedirs(os.path.join(self.home, ".claude"))
r = self.sisi("tick", stdin=self.payload())
self.assertIn("sisi doctor", r.stdout)
self.assertLessEqual(len(r.stdout.strip().splitlines()), 1)
def test_handover_shown_once_per_session(self):
"""R-12-2: handover items for this project print once per session, not every session."""
self.git_init()
self.sisi("install")
from sisi import handover, scope
pid = scope.project_id(self.proj)
handover.add_item({"kind": "learn", "project": pid, "text": "file this fact"})
r1 = self.sisi("tick", stdin=self.payload())
self.assertIn("belong to this project", r1.stdout)
r2 = self.sisi("tick", stdin=self.payload(source="resume"))
self.assertNotIn("belong to this project", r2.stdout)
class PromptReworkTests(SisiCase):
def ctx(self, text):
from sisi import prompt as P
return P.build_context(text, session="rework")
def test_typo_fix_is_silent(self):
"""R-17-3: a trivial request gets no injection."""
self.assertEqual(self.ctx("fix a typo in the README"), "")
def test_question_is_silent(self):
"""R-17-3, R-12-12: a question naming no work gets no recipe."""
self.assertEqual(self.ctx("why is the build slow?"), "")
def test_map_printing_gets_feature_recipe(self):
"""SPEC Appendix B / R-4.1-1: the complex example gets its recipe at prompt time."""
ctx = self.ctx("add multi-page map printing with selectable paper size")
self.assertIn("feature", ctx)
self.assertLessEqual(len(ctx), 2000)
def test_accent_color_gets_ui_recipe(self):
"""SPEC Appendix A: the presentation example gets a fitting recipe."""
ctx = self.ctx("change the accent color of one UI component")
self.assertTrue("web-ui-change" in ctx or "native-gui-change" in ctx, ctx)
def test_no_handover_notice_in_prompt(self):
"""R-17-3: the per-prompt handover notice is gone."""
from sisi import handover, scope
pid = scope.project_id(self.proj)
handover.add_item({"kind": "learn", "project": pid, "text": "file this fact"})
for text in ("fix a typo in the README", "why is the build slow?",
"add multi-page map printing with selectable paper size"):
with self.subTest(text=text):
self.assertNotIn("belong to this project", self.ctx(text))
def test_no_design_block_anywhere(self):
"""Retired design section: no prompt prints its instruction."""
for text in ("build a new orchestration system for agents",
"design and build a plugin platform for the tool"):
with self.subTest(text=text):
self.assertNotIn("design section", self.ctx(text))
if __name__ == "__main__":
unittest.main()
+2
View File
@@ -163,6 +163,8 @@ class ImmediateEffectTests(LearningCase):
ids = [int(l.split()[0][1:]) for l in out if l.startswith("#")]
self.assertEqual(ids, [b, c, a]) # most seen first; the tie goes to the older lesson
self.assertEqual(self.lesson(b)["effect"], "backlog")
tick = self.sisi("tick", stdin=json.dumps({"session_id": "dev1", "cwd": self.proj, "source": "startup"})).stdout
self.assertNotIn("backlog", tick) # session start no longer prints the backlog
class DeliveryTests(LearningCase):
+136
View File
@@ -0,0 +1,136 @@
"""Structured matcher (R-5.2-1, R-5.2-2): labelled set written without the entries' own words.
Each case is (query, acceptable ids, kind) where kind is 'verifier' or 'recipe'.
Queries are phrased as someone who has not read the library would phrase them.
Top-1 / top-3 thresholds below sit a small margin under the level reached when
this set was built; the test fails if matching regresses under them.
"""
import unittest
from support import *
from sisi import verifiers as V
# (query, acceptable verifier ids)
VERIFIER_CASES = [
("fix the race condition in the worker pool", {"thread-sanitizer", "go-race-detector", "loom", "shuttle", "stress-repeat", "lock-order-and-deadlock"}),
("two background jobs keep stepping on the same shared counter", {"thread-sanitizer", "go-race-detector", "loom", "shuttle", "deterministic-simulation"}),
("the parser handles malformed CSV without falling over", {"atheris", "hypothesis", "hostile-input-from-schema", "cargo-fuzz", "proptest", "fast-check", "structure-aware-fuzzing", "jqwik", "go-fuzz", "jazzer"}),
("strange delimited files from users must not crash the import", {"atheris", "hypothesis", "hostile-input-from-schema", "cargo-fuzz", "proptest", "structure-aware-fuzzing"}),
("money rounding is correct to the cent", {"algebraic-laws", "exhaustive-small-domain", "hypothesis", "proptest", "differential-reference", "metamorphic", "golden-files-hand-verified"}),
("the invoice totals always add up whatever lines are on it", {"algebraic-laws", "hypothesis", "proptest", "metamorphic", "derived-view-agreement", "differential-reference"}),
("charges are never a fraction of a cent out", {"algebraic-laws", "exhaustive-small-domain", "hypothesis", "metamorphic", "differential-reference"}),
("any sequence of moves keeps the account balanced", {"algebraic-laws", "stateful-model-test", "model-test-from-spec", "replay-equivalence"}),
("old files from the previous release still open with the same figures", {"old-data-compatibility", "db-migration-safety", "packaging-install-upgrade"}),
("moving the stored records to the new shape loses nothing", {"db-migration-safety", "old-data-compatibility", "differential-old-vs-new"}),
("the page still looks the same where I did not touch it", {"visual-regression-web", "ui-structure-snapshot", "baseline-before-change"}),
("people using only a keyboard can still finish the form", {"accessibility-axe", "e2e-playwright", "owner-acceptance-runbook"}),
("would my checks notice if the calculation were quietly wrong", {"cargo-mutants", "mutmut", "mutation-on-diff", "vacuity-check", "assertion-strength-review", "check-the-checker", "pitest", "go-mutation", "stryker"}),
("the new check passes even when nothing ran at all", {"vacuity-check", "check-the-checker", "red-before-green"}),
("nothing that worked yesterday broke in the tidy-up", {"characterization-tests", "baseline-before-change", "differential-old-vs-new"}),
("a hostile file at the boundary gets a clean refusal, not a crash", {"hostile-input-from-schema", "atheris", "cargo-fuzz", "codeql"}),
("no password or token ends up in the history", {"secret-scanning", "sensitive-data-leak-test"}),
("every state the workflow can sit in is one we meant to allow", {"tlaplus", "quint", "alloy", "small-scope-enumeration", "illegal-states-unrepresentable", "model-coverage"}),
("after the power dies mid-save the data reopen intact", {"fault-injection-storage"}),
("reading it back gives exactly what was written, every shape of value", {"round-trip", "stateful-model-test"}),
("the service still answers each caller the way they expect", {"contract-testing-pact", "smoke-after-deploy", "load-test-k6"}),
("it works from a brand-new checkout, not just my messy tree", {"clean-clone-build"}),
]
RECIPE_CASES = [
("fix the race condition", {"concurrent-code"}),
("two jobs running at once keep losing each other's updates", {"concurrent-code"}),
("add multi-page map printing with selectable paper size", {"feature"}),
("change the accent color of one UI component", {"web-ui-change"}),
("let people print a big map over several sheets of paper", {"feature"}),
("make the settings page button a different colour", {"web-ui-change"}),
("the total on invoices is a cent out when it rounds", {"numeric-or-financial-core"}),
("users' spreadsheet files with broken rows break the import", {"parser-or-codec"}),
("numbers coming out of the tax calculation cannot be trusted", {"numeric-or-financial-core"}),
("reported defect: the export button does nothing on the second click", {"bugfix"}),
("it worked before the tidy-up and must behave identically after", {"refactor"}),
("restructure the internals without changing what anyone sees", {"refactor"}),
("ship the next version and put the tag on it", {"release"}),
("move all the stored records onto the new layout safely", {"data-migration"}),
("the stored shape is changing and old records must survive", {"data-migration"}),
("someone found a way in through the search box input", {"security-fix"}),
("make the nightly job finish in half the time", {"performance-work"}),
("why is everything so sluggish since the last change", {"performance-work"}),
("rewrite the bit that turns text files into tables", {"parser-or-codec"}),
("a whole new app from this one-line idea", {"new-product"}),
("a package other teams will build on top of", {"new-library"}),
("the bit that keeps files on disk and reads them back after a crash", {"storage-engine"}),
]
ALL_CASES = ([(q, ids, "verifier") for q, ids in VERIFIER_CASES]
+ [(q, ids, "recipe") for q, ids in RECIPE_CASES])
# Measured when built: new top-1 0.75, top-3 0.93 (old word overlap: 0.55 / 0.68).
# Thresholds are that minus a small margin.
TOP1_MIN = 0.68
TOP3_MIN = 0.88
def _ranked_ids(query, kind):
if kind == "verifier":
return [e["id"] for _, e in V.rank_verifiers(query)]
return [r["id"] for _, r in V.rank_recipes(query)]
class LabelledSetTests(SisiCase):
def test_labelled_set_accuracy(self):
"""R-5.2-2: matching is good enough on requests that share no words with the entries."""
self.assertGreaterEqual(len(ALL_CASES), 40)
top1 = top3 = 0
misses = []
for query, acceptable, kind in ALL_CASES:
ids = _ranked_ids(query, kind)
if ids and ids[0] in acceptable:
top1 += 1
if any(i in acceptable for i in ids[:3]):
top3 += 1
else:
misses.append((query, ids[:3]))
n = len(ALL_CASES)
self.assertGreaterEqual(top3 / n, TOP3_MIN, "top-3 misses: %r" % (misses,))
self.assertGreaterEqual(top1 / n, TOP1_MIN, "top-1 too low; misses: %r" % (misses,))
def test_audit_failures_rank_first(self):
"""R-5.2-1: the audit's named failures are fixed."""
self.assertEqual(_ranked_ids("fix the race condition", "recipe")[0], "concurrent-code")
ids = _ranked_ids("the parser handles malformed CSV", "verifier")
fuzz_or_property = {"atheris", "hypothesis", "cargo-fuzz", "proptest", "fast-check",
"hostile-input-from-schema", "structure-aware-fuzzing", "jqwik", "go-fuzz", "jazzer"}
self.assertTrue(any(i in fuzz_or_property for i in ids[:3]), ids[:3])
money = _ranked_ids("money rounding is correct", "verifier")
self.assertTrue(any(i in money for i in
[e["id"] for _, e in V.rank_verifiers("money rounding is correct")
if "money" in e["kinds"]][:3] or money[:3]), money[:3])
def test_spec_examples_get_recipes(self):
"""SPEC Appendix A/B: both worked examples get a fitting recipe."""
self.assertEqual(_ranked_ids("add multi-page map printing with selectable paper size", "recipe")[0], "feature")
self.assertIn(_ranked_ids("change the accent color of one UI component", "recipe")[0],
("web-ui-change", "native-gui-change"))
class RankingTests(SisiCase):
def test_proven_ranks_above_documentation_only(self):
"""R-5.2-6: an entry proven on a real run outranks a docs-only twin."""
import os
vdir = os.path.join(self.tmp, "v2")
os.makedirs(os.path.join(vdir, "prove"))
body = "\n".join("## " + h + "\ntext" for h in V.V_HEADINGS) + "\n"
def entry(id, verified):
return ("---\nid: %s\ntitle: Cache check %s\nanswers: Does the cache evict correctly?\nrung: 3\n"
"section: prove\nlanguages: any\nkinds: general\ncost: low\ndetect:\nran_here: no\n"
"verified: %s\n---\n%s" % (id, id, verified, body))
with open(os.path.join(vdir, "prove", "docs-twin.md"), "w") as f:
f.write(entry("docs-twin", "docs"))
with open(os.path.join(vdir, "prove", "ran-twin.md"), "w") as f:
f.write(entry("ran-twin", "ran"))
ranked = V.rank_verifiers("cache evict", entries=V.load_verifiers(vdir))
self.assertEqual(ranked[0][1]["id"], "ran-twin")
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -452,7 +452,7 @@ class MigrationTests(PersonalCase):
from sisi import trust
self.assertTrue(trust.is_trusted(self.proj))
self.assertEqual(self.ok("tick", stdin="{}").returncode, 0)
self.assertIn("Always watch", self.sisi("tick", stdin="{}").stdout)
self.assertEqual(self.sisi("tick", stdin="{}").stdout, "") # no lesson list at session start
def test_migrate_merges_when_both_old_and_new_databases_exist(self):
self.legacy_state(extra_lesson=True)
+2 -2
View File
@@ -429,7 +429,7 @@ class TickBlockTests(RetroCase):
def test_block_is_framed_as_information(self):
self.make("Prefer a readiness probe over a fixed sleep when waiting for servers", 3)
out = self.tick()
out = retro.tick_block(self.proj, session="t")
self.assertIn("notes left by earlier agents", out)
self.assertIn("not as commands", out)
self.assertIn("(seen 3)", out)
@@ -442,7 +442,7 @@ class TickBlockTests(RetroCase):
self.make("global heavy lesson about caching", 9, repo=self.tmp + "/other")
self.make("local light lesson about probes", 1)
self.make("rejected lesson never shown", 20, status="rejected")
lines = [l for l in self.tick().splitlines() if l.startswith("- ")]
lines = [l for l in retro.tick_block(self.proj, session="t").splitlines() if l.startswith("- ")]
self.assertTrue(lines[0].startswith("- local light"), lines)
self.assertTrue(lines[1].startswith("- global heavy"))
self.assertFalse(any("rejected" in l for l in lines))
+110
View File
@@ -0,0 +1,110 @@
"""Risk profiles (R-5.3-1, R-5.3-2, R-5.3-3..R-5.3-10)."""
import json, os, random, unittest
from support import *
from sisi import risk
class FloorTests(SisiCase):
def test_docs_only_is_trivial(self):
"""R-5.3-4: documentation/text/styling only is trivial."""
p, reasons = risk.assess(["README.md", "docs/guide.txt", "web/site.css"])
self.assertEqual(p, "trivial")
self.assertTrue(reasons)
def test_single_module_is_isolated(self):
"""R-5.3-5: one module's behaviour is isolated."""
p, _ = risk.assess(["src/calc.py"])
self.assertEqual(p, "isolated")
def test_logic_kinds(self):
"""R-5.3-6: algorithms, parsing and money are logic."""
for path in ("src/parser/lexer.py", "src/money/rounding.py", "src/algo/sort.py"):
with self.subTest(path=path):
p, _ = risk.assess([path])
self.assertEqual(p, "logic")
def test_two_packages_is_integration(self):
"""R-5.3-7, R-5.3-11: several top-level packages is integration."""
p, reasons = risk.assess(["src/alpha/a.py", "src/beta/b.py"])
self.assertEqual(p, "integration")
self.assertTrue(any("package" in r for r in reasons))
def test_migration_is_data(self):
"""R-5.3-8: schema/persistence/migration is data."""
p, _ = risk.assess(["db/migrations/0002_add_col.sql"])
self.assertEqual(p, "data")
def test_auth_is_critical(self):
"""R-5.3-9: authorization/secrets/concurrency primitives are critical."""
for path in ("src/auth/login.py", "src/crypto/keys.py", "src/sync/mutex.py"):
with self.subTest(path=path):
p, _ = risk.assess([path])
self.assertEqual(p, "critical")
def test_diff_keyword_raises_floor(self):
"""R-5.3-1: content keywords count, not only paths."""
p, _ = risk.assess(["src/util.py"], diff_text="+ encrypt the password at rest")
self.assertEqual(p, "critical")
def test_adding_path_never_lowers_floor(self):
"""R-5.3-1: property — the floor is monotone in the change set."""
rng = random.Random(7)
pool = ["README.md", "src/a/x.py", "src/b/y.py", "db/migrations/m.sql",
"src/auth/login.py", "src/parser/p.py", "VERSION", "web/site.css"]
order = {name: i for i, name in enumerate(risk.PROFILES)}
for _ in range(80):
base = rng.sample(pool, rng.randint(0, 4))
extra = rng.choice(pool)
before, _ = risk.assess(base)
after, _ = risk.assess(base + [extra])
self.assertGreaterEqual(order[after], order[before], (base, extra))
def test_project_override_and_requirements_table(self):
"""R-5.3-3: a project may override; each profile carries its requirements."""
p, _ = risk.assess(["src/special/thing.py"],
extra_patterns=[{"glob": "**/special/**", "profile": "data",
"reason": "project override: special holds stored data"}])
self.assertEqual(p, "data")
req = risk.requirements_for("trivial")
self.assertFalse(req["contract"])
self.assertTrue(risk.requirements_for("critical")["independent_evidence"])
self.assertTrue(risk.requirements_for("release")["contract"])
class RiskCliTests(SisiCase):
def _repo_with(self, files):
self.git_init()
for rel, text in files.items():
p = os.path.join(self.proj, rel)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "w") as f:
f.write(text)
def test_risk_json_readme_change(self):
"""R-5.3-2: a README edit does not get the full process."""
self._repo_with({"README.md": "# hi\nchanged\n"})
r = self.sisi("risk", "--json")
self.assertEqual(r.returncode, 0, r.stderr)
d = json.loads(r.stdout)
self.assertEqual(d["floor"], "trivial")
self.assertIn("requirements", d)
def test_risk_json_migration_change(self):
"""R-5.3-8: a migrations change floors at data."""
self._repo_with({"db/migrations/0001.sql": "ALTER TABLE t ADD c INT;\n"})
d = json.loads(self.sisi("risk", "--json").stdout)
self.assertEqual(d["floor"], "data")
def test_risk_declared_profile_from_contract(self):
"""R-5.3-3: the declared profile in .sisi/contract.json is reported."""
self._repo_with({"src/a.py": "x = 1\n"})
os.makedirs(os.path.join(self.proj, ".sisi"), exist_ok=True)
with open(os.path.join(self.proj, ".sisi", "contract.json"), "w") as f:
json.dump({"id": "t", "goal": "g", "checks": [], "risk": {"profile": "logic"}}, f)
d = json.loads(self.sisi("risk", "--json").stdout)
self.assertEqual(d["declared"], "logic")
if __name__ == "__main__":
unittest.main()
+4 -4
View File
@@ -316,17 +316,17 @@ class TickDeepTests(SisiCase):
self.git_init()
def test_line_for_not_fresh_states_silent_when_fresh_or_untrusted(self):
# Session start no longer prints deep-check state; `sisi verify --state` owns it.
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.assertIn("never-run", self.tick())
self.assertEqual(len(self.tick().strip().splitlines()), 1)
self.assertEqual(self.tick(), "")
self.sisi("verify", "--deep")
self.assertEqual(self.tick(), "")
with open(os.path.join(self.proj, "n.txt"), "w") as f:
f.write("x")
self.assertIn("stale-pass", self.tick())
self.assertEqual(self.tick(), "")
self.write_contract(contract([check("f", "true"), deepc("d", "false")]))
self.sisi("verify", "--deep")
self.assertIn("failed", self.tick())
self.assertEqual(self.tick(), "")
self.write_contract(contract([check("f", "true"), deepc("d")]), trusted=False)
os.remove(os.path.join(self.data, "trusted.json"))
self.assertEqual(self.tick(), "")