clarent-methods 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. clarent/__init__.py +2 -0
  2. clarent/__main__.py +5 -0
  3. clarent/_methods/ach/CARD.md +46 -0
  4. clarent/_methods/ach/clarent_ach/__init__.py +6 -0
  5. clarent/_methods/ach/clarent_ach/__main__.py +5 -0
  6. clarent/_methods/ach/clarent_ach/cli.py +123 -0
  7. clarent/_methods/ach/clarent_ach/engine.py +214 -0
  8. clarent/_methods/ach/clarent_ach/i18n.py +160 -0
  9. clarent/_methods/ach/clarent_ach/model.py +174 -0
  10. clarent/_methods/ach/clarent_ach/render.py +72 -0
  11. clarent/_methods/ach/examples/flaky-test.es.json +156 -0
  12. clarent/_methods/ach/examples/flaky-test.json +156 -0
  13. clarent/_methods/ach/method.toml +43 -0
  14. clarent/_methods/ach/skill/SKILL.md +58 -0
  15. clarent/_methods/ach/tests/test_ach.py +231 -0
  16. clarent/_methods/redteam/CARD.md +66 -0
  17. clarent/_methods/redteam/clarent_redteam/__init__.py +6 -0
  18. clarent/_methods/redteam/clarent_redteam/__main__.py +5 -0
  19. clarent/_methods/redteam/clarent_redteam/catalog.py +192 -0
  20. clarent/_methods/redteam/clarent_redteam/cli.py +189 -0
  21. clarent/_methods/redteam/clarent_redteam/engine.py +281 -0
  22. clarent/_methods/redteam/clarent_redteam/i18n.py +199 -0
  23. clarent/_methods/redteam/clarent_redteam/model.py +320 -0
  24. clarent/_methods/redteam/clarent_redteam/render.py +103 -0
  25. clarent/_methods/redteam/examples/design-doc/design.es.md +27 -0
  26. clarent/_methods/redteam/examples/design-doc/design.md +27 -0
  27. clarent/_methods/redteam/examples/design-doc/findings.es.json +132 -0
  28. clarent/_methods/redteam/examples/design-doc/findings.json +132 -0
  29. clarent/_methods/redteam/examples/design-doc/findings.rejected.json +130 -0
  30. clarent/_methods/redteam/examples/pr/change.diff +34 -0
  31. clarent/_methods/redteam/examples/pr/description.md +13 -0
  32. clarent/_methods/redteam/examples/pr/findings.json +114 -0
  33. clarent/_methods/redteam/method.toml +43 -0
  34. clarent/_methods/redteam/skill/SKILL.md +52 -0
  35. clarent/_methods/redteam/tests/test_redteam.py +640 -0
  36. clarent/_methods/triz-matrix/CARD.md +50 -0
  37. clarent/_methods/triz-matrix/clarent_triz/__init__.py +6 -0
  38. clarent/_methods/triz-matrix/clarent_triz/__main__.py +5 -0
  39. clarent/_methods/triz-matrix/clarent_triz/cli.py +184 -0
  40. clarent/_methods/triz-matrix/clarent_triz/data/DATA_LICENSE.md +51 -0
  41. clarent/_methods/triz-matrix/clarent_triz/data/catalog.json +89 -0
  42. clarent/_methods/triz-matrix/clarent_triz/data/matrix.json +11920 -0
  43. clarent/_methods/triz-matrix/clarent_triz/engine.py +103 -0
  44. clarent/_methods/triz-matrix/clarent_triz/i18n.py +134 -0
  45. clarent/_methods/triz-matrix/clarent_triz/model.py +179 -0
  46. clarent/_methods/triz-matrix/clarent_triz/render.py +101 -0
  47. clarent/_methods/triz-matrix/examples/search-api.es.json +9 -0
  48. clarent/_methods/triz-matrix/examples/search-api.json +9 -0
  49. clarent/_methods/triz-matrix/method.toml +58 -0
  50. clarent/_methods/triz-matrix/skill/SKILL.md +50 -0
  51. clarent/_methods/triz-matrix/tests/test_triz.py +306 -0
  52. clarent/cli.py +95 -0
  53. clarent/registry.py +175 -0
  54. clarent_methods-0.1.0.dist-info/METADATA +227 -0
  55. clarent_methods-0.1.0.dist-info/RECORD +59 -0
  56. clarent_methods-0.1.0.dist-info/WHEEL +4 -0
  57. clarent_methods-0.1.0.dist-info/entry_points.txt +2 -0
  58. clarent_methods-0.1.0.dist-info/licenses/LICENSE +202 -0
  59. clarent_methods-0.1.0.dist-info/licenses/NOTICE +12 -0
