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.
- clarent/__init__.py +2 -0
- clarent/__main__.py +5 -0
- clarent/_methods/ach/CARD.md +46 -0
- clarent/_methods/ach/clarent_ach/__init__.py +6 -0
- clarent/_methods/ach/clarent_ach/__main__.py +5 -0
- clarent/_methods/ach/clarent_ach/cli.py +123 -0
- clarent/_methods/ach/clarent_ach/engine.py +214 -0
- clarent/_methods/ach/clarent_ach/i18n.py +160 -0
- clarent/_methods/ach/clarent_ach/model.py +174 -0
- clarent/_methods/ach/clarent_ach/render.py +72 -0
- clarent/_methods/ach/examples/flaky-test.es.json +156 -0
- clarent/_methods/ach/examples/flaky-test.json +156 -0
- clarent/_methods/ach/method.toml +43 -0
- clarent/_methods/ach/skill/SKILL.md +58 -0
- clarent/_methods/ach/tests/test_ach.py +231 -0
- clarent/_methods/redteam/CARD.md +66 -0
- clarent/_methods/redteam/clarent_redteam/__init__.py +6 -0
- clarent/_methods/redteam/clarent_redteam/__main__.py +5 -0
- clarent/_methods/redteam/clarent_redteam/catalog.py +192 -0
- clarent/_methods/redteam/clarent_redteam/cli.py +189 -0
- clarent/_methods/redteam/clarent_redteam/engine.py +281 -0
- clarent/_methods/redteam/clarent_redteam/i18n.py +199 -0
- clarent/_methods/redteam/clarent_redteam/model.py +320 -0
- clarent/_methods/redteam/clarent_redteam/render.py +103 -0
- clarent/_methods/redteam/examples/design-doc/design.es.md +27 -0
- clarent/_methods/redteam/examples/design-doc/design.md +27 -0
- clarent/_methods/redteam/examples/design-doc/findings.es.json +132 -0
- clarent/_methods/redteam/examples/design-doc/findings.json +132 -0
- clarent/_methods/redteam/examples/design-doc/findings.rejected.json +130 -0
- clarent/_methods/redteam/examples/pr/change.diff +34 -0
- clarent/_methods/redteam/examples/pr/description.md +13 -0
- clarent/_methods/redteam/examples/pr/findings.json +114 -0
- clarent/_methods/redteam/method.toml +43 -0
- clarent/_methods/redteam/skill/SKILL.md +52 -0
- clarent/_methods/redteam/tests/test_redteam.py +640 -0
- clarent/_methods/triz-matrix/CARD.md +50 -0
- clarent/_methods/triz-matrix/clarent_triz/__init__.py +6 -0
- clarent/_methods/triz-matrix/clarent_triz/__main__.py +5 -0
- clarent/_methods/triz-matrix/clarent_triz/cli.py +184 -0
- clarent/_methods/triz-matrix/clarent_triz/data/DATA_LICENSE.md +51 -0
- clarent/_methods/triz-matrix/clarent_triz/data/catalog.json +89 -0
- clarent/_methods/triz-matrix/clarent_triz/data/matrix.json +11920 -0
- clarent/_methods/triz-matrix/clarent_triz/engine.py +103 -0
- clarent/_methods/triz-matrix/clarent_triz/i18n.py +134 -0
- clarent/_methods/triz-matrix/clarent_triz/model.py +179 -0
- clarent/_methods/triz-matrix/clarent_triz/render.py +101 -0
- clarent/_methods/triz-matrix/examples/search-api.es.json +9 -0
- clarent/_methods/triz-matrix/examples/search-api.json +9 -0
- clarent/_methods/triz-matrix/method.toml +58 -0
- clarent/_methods/triz-matrix/skill/SKILL.md +50 -0
- clarent/_methods/triz-matrix/tests/test_triz.py +306 -0
- clarent/cli.py +95 -0
- clarent/registry.py +175 -0
- clarent_methods-0.1.0.dist-info/METADATA +227 -0
- clarent_methods-0.1.0.dist-info/RECORD +59 -0
- clarent_methods-0.1.0.dist-info/WHEEL +4 -0
- clarent_methods-0.1.0.dist-info/entry_points.txt +2 -0
- clarent_methods-0.1.0.dist-info/licenses/LICENSE +202 -0
- clarent_methods-0.1.0.dist-info/licenses/NOTICE +12 -0
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Red team command line. Two ways to use it:
|
|
2
|
+
- standalone: python -m clarent_redteam check findings.json
|
|
3
|
+
- via core: clarent redteam check findings.json (the core calls `register`)
|
|
4
|
+
|
|
5
|
+
Exit codes: 0 ok · 1 something actionable (a finding was rejected, --fail-on reached, --strict with warnings) · 2 invalid input.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from . import engine, i18n, render
|
|
16
|
+
from .catalog import CATALOG, CLASSES, RUBRIC, SEVERITY_ORDER, at_least
|
|
17
|
+
from .i18n import t
|
|
18
|
+
from .model import MIN_QUOTE_CHARS, SCHEMA, RedTeamError, parse
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _load(a):
|
|
22
|
+
try:
|
|
23
|
+
data = json.loads(Path(a.path).read_text(encoding="utf-8"))
|
|
24
|
+
except FileNotFoundError:
|
|
25
|
+
raise RedTeamError(t("err_no_file", path=a.path))
|
|
26
|
+
except json.JSONDecodeError as e:
|
|
27
|
+
raise RedTeamError(t("err_bad_json", path=a.path, e=e))
|
|
28
|
+
root = Path(a.root) if getattr(a, "root", None) else None
|
|
29
|
+
return parse(data, Path(a.path).resolve().parent, root=root, targets=getattr(a, "target", None) or None)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _add_common(p: argparse.ArgumentParser) -> None:
|
|
33
|
+
p.add_argument("path", help="findings file (JSON)")
|
|
34
|
+
p.add_argument("--target", action="append", metavar="FILE",
|
|
35
|
+
help="read this file as the target instead of target.files (repeatable)")
|
|
36
|
+
p.add_argument("--root", help="folder where file:line refs are resolved (default: the file's \"root\", else its own folder)")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def register(sub: argparse._SubParsersAction) -> None:
|
|
40
|
+
"""Register the subcommands on a parser (core or standalone)."""
|
|
41
|
+
p = sub.add_parser("init", help="create a findings template for a target file")
|
|
42
|
+
p.add_argument("path")
|
|
43
|
+
p.add_argument("--target", required=True, metavar="FILE", help="the design doc, description or diff to attack")
|
|
44
|
+
p.add_argument("--kind", choices=("design", "pr"), default="design")
|
|
45
|
+
p.add_argument("--force", action="store_true")
|
|
46
|
+
p.set_defaults(func=_init)
|
|
47
|
+
|
|
48
|
+
p = sub.add_parser("validate", help="parse the file and say which findings the engine would reject")
|
|
49
|
+
_add_common(p)
|
|
50
|
+
p.set_defaults(func=_validate)
|
|
51
|
+
|
|
52
|
+
p = sub.add_parser("check", help="reject unbacked findings, score the rest and print the report")
|
|
53
|
+
_add_common(p)
|
|
54
|
+
p.add_argument("--format", choices=("md", "json"), default="md")
|
|
55
|
+
p.add_argument("--out", help="write the report to this file")
|
|
56
|
+
p.add_argument("--strict", action="store_true", help="exit 1 also when there are warnings")
|
|
57
|
+
p.add_argument("--fail-on", metavar="S1|S2|S3|S4", help="exit 1 if an accepted attack is at least this severe")
|
|
58
|
+
p.set_defaults(func=_check)
|
|
59
|
+
|
|
60
|
+
p = sub.add_parser("top", help="print only the top attacks, one line each")
|
|
61
|
+
_add_common(p)
|
|
62
|
+
p.set_defaults(func=_top)
|
|
63
|
+
|
|
64
|
+
p = sub.add_parser("catalog", help="print the fixed attack classes, their guiding questions and the rating scales")
|
|
65
|
+
p.set_defaults(func=_catalog)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _out(text: str) -> None:
|
|
69
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
70
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
71
|
+
print(text)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _init(a) -> int:
|
|
75
|
+
path = Path(a.path)
|
|
76
|
+
if path.exists() and not a.force:
|
|
77
|
+
print("error: " + t("err_exists", path=path), file=sys.stderr)
|
|
78
|
+
return 2
|
|
79
|
+
tgt = Path(a.target)
|
|
80
|
+
try:
|
|
81
|
+
text = tgt.read_text(encoding="utf-8", errors="replace")
|
|
82
|
+
except OSError:
|
|
83
|
+
raise RedTeamError(t("target_missing", path=a.target))
|
|
84
|
+
quote = next((" ".join(l.split()) for l in text.splitlines() if len(" ".join(l.split())) >= MIN_QUOTE_CHARS), "")
|
|
85
|
+
if not quote:
|
|
86
|
+
raise RedTeamError(t("init_no_quote", path=a.target, n=MIN_QUOTE_CHARS))
|
|
87
|
+
# root = the folder refs and target paths are resolved from: the current folder when the target is inside it
|
|
88
|
+
# (the usual case: findings under .clarent/redteam/, run from the repo root), else the target's own folder.
|
|
89
|
+
here = Path.cwd().resolve()
|
|
90
|
+
try:
|
|
91
|
+
tgt.resolve().relative_to(here)
|
|
92
|
+
root_abs = here
|
|
93
|
+
except ValueError:
|
|
94
|
+
root_abs = tgt.resolve().parent
|
|
95
|
+
try:
|
|
96
|
+
root = os.path.relpath(root_abs, path.resolve().parent).replace("\\", "/")
|
|
97
|
+
except ValueError: # different drive on Windows
|
|
98
|
+
root = str(root_abs)
|
|
99
|
+
rel = tgt.resolve().relative_to(root_abs).as_posix()
|
|
100
|
+
data = {
|
|
101
|
+
"schema": SCHEMA,
|
|
102
|
+
"title": t("t_title"),
|
|
103
|
+
"root": root,
|
|
104
|
+
"target": {"kind": a.kind, "files": [rel]},
|
|
105
|
+
"assumptions": [{"id": "A1", "text": t("t_assumption"), "quote": quote, "status": "unverified",
|
|
106
|
+
"check": t("t_check")}],
|
|
107
|
+
"attacks": [{"id": "X1", "class": "failure-modes", "assumption": "A1", "quote": quote, "attack": t("t_attack"),
|
|
108
|
+
"impact": 3, "plausibility": 3, "check": t("t_check")}],
|
|
109
|
+
"skipped_classes": [],
|
|
110
|
+
}
|
|
111
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
112
|
+
path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
113
|
+
print(t("template_created", path=path))
|
|
114
|
+
return 0
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _validate(a) -> int:
|
|
118
|
+
f = _load(a)
|
|
119
|
+
res = engine.analyze(f)
|
|
120
|
+
for w in res.warnings:
|
|
121
|
+
print("warning: " + w)
|
|
122
|
+
for r in res.rejections:
|
|
123
|
+
print(f"rejected {t('kind_' + r.kind)} {r.id}: {r.detail}")
|
|
124
|
+
print(t("valid_ok", a=len(res.assumptions), x=len(res.attacks), r=len(res.rejections)))
|
|
125
|
+
return 1 if res.rejections else 0
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _check(a) -> int:
|
|
129
|
+
if a.fail_on and a.fail_on.upper() not in SEVERITY_ORDER:
|
|
130
|
+
raise RedTeamError(t("err_bad_severity"))
|
|
131
|
+
f = _load(a)
|
|
132
|
+
res = engine.analyze(f)
|
|
133
|
+
out = (json.dumps(engine.to_dict(res, f.title), indent=2, ensure_ascii=False)
|
|
134
|
+
if a.format == "json" else render.markdown(f, res))
|
|
135
|
+
if a.out:
|
|
136
|
+
Path(a.out).write_text(out, encoding="utf-8")
|
|
137
|
+
print(t("report_written", path=a.out))
|
|
138
|
+
else:
|
|
139
|
+
_out(out)
|
|
140
|
+
code = 1 if res.rejections else 0
|
|
141
|
+
if a.strict and res.warnings:
|
|
142
|
+
code = 1
|
|
143
|
+
if a.fail_on and any(at_least(x.severity, a.fail_on.upper()) for x in res.attacks):
|
|
144
|
+
code = 1
|
|
145
|
+
return code
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _top(a) -> int:
|
|
149
|
+
f = _load(a)
|
|
150
|
+
res = engine.analyze(f)
|
|
151
|
+
if not res.top:
|
|
152
|
+
print(t("top_none"))
|
|
153
|
+
return 1
|
|
154
|
+
for x in res.top:
|
|
155
|
+
print(t("top_line", rank=x.rank, id=x.id, sev=x.severity, risk=x.risk, cls=x.class_id, text=x.text))
|
|
156
|
+
return 1 if res.rejections else 0
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _catalog(a) -> int:
|
|
160
|
+
lang = i18n.get_lang()
|
|
161
|
+
L = []
|
|
162
|
+
for i, c in enumerate(CLASSES, 1):
|
|
163
|
+
e = CATALOG[c]
|
|
164
|
+
L.append(t("catalog_head", i=i, id=c, name=e[lang]["name"], origin=e["origin"]))
|
|
165
|
+
L.append(" " + e[lang]["question"])
|
|
166
|
+
L += [" - " + p for p in e[lang]["prompts"]]
|
|
167
|
+
L.append(t("catalog_source", pages=e["pages"]))
|
|
168
|
+
for key in ("impact", "plausibility"):
|
|
169
|
+
L += ["", t("rubric_head", key=key)]
|
|
170
|
+
L += [f" {n}: {txt}" for n, txt in RUBRIC[key][lang].items()]
|
|
171
|
+
_out("\n".join(L))
|
|
172
|
+
return 0
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def main(argv: list[str] | None = None) -> int:
|
|
176
|
+
ap = argparse.ArgumentParser(prog="clarent-redteam", description="Red team: attack a design or a PR with a fixed catalog")
|
|
177
|
+
ap.add_argument("--lang", choices=sorted(i18n.M), default=i18n.get_lang(),
|
|
178
|
+
help="output language (default: $CLARENT_LANG or en)")
|
|
179
|
+
register(ap.add_subparsers(dest="cmd", required=True))
|
|
180
|
+
args = ap.parse_args(argv)
|
|
181
|
+
i18n.set_lang(args.lang)
|
|
182
|
+
for stream in (sys.stdout, sys.stderr):
|
|
183
|
+
if hasattr(stream, "reconfigure"):
|
|
184
|
+
stream.reconfigure(encoding="utf-8")
|
|
185
|
+
try:
|
|
186
|
+
return args.func(args)
|
|
187
|
+
except RedTeamError as e:
|
|
188
|
+
print(f"error: {e}", file=sys.stderr)
|
|
189
|
+
return 2
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""The deterministic core: reject what cannot be backed, score what can, and list what to verify next.
|
|
2
|
+
|
|
3
|
+
What the engine does, in order (no LLM involved anywhere):
|
|
4
|
+
|
|
5
|
+
1. **Anchor.** Every assumption and every attack must quote a passage that appears *literally* in the target
|
|
6
|
+
(whitespace is ignored, nothing else). No quote, a quote that is too short, or a quote that is not there: rejected.
|
|
7
|
+
2. **Back the status.** `verified` and `contradicted` need at least one evidence item. A `file:line` ref must point at
|
|
8
|
+
a line that exists. Anything else a model wrote is free text (a command, a log excerpt) and is only required to be
|
|
9
|
+
non-empty: the engine cannot run it, and the report says so.
|
|
10
|
+
3. **Cascade and de-duplicate.** An attack on a rejected assumption is rejected. Two attacks of the same class on the
|
|
11
|
+
same assumption with near-identical text count once.
|
|
12
|
+
4. **Score.** `risk = impact x effective plausibility`, both on 1..5. The assumption's status moves plausibility:
|
|
13
|
+
`contradicted` -> 5 (the premise is already false); `verified` -> at most 2 (the premise holds); `unverified` -> as rated.
|
|
14
|
+
Severity bands S1..S4 and every constant are Clarent's parametrization.
|
|
15
|
+
5. **Report.** Assumption matrix (assumption x attack class), the top 3 attacks, what to verify next, class coverage.
|
|
16
|
+
|
|
17
|
+
The engine never judges whether an attack is *right*; it judges whether it is *anchored and backed*.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import re
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
|
|
24
|
+
from .catalog import CATALOG, CLASSES, SEVERITY_ORDER, severity
|
|
25
|
+
from .i18n import t
|
|
26
|
+
from .model import MIN_QUOTE_CHARS, Assumption, Attack, Findings, check_ref, find_quote
|
|
27
|
+
|
|
28
|
+
TOP_N = 3
|
|
29
|
+
DUPLICATE_JACCARD = 0.8
|
|
30
|
+
FEW_ASSUMPTIONS = 3
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Rejection:
|
|
35
|
+
kind: str # 'assumption' | 'attack'
|
|
36
|
+
id: str
|
|
37
|
+
code: str
|
|
38
|
+
detail: str
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class AssumptionRow:
|
|
43
|
+
id: str
|
|
44
|
+
text: str
|
|
45
|
+
status: str
|
|
46
|
+
where: str # file:line of the anchoring quote
|
|
47
|
+
evidence: tuple[tuple[str, str], ...]
|
|
48
|
+
attacks_by_class: dict[str, tuple[str, ...]]
|
|
49
|
+
max_risk: int
|
|
50
|
+
check: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class AttackRow:
|
|
55
|
+
rank: int
|
|
56
|
+
id: str
|
|
57
|
+
class_id: str
|
|
58
|
+
assumption: str
|
|
59
|
+
assumption_status: str
|
|
60
|
+
impact: int
|
|
61
|
+
plausibility: int
|
|
62
|
+
effective_plausibility: int
|
|
63
|
+
risk: int
|
|
64
|
+
severity: str
|
|
65
|
+
where: str
|
|
66
|
+
quote: str
|
|
67
|
+
text: str
|
|
68
|
+
check: str
|
|
69
|
+
evidence_count: int
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class Coverage:
|
|
74
|
+
class_id: str
|
|
75
|
+
attack_ids: tuple[str, ...]
|
|
76
|
+
skipped_reason: str # '' if not skipped
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class VerifyNext:
|
|
81
|
+
assumption: str
|
|
82
|
+
text: str
|
|
83
|
+
max_risk: int
|
|
84
|
+
check: str
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class Result:
|
|
89
|
+
assumptions: list[AssumptionRow] = field(default_factory=list)
|
|
90
|
+
attacks: list[AttackRow] = field(default_factory=list)
|
|
91
|
+
top: list[AttackRow] = field(default_factory=list)
|
|
92
|
+
rejections: list[Rejection] = field(default_factory=list)
|
|
93
|
+
coverage: list[Coverage] = field(default_factory=list)
|
|
94
|
+
verify_next: list[VerifyNext] = field(default_factory=list)
|
|
95
|
+
warnings: list[str] = field(default_factory=list)
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def worst_severity(self) -> str | None:
|
|
99
|
+
return min((a.severity for a in self.attacks), key=SEVERITY_ORDER.index, default=None)
|
|
100
|
+
|
|
101
|
+
def status_counts(self) -> dict[str, int]:
|
|
102
|
+
c = {"verified": 0, "unverified": 0, "contradicted": 0}
|
|
103
|
+
for a in self.assumptions:
|
|
104
|
+
c[a.status] += 1
|
|
105
|
+
return c
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# ------------------------------------------------------------------ helpers
|
|
109
|
+
def effective_plausibility(plausibility: int, status: str) -> int:
|
|
110
|
+
"""Move plausibility with the assumption's status (Clarent's rule, see module docstring)."""
|
|
111
|
+
if status == "contradicted":
|
|
112
|
+
return 5
|
|
113
|
+
if status == "verified":
|
|
114
|
+
return min(plausibility, 2)
|
|
115
|
+
return plausibility
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _words(s: str) -> set[str]:
|
|
119
|
+
return set(re.findall(r"\w+", s.lower()))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _jaccard(a: str, b: str) -> float:
|
|
123
|
+
wa, wb = _words(a), _words(b)
|
|
124
|
+
return len(wa & wb) / len(wa | wb) if wa | wb else 0.0
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _ref_problem(refs, root) -> str | None:
|
|
128
|
+
"""None if every evidence item is usable, else the reason (translated)."""
|
|
129
|
+
for e in refs:
|
|
130
|
+
if not e.ref or not e.observation:
|
|
131
|
+
return t("r_ref_invalid", ref=e.ref or "—", why=t("why_empty"))
|
|
132
|
+
ok, why = check_ref(e.ref, root)
|
|
133
|
+
if not ok:
|
|
134
|
+
key, _, n = why.partition(":")
|
|
135
|
+
return t("r_ref_invalid", ref=e.ref, why=t(key, n=n) if n else t(key))
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _anchor(quote: str, f: Findings) -> tuple[str, str]:
|
|
140
|
+
"""Return (where, '') if the quote anchors in the target, else ('', rejection code)."""
|
|
141
|
+
if not quote:
|
|
142
|
+
return "", "quote_missing"
|
|
143
|
+
if len(" ".join(quote.split())) < MIN_QUOTE_CHARS:
|
|
144
|
+
return "", "quote_short"
|
|
145
|
+
hit = find_quote(f.files, quote)
|
|
146
|
+
if hit is None:
|
|
147
|
+
return "", "quote_not_found"
|
|
148
|
+
return f"{hit[0]}:{hit[1]}", ""
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _reject_msg(code: str, quote: str) -> str:
|
|
152
|
+
if code == "quote_short":
|
|
153
|
+
return t("r_quote_short", n=len(" ".join(quote.split())), min=MIN_QUOTE_CHARS)
|
|
154
|
+
return t("r_" + code)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# ------------------------------------------------------------------ analysis
|
|
158
|
+
def analyze(f: Findings) -> Result:
|
|
159
|
+
res = Result()
|
|
160
|
+
rej = res.rejections
|
|
161
|
+
|
|
162
|
+
# 1-2. assumptions
|
|
163
|
+
good_a: dict[str, tuple[Assumption, str]] = {}
|
|
164
|
+
for a in f.assumptions:
|
|
165
|
+
where, code = _anchor(a.quote, f)
|
|
166
|
+
if code:
|
|
167
|
+
rej.append(Rejection("assumption", a.id, code, _reject_msg(code, a.quote)))
|
|
168
|
+
continue
|
|
169
|
+
problem = _ref_problem(a.evidence, f.root)
|
|
170
|
+
if problem:
|
|
171
|
+
rej.append(Rejection("assumption", a.id, "ref_invalid", problem))
|
|
172
|
+
continue
|
|
173
|
+
if a.status in ("verified", "contradicted") and not a.evidence:
|
|
174
|
+
rej.append(Rejection("assumption", a.id, "no_evidence", t("r_no_evidence", status=a.status)))
|
|
175
|
+
continue
|
|
176
|
+
good_a[a.id] = (a, where)
|
|
177
|
+
|
|
178
|
+
# 1-3. attacks
|
|
179
|
+
accepted: list[Attack] = []
|
|
180
|
+
where_of: dict[str, str] = {}
|
|
181
|
+
for x in f.attacks:
|
|
182
|
+
if x.assumption not in good_a:
|
|
183
|
+
rej.append(Rejection("attack", x.id, "assumption_rejected", t("r_assumption_rejected", aid=x.assumption)))
|
|
184
|
+
continue
|
|
185
|
+
where, code = _anchor(x.quote, f)
|
|
186
|
+
if code:
|
|
187
|
+
rej.append(Rejection("attack", x.id, code, _reject_msg(code, x.quote)))
|
|
188
|
+
continue
|
|
189
|
+
problem = _ref_problem(x.evidence, f.root)
|
|
190
|
+
if problem:
|
|
191
|
+
rej.append(Rejection("attack", x.id, "ref_invalid", problem))
|
|
192
|
+
continue
|
|
193
|
+
if not x.check:
|
|
194
|
+
rej.append(Rejection("attack", x.id, "check_missing", t("r_check_missing")))
|
|
195
|
+
continue
|
|
196
|
+
twin = next((y for y in accepted if y.class_id == x.class_id and y.assumption == x.assumption
|
|
197
|
+
and _jaccard(y.text, x.text) >= DUPLICATE_JACCARD), None)
|
|
198
|
+
if twin is not None:
|
|
199
|
+
rej.append(Rejection("attack", x.id, "duplicate", t("r_duplicate", other=twin.id)))
|
|
200
|
+
continue
|
|
201
|
+
accepted.append(x)
|
|
202
|
+
where_of[x.id] = where
|
|
203
|
+
|
|
204
|
+
# 4. score
|
|
205
|
+
scored = []
|
|
206
|
+
for x in accepted:
|
|
207
|
+
a, _ = good_a[x.assumption]
|
|
208
|
+
eff = effective_plausibility(x.plausibility, a.status)
|
|
209
|
+
risk = x.impact * eff
|
|
210
|
+
scored.append((x, a.status, eff, risk))
|
|
211
|
+
scored.sort(key=lambda s: (-s[3], -s[0].impact, -len(s[0].evidence), s[0].id))
|
|
212
|
+
for i, (x, status, eff, risk) in enumerate(scored, 1):
|
|
213
|
+
res.attacks.append(AttackRow(i, x.id, x.class_id, x.assumption, status, x.impact, x.plausibility, eff, risk,
|
|
214
|
+
severity(risk), where_of[x.id], x.quote, x.text, x.check, len(x.evidence)))
|
|
215
|
+
res.top = res.attacks[:TOP_N]
|
|
216
|
+
|
|
217
|
+
# 5. matrix, coverage, verify-next
|
|
218
|
+
for a in f.assumptions:
|
|
219
|
+
if a.id not in good_a:
|
|
220
|
+
continue
|
|
221
|
+
_, where = good_a[a.id]
|
|
222
|
+
mine = [r for r in res.attacks if r.assumption == a.id]
|
|
223
|
+
by_class = {c: tuple(r.id for r in mine if r.class_id == c) for c in CLASSES}
|
|
224
|
+
res.assumptions.append(AssumptionRow(a.id, a.text, a.status, where, tuple((e.ref, e.observation) for e in a.evidence),
|
|
225
|
+
by_class, max((r.risk for r in mine), default=0), a.check))
|
|
226
|
+
skipped = {s.class_id: s.reason for s in f.skipped}
|
|
227
|
+
for c in CLASSES:
|
|
228
|
+
ids = tuple(r.id for r in res.attacks if r.class_id == c)
|
|
229
|
+
res.coverage.append(Coverage(c, ids, skipped.get(c, "")))
|
|
230
|
+
for row in sorted((r for r in res.assumptions if r.status == "unverified" and r.max_risk),
|
|
231
|
+
key=lambda r: (-r.max_risk, r.id)):
|
|
232
|
+
res.verify_next.append(VerifyNext(row.id, row.text, row.max_risk, row.check))
|
|
233
|
+
|
|
234
|
+
_warnings(f, res)
|
|
235
|
+
return res
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _warnings(f: Findings, res: Result) -> None:
|
|
239
|
+
w = res.warnings
|
|
240
|
+
w.extend(f.warnings)
|
|
241
|
+
lang_name = lambda c: _name(c)
|
|
242
|
+
for cov in res.coverage:
|
|
243
|
+
if not cov.attack_ids and not cov.skipped_reason:
|
|
244
|
+
w.append(t("w_class_uncovered", name=lang_name(cov.class_id)))
|
|
245
|
+
if cov.attack_ids and cov.skipped_reason:
|
|
246
|
+
w.append(t("w_skip_and_attacks", name=lang_name(cov.class_id)))
|
|
247
|
+
for a in res.assumptions:
|
|
248
|
+
if not any(a.attacks_by_class.values()):
|
|
249
|
+
w.append(t("w_unattacked", aid=a.id))
|
|
250
|
+
if a.status == "unverified" and not a.check:
|
|
251
|
+
w.append(t("w_unverified_no_check", aid=a.id))
|
|
252
|
+
if len(res.assumptions) < FEW_ASSUMPTIONS:
|
|
253
|
+
w.append(t("w_few_assumptions", n=len(res.assumptions)))
|
|
254
|
+
if len(res.attacks) < TOP_N:
|
|
255
|
+
w.append(t("w_few_attacks", n=len(res.attacks)))
|
|
256
|
+
shaky = sorted({r.assumption for r in res.top if r.assumption_status == "unverified"})
|
|
257
|
+
if shaky:
|
|
258
|
+
w.append(t("w_top_unverified", ids=", ".join(shaky)))
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _name(class_id: str) -> str:
|
|
262
|
+
from .i18n import get_lang
|
|
263
|
+
return CATALOG[class_id][get_lang()]["name"]
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def to_dict(res: Result, title: str = "") -> dict:
|
|
267
|
+
"""Stable JSON form (schema clarent.redteam.report/1)."""
|
|
268
|
+
return {
|
|
269
|
+
"schema": "clarent.redteam.report/1",
|
|
270
|
+
"title": title,
|
|
271
|
+
"counts": {**res.status_counts(), "attacks": len(res.attacks), "rejected": len(res.rejections)},
|
|
272
|
+
"worst_severity": res.worst_severity,
|
|
273
|
+
"top": [r.id for r in res.top],
|
|
274
|
+
"attacks": [vars(r) for r in res.attacks],
|
|
275
|
+
"assumptions": [{**vars(r), "evidence": [list(e) for e in r.evidence]} for r in res.assumptions],
|
|
276
|
+
"coverage": [{"class": c.class_id, "attacks": list(c.attack_ids), "skipped_reason": c.skipped_reason}
|
|
277
|
+
for c in res.coverage],
|
|
278
|
+
"verify_next": [vars(v) for v in res.verify_next],
|
|
279
|
+
"rejected": [vars(r) for r in res.rejections],
|
|
280
|
+
"warnings": list(res.warnings),
|
|
281
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Mensajes en inglés (por defecto) y español. Idioma: --lang, o CLARENT_LANG, o 'en'."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
_LANG = os.environ.get("CLARENT_LANG", "en")
|
|
7
|
+
|
|
8
|
+
M: dict[str, dict[str, str]] = {
|
|
9
|
+
"en": {
|
|
10
|
+
# --- input errors (exit 2)
|
|
11
|
+
"root_not_object": "the file root must be a JSON object",
|
|
12
|
+
"bad_schema": "unsupported 'schema' {got!r}; this version reads 'clarent.redteam/1'",
|
|
13
|
+
"bad_kind": "target.kind must be 'design' or 'pr' (got {v!r})",
|
|
14
|
+
"no_target": "no target: set target.files in the file or pass --target FILE",
|
|
15
|
+
"target_not_list": "target.files must be a non-empty list of file paths",
|
|
16
|
+
"target_missing": "target file not found: {path}",
|
|
17
|
+
"target_outside": "target path {path!r} points outside the root {root}",
|
|
18
|
+
"target_big": "target file {path} is larger than {mb} MB",
|
|
19
|
+
"target_unreadable": "cannot read target file {path}: {e}",
|
|
20
|
+
"need_list": "'{key}' must be a non-empty list",
|
|
21
|
+
"missing_field": "{where}: missing required field '{key}'",
|
|
22
|
+
"dup_id": "{where}: duplicate id {id!r}",
|
|
23
|
+
"bad_class": "{where}: 'class' must be one of {allowed} (got {v!r})",
|
|
24
|
+
"bad_status": "{where}: 'status' must be one of {allowed} (got {v!r})",
|
|
25
|
+
"bad_rating": "{where}: '{key}' must be an integer from 1 to 5 (got {v!r})",
|
|
26
|
+
"unknown_assumption": "{where}: refers to unknown assumption {aid!r}",
|
|
27
|
+
"not_object": "{where}: must be a JSON object",
|
|
28
|
+
"evidence_not_list": "{where}: 'evidence' must be a list of {{ref, observation}}",
|
|
29
|
+
"err_no_file": "file not found: {path}", "err_bad_json": "invalid JSON in {path}: {e}",
|
|
30
|
+
"err_exists": "{path} already exists (use --force)", "err_bad_lang": "unsupported language {lang!r}",
|
|
31
|
+
"err_bad_severity": "--fail-on must be one of S1, S2, S3, S4",
|
|
32
|
+
"template_created": "template created: {path} (edit it, then run: validate / check)",
|
|
33
|
+
"init_no_quote": "target {path} has no line of at least {n} characters to use as a placeholder quote",
|
|
34
|
+
# --- parse warnings
|
|
35
|
+
"w_skip_no_reason": "class {name!r} is listed in skipped_classes without a reason: it counts as not covered",
|
|
36
|
+
# --- rejection reasons (engine)
|
|
37
|
+
"r_quote_missing": "no 'quote': a finding must be anchored to a literal passage of the target",
|
|
38
|
+
"r_quote_short": "the quote has {n} characters; at least {min} are required to anchor a finding",
|
|
39
|
+
"r_quote_not_found": "the quote does not appear in the target (compared literally, ignoring only whitespace)",
|
|
40
|
+
"r_ref_invalid": "evidence ref {ref!r} is not valid: {why}",
|
|
41
|
+
"why_empty": "empty ref or observation",
|
|
42
|
+
"why_not_found": "file not found",
|
|
43
|
+
"why_outside": "path leaves the root",
|
|
44
|
+
"why_line": "line out of range (the file has {n} lines)",
|
|
45
|
+
"r_no_evidence": "status '{status}' needs at least one evidence item with a ref and an observation",
|
|
46
|
+
"r_check_missing": "no 'check': say how to verify this attack (a command or a concrete question)",
|
|
47
|
+
"r_duplicate": "duplicate of {other} (same class and assumption, near-identical text)",
|
|
48
|
+
"r_assumption_rejected": "its assumption {aid} was rejected",
|
|
49
|
+
"kind_assumption": "assumption", "kind_attack": "attack",
|
|
50
|
+
# --- warnings (engine)
|
|
51
|
+
"w_class_uncovered": "class '{name}' has no accepted attack and is not in skipped_classes: apply it or say why it does not apply.",
|
|
52
|
+
"w_skip_and_attacks": "class '{name}' is skipped and also has attacks: remove one of the two.",
|
|
53
|
+
"w_unattacked": "assumption {aid} has no accepted attack.",
|
|
54
|
+
"w_few_assumptions": "Only {n} accepted assumptions: a key assumptions check usually finds more.",
|
|
55
|
+
"w_few_attacks": "Only {n} accepted attacks: the top list has fewer than 3 entries.",
|
|
56
|
+
"w_unverified_no_check": "assumption {aid} is unverified and has no 'check' (how to verify it).",
|
|
57
|
+
"w_top_unverified": "Top attacks rest on unverified assumptions ({ids}): verify them first (see 'Verify next').",
|
|
58
|
+
# --- report
|
|
59
|
+
"h_title": "Red team: {title}",
|
|
60
|
+
"target_line": "**Target ({kind}):** {files}",
|
|
61
|
+
"h_summary": "Summary",
|
|
62
|
+
"s_assumptions": "Assumptions: {n} accepted ({v} verified, {u} unverified, {c} contradicted).",
|
|
63
|
+
"s_attacks": "Attacks: {n} accepted, ranked by risk = impact × plausibility.",
|
|
64
|
+
"s_severity": "Highest severity: {sev}.",
|
|
65
|
+
"s_none_severity": "No accepted attacks.",
|
|
66
|
+
"s_rejected": "⚠ **{n} finding(s) rejected** (see Rejected findings): the engine does not count them.",
|
|
67
|
+
"not_probability": "Risk is a prioritization score, **not a probability**.",
|
|
68
|
+
"h_top": "Top {n} attacks by impact",
|
|
69
|
+
"h_matrix": "Assumption matrix",
|
|
70
|
+
"h_verify": "Verify next",
|
|
71
|
+
"verify_line": "**{aid}** {text} (highest linked risk {risk}) — {check}",
|
|
72
|
+
"verify_none": "No unverified assumption has an accepted attack.",
|
|
73
|
+
"h_attacks": "All accepted attacks",
|
|
74
|
+
"h_coverage": "Class coverage",
|
|
75
|
+
"h_rejected": "Rejected findings",
|
|
76
|
+
"h_warnings": "Warnings",
|
|
77
|
+
"col_rank": "#", "col_attack": "Attack", "col_class": "Class", "col_assumption": "Assumption",
|
|
78
|
+
"col_risk": "Risk", "col_sev": "Sev.", "col_where": "Where", "col_check": "How to check",
|
|
79
|
+
"col_status": "Status", "col_evidence": "Evidence", "col_id": "ID", "col_reason": "Reason",
|
|
80
|
+
"col_kind": "Kind", "col_impact": "Impact", "col_plaus": "Plausibility",
|
|
81
|
+
"status_verified": "verified", "status_unverified": "unverified", "status_contradicted": "contradicted",
|
|
82
|
+
"cov_attacks": "{n} attack(s): {ids}",
|
|
83
|
+
"cov_skipped": "skipped — {reason}",
|
|
84
|
+
"cov_uncovered": "NOT COVERED",
|
|
85
|
+
"plaus_note": "plausibility {p} → {e} (assumption {status})",
|
|
86
|
+
"footer": ("_Generated by Clarent · red team (UFMCS Red Team Handbook techniques; the six attack classes, "
|
|
87
|
+
"rating scales and severity bands are Clarent's parametrization)._"),
|
|
88
|
+
# --- cli
|
|
89
|
+
"valid_ok": "ok: {a} assumptions and {x} attacks accepted, {r} rejected",
|
|
90
|
+
"top_line": "{rank}. {id} [{sev} risk={risk}] ({cls}) {text}",
|
|
91
|
+
"top_none": "no accepted attacks",
|
|
92
|
+
"catalog_head": "{i}. {id} — {name} [{origin}]",
|
|
93
|
+
"catalog_source": " source: {pages}",
|
|
94
|
+
"rubric_head": "{key} (1-5):",
|
|
95
|
+
"t_title": "Describe the design or the change", "t_assumption": "A thing the text takes for granted",
|
|
96
|
+
"t_attack": "What goes wrong if that assumption is false", "t_check": "A command or a concrete question that settles it",
|
|
97
|
+
"report_written": "report written to {path}",
|
|
98
|
+
},
|
|
99
|
+
"es": {
|
|
100
|
+
"root_not_object": "la raíz del archivo debe ser un objeto JSON",
|
|
101
|
+
"bad_schema": "'schema' {got!r} no soportado; esta versión lee 'clarent.redteam/1'",
|
|
102
|
+
"bad_kind": "target.kind debe ser 'design' o 'pr' (recibido: {v!r})",
|
|
103
|
+
"no_target": "no hay objetivo: define target.files en el archivo o pasa --target ARCHIVO",
|
|
104
|
+
"target_not_list": "target.files debe ser una lista no vacía de rutas",
|
|
105
|
+
"target_missing": "no existe el archivo objetivo: {path}",
|
|
106
|
+
"target_outside": "la ruta objetivo {path!r} sale de la raíz {root}",
|
|
107
|
+
"target_big": "el archivo objetivo {path} pesa más de {mb} MB",
|
|
108
|
+
"target_unreadable": "no se puede leer el archivo objetivo {path}: {e}",
|
|
109
|
+
"need_list": "'{key}' debe ser una lista no vacía",
|
|
110
|
+
"missing_field": "{where}: falta el campo obligatorio '{key}'",
|
|
111
|
+
"dup_id": "{where}: id duplicado {id!r}",
|
|
112
|
+
"bad_class": "{where}: 'class' debe ser uno de {allowed} (recibido: {v!r})",
|
|
113
|
+
"bad_status": "{where}: 'status' debe ser uno de {allowed} (recibido: {v!r})",
|
|
114
|
+
"bad_rating": "{where}: '{key}' debe ser un entero de 1 a 5 (recibido: {v!r})",
|
|
115
|
+
"unknown_assumption": "{where}: se refiere a un supuesto inexistente {aid!r}",
|
|
116
|
+
"not_object": "{where}: debe ser un objeto JSON",
|
|
117
|
+
"evidence_not_list": "{where}: 'evidence' debe ser una lista de {{ref, observation}}",
|
|
118
|
+
"err_no_file": "no existe el archivo: {path}", "err_bad_json": "JSON inválido en {path}: {e}",
|
|
119
|
+
"err_exists": "{path} ya existe (usa --force)", "err_bad_lang": "idioma no soportado {lang!r}",
|
|
120
|
+
"err_bad_severity": "--fail-on debe ser S1, S2, S3 o S4",
|
|
121
|
+
"template_created": "plantilla creada: {path} (edítala y luego ejecuta: validate / check)",
|
|
122
|
+
"init_no_quote": "el objetivo {path} no tiene una línea de al menos {n} caracteres para usar como cita de ejemplo",
|
|
123
|
+
"w_skip_no_reason": "la clase {name!r} está en skipped_classes sin motivo: cuenta como no cubierta",
|
|
124
|
+
"r_quote_missing": "falta 'quote': un hallazgo debe anclarse a un pasaje literal del objetivo",
|
|
125
|
+
"r_quote_short": "la cita tiene {n} caracteres; se exigen al menos {min} para anclar un hallazgo",
|
|
126
|
+
"r_quote_not_found": "la cita no aparece en el objetivo (se compara literalmente, ignorando solo espacios en blanco)",
|
|
127
|
+
"r_ref_invalid": "la ref de evidencia {ref!r} no es válida: {why}",
|
|
128
|
+
"why_empty": "ref u observación vacía",
|
|
129
|
+
"why_not_found": "no existe el archivo",
|
|
130
|
+
"why_outside": "la ruta sale de la raíz",
|
|
131
|
+
"why_line": "línea fuera de rango (el archivo tiene {n} líneas)",
|
|
132
|
+
"r_no_evidence": "el estado '{status}' exige al menos una evidencia con ref y observación",
|
|
133
|
+
"r_check_missing": "falta 'check': indica cómo comprobar este ataque (un comando o una pregunta concreta)",
|
|
134
|
+
"r_duplicate": "duplicado de {other} (misma clase y supuesto, texto casi idéntico)",
|
|
135
|
+
"r_assumption_rejected": "su supuesto {aid} fue rechazado",
|
|
136
|
+
"kind_assumption": "supuesto", "kind_attack": "ataque",
|
|
137
|
+
"w_class_uncovered": "la clase '{name}' no tiene ataques aceptados y no está en skipped_classes: aplícala o explica por qué no aplica.",
|
|
138
|
+
"w_skip_and_attacks": "la clase '{name}' está omitida y además tiene ataques: quita una de las dos.",
|
|
139
|
+
"w_unattacked": "el supuesto {aid} no tiene ataques aceptados.",
|
|
140
|
+
"w_few_assumptions": "Solo {n} supuestos aceptados: una revisión de supuestos clave suele encontrar más.",
|
|
141
|
+
"w_few_attacks": "Solo {n} ataques aceptados: la lista de los principales tiene menos de 3 entradas.",
|
|
142
|
+
"w_unverified_no_check": "el supuesto {aid} está sin verificar y no tiene 'check' (cómo verificarlo).",
|
|
143
|
+
"w_top_unverified": "Los principales ataques descansan en supuestos sin verificar ({ids}): verifícalos primero (ver 'Verificar a continuación').",
|
|
144
|
+
"h_title": "Red team: {title}",
|
|
145
|
+
"target_line": "**Objetivo ({kind}):** {files}",
|
|
146
|
+
"h_summary": "Resumen",
|
|
147
|
+
"s_assumptions": "Supuestos: {n} aceptados ({v} verificados, {u} sin verificar, {c} contradichos).",
|
|
148
|
+
"s_attacks": "Ataques: {n} aceptados, ordenados por riesgo = impacto × plausibilidad.",
|
|
149
|
+
"s_severity": "Mayor severidad: {sev}.",
|
|
150
|
+
"s_none_severity": "No hay ataques aceptados.",
|
|
151
|
+
"s_rejected": "⚠ **{n} hallazgo(s) rechazado(s)** (ver Hallazgos rechazados): el motor no los cuenta.",
|
|
152
|
+
"not_probability": "El riesgo es un puntaje de priorización, **no una probabilidad**.",
|
|
153
|
+
"h_top": "Los {n} ataques de mayor impacto",
|
|
154
|
+
"h_matrix": "Matriz de supuestos",
|
|
155
|
+
"h_verify": "Verificar a continuación",
|
|
156
|
+
"verify_line": "**{aid}** {text} (mayor riesgo asociado {risk}) — {check}",
|
|
157
|
+
"verify_none": "Ningún supuesto sin verificar tiene ataques aceptados.",
|
|
158
|
+
"h_attacks": "Todos los ataques aceptados",
|
|
159
|
+
"h_coverage": "Cobertura por clase",
|
|
160
|
+
"h_rejected": "Hallazgos rechazados",
|
|
161
|
+
"h_warnings": "Advertencias",
|
|
162
|
+
"col_rank": "#", "col_attack": "Ataque", "col_class": "Clase", "col_assumption": "Supuesto",
|
|
163
|
+
"col_risk": "Riesgo", "col_sev": "Sev.", "col_where": "Dónde", "col_check": "Cómo comprobarlo",
|
|
164
|
+
"col_status": "Estado", "col_evidence": "Evidencia", "col_id": "ID", "col_reason": "Motivo",
|
|
165
|
+
"col_kind": "Tipo", "col_impact": "Impacto", "col_plaus": "Plausibilidad",
|
|
166
|
+
"status_verified": "verificado", "status_unverified": "sin verificar", "status_contradicted": "contradicho",
|
|
167
|
+
"cov_attacks": "{n} ataque(s): {ids}",
|
|
168
|
+
"cov_skipped": "omitida — {reason}",
|
|
169
|
+
"cov_uncovered": "SIN CUBRIR",
|
|
170
|
+
"plaus_note": "plausibilidad {p} → {e} (supuesto {status})",
|
|
171
|
+
"footer": ("_Generado por Clarent · red team (técnicas del Red Team Handbook de UFMCS; las seis clases de ataque, "
|
|
172
|
+
"las escalas y las bandas de severidad son parametrización de Clarent)._"),
|
|
173
|
+
"valid_ok": "ok: {a} supuestos y {x} ataques aceptados, {r} rechazados",
|
|
174
|
+
"top_line": "{rank}. {id} [{sev} riesgo={risk}] ({cls}) {text}",
|
|
175
|
+
"top_none": "no hay ataques aceptados",
|
|
176
|
+
"catalog_head": "{i}. {id} — {name} [{origin}]",
|
|
177
|
+
"catalog_source": " fuente: {pages}",
|
|
178
|
+
"rubric_head": "{key} (1-5):",
|
|
179
|
+
"t_title": "Describe el diseño o el cambio", "t_assumption": "Algo que el texto da por sentado",
|
|
180
|
+
"t_attack": "Qué sale mal si ese supuesto es falso", "t_check": "Un comando o una pregunta concreta que lo resuelva",
|
|
181
|
+
"report_written": "reporte escrito en {path}",
|
|
182
|
+
},
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def set_lang(lang: str) -> None:
|
|
187
|
+
global _LANG
|
|
188
|
+
if lang not in M:
|
|
189
|
+
raise ValueError(f"unsupported language {lang!r}; use one of {sorted(M)}")
|
|
190
|
+
_LANG = lang
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def get_lang() -> str:
|
|
194
|
+
return _LANG
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def t(key: str, /, **kw) -> str:
|
|
198
|
+
s = M[_LANG][key]
|
|
199
|
+
return s.format(**kw) if kw else s
|