diff --git a/canon/core.md b/canon/core.md index 123a306..8e1d0ac 100644 --- a/canon/core.md +++ b/canon/core.md @@ -7,17 +7,8 @@ commands mentioned here. ## 1. Choose the approach from the goal {#choose-the-approach} Before sizeable work, think from the goal and the human's standing principles (`sisi oracle`) -to what they imply. Fill the contract's `design` section first (`sisi design` prints the -principles and the questions): - -- what the goal and the principles imply that the request did not spell out; -- what the environment, the tool or the existing system already provides - use that instead - of building it, and give evidence it exists; -- at least two other approaches, one line each on cost and risk; -- the one chosen, and why it is the one the human would pick; -- for each principle, the objection the human would raise and how the design answers it, or - why it does not apply; -- an independent attack on the design as the human would make it, and what changed. +to what they imply: what the request did not spell out, and what the environment, the tool or +the existing system already provides - use that instead of building it. Why: the human should never have to state a consequence of something they already said. A well-built answer to the wrong approach wastes everything spent building it. diff --git a/canon/risk.json b/canon/risk.json new file mode 100644 index 0000000..e0397c5 --- /dev/null +++ b/canon/risk.json @@ -0,0 +1,74 @@ +{ + "profiles": ["trivial", "isolated", "logic", "integration", "data", "critical", "release"], + "requirements": { + "trivial": {"contract": false, "checks": "the diff; a targeted check when one exists", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "only on an anomaly (two send-backs, or a human correction)"}, + "isolated": {"contract": true, "checks": "at least one that is not vacuous", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes"}, + "logic": {"contract": true, "checks": "as isolated, each with covers", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes"}, + "integration": {"contract": true, "checks": "as logic, plus invariants", "requirement_model": true, "risk_note": true, "independent_evidence": false, "retro": "yes"}, + "data": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"}, + "critical": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"}, + "release": {"contract": true, "checks": "every check (--all)", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"} + }, + "patterns": [ + {"glob": "**/migrations/**", "profile": "data", "reason": "database migration changes stored data shape"}, + {"glob": "**/migration/**", "profile": "data", "reason": "data migration code"}, + {"glob": "**/*.sql", "profile": "data", "reason": "SQL changes stored data or schema"}, + {"glob": "**/schema/**", "profile": "data", "reason": "schema definition"}, + {"glob": "**/*.schema.*", "profile": "data", "reason": "schema definition"}, + {"glob": "**/alembic/**", "profile": "data", "reason": "database migration history"}, + {"glob": "**/db/**", "profile": "data", "reason": "persistence layer"}, + {"glob": "**/storage/**", "profile": "data", "reason": "persistence layer"}, + {"glob": "**/persist*/**", "profile": "data", "reason": "persistence layer"}, + {"glob": "**/auth/**", "profile": "critical", "reason": "authorization or authentication code"}, + {"glob": "**/*auth*", "profile": "critical", "reason": "authorization or authentication code"}, + {"glob": "**/*secret*", "profile": "critical", "reason": "secret handling"}, + {"glob": "**/*crypto*", "profile": "critical", "reason": "cryptography"}, + {"glob": "**/*encrypt*", "profile": "critical", "reason": "cryptography"}, + {"glob": "**/*payment*", "profile": "critical", "reason": "payments move money"}, + {"glob": "**/*billing*", "profile": "critical", "reason": "billing moves money"}, + {"glob": "**/*mutex*", "profile": "critical", "reason": "concurrency primitive"}, + {"glob": "**/*semaphore*", "profile": "critical", "reason": "concurrency primitive"}, + {"glob": "**/*lock*", "profile": "critical", "reason": "concurrency primitive"}, + {"glob": "**/hooks/**", "profile": "critical", "reason": "hook wiring runs on every session"}, + {"glob": "**/*hook*", "profile": "critical", "reason": "hook wiring runs automatically"}, + {"glob": "**/install*", "profile": "critical", "reason": "installer changes the user's machine"}, + {"glob": "install*", "profile": "critical", "reason": "installer changes the user's machine"}, + {"glob": "**/setup.py", "profile": "critical", "reason": "installer runs at install time"}, + {"glob": "**/PKGBUILD", "profile": "critical", "reason": "package build script runs as root tooling"}, + {"glob": "VERSION", "profile": "release", "reason": "version marker for a release"}, + {"glob": "**/release/**", "profile": "release", "reason": "release machinery"}, + {"glob": "**/*release*", "profile": "release", "reason": "release machinery"}, + {"glob": "**/api/**", "profile": "integration", "reason": "public interface surface"}, + {"glob": "**/public/**", "profile": "integration", "reason": "public interface surface"}, + {"glob": "include/**", "profile": "integration", "reason": "public headers are an interface"}, + {"glob": "**/parser/**", "profile": "logic", "reason": "parsing logic has a broad input space"}, + {"glob": "**/*pars*", "profile": "logic", "reason": "parsing logic has a broad input space"}, + {"glob": "**/*lexer*", "profile": "logic", "reason": "lexing logic has a broad input space"}, + {"glob": "**/*codec*", "profile": "logic", "reason": "encode/decode logic"}, + {"glob": "**/money/**", "profile": "logic", "reason": "money arithmetic must be exact"}, + {"glob": "**/*money*", "profile": "logic", "reason": "money arithmetic must be exact"}, + {"glob": "**/*rounding*", "profile": "logic", "reason": "rounding rules decide money"}, + {"glob": "**/*pricing*", "profile": "logic", "reason": "pricing arithmetic"}, + {"glob": "**/algo*/**", "profile": "logic", "reason": "algorithmic logic"}, + {"glob": "**/*algorithm*", "profile": "logic", "reason": "algorithmic logic"}, + {"glob": "**/*state-machine*", "profile": "logic", "reason": "state machine transitions"}, + {"glob": "**/*statemachine*", "profile": "logic", "reason": "state machine transitions"}, + {"glob": "**/*.md", "profile": "trivial", "reason": "documentation only"}, + {"glob": "**/*.txt", "profile": "trivial", "reason": "plain text only"}, + {"glob": "**/*.rst", "profile": "trivial", "reason": "documentation only"}, + {"glob": "docs/**", "profile": "trivial", "reason": "documentation only"}, + {"glob": "**/*.css", "profile": "trivial", "reason": "styling only"}, + {"glob": "**/*.scss", "profile": "trivial", "reason": "styling only"}, + {"keyword": "migration", "profile": "data", "reason": "diff mentions a data migration"}, + {"keyword": "schema change", "profile": "data", "reason": "diff changes a schema"}, + {"keyword": "alter table", "profile": "data", "reason": "diff alters stored data"}, + {"keyword": "password", "profile": "critical", "reason": "diff handles credentials"}, + {"keyword": "secret", "profile": "critical", "reason": "diff handles secrets"}, + {"keyword": "encrypt", "profile": "critical", "reason": "diff uses cryptography"}, + {"keyword": "authorize", "profile": "critical", "reason": "diff makes authorization decisions"}, + {"keyword": "authentication", "profile": "critical", "reason": "diff handles authentication"}, + {"keyword": "payment", "profile": "critical", "reason": "diff moves money"}, + {"keyword": "mutex", "profile": "critical", "reason": "diff uses a concurrency primitive"}, + {"keyword": "release candidate", "profile": "release", "reason": "diff prepares a release"} + ] +} diff --git a/docs/learning.md b/docs/learning.md index ee0c20a..18c656b 100644 --- a/docs/learning.md +++ b/docs/learning.md @@ -82,11 +82,7 @@ what "done" means, verifying, or being sent back by the gate. that prints it in full (`sisi done ID`, `sisi lessons show ID`), within a 2,000-character cap. A recipe counts only when at least two distinct non-generic request words hit its title, applies-to or id, at least one of them in its title (matched on stems, so "tag" meets - "tagging") — the same strict floor lessons use. When the request reads as design or build work - (a design, build, implement or create stem on a non-trivial message; never on a question or a - small edit such as a rename or a typo), the owner's standing principles are also injected in - short lines with the instruction to fill the contract's design section first, inside the same - cap. A message that is a question to the agent and + "tagging") — the same strict floor lessons use. A message that is a question to the agent and names no work (no fix, build, change or the like), trivial messages (a bare yes or no, a slash command, a short question) and unmatched requests inject nothing at all. These showings count as *listed* at place `prompt`. The hook never blocks a turn: any error exits @@ -370,10 +366,6 @@ universal lessons that merely mention common file names such as README or CHANGE pass, and universal changes whose moment names a project, which also pass because only the delivered part is checked), and long real-style multi-part requests plus plain questions for request-time recipe delivery (a hit is the expected recipe; any other recipe is a false match). -The design-section validation is measured the same way in the design tests: a labelled set of -good design sections against filler ones (a hit is a good section passing; a false pass is a -filler section passing), plus labelled design-work requests for request-time delivery. - Delivery therefore depends on the quality of the when-terms the recording agent writes. Thin or copy-of-the-text terms leave a lesson findable only by its own wording, exactly the failure they exist to prevent. What sisi ultimately measures is not match scores but the outcome that matters: diff --git a/sisi/cli.py b/sisi/cli.py index a4e5e7a..a858706 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -68,9 +68,8 @@ A shared rulebook and enforced definitions of done for every AI coding CLI. to every user who installs sisi? Both yes: core (in force for you, queued for the product). (a) only: user (your standing principles). Neither: project (handed over to it) - sisi design the owner's standing principles and the design questions to - answer in a contract's design section before sizeable work - (implies, provided, alternatives, chosen, objections, challenge) + sisi risk [--json] risk floor for the working-tree change, with reasons and + what that profile requires sisi handover [--all] | done ID --where PATH [--quote FRAGMENT] project items waiting to be filed in this project's own docs or work list; done confirms one is filed (the named file must contain @@ -132,19 +131,6 @@ def cmd_contract(args): print("created %s as a SKELETON, not a contract yet: replace the placeholder check with a real command " "(rung 1-4) and add every check that shows the work is done. Until then `sisi verify` fails and " "the end-of-turn gate ignores it." % p) - try: - from . import principles - lines = principles.short_lines() - if lines: - print("\nThe owner's standing principles (the design section must answer each one's objection):") - for ln in lines: - print(ln) - print("\nFor sizeable work, fill the contract's design section first (the skeleton is in " - "the file; `sisi design` prints the questions): what the goal and these principles " - "imply, what already exists to use, alternatives, the choice, each principle's " - "objection, and an independent challenge. The gate sends a large change back without it.") - except Exception: - pass try: from . import retro block = retro.delivery_block(goal or "", "contract-init", extra="contract checks verified") @@ -164,9 +150,6 @@ def cmd_contract(args): print("sisi: cannot read %s: %s" % (p, e)) return 1 errs = C.validate(c) - if isinstance(c, dict) and "design" in c and not C.is_unedited_skeleton(c): - from . import design as _D - errs = errs + _D.validate_design(c, cwd=C.project_dir(p)) for e in errs: print(" - " + e) if not errs: @@ -485,9 +468,9 @@ def main(argv): return cycle.cmd_improve(args) if cmd == "oracle": return cmd_oracle() - if cmd == "design": - from . import design - return design.main(args) + if cmd == "risk": + from . import risk + return risk.main(args) if cmd == "status": return cmd_status() if cmd == "time": diff --git a/sisi/contract.py b/sisi/contract.py index c5b1792..4782fbf 100644 --- a/sisi/contract.py +++ b/sisi/contract.py @@ -38,7 +38,6 @@ def is_unedited_skeleton(c): def skeleton(goal=None, cwd=None): name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd or os.getcwd())).lower()).strip("-") - from . import design as _design return { "id": name or "work", "goal": goal or "TODO: one sentence describing the outcome", @@ -63,7 +62,6 @@ def skeleton(goal=None, cwd=None): "invariants": [], "assumptions": [], "questions": [], - "design": _design.skeleton(), } diff --git a/sisi/design.py b/sisi/design.py deleted file mode 100644 index 56aec6a..0000000 --- a/sisi/design.py +++ /dev/null @@ -1,257 +0,0 @@ -"""Choosing the approach as a checked step: the contract's `design` section and `sisi design`. - -The design section records, before building: what the goal and the owner's standing principles -(`sisi oracle`) imply that the request did not spell out; what the environment, host tool or -existing system already provides that should be used instead of built; at least two -alternatives with cost and risk; the chosen one and why it is what the owner would pick; for -every standing principle, the objection the owner would raise and how the design answers it -(or why it does not apply); and an independent challenge, by a different model or a subagent -playing the owner, with what changed in response. - -Validation is structural only, but it is aimed at filler: entries must be non-trivial, -`provided` must name at least one thing that verifiably exists (a `command:NAME` on PATH or a -`file:PATH` in the repository, given as evidence), alternatives must differ from each other -and from the chosen approach, and the challenge must contain an objection plus a change (or a -stated reason for no change) from someone who is not the author. - -One thing is honestly not checkable: that the challenge was recorded before the first code -edit. The edit-attribution data in sisi/watch.py records which paths a session changed, but no -first-edit timestamp survives (the only timestamp is on a pending before-snapshot, consumed -when the command finishes), so validation requires a parseable `recorded_at` that is not in -the future and no more. -""" -import json, os, re, shutil -from datetime import datetime, timezone - -QUESTIONS = """Before building, answer these in the contract's design section: - implies what the goal and the owner's standing principles imply that the request did - not spell out (consequences of what the owner already said) - provided what the environment, the host tool or the existing system already provides - that should be used instead of built; give evidence for each item as - "command:NAME" (on PATH) or "file:PATH" (in the repository) - alternatives at least two approaches, one line each on cost and on risk - chosen which approach, and why it is the one the owner would pick - objections one entry per standing principle: when it applies, the objection the owner - would raise and how the design answers it; when it does not, why not - challenge an independent attack on the design by a different model or a subagent, - playing the owner (what will he say is missing or wrong), who did it, when it - was recorded, and what was changed in response (or why nothing changed)""" - -_FILLER = {"tbd", "todo", "n/a", "na", "none", "nothing", "as requested", "best", "low", - "high", "medium", "x", "y", "-", "stuff", "things", "various", "etc", "placeholder", - "as above", "see above", "obvious", "standard", "normal", "usual"} - - -def _norm(s): - return " ".join(str(s or "").split()).lower().strip(" .!?:;\"'") - - -def _trivial(s, min_chars, min_words): - t = " ".join(str(s or "").split()) - n = _norm(t) - if not t or n in _FILLER or "todo" in n or "placeholder" in n: - return True - return len(t) < min_chars or len(t.split()) < min_words - - -def skeleton(principle_recs=None): - if principle_recs is None: - try: - from . import principles - principle_recs = principles.statements() - except Exception: - principle_recs = [] - from . import principles as P - return { - "implies": ["TODO: what the goal and the owner's principles imply that the request did not spell out"], - "provided": [{"what": "TODO: what already exists that this should use instead of building", - "evidence": "command:TODO or file:TODO"}], - "alternatives": [ - {"name": "TODO first approach", "cost": "TODO cost in one line", "risk": "TODO risk in one line"}, - {"name": "TODO second approach", "cost": "TODO cost in one line", "risk": "TODO risk in one line"}], - "chosen": {"name": "TODO chosen approach", - "why": "TODO why this is the one the owner would pick"}, - "objections": [{"principle": P.plain_of(r), "applicable": True, - "objection": "TODO the objection the owner would raise", - "answer": "TODO how the design answers it"} for r in principle_recs], - "challenge": {"by": "TODO who attacked it (a different model or a subagent)", - "recorded_at": "TODO ISO timestamp, recorded before building", - "objections": ["TODO what the owner would say is missing or wrong"], - "changes": ["TODO what was changed in response"]}, - } - - -def _as_list(v): - if v is None: - return [] - return v if isinstance(v, list) else [v] - - -def _text_of(v, keys=()): - if isinstance(v, str): - return v - if isinstance(v, dict): - for k in keys: - if isinstance(v.get(k), str) and v[k].strip(): - return v[k] - return "" - - -def _evidence_ok(item, cwd): - """True when a `provided` item verifiably names something that exists.""" - evidences = [] - if isinstance(item, dict): - for k in ("evidence", "exists", "check"): - if isinstance(item.get(k), str): - evidences.append(item[k]) - text = _text_of(item, ("what", "name", "use", "text")) - else: - text = str(item or "") - for ev in evidences + [text]: - for m in re.finditer(r"command:([A-Za-z0-9_./-]+)", ev or ""): - if shutil.which(m.group(1)): - return True - for m in re.finditer(r"(?:file|path):([^\s\"']+)", ev or ""): - p = m.group(1).rstrip(".,;)") - if os.path.exists(p if os.path.isabs(p) else os.path.join(cwd, p)): - return True - for tok in re.findall(r"[A-Za-z0-9_./~-]+", text): - if "/" in tok and os.path.exists(os.path.join(cwd, tok.rstrip(".,;)"))): - return True - return False - - -def _match_principle(field, principle_recs): - from . import principles as P - if isinstance(field, int) and 1 <= field <= len(principle_recs): - return field - 1 - f = _norm(field) - m = re.fullmatch(r"p(\d+)", f) - if m and 1 <= int(m.group(1)) <= len(principle_recs): - return int(m.group(1)) - 1 - for i, rec in enumerate(principle_recs): - for cand in (rec["text"], P.plain_of(rec)): - c = _norm(cand) - if f == c or (f and c and (f in c or c in f)): - return i - return None - - -def validate_design(contract, cwd=None, principle_recs=None): - """Structural refusal reasons for a contract's design section; empty means acceptable.""" - cwd = cwd or os.getcwd() - if principle_recs is None: - try: - from . import principles - principle_recs = principles.statements() - except Exception: - principle_recs = [] - if not isinstance(contract, dict) or not isinstance(contract.get("design"), dict): - return ["design section is missing: sizeable work needs a `design` section in the " - "contract (`sisi design` prints the owner's principles and the questions)"] - d = contract["design"] - errs = [] - goal = _norm(contract.get("goal")) - implies = _as_list(d.get("implies")) - if not implies or all(_trivial(_text_of(x, ("text", "implies")), 40, 7) for x in implies): - errs.append("design.implies: name at least one consequence of the goal and the owner's " - "principles that the request did not spell out (a real sentence, not filler)") - elif any(_norm(_text_of(x, ("text", "implies"))) == goal for x in implies): - errs.append("design.implies: restating the goal is not an implication") - provided = _as_list(d.get("provided")) - if not provided: - errs.append("design.provided: name what the environment, host tool or existing system " - "already provides that should be used instead of built") - else: - if all(_trivial(_text_of(x, ("what", "name", "use", "text")), 25, 5) for x in provided): - errs.append("design.provided: each item must say concretely what already exists") - elif not any(_evidence_ok(x, cwd) for x in provided): - errs.append("design.provided: at least one item must name something that verifiably " - "exists, with evidence as \"command:NAME\" (on PATH) or \"file:PATH\" " - "(in the repository)") - chosen_name = _text_of(d.get("chosen"), ("name", "approach", "chosen")) - alts = _as_list(d.get("alternatives")) - alt_names = [_norm(_text_of(a, ("name", "approach"))) for a in alts] - if len(alts) < 2: - errs.append("design.alternatives: at least two approaches are required") - else: - if any(not n or _trivial(n, 4, 1) for n in alt_names) or len(set(alt_names)) != len(alt_names): - errs.append("design.alternatives: the approaches must be distinct and named") - if _norm(chosen_name) and _norm(chosen_name) in alt_names: - errs.append("design.alternatives: alternatives must differ from the chosen approach " - "(they are the approaches not taken, with their cost and risk)") - for a in alts: - if not isinstance(a, dict) or _trivial(a.get("cost"), 12, 3) or _trivial(a.get("risk"), 12, 3): - errs.append("design.alternatives: each approach needs one real line on cost and one on risk") - break - why = _text_of(d.get("chosen"), ("why", "reason")) if isinstance(d.get("chosen"), dict) else "" - if _trivial(chosen_name, 4, 1): - errs.append("design.chosen: name the chosen approach") - if _trivial(why, 40, 7): - errs.append("design.chosen.why: say why this is the approach the owner would pick " - "(a real sentence, not filler)") - objections = _as_list(d.get("objections")) - covered = {} - for o in objections: - if isinstance(o, dict): - i = _match_principle(o.get("principle"), principle_recs) - if i is not None: - covered[i] = o - for i, rec in enumerate(principle_recs): - from . import principles as P - o = covered.get(i) - if o is None: - errs.append("design.objections: no entry for the standing principle %r - state the " - "owner's objection and its answer, or why it does not apply" - % P.plain_of(rec)[:80]) - continue - if o.get("applicable") is False: - if _trivial(o.get("reason"), 20, 4): - errs.append("design.objections: principle %r is marked not applicable without a reason" - % P.plain_of(rec)[:80]) - elif _trivial(o.get("objection"), 20, 4) or _trivial(o.get("answer"), 20, 4): - errs.append("design.objections: principle %r needs the objection the owner would " - "raise and how the design answers it" % P.plain_of(rec)[:80]) - ch = d.get("challenge") if isinstance(d.get("challenge"), dict) else {} - by = _text_of(ch, ("by", "who", "challenger")) - if _trivial(by, 3, 1) or _norm(by) in ("self", "me", "myself", "the agent", "author"): - errs.append("design.challenge.by: name who attacked the design (a different model or a " - "subagent playing the owner, not the author)") - cobjs = _as_list(ch.get("objections")) - if not cobjs or all(_trivial(_text_of(x, ("text", "objection")), 25, 5) for x in cobjs): - errs.append("design.challenge: at least one real objection from the challenger is required") - changes = _as_list(ch.get("changes")) - if (not changes or all(_trivial(_text_of(x, ("text", "change")), 25, 5) for x in changes)) \ - and _trivial(ch.get("no_change_reason"), 25, 5): - errs.append("design.challenge: say what was changed in response, or why nothing changed") - ts = ch.get("recorded_at") - if not isinstance(ts, str) or not ts.strip() or "todo" in _norm(ts): - errs.append("design.challenge.recorded_at: when the challenge was recorded (an ISO timestamp, before building)") - else: - try: - when = datetime.fromisoformat(ts.strip().replace("Z", "+00:00")) - now = datetime.now(timezone.utc) if when.tzinfo else datetime.now() - if (when - now).total_seconds() > 3600: - errs.append("design.challenge.recorded_at: %r is in the future" % ts) - except ValueError: - errs.append("design.challenge.recorded_at: %r is not an ISO timestamp" % ts) - return errs - - -def main(args=()): - """`sisi design`: the owner's principles and the design questions, before a contract exists.""" - from . import principles - print("Choosing the approach: work out what the goal and the owner's principles imply, " - "use what already exists, and have the design attacked as the owner would - before building.\n") - recs = principles.statements() - if recs: - print("The owner's standing principles (`sisi oracle` prints them in full, with his words):") - for i, rec in enumerate(recs, 1): - print("%d. %s" % (i, principles.plain_of(rec))) - print() - else: - print("No standing principles are recorded yet (`sisi learn --scope user \"\"` records one).\n") - print(QUESTIONS) - print("\nSkeleton for .sisi/contract.json (the gate checks it on a large change):") - print(json.dumps({"design": skeleton(recs)}, indent=2)) - return 0 diff --git a/sisi/gate.py b/sisi/gate.py index c88cb44..012c491 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -569,33 +569,6 @@ def _measure_work(cwd, base=None): return m -def _design_required(sess, cwd, top, g, payload, attr): - """The design section is required exactly where a contract is already required: a large - change (the gate's growth thresholds). Small edits, subagents, and sessions that edited - nothing here are exempt. Returns True when required, else None.""" - if payload.get("agent_id") or payload.get("agent_transcript_path"): - return None # a subagent works to its parent's brief; the parent owns the design - if attr is not None and not attr.get("writing") and not attr.get("unknown"): - return None # this session edited nothing: no design is owed for others' work - if not top: - return None - try: - if sess.get("baseline") is not None: - now = _measure_work(cwd, sess.get("head")) - base = sess["baseline"] - dl = max(0, now["lines"] - base["lines"]) - df = len(set(now["files"]) - set(base["files"])) - else: - m = _measure_work(cwd, gitutil.head(cwd)) - dl, df = m["lines"], len(m["files"]) - except Exception as e: - store.log_error("gate-design-measure", e) - return None - if not (dl > int(g.get("growth_lines", 40)) or df > int(g.get("growth_files", 3))): - return None - return True - - def _decide(payload): """Return ('allow', message_or_None) or ('block', reason).""" cfg = store.config() @@ -785,22 +758,6 @@ def _decide(payload): if path: if c is not None and not errs: - try: - if _design_required(sess, cwd, top, g, payload, attr): - from . import design as _design - derrs = _design.validate_design(c, cwd=project) - if derrs: - missing = "missing" if "design" not in c else "invalid" - return ctx.block( - "sisi: this is a large change and the contract's design section is %s " - "(send-back {n}). Choosing the approach is a checked step: fill the " - "design section before building (`sisi design` prints the owner's " - "standing principles and the questions; `sisi oracle` prints the " - "principles in his words). Do not report this work as done.\n\n%s" - % (missing, "\n".join("- " + e for e in derrs)), - c["id"] if c else None, project, kind="design") - except Exception as e: # the design check must never break the gate - store.log_error("gate-design", e) deadline = time.time() + float(g.get("budget_s", 120)) if c is not None: errs = C.validate(c) @@ -891,9 +848,7 @@ def _decide(payload): return ctx.allow() return ctx.block("sisi: this session has changed %d lines and %d files since its start and there is no " "contract (send-back {n}). Write `.sisi/contract.json` (`sisi contract init` makes the " - "skeleton; give it at least one check with a real command, and for a change this size " - "fill its design section - `sisi design` prints the owner's principles and the " - "questions), then run `sisi verify`. If " + "skeleton; give it at least one check with a real command), then run `sisi verify`. If " "the change needs no checks, run `sisi contract waive \"\"` instead." % (dl, df)) diff --git a/sisi/principles.py b/sisi/principles.py index 2ded6f8..1ed1da7 100644 --- a/sisi/principles.py +++ b/sisi/principles.py @@ -2,7 +2,7 @@ statements until the product carries them, and not-yet-tiered ones meanwhile), live at once. A statement takes effect the moment it is recorded: `sisi oracle` prints it, request-time -delivery hands it over, and a contract's design section must answer its objections. There is +delivery hands it over when it matches a request. There is no quarantine and no holding file. The oracle is a proper document (oracle.md in the personal folder) whose structure a learning round owns through the whole-document edit in sisi/documents.py, tracing every statement into the text like any other document; until a diff --git a/sisi/risk.py b/sisi/risk.py new file mode 100644 index 0000000..9e59db3 --- /dev/null +++ b/sisi/risk.py @@ -0,0 +1,206 @@ +"""Risk profiles: ceremony follows risk, not diff size (SPEC 5.3, target section 3). + +`assess` is a pure function from changed paths (and optionally diff text) to a floor +profile plus the reasons. Tables come from canon/risk.json, a user-store adjustment +file, and a project override at .sisi/risk.json; later tables only add patterns. +""" +import fnmatch, json, os, subprocess + +PROFILES = ["trivial", "isolated", "logic", "integration", "data", "critical", "release"] +_ORDER = {name: i for i, name in enumerate(PROFILES)} +_TRIVIAL_PROFILES = {"trivial"} + + +def _load_json(path): + try: + with open(path, encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else {} + except (OSError, ValueError): + return {} + + +def default_table(): + from . import paths + return _load_json(paths.canon("risk.json")) + + +def requirements_for(profile, table=None): + """What a profile carries (target section 3 table), held as data for the gate.""" + table = table or default_table() + reqs = table.get("requirements") or {} + if profile in reqs: + return dict(reqs[profile]) + # Fall back to the built-in table shape so a partial override still answers. + return dict(default_table().get("requirements", {}).get(profile, {})) + + +def _patterns_from(table): + out = [] + for p in (table or {}).get("patterns") or []: + if isinstance(p, dict) and p.get("profile") in _ORDER and (p.get("glob") or p.get("keyword")): + out.append(p) + return out + + +def load_patterns(cwd=None): + """Canon patterns plus user-store and project adjustments, in that order.""" + from . import paths + pats = _patterns_from(default_table()) + pats += _patterns_from(_load_json(paths.data_file("risk.json"))) + if cwd: + from . import gitutil + root = gitutil.root(cwd) or os.path.abspath(cwd) + pats += _patterns_from(_load_json(os.path.join(root, ".sisi", "risk.json"))) + return pats + + +def _glob_match(path, pattern): + p = path.replace(os.sep, "/") + pat = pattern.replace(os.sep, "/") + if fnmatch.fnmatch(p, pat): + return True + # A leading **/ should also match at the root. + if pat.startswith("**/") and fnmatch.fnmatch(p, pat[3:]): + return True + # A trailing /** should match the directory itself and anything under it. + if pat.endswith("/**") and (p == pat[:-3] or p.startswith(pat[:-2])): + return True + return False + + +def _packages(paths): + pkgs = set() + for raw in paths: + parts = [x for x in raw.replace(os.sep, "/").split("/") if x and x != "."] + if len(parts) < 2: + continue + if parts[0] in ("src", "lib", "app") and len(parts) >= 3: + pkgs.add(parts[1]) + elif len(parts) >= 2: + pkgs.add(parts[0]) + return pkgs + + +def assess(paths, diff_text=None, extra_patterns=None, patterns=None): + """Return (floor_profile, reasons). Adding a path never lowers the floor.""" + pats = list(patterns if patterns is not None else _patterns_from(default_table())) + if extra_patterns: + pats += [p for p in extra_patterns if isinstance(p, dict) and p.get("profile") in _ORDER] + clean = [str(p).replace(os.sep, "/") for p in (paths or []) if str(p).strip()] + if not clean: + return "trivial", ["no changed paths"] + best, reasons = "trivial", [] + matched_profiles = [] + trivial_hits = set() + for pat in pats: + prof = pat["profile"] + reason = pat.get("reason") or prof + if pat.get("glob"): + hits = [p for p in clean if _glob_match(p, pat["glob"])] + if hits: + matched_profiles.append(prof) + if prof == "trivial": + trivial_hits.update(hits) + if _ORDER[prof] >= _ORDER[best]: + if _ORDER[prof] > _ORDER[best]: + best, reasons = prof, [] + reasons.append("%s: %s" % (hits[0], reason)) + if pat.get("keyword") and diff_text: + if pat["keyword"].lower() in diff_text.lower(): + matched_profiles.append(prof) + if _ORDER[prof] >= _ORDER[best]: + if _ORDER[prof] > _ORDER[best]: + best, reasons = prof, [] + reasons.append("diff: %s" % reason) + # Structural rules that patterns cannot express. Documentation and styling + # paths do not count as packages: two docs folders are not an integration. + pkgs = _packages([p for p in clean if p not in trivial_hits]) + if len(pkgs) >= 2 and _ORDER["integration"] >= _ORDER[best]: + if _ORDER["integration"] > _ORDER[best]: + best, reasons = "integration", [] + reasons.append("touches %d top-level packages (%s): integration surface" + % (len(pkgs), ", ".join(sorted(pkgs)))) + if best == "trivial" and len(trivial_hits) == len(clean): + return "trivial", reasons or ["documentation, text or styling only"] + if best == "trivial": + return "isolated", ["one module's behaviour changed"] + if not reasons: + reasons = ["%s: matched the %s profile" % (clean[0], best)] + # Keep reasons short and de-duplicated, strongest first is unnecessary: keep order. + seen, out = set(), [] + for r in reasons: + if r not in seen: + seen.add(r) + out.append(r) + return best, out[:6] + + +def floor_for_working_tree(cwd): + """(floor, reasons, files) for the working tree against HEAD, untracked included.""" + from . import gitutil + m = gitutil.measure(cwd) + files = m.get("files") or [] + diff_text = "" + try: + top = gitutil.root(cwd) or cwd + base = gitutil.head(cwd) or gitutil.EMPTY_TREE + p = subprocess.run(["git", "diff", "--no-ext-diff", base], cwd=top, + capture_output=True, timeout=10) + diff_text = p.stdout.decode("utf-8", "replace")[:200000] + # Untracked file contents are part of the change too. + for rel in files[:50]: + fp = os.path.join(top, rel) + try: + if os.path.isfile(fp) and os.path.getsize(fp) < 200000: + with open(fp, encoding="utf-8", errors="replace") as f: + diff_text += "\n" + f.read(20000) + except OSError: + pass + except Exception: + diff_text = "" + profile, reasons = assess(files, diff_text=diff_text, patterns=load_patterns(cwd)) + return profile, reasons, files + + +def declared_profile(cwd): + """The profile declared in .sisi/contract.json, if any.""" + try: + with open(os.path.join(cwd, ".sisi", "contract.json"), encoding="utf-8") as f: + c = json.load(f) + if isinstance(c, dict): + r = c.get("risk") + if isinstance(r, dict) and r.get("profile") in _ORDER: + return r["profile"] + if c.get("risk_profile") in _ORDER: + return c["risk_profile"] + except (OSError, ValueError): + pass + return None + + +def main(args=()): + """`sisi risk [--json]`: floor, reasons, declared profile, and what the floor requires.""" + args = list(args) + as_json = "--json" in args + cwd = os.getcwd() + floor, reasons, files = floor_for_working_tree(cwd) + declared = declared_profile(cwd) + reqs = requirements_for(floor) + if as_json: + print(json.dumps({"floor": floor, "reasons": reasons, "files": files, + "declared": declared, "requirements": reqs}, indent=2)) + return 0 + print("risk floor: %s" % floor) + for r in reasons: + print(" - %s" % r) + print("declared: %s" % (declared or "none (no .sisi/contract.json risk.profile)")) + print("requires: contract=%s, checks=%s, requirement model=%s, risk note=%s, " + "independent evidence=%s, retro=%s" + % ("yes" if reqs.get("contract") else "no", reqs.get("checks", "-"), + "yes" if reqs.get("requirement_model") else "no", + "yes" if reqs.get("risk_note") else "no", + "yes" if reqs.get("independent_evidence") else "no", reqs.get("retro", "-"))) + if files: + print("changed files: %d" % len(files)) + return 0 diff --git a/sisi/rulecmd.py b/sisi/rulecmd.py index b824f2f..e9cdd15 100644 --- a/sisi/rulecmd.py +++ b/sisi/rulecmd.py @@ -33,14 +33,6 @@ def _question_gate(): return False -def _design_gate(): - try: - from . import design, gate - return callable(design.validate_design) and callable(gate._design_required) - except Exception: - return False - - def _delivery_measured(): try: from . import delivery @@ -52,10 +44,7 @@ def _delivery_measured(): _NOT = "not enforced: depends on the agent" ENFORCEMENT = { - "choose-the-approach": lambda: ("end-of-turn check sends a large change back when the contract's " - "design section is missing or fails validation (small edits and " - "subagents exempt)" - if _gate_wired() and _design_gate() else _NOT), + "choose-the-approach": lambda: _NOT, "know-done": lambda: ("end-of-turn check sends the agent back (no contract on a large change)" if _gate_wired() else _NOT), "strongest-check": lambda: ("minimum rungs refused when the contract is checked; the choice of check depends on the agent" diff --git a/tests/test_design.py b/tests/test_design.py deleted file mode 100644 index 80ea3db..0000000 --- a/tests/test_design.py +++ /dev/null @@ -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() diff --git a/tests/test_risk.py b/tests/test_risk.py new file mode 100644 index 0000000..67ec085 --- /dev/null +++ b/tests/test_risk.py @@ -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()