@@ -0,0 +1,231 @@
1
+ """ACH tests. Stdlib only: `python -m unittest discover -s methods/ach/tests` (from any directory)."""
2
+ import copy
3
+ import io
4
+ import json
5
+ import tempfile
6
+ import sys
7
+ import unittest
8
+ from contextlib import redirect_stderr, redirect_stdout
9
+ from pathlib import Path
10
+
11
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # run from any directory
12
+
13
+ from clarent_ach import ACHError, engine, i18n, main, parse
14
+ from clarent_ach.render import markdown
15
+
16
+ EXAMPLE = Path(__file__).resolve().parent.parent / "examples" / "flaky-test.json"
17
+ EXAMPLE_ES = EXAMPLE.with_name("flaky-test.es.json")
18
+
19
+
20
+ def setUpModule():
21
+ i18n.set_lang("en")
22
+
23
+
24
+ def base():
25
+ """Matriz mínima: A es contradicha, B no, 'O' es el comodín."""
26
+ return {
27
+ "hypotheses": [
28
+ {"id": "A", "text": "a"},
29
+ {"id": "B", "text": "b"},
30
+ {"id": "O", "text": "otra", "catch_all": True},
31
+ ],
32
+ "evidence": [
33
+ {"id": "E1", "text": "e1", "ref": "x", "credibility": "high", "relevance": "high",
34
+ "ratings": {"A": "II", "B": "C", "O": "N"}},
35
+ ],
36
+ }
37
+
38
+
39
+ class ParseTests(unittest.TestCase):
40
+ def test_requires_two_hypotheses(self):
41
+ d = base(); d["hypotheses"] = d["hypotheses"][:1]
42
+ with self.assertRaises(ACHError):
43
+ parse(d)
44
+
45
+ def test_duplicate_ids_rejected(self):
46
+ d = base(); d["hypotheses"][1]["id"] = "A"
47
+ with self.assertRaises(ACHError):
48
+ parse(d)
49
+
50
+ def test_unknown_hypothesis_in_ratings_rejected(self):
51
+ d = base(); d["evidence"][0]["ratings"]["ZZ"] = "C"
52
+ with self.assertRaises(ACHError):
53
+ parse(d)
54
+
55
+ def test_invalid_rating_rejected(self):
56
+ d = base(); d["evidence"][0]["ratings"]["A"] = "MAYBE"
57
+ with self.assertRaises(ACHError):
58
+ parse(d)
59
+
60
+ def test_missing_required_field_is_a_clean_error(self):
61
+ # regression: t("missing_field", key=...) used to raise TypeError (the message key was not positional-only)
62
+ d = base(); del d["hypotheses"][0]["id"]
63
+ with self.assertRaises(ACHError) as cm:
64
+ parse(d)
65
+ self.assertIn("missing required field 'id'", str(cm.exception))
66
+
67
+ def test_all_catch_all_rejected(self):
68
+ d = base()
69
+ for h in d["hypotheses"]:
70
+ h["catch_all"] = True
71
+ with self.assertRaises(ACHError):
72
+ parse(d)
73
+
74
+ def test_uncited_observed_evidence_warns_and_strict_fails(self):
75
+ d = base(); d["evidence"][0]["ref"] = ""
76
+ self.assertTrue(any("without 'ref'" in w for w in parse(d).warnings))
77
+ with self.assertRaises(ACHError):
78
+ parse(d, strict=True)
79
+
80
+ def test_missing_rating_assumed_neutral_with_warning(self):
81
+ d = base(); del d["evidence"][0]["ratings"]["O"]
82
+ an = parse(d)
83
+ self.assertEqual(an.evidence[0].value("O"), 0)
84
+ self.assertTrue(any("no rating" in w for w in an.warnings))
85
+
86
+
87
+ class ScoreTests(unittest.TestCase):
88
+ def test_inconsistency_is_weighted_and_only_penalizes_inconsistent(self):
89
+ res = engine.score(parse(base()))
90
+ by = {s.id: s for s in res.scores}
91
+ self.assertEqual(by["A"].inconsistency, 9 * 2) # peso 3x3, II = 2
92
+ self.assertEqual(by["B"].inconsistency, 0)
93
+ self.assertEqual(res.leaders, ("B",))
94
+
95
+ def test_consistent_evidence_never_changes_ranking(self):
96
+ d = base()
97
+ before = engine.score(parse(d))
98
+ d["evidence"].append({"id": "E2", "text": "x", "ref": "r", "credibility": "high",
99
+ "relevance": "high", "ratings": {"A": "C", "B": "CC", "O": "C"}})
100
+ after = engine.score(parse(d))
101
+ self.assertEqual([(s.id, s.inconsistency) for s in before.scores],
102
+ [(s.id, s.inconsistency) for s in after.scores])
103
+
104
+ def test_evidence_kinds(self):
105
+ d = base()
106
+ d["evidence"] += [
107
+ {"id": "E2", "text": "igual", "ref": "r", "ratings": {"A": "C", "B": "C", "O": "C"}},
108
+ {"id": "E3", "text": "solo apoya", "ref": "r", "ratings": {"A": "C", "B": "CC", "O": "N"}},
109
+ ]
110
+ kinds = {x.id: x.kind for x in engine.score(parse(d)).diagnostics}
111
+ self.assertEqual(kinds, {"E1": "diagnostic", "E2": "non-diagnostic", "E3": "supports-only"})
112
+
113
+ def test_catch_all_never_leads_but_warns(self):
114
+ d = base()
115
+ d["evidence"][0]["ratings"] = {"A": "II", "B": "II", "O": "N"}
116
+ res = engine.score(parse(d))
117
+ self.assertNotIn("O", res.leaders)
118
+ self.assertTrue(any("catch-all" in w for w in res.warnings))
119
+
120
+ def test_no_discrimination_when_all_equal(self):
121
+ d = base(); d["evidence"][0]["ratings"] = {"A": "C", "B": "C", "O": "C"}
122
+ res = engine.score(parse(d))
123
+ self.assertEqual(res.verdict, "no-discrimination")
124
+
125
+ def test_fragile_when_removing_one_evidence_flips_leader(self):
126
+ d = base()
127
+ d["evidence"] = [
128
+ {"id": "E1", "text": "e1", "ref": "r", "credibility": "high", "relevance": "high",
129
+ "ratings": {"A": "II", "B": "N", "O": "N"}},
130
+ {"id": "E2", "text": "e2", "ref": "r", "credibility": "low", "relevance": "low",
131
+ "ratings": {"A": "N", "B": "I", "O": "N"}},
132
+ {"id": "E3", "text": "e3", "ref": "r", "credibility": "low", "relevance": "low",
133
+ "ratings": {"A": "N", "B": "I", "O": "N"}},
134
+ {"id": "E4", "text": "e4", "ref": "r", "credibility": "low", "relevance": "low",
135
+ "ratings": {"A": "N", "B": "N", "O": "N"}},
136
+ ]
137
+ res = engine.score(parse(d))
138
+ self.assertEqual(res.leaders, ("B",))
139
+ self.assertTrue(res.fragile) # sin E1, el líder pasa a ser A y B empata
140
+ self.assertTrue(next(s for s in res.sensitivity if s.evidence_id == "E1").changes_leader)
141
+
142
+ def test_deterministic(self):
143
+ an = parse(json.loads(EXAMPLE.read_text(encoding="utf-8")))
144
+ self.assertEqual(engine.score(an), engine.score(an))
145
+
146
+ def test_proposed_evidence_does_not_affect_scores(self):
147
+ d = base()
148
+ d["evidence"].append({"id": "T1", "text": "t", "status": "proposed",
149
+ "ratings": {"A": "II", "B": "CC", "O": "N"}})
150
+ with_t = engine.score(parse(d))
151
+ without = engine.score(parse(base()))
152
+ self.assertEqual([(s.id, s.inconsistency) for s in with_t.scores],
153
+ [(s.id, s.inconsistency) for s in without.scores])
154
+
155
+
156
+ class NextTestTests(unittest.TestCase):
157
+ def test_example_golden(self):
158
+ an = parse(json.loads(EXAMPLE.read_text(encoding="utf-8")))
159
+ res = engine.score(an)
160
+ self.assertEqual(res.leaders, ("H1", "H5"))
161
+ self.assertEqual({s.id: s.inconsistency for s in res.scores},
162
+ {"H1": 0, "H5": 0, "H6": 0, "H2": 21, "H3": 27, "H4": 33})
163
+ self.assertEqual({s.id for s in res.scores if s.refuted}, {"H2", "H3", "H4"})
164
+ # T1 separa H1 de H5 -> primera. T3 trata igual a H1 y H5 -> descartada.
165
+ self.assertEqual([t.id for t in res.next_tests], ["T1", "T2"])
166
+ self.assertEqual(res.next_tests[0].priority, 36.0)
167
+
168
+ def test_cost_lowers_priority(self):
169
+ d = base()
170
+ for cost, tid in (("low", "T1"), ("high", "T2")):
171
+ d["evidence"].append({"id": tid, "text": tid, "status": "proposed", "cost": cost,
172
+ "credibility": "high", "relevance": "high",
173
+ "ratings": {"A": "CC", "B": "II", "O": "N"}})
174
+ d["evidence"][0]["ratings"] = {"A": "N", "B": "N", "O": "N"} # A y B siguen vivas
175
+ res = engine.score(parse(d))
176
+ self.assertEqual([t.id for t in res.next_tests], ["T1", "T2"])
177
+
178
+
179
+ class CliTests(unittest.TestCase):
180
+ def run_cli(self, *argv):
181
+ out, err = io.StringIO(), io.StringIO()
182
+ with redirect_stdout(out), redirect_stderr(err):
183
+ try:
184
+ code = main(list(argv))
185
+ except SystemExit as e:
186
+ code = e.code
187
+ return code, out.getvalue(), err.getvalue()
188
+
189
+ def test_init_validate_score_roundtrip(self):
190
+ with tempfile.TemporaryDirectory() as tmp:
191
+ p = str(Path(tmp) / "a.json")
192
+ self.assertEqual(self.run_cli("init", p)[0], 0)
193
+ self.assertEqual(self.run_cli("init", p)[0], 2) # no sobrescribe
194
+ self.assertEqual(self.run_cli("validate", p)[0], 0)
195
+ code, out, _ = self.run_cli("score", p, "--format", "json")
196
+ self.assertEqual(code, 0)
197
+ self.assertIn("scores", json.loads(out))
198
+
199
+ def test_bad_file_gives_clean_error_not_traceback(self):
200
+ code, _, err = self.run_cli("score", "no-existe.json")
201
+ self.assertEqual(code, 2)
202
+ self.assertIn("error:", err)
203
+
204
+ def test_markdown_report_has_key_sections(self):
205
+ an = parse(json.loads(EXAMPLE.read_text(encoding="utf-8")))
206
+ md = markdown(an, engine.score(an))
207
+ for section in ("## Hypothesis ranking", "## Matrix", "## Sensitivity", "## Recommended next test", "not a probability"):
208
+ self.assertIn(section, md)
209
+
210
+ def test_example_is_valid_in_strict_mode(self):
211
+ self.assertEqual(self.run_cli("validate", str(EXAMPLE), "--strict")[0], 0)
212
+
213
+ def test_spanish_output_and_same_numbers(self):
214
+ try:
215
+ code_es, out_es, _ = self.run_cli("--lang", "es", "score", str(EXAMPLE_ES), "--format", "json")
216
+ code_en, out_en, _ = self.run_cli("--lang", "en", "score", str(EXAMPLE), "--format", "json")
217
+ self.assertEqual((code_es, code_en), (0, 0))
218
+ strip = lambda o: [(s["id"], s["inconsistency"]) for s in json.loads(o)["scores"]]
219
+ self.assertEqual(strip(out_es), strip(out_en)) # el idioma no cambia el cálculo
220
+ _, md_es, _ = self.run_cli("--lang", "es", "score", str(EXAMPLE_ES))
221
+ self.assertIn("## Ranking de hipótesis", md_es)
222
+ self.assertIn("no una probabilidad", md_es)
223
+ finally:
224
+ i18n.set_lang("en")
225
+
226
+ def test_unsupported_language_rejected(self):
227
+ self.assertEqual(self.run_cli("--lang", "xx", "validate", str(EXAMPLE))[0], 2) # argparse exit
228
+
229
+
230
+ if __name__ == "__main__":
231
+ unittest.main()
@@ -0,0 +1,66 @@
1
+ # Red Team — methodology card
2
+
3
+ ## Origin
4
+ "Red teaming" in the sense used here comes from the US Army's University of Foreign Military and Cultural Studies (UFMCS), whose *Red Team Handbook* collects techniques to challenge a plan before committing to it: check its assumptions, imagine its failure, argue the opposite, look at it through the adversary's eyes. The techniques themselves come from several traditions that the Handbook cites (intelligence analysis, Gary Klein's decision research). Clarent does not reproduce the Handbook's text or its exercises; it takes a few of its techniques, adds three classes of its own, and puts a deterministic gate in front of what a model writes.
5
+
6
+ ## Sources
7
+ - UFMCS, *Red Team Handbook* v5 (15 Apr 2011) — https://newandimproved.com/wp-content/uploads/2014/04/ufmcs_red_team_handbook_apr2011.pdf — `read`. Sections read in full, by printed page: Validating Assumptions pp. 85–88 (an assumption is "information accepted as true in the absence of facts", and must be both *valid* and *necessary*; a red team challenges invalid or unneeded assumptions and finds the unstated ones); Pre-mortem Analysis pp. 138–140 (imagine the plan has failed and write the reasons); ADSO "String of Pearls" p. 140 (sensitivity of a plan to faulty assumptions, to dependencies not in place, and to second- and third-order effects); Key Assumptions Check pp. 151–152 (write down the analytic line, list the premises "both stated and unstated", challenge each, keep those that "must be true"); Devil's Advocacy p. 161; High-Impact/Low-Probability Analysis p. 165; "What If?" Analysis pp. 166–167; Red Team Analysis pp. 173–174 (model how the adversary would think). The copy read is hosted on newandimproved.com, not on a US government site.
8
+ - Klein, *Performing a Project Premortem*, IEEE Engineering Management Review (2008), a reprint of the Harvard Business Review article of September 2007 — https://doi.org/10.1109/EMR.2008.4534313 — `exists` (Crossref record with matching title, author and year; the text was not opened). The Handbook credits the pre-mortem to Klein and cites his book.
9
+ - Klein, *Sources of Power: How People Make Decisions* (MIT Press, 1998) — https://openlibrary.org/works/OL2731587W — `exists` (Open Library record; not opened). This is the book the Handbook cites for the pre-mortem (footnote 94).
10
+ - Heuer & Pherson, *Structured Analytic Techniques for Intelligence Analysis* (3rd ed.) — ISBN-10 150636893X as listed in web search results — `exists` (not opened).
11
+
12
+ ## Problem it solves
13
+ A design document or a PR is written by someone who already believes it. The assumptions it rests on are mostly unstated, the failure cases are the ones the author already thought of, and a reviewer who asks a model to "find problems" gets a fluent list of generic worries with nothing behind them. Red Team forces the attack to be *anchored* (it quotes the text it attacks), *backed* (what it calls verified or contradicted cites something that exists), *complete* (six classes, each applied or explicitly skipped) and *ranked* (a short list of what to look at first, and what to verify before trusting it).
14
+
15
+ ## When to use / when NOT to use
16
+ - Use: before approving a design doc, ADR or RFC; before merging a PR that changes behavior in ways tests do not pin down (retries, migrations, concurrency, permissions); when everyone agrees too fast.
17
+ - Do not use: to review code for bugs line by line (use a code review tool; this method attacks *claims*, not syntax); on a text with no claims to attack (a changelog, a rename); to produce a security assessment — the "abuse" class is a prompt to think about misuse, not a penetration test or a threat model.
18
+
19
+ ## How it maps to software work
20
+ A *target* is a design document or a PR (its description plus its diff). An **assumption** is something the target takes for granted, stated or not, that must be true for it to work; each carries a literal quote that it rests on and a status: `verified` (something checked backs it), `contradicted` (something checked says it is false) or `unverified` (nobody has looked). An **attack** says what goes wrong if an assumption is false or abused, in one of six **classes**:
21
+
22
+ | Class | Question | Origin |
23
+ |-------|----------|--------|
24
+ | `key-assumptions` | What must be true, and has each thing been checked? | Handbook: Key Assumptions Check; Validating Assumptions |
25
+ | `failure-modes` | How does it fail, and what happens next? | Handbook: Pre-mortem; "What If?" |
26
+ | `abuse` | How can someone use it in a way its author did not intend? | Handbook: Red Team Analysis, adapted (the adversary is a hostile or careless user) |
27
+ | `scale` | What breaks at 10x or 100x? | **Clarent's own**; no Handbook technique by this name |
28
+ | `dependency` | What does it depend on that it does not control? | **Clarent's own**; related to the String of Pearls (dependencies not in place) |
29
+ | `reversibility` | If this is wrong, how do you go back? | **Clarent's own** |
30
+
31
+ The questions, the wording of the prompts (`clarent redteam catalog`), and the rating rubrics are Clarent's, not the Handbook's.
32
+
33
+ ## Inputs and outputs
34
+ - Input: `findings.json` (`schema: "clarent.redteam/1"`): the target files (`target.files`, with `kind` `design` or `pr`; for a PR use the description and a saved `gh pr diff`), a `root` folder, the `assumptions` and the `attacks` a model proposes, and `skipped_classes` with a reason for each class that does not apply. Every assumption and attack carries a `quote`; every attack carries `check` (a command or a concrete question), `impact` and `plausibility` (1–5), and optional `evidence`.
35
+ - Output: Markdown or JSON (`--format json`, `schema: "clarent.redteam.report/1"`): summary, **top 3 attacks**, the **assumption matrix** (assumption × class, with status and evidence), **verify next**, all attacks ranked, class coverage, rejected findings and warnings.
36
+ - Commands: `clarent redteam {init,validate,check,top,catalog}`; `check --fail-on S1|S2|S3|S4` and `--strict` for CI. Exit codes: 0 ok · 1 a finding was rejected, or `--fail-on`/`--strict` was reached · 2 invalid input.
37
+ - Example (3 lines): `clarent redteam init .clarent/redteam/adr-14.json --target docs/adr-14.md` → fill in assumptions and attacks (the skill does this) → `clarent redteam check .clarent/redteam/adr-14.json`.
38
+
39
+ ## Algorithm (what is deterministic)
40
+ 1. **Anchor.** Each assumption and attack must quote the target. The quote is searched character by character, case included; the only normalization is that any run of whitespace counts as one space (so a quote may span a line break). For a diff, a quote without the `+`/`-` markers also anchors to the changed line. A missing quote, one shorter than 12 characters, or one not in the target: **rejected**. The report shows where each quote was found (`file:line`).
41
+ 2. **Back the status.** `verified` and `contradicted` need at least one evidence item `{ref, observation}`. A ref written as `file:line` or `file:a-b` must point at an existing line under the root (paths cannot leave the root); a free-text ref (a command, a log excerpt) is only required to be non-empty. Otherwise **rejected**.
42
+ 3. **Cascade and de-duplicate.** An attack on a rejected assumption is rejected. An attack without `check` is rejected. Two attacks of the same class on the same assumption whose words overlap by 80% or more (Jaccard) count once.
43
+ 4. **Score.** `risk = impact × effective plausibility`. The assumption's status moves plausibility: `contradicted` → 5 (the premise is already false), `verified` → at most 2 (the premise holds), `unverified` → as rated. Severity: `S1` risk ≥ 20, `S2` ≥ 12, `S3` ≥ 6, otherwise `S4`. Ties: higher impact, then more evidence items, then id.
44
+ 5. **Report.** Assumption matrix, top 3, "verify next" (unverified assumptions ordered by the highest risk of the attacks that depend on them), coverage of the six classes, and warnings: a class neither applied nor skipped with a reason; an assumption nobody attacked; fewer than 3 assumptions or 3 attacks; a top attack that rests on an unverified assumption.
45
+
46
+ ## Limitations
47
+ - **The engine proves that a finding is anchored and backed, not that it is right.** A quote that exists can still be attacked with a wrong argument. A free-text `ref` is never executed; whether a command was really run and said what the observation says is on the person (or the model) who wrote it.
48
+ - The six classes, the 12-character minimum quote, the 80% duplicate threshold, the 1–5 rubrics, the plausibility rule and the severity bands are **Clarent's own constants**, chosen by judgment and not calibrated against any data. Three of the six classes have no counterpart in the Handbook.
49
+ - Risk is a prioritization score, **not a probability** and not a measure of how likely the target is to fail.
50
+ - A fixed catalog finds what the catalog asks about. It does not replace a domain expert, a threat model or a security review.
51
+ - The Handbook's Team A / Team B technique (two independent analyses compared for disagreement) is **not implemented** yet.
52
+ - Nothing here is evidence that using it improves reviews; see Evaluation.
53
+
54
+ ## Prior art (GitHub scan)
55
+ Scanned 2026-11-25 with short queries (raw data: `research/data/github-scan-redteam.json`). I read READMEs and file lists, not source code. The space is more crowded than `research/novelty.md` recorded on 2026-11-24:
56
+ - **Plan stress-tests as prompts.** `aaddrick/contrarian` (43 stars, Unlicense): a subagent and skill that steel-mans a plan, audits assumptions, runs a pre-mortem and returns severity-rated findings; its repository holds prompts and install checks, no engine. Descriptions only: `Hainrixz/abogado-del-diablo` (43), `orange2ai/devils-advocate-skill` (33), `wtfzambo/devils-advocate` (5). Pre-mortem skills are well covered (`Hi1talib1World/Premortem` 88, `AndyShaman/premortem` 61, `MADEVAL/Pre-Mortem-Skill` 59).
57
+ - **Adversarial PR review.** `liliu-z/magpie` (180 stars): several models review a PR, debate, and a tool-equipped verifier audits each issue against the code. `liatrio-labs/claude-code-gauntlet` (13, Apache-2.0): seven specialist agents plus a skeptical validator and a blind challenger; reports a benchmark of 15 PRs. `YahampathChandika/adv-review` (6, MIT): every finding must survive a skeptic told to refute it; reports a calibration on 21 PRs with planted defects. `zhjai/agent-arena` (25): evidence-first multi-agent debate. In all of them the verification is another model pass.
58
+ - **Not what this is:** the large red-team ecosystem for offensive security (for example `elementalsouls/Claude-BugHunter`, 22.8k stars) is a different use case.
59
+ - **What I did not find** in the READMEs and file lists read: a gate that rejects findings by checking quotes against the text, an assumption matrix with verified/unverified/contradicted status that feeds the ranking, or a fixed class catalog with coverage warnings. That is Clarent's angle, and it is narrow: the existing tools may do more than their READMEs say, and their benchmarks (which Clarent does not have yet) are a real advantage.
60
+
61
+ ## Worked example
62
+ `examples/design-doc/` — a **synthetic** design for moving notifications to a stream consumer, in English (`design.md` + `findings.json`) and Spanish (`design.es.md` + `findings.es.json`); `examples/pr/` — a synthetic PR (`description.md` + `change.diff` + `findings.json`); `examples/design-doc/findings.rejected.json` — the same design with nine findings the engine must refuse.
63
+ `python -m clarent_redteam check examples/design-doc/findings.json` → 6 assumptions (1 verified, 3 unverified, 2 contradicted), 7 attacks, top 3: X3 (rollout leaves no way back, risk 25, S1), X1 (a Redis outage leaves rows nobody reads, 20, S1), X2 (acknowledging on read can lose a notification, 16, S2); the report flags that X2 rests on an unverified assumption and lists what to verify first. The same command on `findings.rejected.json` exits 1 and lists why each of the nine findings was refused.
64
+
65
+ ## Evaluation
66
+ Not yet measured. Planned: take 10 real design docs or PRs where a defect was found after merge; run the method with and without the engine's rejection step; count (a) how many findings the gate rejects and whether those were in fact unsupported, (b) whether a contradicted or unverified assumption covers the defect that later appeared, (c) reviewer time. Publish the result even if it is null.
@@ -0,0 +1,6 @@
1
+ """Red team: attack a design document or a PR with a fixed catalog; the engine rejects what it cannot anchor."""
2
+ from .cli import main, register # noqa: F401
3
+ from .engine import analyze # noqa: F401
4
+ from .model import RedTeamError, parse # noqa: F401
5
+
6
+ __all__ = ["main", "register", "analyze", "parse", "RedTeamError"]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,192 @@
1
+ """The fixed catalog of attack classes, the rating rubrics and the severity bands.
2
+
3
+ Everything here is data the engine and the report rely on; changing it changes results, so it is covered by tests.
4
+
5
+ Provenance is stated per class (`origin`):
6
+ * "handbook": the class applies a technique that the UFMCS Red Team Handbook v5 (15 Apr 2011) describes; `pages`
7
+ are the printed page numbers I read.
8
+ * "clarent": the class is Clarent's own adaptation to software work; the Handbook has no technique by that name.
9
+ The questions and rubrics below are Clarent's wording, not the Handbook's.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ CLASSES = ("key-assumptions", "failure-modes", "abuse", "scale", "dependency", "reversibility")
14
+
15
+ CATALOG: dict[str, dict] = {
16
+ "key-assumptions": {
17
+ "origin": "handbook",
18
+ "pages": "Key Assumptions Check, p. 151-152; Validating Assumptions, p. 85-88",
19
+ "en": {
20
+ "name": "Key assumptions",
21
+ "question": "What must be true for this to work, and has each of those things been checked?",
22
+ "prompts": [
23
+ "What does the text take for granted without saying so: inputs, ordering, who calls it, volume, environment?",
24
+ "Is each assumption a fact, an opinion or a preconception? Is it needed at all, or can the plan work without it?",
25
+ "What would change if it were wrong, and what would you see first?",
26
+ ],
27
+ },
28
+ "es": {
29
+ "name": "Supuestos clave",
30
+ "question": "¿Qué tiene que ser cierto para que esto funcione, y se ha comprobado cada cosa?",
31
+ "prompts": [
32
+ "¿Qué da el texto por sentado sin decirlo: entradas, orden, quién llama, volumen, entorno?",
33
+ "¿Cada supuesto es un hecho, una opinión o un prejuicio? ¿Hace falta, o el plan funciona sin él?",
34
+ "¿Qué cambiaría si fuera falso y qué verías primero?",
35
+ ],
36
+ },
37
+ },
38
+ "failure-modes": {
39
+ "origin": "handbook",
40
+ "pages": "Pre-mortem Analysis, p. 138-140; \"What If?\" Analysis, p. 166-167",
41
+ "en": {
42
+ "name": "Failure modes",
43
+ "question": "How does it fail, and what happens next?",
44
+ "prompts": [
45
+ "Imagine it has already failed in production: write down the reasons (pre-mortem).",
46
+ "Which partial failures (timeout, duplicate, reordering, crash half-way) leave the system in an inconsistent state?",
47
+ "Who would notice the failure, and how long would it take?",
48
+ ],
49
+ },
50
+ "es": {
51
+ "name": "Modos de falla",
52
+ "question": "¿Cómo falla y qué pasa después?",
53
+ "prompts": [
54
+ "Imagina que ya falló en producción: escribe las razones (pre-mortem).",
55
+ "¿Qué fallas parciales (timeout, duplicado, reordenamiento, caída a medias) dejan el sistema inconsistente?",
56
+ "¿Quién notaría la falla y cuánto tardaría?",
57
+ ],
58
+ },
59
+ },
60
+ "abuse": {
61
+ "origin": "handbook",
62
+ "pages": "Red Team Analysis, p. 173-174 (adapted: the adversary is a hostile or careless user, not a state)",
63
+ "en": {
64
+ "name": "Abuse",
65
+ "question": "How can someone use it in a way its author did not intend?",
66
+ "prompts": [
67
+ "Think as the adversary or the careless user: which input, sequence or permission breaks the rules?",
68
+ "Who can call this, and what limits apply to them?",
69
+ "What is exposed if one client, credential or tenant is hostile?",
70
+ ],
71
+ },
72
+ "es": {
73
+ "name": "Abuso",
74
+ "question": "¿Cómo puede alguien usarlo de una forma que su autor no pensó?",
75
+ "prompts": [
76
+ "Piensa como el adversario o el usuario descuidado: ¿qué entrada, secuencia o permiso rompe las reglas?",
77
+ "¿Quién puede llamarlo y qué límites tiene?",
78
+ "¿Qué queda expuesto si un cliente, credencial o inquilino es hostil?",
79
+ ],
80
+ },
81
+ },
82
+ "scale": {
83
+ "origin": "clarent",
84
+ "pages": "no Handbook technique; closest in spirit: High-Impact/Low-Probability Analysis, p. 165",
85
+ "en": {
86
+ "name": "Scale",
87
+ "question": "What breaks at 10x or 100x?",
88
+ "prompts": [
89
+ "Volume, cardinality, concurrency, payload size, number of tenants: which one grows and what is its limit?",
90
+ "What is quadratic or unbounded (queues, retries, fan-out, memory, cost)?",
91
+ "What happens during a burst rather than on average?",
92
+ ],
93
+ },
94
+ "es": {
95
+ "name": "Escala",
96
+ "question": "¿Qué se rompe a 10x o 100x?",
97
+ "prompts": [
98
+ "Volumen, cardinalidad, concurrencia, tamaño de carga, número de inquilinos: ¿cuál crece y cuál es su límite?",
99
+ "¿Qué es cuadrático o sin cota (colas, reintentos, fan-out, memoria, costo)?",
100
+ "¿Qué pasa en una ráfaga y no en el promedio?",
101
+ ],
102
+ },
103
+ },
104
+ "dependency": {
105
+ "origin": "clarent",
106
+ "pages": "no Handbook technique; related: ADSO \"String of Pearls\", p. 140 (dependencies not in place, 2nd and 3rd order effects)",
107
+ "en": {
108
+ "name": "Dependency",
109
+ "question": "What does it depend on that it does not control?",
110
+ "prompts": [
111
+ "External services, libraries, configuration, other teams, deploy order, clocks, credentials: which are assumed to be there?",
112
+ "What happens when a dependency is slow, wrong, rate-limited or gone?",
113
+ "Does the change make something else depend on it without that other thing knowing?",
114
+ ],
115
+ },
116
+ "es": {
117
+ "name": "Dependencia",
118
+ "question": "¿De qué depende que no controla?",
119
+ "prompts": [
120
+ "Servicios externos, bibliotecas, configuración, otros equipos, orden de despliegue, relojes, credenciales: ¿cuáles se dan por presentes?",
121
+ "¿Qué pasa si una dependencia está lenta, equivocada, limitada o ausente?",
122
+ "¿El cambio hace que otra cosa dependa de esto sin que esa otra cosa lo sepa?",
123
+ ],
124
+ },
125
+ },
126
+ "reversibility": {
127
+ "origin": "clarent",
128
+ "pages": "no Handbook technique",
129
+ "en": {
130
+ "name": "Reversibility",
131
+ "question": "If this is wrong, how do you go back?",
132
+ "prompts": [
133
+ "Is there a point of no return (migration, deletion, external side effect, sent message)?",
134
+ "Can it be rolled back without losing data, and who does it, how fast?",
135
+ "Does the rollback path still work after the rollout is complete?",
136
+ ],
137
+ },
138
+ "es": {
139
+ "name": "Reversibilidad",
140
+ "question": "Si esto está mal, ¿cómo se vuelve atrás?",
141
+ "prompts": [
142
+ "¿Hay un punto sin retorno (migración, borrado, efecto externo, mensaje enviado)?",
143
+ "¿Se puede deshacer sin perder datos, quién lo hace y en cuánto tiempo?",
144
+ "¿El camino de vuelta sigue funcionando cuando el despliegue ya terminó?",
145
+ ],
146
+ },
147
+ },
148
+ }
149
+
150
+ # Ratings the model assigns; both scales are 1..5. Clarent's own rubric (the Handbook has none).
151
+ RUBRIC = {
152
+ "impact": {
153
+ "en": {1: "cosmetic or a nuisance",
154
+ 2: "a feature degrades; users can work around it",
155
+ 3: "an incident with a known workaround",
156
+ 4: "data loss, a security exposure or a major outage, recoverable with effort",
157
+ 5: "irreversible data loss, a breach, or the whole product down"},
158
+ "es": {1: "cosmético o una molestia",
159
+ 2: "una función se degrada; hay forma de evitarlo",
160
+ 3: "un incidente con solución conocida",
161
+ 4: "pérdida de datos, exposición de seguridad o caída mayor, recuperable con esfuerzo",
162
+ 5: "pérdida irreversible de datos, brecha, o todo el producto caído"},
163
+ },
164
+ "plausibility": {
165
+ "en": {1: "needs several independent things to go wrong",
166
+ 2: "could happen, but nothing in the text suggests it",
167
+ 3: "plausible within a year of operation",
168
+ 4: "likely; a normal event for a system of this kind",
169
+ 5: "will happen, or is already happening"},
170
+ "es": {1: "requiere que varias cosas independientes salgan mal",
171
+ 2: "podría pasar, pero nada en el texto lo sugiere",
172
+ 3: "plausible dentro de un año de operación",
173
+ 4: "probable; un evento normal en un sistema así",
174
+ 5: "va a pasar, o ya está pasando"},
175
+ },
176
+ }
177
+
178
+ # risk = impact x effective plausibility (1..25). Severity bands: Clarent's own, not from any source.
179
+ SEVERITY_ORDER = ("S1", "S2", "S3", "S4") # most to least severe
180
+ SEVERITY_MIN_RISK = {"S1": 20, "S2": 12, "S3": 6, "S4": 0}
181
+
182
+
183
+ def severity(risk: int) -> str:
184
+ for s in SEVERITY_ORDER:
185
+ if risk >= SEVERITY_MIN_RISK[s]:
186
+ return s
187
+ return "S4"
188
+
189
+
190
+ def at_least(sev: str, threshold: str) -> bool:
191
+ """True if `sev` is as severe as `threshold` (S1 is the most severe)."""
192
+ return SEVERITY_ORDER.index(sev) <= SEVERITY_ORDER.index(threshold)