From 7572f27154e2e88cd4e0cd68da0901bbe7cb4fed Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 11:40:00 -0700 Subject: [PATCH] Risk table: kind before name, token matching, dependency floor, labelled set; short route --explain Co-Authored-By: Claude Sonnet 5.5 --- canon/risk.json | 83 ++-- sisi/risk.py | 217 ++++++--- sisi/routing.py | 28 +- tests/risk_labels.json | 887 ++++++++++++++++++++++++++++++++++++ tests/test_orchestration.py | 39 ++ tests/test_risk.py | 83 ++++ 6 files changed, 1227 insertions(+), 110 deletions(-) create mode 100644 tests/risk_labels.json diff --git a/canon/risk.json b/canon/risk.json index e0397c5..5fecff1 100644 --- a/canon/risk.json +++ b/canon/risk.json @@ -10,58 +10,43 @@ "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"}, + {"stage": "kind", "kind": "doc", "glob": ["**/*.{md,mdx,rst,adoc}", "**/{license,licence,copying,notice,authors,contributors}*", "**/.{gitignore,gitattributes,editorconfig,dockerignore,prettierignore,prettierrc*}", "docs/**", "**/docs/**"], "profile": "trivial", "reason": "documentation or repository metadata; no behaviour"}, + {"stage": "kind", "kind": "asset", "glob": "**/*.{png,jpg,jpeg,gif,svg,ico,webp,avif,bmp,woff,woff2,ttf,otf,eot,mp3,mp4,wav,ogg,webm,pdf}", "profile": "trivial", "reason": "static asset or image; no behaviour"}, + {"stage": "kind", "kind": "style", "glob": "**/*.{css,scss,sass,less,styl}", "profile": "trivial", "reason": "styling only"}, + {"stage": "kind", "kind": "content", "glob": ["**/{locales,locale,i18n,translations}/**", "**/*.{po,pot}"], "profile": "trivial", "reason": "translated strings or copy; no behaviour"}, + {"stage": "kind", "kind": "template", "glob": "**/.env.{example,sample,template,dist}", "profile": "isolated", "reason": "template of settings, no secrets, but it documents the configuration surface"}, + {"stage": "kind", "kind": "fixture", "glob": ["**/{fixtures,testdata,golden,__snapshots__,__mocks__}/**", "**/*.snap"], "profile": "isolated", "reason": "test fixture or snapshot; data for tests, not behaviour"}, + {"stage": "kind", "kind": "test", "glob": ["**/{tests,test,__tests__,e2e}/**", "**/spec/**/*.rb", "**/test_*.*", "**/*_test.*", "**/*_spec.*", "**/*.{test,spec}.*", "**/*{Test,Tests}.{java,kt,swift,cs,php,scala}"], "profile": "isolated", "reason": "test code: not trivial, and a test of data or critical code is at least logic", "elevate": true}, + {"stage": "kind", "kind": "generated", "glob": ["**/{dist,target,__generated__,generated}/**", "**/*.{pb.go,generated.*,min.js,min.css,g.dart}", "**/*_pb2.py", "**/*_pb2_grpc.py", "**/__pycache__/**", "**/*.pyc"], "profile": "isolated", "reason": "generated or built output; the source that produces it carries the risk"}, + {"stage": "kind", "kind": "lockfile", "glob": ["**/*.lock", "**/*.lockb", "**/*-lock.{json,yaml,yml}", "**/*.lock.json", "**/{go.sum,package.resolved,gradle.lockfile,flake.lock}", "**/npm-shrinkwrap.json"], "profile": "integration", "reason": "lockfile: the code you depend on changes without you writing it"}, + {"stage": "kind", "kind": "manifest", "glob": ["**/{package.json,cargo.toml,go.mod,gemfile,pipfile,pyproject.toml,setup.py,setup.cfg,pom.xml,composer.json,package.swift,podfile,cartfile,mix.exs,pubspec.yaml,vcpkg.json,conanfile.txt,deno.json}", "**/requirements*.txt", "**/build.gradle*", "**/settings.gradle*", "**/*.{gemspec,csproj,fsproj}"], "profile": "integration", "reason": "dependency or packaging manifest: what your code depends on changes"}, + {"stage": "kind", "kind": "vendor", "glob": "**/{vendor,third_party,third-party,node_modules}/**", "profile": "integration", "reason": "vendored code you did not write"}, + {"stage": "kind", "kind": "build", "glob": "**/cmakelists.txt", "profile": "isolated", "reason": "build script; text extension, not documentation"}, + {"stage": "kind", "kind": "text", "glob": "**/*.txt", "profile": "trivial", "reason": "plain text only"}, + {"stage": "name", "token": ["auth", "authn", "authz", "authenticat*", "authoriz*", "oauth", "oidc", "saml", "jwt", "rbac", "acl", "iam", "permission*", "sudoers", "security"], "profile": "critical", "reason": "authentication, authorization or access control"}, + {"stage": "name", "token": ["password*", "passwd", "credential*", "secret*", "keystore", "keychain", "keyring", "token*"], "scope": "dir", "profile": "critical", "reason": "secrets and credentials"}, + {"stage": "name", "token": ["password*", "passwd", "credential*", "secret*", "keystore", "keychain", "keyring"], "scope": "stem", "profile": "critical", "reason": "secrets and credentials"}, + {"stage": "name", "token": ["crypto*", "encrypt*", "decrypt*", "cipher*", "sha256", "aes", "tls"], "profile": "critical", "reason": "cryptography"}, + {"stage": "name", "glob": ["**/.env", "**/.env.*", "**/*.pem", "**/*.key", "**/id_rsa*"], "profile": "critical", "reason": "real environment or key file may hold secrets"}, + {"stage": "name", "token": ["payment*", "billing", "checkout"], "profile": "critical", "reason": "payments and billing move money"}, + {"stage": "name", "token": ["mutex", "semaphore", "spinlock", "rwlock", "lock", "locks", "locking"], "profile": "critical", "reason": "concurrency primitive"}, + {"stage": "name", "glob": ["**/{install,uninstall,installer,postinst,preinst}.{sh,bash,ps1,bat,py,rb,go,rs,js}", "**/PKGBUILD", "**/pkgbuild", "**/{postinst,preinst,postrm,prerm}"], "profile": "critical", "reason": "installer changes the user's machine"}, + {"stage": "name", "glob": ["VERSION", "**/{release,releases,publish,deploy}.{sh,bash,ps1,py,rb,go,rs,mk,yml,yaml,toml,json,gradle}", "**/{release,releases}/**", "**/.goreleaser*", "**/release.config.*", "**/.github/workflows/*{release,publish,deploy}*"], "profile": "release", "reason": "release or deployment machinery"}, + {"stage": "name", "glob": ["**/*.{sql,prisma,ddl,cql}", "**/db/schema.rb", "**/db/migrate/**"], "token": ["migrations", "migration", "migrate", "alembic", "flyway", "liquibase"], "profile": "data", "reason": "database migration or schema: stored data changes shape"}, + {"stage": "name", "token": ["db", "database", "storage", "persist*", "backup", "restore"], "scope": "dir", "profile": "data", "reason": "persistence layer"}, + {"stage": "name", "token": ["backup", "restore"], "scope": "stem", "profile": "data", "reason": "persistence layer or backup"}, + {"stage": "name", "glob": ["include/**", "**/*.{proto,graphql,gql,thrift,avsc,wsdl}", "**/openapi*", "**/swagger*", "**/*.schema.json", "**/protos/**", "**/proto/**"], "profile": "integration", "reason": "public interface surface"}, + {"stage": "name", "token": ["api", "apis"], "scope": "dir", "profile": "integration", "reason": "public interface surface"}, + {"stage": "name", "glob": ["**/*{feature_flag,feature-flag,featureflag}*", "**/{flags,feature_flags,feature-flags}.*", "**/feature[_-]flags/**"], "profile": "integration", "reason": "runtime switches change behaviour across modules"}, + {"stage": "name", "glob": ["**/*.{tf,tfvars}", "**/dockerfile*", "**/*.dockerfile", "**/docker-compose*.{yml,yaml}", "**/compose*.{yml,yaml}", "**/.github/workflows/**", "**/.gitlab-ci.yml", "**/jenkinsfile", "**/.circleci/**", "**/.travis.yml", "**/azure-pipelines.yml", "**/{terraform,k8s,kubernetes,helm,charts,ansible,infra,infrastructure,deploy}/**"], "profile": "integration", "reason": "infrastructure, pipeline or container definition"}, + {"stage": "name", "glob": ["**/.githooks/**", "**/.husky/**"], "profile": "integration", "reason": "git hook runs automatically on every commit"}, + {"stage": "name", "token": ["pars*", "lexer", "lexing", "tokeniz*", "codec"], "profile": "logic", "reason": "parsing has a broad input space"}, + {"stage": "name", "token": ["money", "currenc*", "rounding", "pricing", "tax"], "profile": "logic", "reason": "money arithmetic must be exact"}, + {"stage": "name", "glob": ["**/*state-machine*", "**/*statemachine*", "**/*state_machine*"], "token": ["algo", "algos", "algorithm*", "fsm"], "profile": "logic", "reason": "algorithmic logic"}, {"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": "drop table", "profile": "data", "reason": "diff drops 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"}, diff --git a/sisi/risk.py b/sisi/risk.py index 9e59db3..0be5ed7 100644 --- a/sisi/risk.py +++ b/sisi/risk.py @@ -3,12 +3,38 @@ `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. + +How ONE path is classified (`classify_path`), in this order: + 1. Kind stage (patterns with "stage": "kind"; the first match wins and is final). + What the file IS comes before what it is called: documentation, assets, styling, + fixtures, tests, generated output, lockfiles and manifests, vendored code. So + `docs/installation.md` is documentation and `Cargo.lock` is a lockfile whatever + their names contain. Documentation, assets and styling are trivial; fixtures, + generated output and ordinary tests are isolated; lockfiles, manifests and vendored + code are integration (behaviour of code you did not write changes: not trivial, but + not critical either). A test of data, critical or release code is `logic`: it is not + itself critical, but it is not trivial. A test of anything else stays isolated. + 2. Name stage (patterns with "stage": "name"): globs on the path, and tokens on the + directory names and file stem split on punctuation and camelCase (`AuthorCard` is + "author", "card", never "auth"; `sparse` is not "pars*"). The highest matching + profile wins. A source file that matches nothing is isolated. + 3. Override patterns (no "stage": project and user-store adjustments) only raise. +How a CHANGE is classified (`assess`): the highest floor among its paths; a change that +touches two or more top-level packages (tests, docs, fixtures, generated output and root +files do not count as packages) is at least integration; diff keywords raise the floor but +only from the diff of files that are not docs, tests, fixtures, lockfiles or manifests. +Every rule is a maximum over a growing set, so adding a path never lowers the floor. """ -import fnmatch, json, os, subprocess +import fnmatch, json, os, re, subprocess PROFILES = ["trivial", "isolated", "logic", "integration", "data", "critical", "release"] _ORDER = {name: i for i, name in enumerate(PROFILES)} _TRIVIAL_PROFILES = {"trivial"} +_DEFAULT_REASON = "ordinary source file: one module's behaviour" +_CONTAINERS = {"src", "lib", "app", "packages", "apps", "services", "crates", "modules", "libs", + "cmd", "internal", "pkg"} +_NO_PACKAGE_KINDS = {"doc", "asset", "style", "content", "template", "fixture", "test", "generated", "text"} +_TOKEN_RE = re.compile(r"[A-Z]+(?![a-z])|[A-Z]?[a-z]+|[0-9]+") def _load_json(path): @@ -38,7 +64,7 @@ def requirements_for(profile, table=None): 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")): + if isinstance(p, dict) and p.get("profile") in _ORDER and (p.get("glob") or p.get("token") or p.get("keyword")): out.append(p) return out @@ -55,33 +81,127 @@ def load_patterns(cwd=None): return pats +def _expand_braces(pat): + m = re.search(r"\{([^{}]*)\}", pat) + if not m: + return [pat] + out = [] + for alt in m.group(1).split(","): + out += _expand_braces(pat[:m.start()] + alt + pat[m.end():]) + return out + + def _glob_match(path, pattern): - p = path.replace(os.sep, "/") - pat = pattern.replace(os.sep, "/") - if fnmatch.fnmatch(p, pat): + p = path.replace(os.sep, "/").lower() + for pat in _expand_braces(pattern.replace(os.sep, "/").lower()): + if fnmatch.fnmatchcase(p, pat): + return True + # A leading **/ should also match at the root. + if pat.startswith("**/") and fnmatch.fnmatchcase(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 _as_list(v): + return [v] if isinstance(v, str) else list(v or []) + + +def _tokens(name): + return [t.lower() for t in _TOKEN_RE.findall(name)] + + +def _path_tokens(path): + """(directory tokens, file stem tokens) of a path.""" + parts = [x for x in path.replace(os.sep, "/").split("/") if x and x != "."] + if not parts: + return [], [] + stem = parts[-1].rsplit(".", 1)[0] if "." in parts[-1].lstrip(".") else parts[-1] + dirs = [t for d in parts[:-1] for t in _tokens(d)] + return dirs, _tokens(stem) + + +def _token_match(path, wanted, scope): + dirs, stem = _path_tokens(path) + have = (dirs if scope == "dir" else stem if scope == "stem" else dirs + stem) + for w in wanted: + w = w.lower() + for t in have: + if (t.startswith(w[:-1]) if w.endswith("*") else t == w): + return True + return False + + +def _pattern_hits(path, pat): + if pat.get("glob") and any(_glob_match(path, g) for g in _as_list(pat["glob"])): 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])): + if pat.get("token") and _token_match(path, _as_list(pat["token"]), pat.get("scope") or "any"): return True return False +def _name_stage(path, pats): + """(profile, reason) from the name patterns: the highest match, else an ordinary file.""" + best = None + for pat in pats: + if pat.get("stage") == "name" and _pattern_hits(path, pat): + if best is None or _ORDER[pat["profile"]] > _ORDER[best[0]]: + best = (pat["profile"], pat.get("reason") or pat["profile"]) + return best or ("isolated", _DEFAULT_REASON) + + +def classify_path(path, patterns=None): + """(profile, kind, reason) for one path. `kind` is the kind-stage match, or None.""" + pats = list(patterns if patterns is not None else _patterns_from(default_table())) + p = str(path).replace(os.sep, "/") + kind, profile, reason = None, None, None + for pat in pats: + if pat.get("stage") == "kind" and _pattern_hits(p, pat): + kind, profile, reason = pat.get("kind") or "kind", pat["profile"], pat.get("reason") or pat["profile"] + if pat.get("elevate"): + name_prof, name_reason = _name_stage(p, pats) + if _ORDER[name_prof] >= _ORDER["data"]: + profile, reason = "logic", "test of %s code (%s)" % (name_prof, name_reason) + break + if kind is None: + profile, reason = _name_stage(p, pats) + for pat in pats: # overrides (no stage) only raise + if pat.get("stage") not in ("kind", "name") and (pat.get("glob") or pat.get("token")) \ + and _pattern_hits(p, pat) and _ORDER[pat["profile"]] > _ORDER[profile]: + profile, reason = pat["profile"], pat.get("reason") or pat["profile"] + return profile, kind, reason + + 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: + if parts[0] in _CONTAINERS and len(parts) >= 3: pkgs.add(parts[1]) - elif len(parts) >= 2: + else: pkgs.add(parts[0]) return pkgs +_DIFF_HEAD = re.compile(r"^diff --git a/(.+?) b/(.+)$", re.M) + + +def _diff_blocks(diff_text): + """[(path or None, text)]: text before the first `diff --git` header has no path.""" + heads = list(_DIFF_HEAD.finditer(diff_text)) + if not heads: + return [(None, diff_text)] + out = [(None, diff_text[:heads[0].start()])] + for i, m in enumerate(heads): + end = heads[i + 1].start() if i + 1 < len(heads) else len(diff_text) + out.append((m.group(2), diff_text[m.start():end])) + return out + + 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())) @@ -91,49 +211,34 @@ def assess(paths, diff_text=None, extra_patterns=None, patterns=None): 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 offer(prof, text): + nonlocal best, reasons + if _ORDER[prof] > _ORDER[best]: + best, reasons = prof, [] + if prof == best and text not in reasons: + reasons.append(text) + + kinds = {} + for p in clean: + prof, kind, why = classify_path(p, pats) + kinds[p] = kind + offer(prof, "%s: %s" % (p, why)) + if diff_text: + for dpath, text in _diff_blocks(diff_text): + if dpath is not None and classify_path(dpath, pats)[1]: + continue # docs, tests, lockfiles and the like are not scanned for keywords + low = text.lower() + for pat in pats: + kw = pat.get("keyword") + if kw and re.search(r"\b" + re.escape(kw.lower()), low): + offer(pat["profile"], "diff: %s" % (pat.get("reason") or pat["profile"])) + # Structural rule that patterns cannot express: several top-level packages. + pkgs = _packages([p for p in clean if kinds[p] not in _NO_PACKAGE_KINDS]) + if len(pkgs) >= 2: + offer("integration", "touches %d top-level packages (%s): integration surface" + % (len(pkgs), ", ".join(sorted(pkgs)))) + return best, reasons[:6] def floor_for_working_tree(cwd): @@ -154,7 +259,7 @@ def floor_for_working_tree(cwd): 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) + diff_text += "\ndiff --git a/%s b/%s\n" % (rel, rel) + f.read(20000) except OSError: pass except Exception: diff --git a/sisi/routing.py b/sisi/routing.py index ea7f266..e0507c9 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -280,6 +280,10 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, "load_ratios": {c["worker"]: load_ratio(c) for c in candidates}} +MAX_EXPLAIN_LINES = 20 +EXPLAIN_TAIL_LINES = 5 # worker, mechanism, exclusion note, cold-start notice, request for facts + + def explain_choice(result, kind, difficulty): """Plain lines for `--explain`, from a choose() result.""" choice = result["choice"] @@ -325,10 +329,24 @@ def explain_choice(result, kind, difficulty): groups[reason] = [] order.append(reason) groups[reason].append(worker) - for reason in order: + # `--explain` stays short whatever the catalogue size (R-7.2-1): one line per reason with a + # count and at most 3 example names; if reasons alone would overflow MAX_EXPLAIN_LINES, the + # smallest groups share one closing line that still names each reason and its count. + def group_line(reason): names = groups[reason] - shown = ", ".join(names[:12]) - if len(names) > 12: - shown += " (and %d more)" % (len(names) - 12) - lines.append("passed over %s: %s" % (shown, reason)) + shown = ", ".join(names[:3]) + more = " and %d more" % (len(names) - 3) if len(names) > 3 else "" + return "passed over %d worker(s) (%s%s): %s" % (len(names), shown, more, reason) + + room = max(MAX_EXPLAIN_LINES - len(lines) - EXPLAIN_TAIL_LINES, 1) + ranked = sorted(order, key=lambda r: -len(groups[r])) + keep = ranked if len(ranked) <= room else ranked[:room - 1] + for reason in order: + if reason in keep: + lines.append(group_line(reason)) + rest = [r for r in ranked if r not in keep] + if rest: + lines.append("passed over %d more worker(s) for %d other reasons: %s" + % (sum(len(groups[r]) for r in rest), len(rest), + "; ".join("%s (%d)" % (r, len(groups[r])) for r in rest))) return lines diff --git a/tests/risk_labels.json b/tests/risk_labels.json new file mode 100644 index 0000000..df7c7eb --- /dev/null +++ b/tests/risk_labels.json @@ -0,0 +1,887 @@ +[ + { + "path": "src/calc.py", + "floor": "isolated", + "why": "ordinary module" + }, + { + "path": "src/pkg/utils.py", + "floor": "isolated", + "why": "ordinary module" + }, + { + "path": "src/__init__.py", + "floor": "isolated", + "why": "ordinary module" + }, + { + "path": "tests/test_calc.py", + "floor": "isolated", + "why": "test of ordinary code" + }, + { + "path": "tests/conftest.py", + "floor": "isolated", + "why": "test support code" + }, + { + "path": "tests/test_auth.py", + "floor": "logic", + "why": "test of critical code: not critical itself, but not trivial" + }, + { + "path": "tests/auth/test_login.py", + "floor": "logic", + "why": "test of critical code" + }, + { + "path": "tests/test_migrations.py", + "floor": "logic", + "why": "test of data code" + }, + { + "path": "tests/fixtures/users.json", + "floor": "isolated", + "why": "test fixture" + }, + { + "path": "tests/fixtures/seed.sql", + "floor": "isolated", + "why": "SQL that is only test data" + }, + { + "path": "app/auth/permissions.py", + "floor": "critical", + "why": "authorization code" + }, + { + "path": "app/auth/README.md", + "floor": "trivial", + "why": "documentation inside a critical directory" + }, + { + "path": "app/payments/charge.py", + "floor": "critical", + "why": "moves money" + }, + { + "path": "app/billing/invoice.py", + "floor": "critical", + "why": "billing moves money" + }, + { + "path": "app/crypto/hash.py", + "floor": "critical", + "why": "cryptography" + }, + { + "path": "app/models/user.py", + "floor": "isolated", + "why": "ordinary model" + }, + { + "path": "app/models/concerns/authenticatable.py", + "floor": "critical", + "why": "authentication behaviour" + }, + { + "path": "alembic/versions/3f2a_add_users.py", + "floor": "data", + "why": "migration history" + }, + { + "path": "migrations/0003_add_index.sql", + "floor": "data", + "why": "schema migration" + }, + { + "path": "app/db/session.py", + "floor": "data", + "why": "persistence layer" + }, + { + "path": "src/db/README.md", + "floor": "trivial", + "why": "documentation inside a data directory" + }, + { + "path": "src/sparse.py", + "floor": "isolated", + "why": "name contains 'pars' but is not parsing" + }, + { + "path": "src/sparse_matrix.py", + "floor": "isolated", + "why": "name contains 'pars' but is not parsing" + }, + { + "path": "src/parser.py", + "floor": "logic", + "why": "parsing has a broad input space" + }, + { + "path": "src/tokenizer.py", + "floor": "logic", + "why": "tokenizing has a broad input space" + }, + { + "path": "src/utils/parse_date.py", + "floor": "logic", + "why": "parsing has a broad input space" + }, + { + "path": "src/money/rounding.py", + "floor": "logic", + "why": "money arithmetic must be exact" + }, + { + "path": "src/pricing/discount.py", + "floor": "logic", + "why": "pricing arithmetic" + }, + { + "path": "src/algo/sort.py", + "floor": "logic", + "why": "algorithmic logic" + }, + { + "path": "setup.py", + "floor": "integration", + "why": "dependency and packaging manifest" + }, + { + "path": "pyproject.toml", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "requirements.txt", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "requirements-dev.txt", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "poetry.lock", + "floor": "integration", + "why": "lockfile: code you did not write changes" + }, + { + "path": "uv.lock", + "floor": "integration", + "why": "lockfile" + }, + { + "path": "Pipfile.lock", + "floor": "integration", + "why": "lockfile" + }, + { + "path": "docs/index.rst", + "floor": "trivial", + "why": "documentation" + }, + { + "path": "scripts/install.sh", + "floor": "critical", + "why": "installer changes the user's machine" + }, + { + "path": "install.sh", + "floor": "critical", + "why": "installer changes the user's machine" + }, + { + "path": "docs/installation.md", + "floor": "trivial", + "why": "documentation about installing" + }, + { + "path": "PKGBUILD", + "floor": "critical", + "why": "package build script" + }, + { + "path": "src/components/InstallButton.tsx", + "floor": "isolated", + "why": "UI component, not an installer" + }, + { + "path": "package.json", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "package-lock.json", + "floor": "integration", + "why": "lockfile" + }, + { + "path": "yarn.lock", + "floor": "integration", + "why": "lockfile" + }, + { + "path": "pnpm-lock.yaml", + "floor": "integration", + "why": "lockfile" + }, + { + "path": "Cargo.lock", + "floor": "integration", + "why": "lockfile" + }, + { + "path": "flake.lock", + "floor": "integration", + "why": "lockfile" + }, + { + "path": "Gemfile.lock", + "floor": "integration", + "why": "lockfile" + }, + { + "path": "go.sum", + "floor": "integration", + "why": "lockfile" + }, + { + "path": "src/hooks/useCart.ts", + "floor": "isolated", + "why": "React hook, not a tool hook" + }, + { + "path": "src/hooks/useLocalStorage.ts", + "floor": "isolated", + "why": "React hook over browser storage" + }, + { + "path": "src/components/AuthorCard.tsx", + "floor": "isolated", + "why": "'author' is not 'auth'" + }, + { + "path": "src/components/Button.tsx", + "floor": "isolated", + "why": "ordinary UI component" + }, + { + "path": "src/components/Button.test.tsx", + "floor": "isolated", + "why": "test of ordinary code" + }, + { + "path": "src/components/__snapshots__/Button.test.tsx.snap", + "floor": "isolated", + "why": "snapshot" + }, + { + "path": "src/styles/main.css", + "floor": "trivial", + "why": "styling only" + }, + { + "path": "src/styles/theme.scss", + "floor": "trivial", + "why": "styling only" + }, + { + "path": "public/logo.png", + "floor": "trivial", + "why": "static asset" + }, + { + "path": "public/favicon.ico", + "floor": "trivial", + "why": "static asset" + }, + { + "path": "public/index.html", + "floor": "isolated", + "why": "markup that can carry behaviour" + }, + { + "path": "src/pages/api/users.ts", + "floor": "integration", + "why": "public interface surface" + }, + { + "path": "server/routes/auth.ts", + "floor": "critical", + "why": "authentication routes" + }, + { + "path": "server/middleware/jwt.ts", + "floor": "critical", + "why": "token verification" + }, + { + "path": "server/src/queue/lock.ts", + "floor": "critical", + "why": "concurrency primitive" + }, + { + "path": "src/locales/en.json", + "floor": "trivial", + "why": "translated strings" + }, + { + "path": "src/utils/clock.ts", + "floor": "isolated", + "why": "'clock' is not a lock" + }, + { + "path": "src/utils/block.ts", + "floor": "isolated", + "why": "'block' is not a lock" + }, + { + "path": "tsconfig.json", + "floor": "isolated", + "why": "build configuration of one project" + }, + { + "path": ".eslintrc.json", + "floor": "isolated", + "why": "lint configuration" + }, + { + "path": "AUTHORS.md", + "floor": "trivial", + "why": "documentation" + }, + { + "path": "README.md", + "floor": "trivial", + "why": "documentation" + }, + { + "path": "docs/release-notes.md", + "floor": "trivial", + "why": "documentation about a release" + }, + { + "path": "CHANGELOG.md", + "floor": "trivial", + "why": "documentation" + }, + { + "path": "LICENSE", + "floor": "trivial", + "why": "legal text only" + }, + { + "path": "COPYING", + "floor": "trivial", + "why": "legal text only" + }, + { + "path": "SECURITY.md", + "floor": "trivial", + "why": "documentation" + }, + { + "path": ".gitignore", + "floor": "trivial", + "why": "repository metadata" + }, + { + "path": ".editorconfig", + "floor": "trivial", + "why": "repository metadata" + }, + { + "path": ".env.example", + "floor": "isolated", + "why": "template of settings, no secrets, but documents the config surface" + }, + { + "path": ".env", + "floor": "critical", + "why": "real environment file holds secrets" + }, + { + "path": ".env.production", + "floor": "critical", + "why": "real environment file holds secrets" + }, + { + "path": "dist/bundle.js", + "floor": "isolated", + "why": "build output" + }, + { + "path": "src/generated/api-types.ts", + "floor": "isolated", + "why": "generated code" + }, + { + "path": "src/lib/server.min.js", + "floor": "isolated", + "why": "minified build output" + }, + { + "path": "packages/ui/src/Button.tsx", + "floor": "isolated", + "why": "ordinary UI component in a monorepo" + }, + { + "path": "packages/auth/src/index.ts", + "floor": "critical", + "why": "authentication package" + }, + { + "path": "packages/ui/package.json", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "apps/web/src/App.tsx", + "floor": "isolated", + "why": "ordinary UI component in a monorepo" + }, + { + "path": "apps/web/webpack.config.js", + "floor": "isolated", + "why": "build configuration of one app" + }, + { + "path": "vendor/lib/foo.go", + "floor": "integration", + "why": "vendored code you did not write" + }, + { + "path": "src/components/ReleaseNotes.tsx", + "floor": "isolated", + "why": "UI component, not release machinery" + }, + { + "path": "src/pages/releases.tsx", + "floor": "isolated", + "why": "a web page listing releases" + }, + { + "path": "config/feature_flags.yml", + "floor": "integration", + "why": "runtime switches change behaviour across modules" + }, + { + "path": "src/flags.json", + "floor": "integration", + "why": "runtime switches change behaviour across modules" + }, + { + "path": "go.mod", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "cmd/server/main.go", + "floor": "isolated", + "why": "ordinary entry point" + }, + { + "path": "internal/auth/token.go", + "floor": "critical", + "why": "token handling" + }, + { + "path": "internal/sync/mutex.go", + "floor": "critical", + "why": "concurrency primitive" + }, + { + "path": "internal/storage/s3.go", + "floor": "data", + "why": "persistence layer" + }, + { + "path": "internal/parser/parse.go", + "floor": "logic", + "why": "parsing" + }, + { + "path": "internal/handler/user_handler_test.go", + "floor": "isolated", + "why": "test of ordinary code" + }, + { + "path": "api/v1/user.proto", + "floor": "integration", + "why": "public interface definition" + }, + { + "path": "pkg/api/server.go", + "floor": "integration", + "why": "public interface surface" + }, + { + "path": "internal/pb/user.pb.go", + "floor": "isolated", + "why": "generated code" + }, + { + "path": "Makefile", + "floor": "isolated", + "why": "build script" + }, + { + "path": ".goreleaser.yaml", + "floor": "release", + "why": "release machinery" + }, + { + "path": "Cargo.toml", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "src/main.rs", + "floor": "isolated", + "why": "ordinary entry point" + }, + { + "path": "crates/core/src/lexer.rs", + "floor": "logic", + "why": "lexing" + }, + { + "path": "crates/core/Cargo.toml", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "src/crypto/aes.rs", + "floor": "critical", + "why": "cryptography" + }, + { + "path": "tests/integration_test.rs", + "floor": "isolated", + "why": "test of ordinary code" + }, + { + "path": "build.rs", + "floor": "isolated", + "why": "build script" + }, + { + "path": "pom.xml", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "build.gradle.kts", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "src/main/java/com/acme/OrderService.java", + "floor": "isolated", + "why": "ordinary class" + }, + { + "path": "src/test/java/com/acme/OrderServiceTest.java", + "floor": "isolated", + "why": "test of ordinary code" + }, + { + "path": "src/main/java/com/acme/security/PasswordEncoder.java", + "floor": "critical", + "why": "password handling" + }, + { + "path": "src/main/resources/db/migration/V2__add_orders.sql", + "floor": "data", + "why": "schema migration" + }, + { + "path": "src/main/kotlin/com/acme/pricing/TaxCalculator.kt", + "floor": "logic", + "why": "pricing arithmetic" + }, + { + "path": "src/main/resources/application.yml", + "floor": "isolated", + "why": "application settings" + }, + { + "path": "CMakeLists.txt", + "floor": "isolated", + "why": "build script (text extension, not documentation)" + }, + { + "path": "include/mylib/api.h", + "floor": "integration", + "why": "public header is an interface" + }, + { + "path": "src/mylib.c", + "floor": "isolated", + "why": "ordinary source" + }, + { + "path": "src/spinlock.c", + "floor": "critical", + "why": "concurrency primitive" + }, + { + "path": "src/crypto/sha256.c", + "floor": "critical", + "why": "cryptography" + }, + { + "path": "tests/test_parser.c", + "floor": "isolated", + "why": "test of logic code" + }, + { + "path": "third_party/zlib/inflate.c", + "floor": "integration", + "why": "vendored code you did not write" + }, + { + "path": "Gemfile", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "app/controllers/users_controller.rb", + "floor": "isolated", + "why": "ordinary controller" + }, + { + "path": "db/migrate/20240101_add_x.rb", + "floor": "data", + "why": "schema migration" + }, + { + "path": "db/schema.rb", + "floor": "data", + "why": "schema definition" + }, + { + "path": "spec/models/user_spec.rb", + "floor": "isolated", + "why": "test of ordinary code" + }, + { + "path": "Package.swift", + "floor": "integration", + "why": "dependency manifest" + }, + { + "path": "Package.resolved", + "floor": "integration", + "why": "lockfile" + }, + { + "path": "Sources/App/Views/ProfileView.swift", + "floor": "isolated", + "why": "ordinary view" + }, + { + "path": "Sources/App/Keychain/KeychainStore.swift", + "floor": "critical", + "why": "secret storage" + }, + { + "path": "Tests/AppTests/ProfileTests.swift", + "floor": "isolated", + "why": "test of ordinary code" + }, + { + "path": "scripts/build.sh", + "floor": "isolated", + "why": "build script" + }, + { + "path": "scripts/release.sh", + "floor": "release", + "why": "release machinery" + }, + { + "path": "scripts/deploy.sh", + "floor": "release", + "why": "deployment machinery" + }, + { + "path": "scripts/backup.sh", + "floor": "data", + "why": "backup of stored data" + }, + { + "path": "db/queries/report.sql", + "floor": "data", + "why": "SQL touches stored data" + }, + { + "path": "sql/001_init.sql", + "floor": "data", + "why": "schema definition" + }, + { + "path": "prisma/schema.prisma", + "floor": "data", + "why": "schema definition" + }, + { + "path": "Dockerfile", + "floor": "integration", + "why": "image build changes what runs in production" + }, + { + "path": "docker/Dockerfile.dev", + "floor": "integration", + "why": "image build" + }, + { + "path": "docker-compose.yml", + "floor": "integration", + "why": "service wiring" + }, + { + "path": ".dockerignore", + "floor": "trivial", + "why": "repository metadata" + }, + { + "path": "terraform/main.tf", + "floor": "integration", + "why": "infrastructure change" + }, + { + "path": "terraform/iam.tf", + "floor": "critical", + "why": "access policy" + }, + { + "path": "k8s/deployment.yaml", + "floor": "integration", + "why": "infrastructure change" + }, + { + "path": "charts/app/values.yaml", + "floor": "integration", + "why": "deployment settings" + }, + { + "path": "ansible/playbook.yml", + "floor": "integration", + "why": "infrastructure change" + }, + { + "path": ".github/workflows/ci.yml", + "floor": "integration", + "why": "CI pipeline change affects every merge" + }, + { + "path": ".github/workflows/release.yml", + "floor": "release", + "why": "release pipeline" + }, + { + "path": ".github/workflows/deploy.yml", + "floor": "release", + "why": "deployment pipeline" + }, + { + "path": ".gitlab-ci.yml", + "floor": "integration", + "why": "CI pipeline" + }, + { + "path": "Jenkinsfile", + "floor": "integration", + "why": "CI pipeline" + }, + { + "path": ".githooks/pre-commit", + "floor": "integration", + "why": "runs automatically on every commit" + }, + { + "path": ".husky/pre-commit", + "floor": "integration", + "why": "runs automatically on every commit" + }, + { + "path": ".github/ISSUE_TEMPLATE/bug.md", + "floor": "trivial", + "why": "documentation" + }, + { + "path": "api/openapi.yaml", + "floor": "integration", + "why": "public API schema" + }, + { + "path": "openapi.json", + "floor": "integration", + "why": "public API schema" + }, + { + "path": "schema.graphql", + "floor": "integration", + "why": "public API schema" + }, + { + "path": "proto/events.proto", + "floor": "integration", + "why": "public interface definition" + }, + { + "path": "src/config.schema.json", + "floor": "integration", + "why": "contract for configuration" + }, + { + "path": "docs/architecture.md", + "floor": "trivial", + "why": "documentation" + }, + { + "path": "docs/api/reference.md", + "floor": "trivial", + "why": "documentation of an API" + }, + { + "path": "docs/migrations.md", + "floor": "trivial", + "why": "documentation about migrations" + }, + { + "path": "db/migrations/README.md", + "floor": "trivial", + "why": "documentation of a migration directory" + }, + { + "path": "docs/auth.md", + "floor": "trivial", + "why": "documentation about authentication" + }, + { + "path": "docs/diagrams/flow.png", + "floor": "trivial", + "why": "image" + }, + { + "path": "assets/fonts/inter.woff2", + "floor": "trivial", + "why": "font" + }, + { + "path": "VERSION", + "floor": "release", + "why": "version marker for a release" + }, + { + "path": "src/billing/README.md", + "floor": "trivial", + "why": "documentation inside a critical directory" + } +] \ No newline at end of file diff --git a/tests/test_orchestration.py b/tests/test_orchestration.py index 1be15c5..02cb2ac 100644 --- a/tests/test_orchestration.py +++ b/tests/test_orchestration.py @@ -200,6 +200,45 @@ class RouteTests(OrchCase): self.assertEqual(r.returncode, 0, r.stderr) self.assertIn("mechanism:", r.stdout) + def _big_catalogue(self, n=2000): + names = ["m-%d" % i for i in range(n)] + ["contributor-%d" % i for i in range(40)] + script = FAKE_TOOL.replace('echo "beta-1"; echo "beta-2";', " ".join('echo "%s";' % x for x in names)) + with open(os.path.join(self.bindir, "muse"), "w") as f: + f.write(script) + + def test_explain_stays_short_with_a_huge_catalogue(self): + """R-7.2-1: --explain prints at most 20 lines and 3 example names per reason group, + and still shows every reason group, however many catalogue models were passed over.""" + self._big_catalogue() + self.sisi("workers", "avoid", "m-7", "--why", "fixture avoid", env=self.env()) + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + lines = r.stdout.splitlines() + self.assertLessEqual(len(lines), 20, r.stdout[:2000]) + self.assertTrue(lines[0].startswith("muse/")) + self.assertIn("mechanism:", r.stdout) + self.assertIn("cold start", r.stdout) + self.assertIn("worker facts", r.stdout) + groups = [l for l in lines if l.startswith("passed over")] + for l in groups: + self.assertLessEqual(len(re.findall(r"muse/[\w-]+", l.split("):")[0])), 3, l) + text = "\n".join(groups) + self.assertIn("contributor", text) # the training-tier reason group + self.assertIn("fixture avoid", text) # the user's avoid-pattern group + self.assertIn("equal on price and load", text) # the bulk group + + def test_explain_line_budget_holds_with_many_distinct_reasons(self): + """R-7.2-1: when reasons alone would overflow, groups merge into one line that still + names every reason with its count.""" + from sisi import routing + passed = [("w%d" % i, "reason number %d" % (i % 40)) for i in range(400)] + result = {"choice": None, "passed_over": passed, "stats": {}} + lines = routing.explain_choice(result, "impl", 2) + self.assertLessEqual(len(lines) + 5, 20) + text = "\n".join(lines) + for k in range(40): + self.assertIn("reason number %d" % k, text) + def test_unpriced_catalogue_models_are_not_candidates(self): """Candidates need a judged record, a price or a benchmark prior.""" self.seed_attempts([self.attempt("j%d" % i) for i in range(8)]) diff --git a/tests/test_risk.py b/tests/test_risk.py index 67ec085..7fb1e1f 100644 --- a/tests/test_risk.py +++ b/tests/test_risk.py @@ -72,6 +72,89 @@ class FloorTests(SisiCase): self.assertTrue(risk.requirements_for("release")["contract"]) +LABELS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "risk_labels.json") + + +def _labels(): + with open(LABELS, encoding="utf-8") as f: + return json.load(f) + + +class LabelledSetTests(SisiCase): + """The default table against paths a careful senior engineer has already judged.""" + + def test_labelled_set_is_large_and_covers_every_profile(self): + """R-5.3-3: the set is big enough to mean something and spans every profile.""" + rows = _labels() + self.assertGreaterEqual(len(rows), 120) + self.assertEqual({r["floor"] for r in rows}, set(risk.PROFILES)) + self.assertEqual(len({r["path"] for r in rows}), len(rows)) + for r in rows: + self.assertTrue(r["why"].strip(), r) + + def test_every_labelled_path_gets_its_labelled_floor(self): + """R-5.3-1, R-5.3-2: exact accuracy. Too high wastes a contract and a review on a + trivial change (SPEC 5.3); too low leaves a dangerous change unexamined. Seen failing + first: the old table got 91 of 177 right (lockfiles critical, React hooks critical, + AUTHORS.md critical, release-notes.md release, db/README.md data, sparse.py logic).""" + wrong = [] + for r in _labels(): + got, _ = risk.assess([r["path"]]) + if got != r["floor"]: + wrong.append("%s: labelled %s, got %s (%s)" % (r["path"], r["floor"], got, r["why"])) + self.assertEqual(wrong, [], "\n".join(wrong)) + + def test_no_data_or_critical_path_is_ever_under_classified(self): + """R-5.3-8, R-5.3-9: data and critical paths must never get a lower floor, even if + someone loosens the exact test above. Seen failing first: the old table gave eight of + them a lower floor.""" + order = {name: i for i, name in enumerate(risk.PROFILES)} + under = [] + for r in _labels(): + if r["floor"] in ("data", "critical"): + got, _ = risk.assess([r["path"]]) + if order[got] < order[r["floor"]]: + under.append("%s: %s < %s" % (r["path"], got, r["floor"])) + self.assertEqual(under, [], "\n".join(under)) + + def test_named_false_positives(self): + """R-5.3-2: the known false positives are not escalated.""" + expect = { + "package-lock.json": "integration", "Cargo.lock": "integration", "poetry.lock": "integration", + "flake.lock": "integration", "src/hooks/useCart.ts": "isolated", "AUTHORS.md": "trivial", + "src/components/AuthorCard.tsx": "isolated", "docs/release-notes.md": "trivial", + "src/db/README.md": "trivial", "src/sparse.py": "isolated", "docs/installation.md": "trivial"} + for path, floor in expect.items(): + with self.subTest(path=path): + self.assertEqual(risk.assess([path])[0], floor) + + def test_dependency_change_is_integration_not_trivial_or_critical(self): + """R-5.3-7, R-5.3-11: a manifest or lockfile changes code you did not write.""" + for path in ("package.json", "yarn.lock", "go.mod", "Gemfile.lock", "requirements.txt"): + with self.subTest(path=path): + self.assertEqual(risk.assess([path])[0], "integration") + + def test_test_of_critical_code_is_logic(self): + """R-5.3-9: a test of critical code is not critical, and not trivial.""" + self.assertEqual(risk.assess(["tests/test_auth.py"])[0], "logic") + self.assertEqual(risk.assess(["tests/test_widget.py"])[0], "isolated") + + def test_code_with_its_test_is_not_a_cross_package_change(self): + """R-5.3-2: the commonest change, code plus its test, is not an integration.""" + self.assertEqual(risk.assess(["sisi/risk.py", "tests/test_risk.py"])[0], "isolated") + self.assertEqual(risk.assess(["src/a/x.py", "docs/a.md", "src/a/x.test.ts"])[0], "isolated") + + def test_keywords_in_docs_and_lockfiles_do_not_escalate(self): + """R-5.3-2: a README that says 'password' is not a credentials change; code that does is.""" + doc = "diff --git a/README.md b/README.md\n+ reset your password\n" + lock = "diff --git a/package-lock.json b/package-lock.json\n+ \"crypto-js\": \"4.2.0\"\n" + self.assertEqual(risk.assess(["README.md"], diff_text=doc)[0], "trivial") + self.assertEqual(risk.assess(["package-lock.json"], diff_text=lock)[0], "integration") + code = "diff --git a/src/a.py b/src/a.py\n+ reset your password\n" + self.assertEqual(risk.assess(["src/a.py"], diff_text=code)[0], "critical") + self.assertEqual(risk.assess(["src/a.py", "README.md"], diff_text=doc + code)[0], "critical") + + class RiskCliTests(SisiCase): def _repo_with(self, files): self.git_init()