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
clarent/__init__.py
ADDED
clarent/__main__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# ACH — Analysis of Competing Hypotheses — methodology card
|
|
2
|
+
|
|
3
|
+
## Origin
|
|
4
|
+
Created by Richards J. Heuer Jr. at the CIA to counter confirmation bias in intelligence analysis. Documented in *Psychology of Intelligence Analysis* (CIA Center for the Study of Intelligence, 1999), a collection of articles Heuer wrote between 1978 and 1986. The technique also appears in the UFMCS *Red Team Handbook* as a structured analytic technique.
|
|
5
|
+
|
|
6
|
+
## Sources
|
|
7
|
+
- Heuer, *Psychology of Intelligence Analysis*, CIA/CSI, 1999 — https://www.cia.gov/resources/csi/books-monographs/psychology-of-intelligence-analysis-2/ — `read` (landing page: author, year, 214-page PDF). The text itself was read in a copy hosted by IALEIA, https://www.ialeia.org/docs/Psychology_of_Intelligence_Analysis.pdf (not the CIA site): **Chapter 8 is "Analysis of Competing Hypotheses", p. 95**, and Heuer's preface calls it "arguably the most important single chapter".
|
|
8
|
+
- UFMCS *Red Team Handbook* v5 (15 Apr 2011): Key Assumptions Check p. 151, ACH p. 158 — `read` (table of contents).
|
|
9
|
+
- Heuer & Pherson, *Structured Analytic Techniques for Intelligence Analysis* — `exists`.
|
|
10
|
+
|
|
11
|
+
## Problem it solves
|
|
12
|
+
People pick the first plausible explanation and then collect evidence that fits it. ACH forces you to list rival explanations, test *all* evidence against *all* of them, and focus on what each hypothesis cannot explain.
|
|
13
|
+
|
|
14
|
+
## When to use / when NOT to use
|
|
15
|
+
- Use: a flaky test, an intermittent production error, or an incident with ≥ 3 plausible causes and conflicting signals.
|
|
16
|
+
- Do not use: the cause is already reproduced; the question is a choice between options (use a decision matrix) rather than an explanation.
|
|
17
|
+
|
|
18
|
+
## How it maps to software work
|
|
19
|
+
Hypotheses are candidate root causes; evidence is what you observed by running commands. Clarent adds (our adaptation, not Heuer's): a mandatory `ref` for observed evidence, a catch-all hypothesis that can never lead, and a ranking of *proposed* tests by how well they separate the hypotheses still alive.
|
|
20
|
+
|
|
21
|
+
## Inputs and outputs
|
|
22
|
+
- Input: `.clarent/ach/<slug>.json`, schema in `clarent_ach/model.py` (hypotheses, evidence with ratings `CC|C|N|I|II`, credibility, relevance, cost).
|
|
23
|
+
- Output: Markdown or JSON report with ranking, matrix, diagnosticity, sensitivity, next test, warnings.
|
|
24
|
+
- Example (3 lines): `clarent ach init .clarent/ach/flaky.json` → fill hypotheses and cited evidence → `clarent ach score .clarent/ach/flaky.json` prints the report and the test to run next.
|
|
25
|
+
|
|
26
|
+
## Algorithm (what is deterministic)
|
|
27
|
+
- Score of a hypothesis = Σ over observed evidence of `weight × penalty`, with penalty `I = 1`, `II = 2`, everything else `0`; `weight = credibility × relevance` (1–9). Consistent evidence never adds to the score.
|
|
28
|
+
- Evidence kinds: *diagnostic* (penalties differ across hypotheses), *supports-only* (only C vs CC differ), *non-diagnostic* (identical ratings).
|
|
29
|
+
- Sensitivity: remove each evidence item and recompute; flag the conclusion as fragile if the leader set changes.
|
|
30
|
+
- Next test: among non-refuted, non-catch-all hypotheses, `priority = spread × weight / cost`, where `spread = max(rating) − min(rating)`.
|
|
31
|
+
|
|
32
|
+
## Limitations
|
|
33
|
+
- The numeric constants (penalties, weights, refutation threshold of 6) are Clarent's, not Heuer's.
|
|
34
|
+
- Garbage in, garbage out: ratings are judgments. The `ref` requirement reduces, but does not remove, invented evidence.
|
|
35
|
+
- The output is a ranking, not a probability. Heuer's method is not a Bayesian update.
|
|
36
|
+
- Needs a reasonably complete hypothesis set; the catch-all warning is a reminder, not a guarantee.
|
|
37
|
+
|
|
38
|
+
## Prior art (GitHub scan)
|
|
39
|
+
Scanned 2026-11-24. `Burton/Analysis-of-Competing-Hypotheses` (112 stars, PHP, last push 2012); `suprathermal/ACH-Grounding` (2); `lightcaptainguy/bayesian-ach-reasoning-prototype` (2); prompt-only ACH in `product-on-purpose/thinking-framework-skills`. Adjacent: `doraemonkeys/claude-code-debug-mode` (hypothesis-driven debugging with runtime logs). No deterministic engine with diagnosticity, sensitivity and next-test selection was found. See `research/novelty.md`.
|
|
40
|
+
|
|
41
|
+
## Worked example
|
|
42
|
+
`examples/flaky-test.json` (**synthetic**, English) and `examples/flaky-test.es.json` (Spanish).
|
|
43
|
+
`python -m clarent_ach score examples/flaky-test.json` → leaders H1 and H5 (tie), H2/H3/H4 refuted, T1 recommended first because it separates the two leaders.
|
|
44
|
+
|
|
45
|
+
## Evaluation
|
|
46
|
+
Not yet measured. Planned: 10 real, closed flaky-test/incident cases with known root cause; compare time-to-correct-hypothesis and number of wrong fixes, with and without the skill, and publish the result even if null.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""ACH — Analysis of Competing Hypotheses (Heuer) aplicado a debugging."""
|
|
2
|
+
from .cli import main, register # noqa: F401
|
|
3
|
+
from .engine import score # noqa: F401
|
|
4
|
+
from .model import ACHError, parse # noqa: F401
|
|
5
|
+
|
|
6
|
+
__all__ = ["main", "register", "score", "parse", "ACHError"]
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""ACH command line. Two ways to use it:
|
|
2
|
+
- standalone: python -m clarent_ach score file.json
|
|
3
|
+
- via core: clarent ach score file.json (the core calls `register`)
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import engine, i18n, render
|
|
13
|
+
from .i18n import t
|
|
14
|
+
from .model import ACHError, parse
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _template() -> dict:
|
|
18
|
+
return {
|
|
19
|
+
"title": t("t_title"),
|
|
20
|
+
"question": t("t_question"),
|
|
21
|
+
"hypotheses": [
|
|
22
|
+
{"id": "H1", "text": t("t_h1")},
|
|
23
|
+
{"id": "H2", "text": t("t_h2")},
|
|
24
|
+
{"id": "H3", "text": t("t_h3"), "catch_all": True},
|
|
25
|
+
],
|
|
26
|
+
"evidence": [
|
|
27
|
+
{"id": "E1", "text": t("t_e1"), "status": "observed", "credibility": "high",
|
|
28
|
+
"relevance": "high", "ref": t("t_e1_ref"), "ratings": {"H1": "C", "H2": "I", "H3": "N"}},
|
|
29
|
+
{"id": "T1", "text": t("t_t1"), "status": "proposed", "cost": "low",
|
|
30
|
+
"ratings": {"H1": "CC", "H2": "II", "H3": "N"}},
|
|
31
|
+
],
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _load(path: str, strict: bool):
|
|
36
|
+
try:
|
|
37
|
+
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
38
|
+
except FileNotFoundError:
|
|
39
|
+
raise ACHError(t("err_no_file", path=path))
|
|
40
|
+
except json.JSONDecodeError as e:
|
|
41
|
+
raise ACHError(t("err_bad_json", path=path, e=e))
|
|
42
|
+
return parse(data, strict=strict)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def register(sub: argparse._SubParsersAction) -> None:
|
|
46
|
+
"""Register ACH subcommands on a parser (core or standalone)."""
|
|
47
|
+
p = sub.add_parser("init", help="create an analysis template")
|
|
48
|
+
p.add_argument("path")
|
|
49
|
+
p.add_argument("--force", action="store_true")
|
|
50
|
+
p.set_defaults(func=_init)
|
|
51
|
+
|
|
52
|
+
for name, hlp in (("validate", "validate the file"), ("score", "score and print the report"),
|
|
53
|
+
("next", "list only the recommended tests")):
|
|
54
|
+
p = sub.add_parser(name, help=hlp)
|
|
55
|
+
p.add_argument("path")
|
|
56
|
+
p.add_argument("--strict", action="store_true", help="treat warnings as errors")
|
|
57
|
+
if name == "score":
|
|
58
|
+
p.add_argument("--format", choices=("md", "json"), default="md")
|
|
59
|
+
p.add_argument("--out", help="write the report to this file")
|
|
60
|
+
p.set_defaults(func=globals()[f"_{name}"])
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _init(a) -> int:
|
|
64
|
+
path = Path(a.path)
|
|
65
|
+
if path.exists() and not a.force:
|
|
66
|
+
print("error: " + t("err_exists", path=path), file=sys.stderr)
|
|
67
|
+
return 2
|
|
68
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
path.write_text(json.dumps(_template(), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
70
|
+
print(t("template_created", path=path))
|
|
71
|
+
return 0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _validate(a) -> int:
|
|
75
|
+
an = _load(a.path, a.strict)
|
|
76
|
+
for w in an.warnings:
|
|
77
|
+
print(t("warn_prefix", w=w))
|
|
78
|
+
print(t("validate_ok", h=len(an.hypotheses), o=len(an.observed), p=len(an.proposed)))
|
|
79
|
+
return 0
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _score(a) -> int:
|
|
83
|
+
an = _load(a.path, a.strict)
|
|
84
|
+
res = engine.score(an)
|
|
85
|
+
out = (json.dumps(engine.to_dict(res), indent=2, ensure_ascii=False)
|
|
86
|
+
if a.format == "json" else render.markdown(an, res))
|
|
87
|
+
if a.out:
|
|
88
|
+
Path(a.out).write_text(out, encoding="utf-8")
|
|
89
|
+
print(t("report_written", path=a.out))
|
|
90
|
+
else:
|
|
91
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
92
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
93
|
+
print(out)
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _next(a) -> int:
|
|
98
|
+
an = _load(a.path, a.strict)
|
|
99
|
+
res = engine.score(an)
|
|
100
|
+
if not res.next_tests:
|
|
101
|
+
print(t("no_tests"))
|
|
102
|
+
return 1
|
|
103
|
+
for x in res.next_tests:
|
|
104
|
+
print(t("next_line", id=x.id, p=x.priority, f=",".join(x.separates) or "-",
|
|
105
|
+
a=",".join(x.against) or "-") + f"\n {x.text}")
|
|
106
|
+
return 0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def main(argv: list[str] | None = None) -> int:
|
|
110
|
+
ap = argparse.ArgumentParser(prog="clarent-ach", description="Analysis of Competing Hypotheses")
|
|
111
|
+
ap.add_argument("--lang", choices=sorted(i18n.M), default=i18n.get_lang(),
|
|
112
|
+
help="output language (default: $CLARENT_LANG or en)")
|
|
113
|
+
register(ap.add_subparsers(dest="cmd", required=True))
|
|
114
|
+
args = ap.parse_args(argv)
|
|
115
|
+
i18n.set_lang(args.lang)
|
|
116
|
+
for stream in (sys.stdout, sys.stderr):
|
|
117
|
+
if hasattr(stream, "reconfigure"):
|
|
118
|
+
stream.reconfigure(encoding="utf-8")
|
|
119
|
+
try:
|
|
120
|
+
return args.func(args)
|
|
121
|
+
except ACHError as e:
|
|
122
|
+
print(f"error: {e}", file=sys.stderr)
|
|
123
|
+
return 2
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""ACH scoring engine. Pure and deterministic: same input -> same output.
|
|
2
|
+
|
|
3
|
+
Principles taken from Heuer, *Psychology of Intelligence Analysis* (CIA/CSI, 1999):
|
|
4
|
+
1. INconsistency is scored; consistent evidence does not "add up" because it is
|
|
5
|
+
usually consistent with several hypotheses at once.
|
|
6
|
+
2. Evidence that treats every hypothesis the same does not discriminate.
|
|
7
|
+
3. Sensitivity is tested: does the conclusion change if a key item is wrong?
|
|
8
|
+
4. The result is a ranking, NOT a probability.
|
|
9
|
+
The numeric weights (I=1, II=2, weight = credibility x relevance, refutation threshold)
|
|
10
|
+
are Clarent's own parametrization; they do not come from Heuer.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
from .i18n import t
|
|
17
|
+
from .model import COST_VALUE, Analysis, Evidence
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _penalty(value: int) -> int:
|
|
21
|
+
"""Only inconsistency is penalized: I -> 1, II -> 2, everything else 0."""
|
|
22
|
+
return max(0, -value)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class HypothesisScore:
|
|
27
|
+
id: str
|
|
28
|
+
text: str
|
|
29
|
+
inconsistency: int
|
|
30
|
+
rank: int
|
|
31
|
+
refuted: bool
|
|
32
|
+
catch_all: bool
|
|
33
|
+
contradicted_by: tuple[str, ...] # evidence ids rated I/II, heaviest first
|
|
34
|
+
supported_by: int # how many items are C/CC (informational, NOT scored)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class EvidenceDiagnostic:
|
|
39
|
+
id: str
|
|
40
|
+
weight: int
|
|
41
|
+
spread: int # penalty difference across hypotheses (0 = does not discriminate)
|
|
42
|
+
weighted: int
|
|
43
|
+
kind: str # "diagnostic" | "supports-only" | "non-diagnostic"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Sensitivity:
|
|
48
|
+
evidence_id: str
|
|
49
|
+
leaders_without: tuple[str, ...]
|
|
50
|
+
changes_leader: bool
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class NextTest:
|
|
55
|
+
id: str
|
|
56
|
+
text: str
|
|
57
|
+
contenders_spread: int
|
|
58
|
+
priority: float
|
|
59
|
+
separates: tuple[str, ...] # hypotheses the test predicts as "consistent" (C/CC)
|
|
60
|
+
against: tuple[str, ...] # hypotheses the test predicts as "inconsistent" (I/II)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class Result:
|
|
65
|
+
verdict: str # no-discrimination | single-leader | tied-leaders
|
|
66
|
+
fragile: bool
|
|
67
|
+
margin: int | None # inconsistency(2nd) - inconsistency(leader)
|
|
68
|
+
leaders: tuple[str, ...]
|
|
69
|
+
scores: tuple[HypothesisScore, ...]
|
|
70
|
+
diagnostics: tuple[EvidenceDiagnostic, ...]
|
|
71
|
+
sensitivity: tuple[Sensitivity, ...]
|
|
72
|
+
next_tests: tuple[NextTest, ...]
|
|
73
|
+
warnings: tuple[str, ...]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _inconsistency(an: Analysis, hid: str, skip: str | None = None) -> int:
|
|
77
|
+
return sum(
|
|
78
|
+
e.weight * _penalty(e.value(hid)) for e in an.observed if e.id != skip
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _specific(an: Analysis):
|
|
83
|
+
return [h for h in an.hypotheses if not h.catch_all]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _leaders(an: Analysis, skip: str | None = None) -> tuple[str, ...]:
|
|
87
|
+
"""Leaders among specific hypotheses (the catch-all never leads)."""
|
|
88
|
+
totals = {h.id: _inconsistency(an, h.id, skip) for h in _specific(an)}
|
|
89
|
+
best = min(totals.values())
|
|
90
|
+
return tuple(h.id for h in _specific(an) if totals[h.id] == best)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def score(an: Analysis) -> Result:
|
|
94
|
+
hyp_ids = [h.id for h in an.hypotheses]
|
|
95
|
+
totals = {hid: _inconsistency(an, hid) for hid in hyp_ids}
|
|
96
|
+
spec_ids = [h.id for h in _specific(an)]
|
|
97
|
+
distinct = sorted({totals[i] for i in spec_ids})
|
|
98
|
+
rank_of = {v: i + 1 for i, v in enumerate(sorted(set(totals.values())))}
|
|
99
|
+
|
|
100
|
+
scores = []
|
|
101
|
+
for h in an.hypotheses:
|
|
102
|
+
contra = sorted(
|
|
103
|
+
(e for e in an.observed if _penalty(e.value(h.id)) > 0),
|
|
104
|
+
key=lambda e: (-e.weight * _penalty(e.value(h.id)), e.id),
|
|
105
|
+
)
|
|
106
|
+
scores.append(
|
|
107
|
+
HypothesisScore(
|
|
108
|
+
id=h.id,
|
|
109
|
+
text=h.text,
|
|
110
|
+
inconsistency=totals[h.id],
|
|
111
|
+
rank=rank_of[totals[h.id]],
|
|
112
|
+
refuted=totals[h.id] >= an.refute_threshold,
|
|
113
|
+
catch_all=h.catch_all,
|
|
114
|
+
contradicted_by=tuple(e.id for e in contra),
|
|
115
|
+
supported_by=sum(1 for e in an.observed if e.value(h.id) > 0),
|
|
116
|
+
)
|
|
117
|
+
)
|
|
118
|
+
scores.sort(key=lambda s: (s.inconsistency, s.id))
|
|
119
|
+
|
|
120
|
+
leaders = _leaders(an)
|
|
121
|
+
margin = None
|
|
122
|
+
if len(distinct) > 1:
|
|
123
|
+
margin = distinct[1] - distinct[0]
|
|
124
|
+
|
|
125
|
+
if len(distinct) == 1:
|
|
126
|
+
verdict = "no-discrimination"
|
|
127
|
+
elif len(leaders) == 1:
|
|
128
|
+
verdict = "single-leader"
|
|
129
|
+
else:
|
|
130
|
+
verdict = "tied-leaders"
|
|
131
|
+
|
|
132
|
+
diags = []
|
|
133
|
+
for e in an.observed:
|
|
134
|
+
pens = [_penalty(e.value(hid)) for hid in hyp_ids]
|
|
135
|
+
vals = [e.value(hid) for hid in hyp_ids]
|
|
136
|
+
spread = max(pens) - min(pens)
|
|
137
|
+
if spread > 0:
|
|
138
|
+
kind = "diagnostic"
|
|
139
|
+
elif max(vals) != min(vals):
|
|
140
|
+
kind = "supports-only" # separates C from CC, but ACH does not score consistency
|
|
141
|
+
else:
|
|
142
|
+
kind = "non-diagnostic"
|
|
143
|
+
diags.append(EvidenceDiagnostic(e.id, e.weight, spread, spread * e.weight, kind))
|
|
144
|
+
diags.sort(key=lambda d: (-d.weighted, d.id))
|
|
145
|
+
|
|
146
|
+
sens = []
|
|
147
|
+
for e in an.observed:
|
|
148
|
+
without = _leaders(an, skip=e.id)
|
|
149
|
+
sens.append(Sensitivity(e.id, without, set(without) != set(leaders)))
|
|
150
|
+
fragile = any(s.changes_leader for s in sens) and verdict != "no-discrimination"
|
|
151
|
+
|
|
152
|
+
warnings = list(an.warnings)
|
|
153
|
+
for h in an.hypotheses:
|
|
154
|
+
if h.catch_all and totals[h.id] <= distinct[0]:
|
|
155
|
+
warnings.append(t("w_catch_all_alive", id=h.id))
|
|
156
|
+
if verdict == "no-discrimination":
|
|
157
|
+
warnings.append(t("w_no_discrim"))
|
|
158
|
+
if fragile:
|
|
159
|
+
crit = ", ".join(s.evidence_id for s in sens if s.changes_leader)
|
|
160
|
+
warnings.append(t("w_fragile", crit=crit))
|
|
161
|
+
if all(s.refuted for s in scores if not s.catch_all):
|
|
162
|
+
warnings.append(t("w_all_refuted"))
|
|
163
|
+
|
|
164
|
+
return Result(
|
|
165
|
+
verdict=verdict,
|
|
166
|
+
fragile=fragile,
|
|
167
|
+
margin=margin,
|
|
168
|
+
leaders=leaders,
|
|
169
|
+
scores=tuple(scores),
|
|
170
|
+
diagnostics=tuple(diags),
|
|
171
|
+
sensitivity=tuple(sens),
|
|
172
|
+
next_tests=next_tests(an, scores),
|
|
173
|
+
warnings=tuple(warnings),
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _contenders(scores: list[HypothesisScore]) -> list[str]:
|
|
178
|
+
spec = [s for s in scores if not s.catch_all]
|
|
179
|
+
live = [s.id for s in spec if not s.refuted]
|
|
180
|
+
return live if len(live) >= 2 else [s.id for s in spec]
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def next_tests(an: Analysis, scores: list[HypothesisScore]) -> tuple[NextTest, ...]:
|
|
184
|
+
"""Rank proposed tests by how well they separate the hypotheses still alive.
|
|
185
|
+
|
|
186
|
+
spread = max(rating) - min(rating) among contenders (the test is informative
|
|
187
|
+
whether the outcome is 'yes' or 'no'). priority = spread * weight / cost.
|
|
188
|
+
"""
|
|
189
|
+
contenders = _contenders(scores)
|
|
190
|
+
out = []
|
|
191
|
+
for e in an.proposed:
|
|
192
|
+
vals = {hid: e.value(hid) for hid in contenders}
|
|
193
|
+
spread = max(vals.values()) - min(vals.values())
|
|
194
|
+
if spread == 0:
|
|
195
|
+
continue
|
|
196
|
+
out.append(
|
|
197
|
+
NextTest(
|
|
198
|
+
id=e.id,
|
|
199
|
+
text=e.text,
|
|
200
|
+
contenders_spread=spread,
|
|
201
|
+
priority=round(spread * e.weight / COST_VALUE[e.cost], 3),
|
|
202
|
+
separates=tuple(h for h, v in vals.items() if v > 0),
|
|
203
|
+
against=tuple(h for h, v in vals.items() if v < 0),
|
|
204
|
+
)
|
|
205
|
+
)
|
|
206
|
+
out.sort(key=lambda x: (-x.priority, x.id))
|
|
207
|
+
return tuple(out)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def to_dict(r: Result) -> dict:
|
|
211
|
+
"""Stable serialization for --format json."""
|
|
212
|
+
from dataclasses import asdict
|
|
213
|
+
|
|
214
|
+
return asdict(r)
|
|
@@ -0,0 +1,160 @@
|
|
|
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
|
+
# --- model errors
|
|
11
|
+
"root_not_object": "the file root must be a JSON object",
|
|
12
|
+
"need_2_hyp": "at least 2 hypotheses are required in 'hypotheses'",
|
|
13
|
+
"need_1_ev": "at least 1 item is required in 'evidence'",
|
|
14
|
+
"missing_field": "{where}: missing required field '{key}'",
|
|
15
|
+
"dup_id": "{where}: duplicate id {id!r}",
|
|
16
|
+
"bad_status": "{where}: 'status' must be one of {allowed}",
|
|
17
|
+
"ratings_not_obj": "{where}: 'ratings' must be an object {{hypothesis: rating}}",
|
|
18
|
+
"unknown_hyp": "{where}: rating for unknown hypothesis {hid!r}",
|
|
19
|
+
"bad_rating": "{where}: invalid rating {r!r}; use one of {allowed}",
|
|
20
|
+
"bad_level": "{where}: '{key}' must be one of {allowed} (got {v!r})",
|
|
21
|
+
"all_catch_all": "at least one hypothesis must be specific (not catch_all)",
|
|
22
|
+
"strict_fail": "strict mode, warnings:",
|
|
23
|
+
# --- model warnings
|
|
24
|
+
"w_missing_rating": "{eid}: no rating for {ids} (assumed N)",
|
|
25
|
+
"w_uncited": ("{eid}: observed evidence without 'ref' (command, file:line or log excerpt). "
|
|
26
|
+
"Without a citation it cannot be verified; do not accept it if an LLM inferred it."),
|
|
27
|
+
"w_two_hyp": "Only 2 hypotheses: ACH works best with a broad set that includes a catch-all (\"catch_all\": true).",
|
|
28
|
+
"w_no_catch_all": "No catch-all ('something else') hypothesis: mark one with \"catch_all\": true.",
|
|
29
|
+
"w_few_obs": "Only {n} observed evidence items: the ranking is unreliable.",
|
|
30
|
+
"w_only_confirms": ("No observed evidence is inconsistent with any hypothesis: "
|
|
31
|
+
"the matrix only confirms. ACH seeks to refute, not to confirm."),
|
|
32
|
+
# --- engine warnings
|
|
33
|
+
"w_no_discrim": "Observed evidence does not discriminate between hypotheses: gather diagnostic evidence (see 'next').",
|
|
34
|
+
"w_fragile": "Fragile conclusion: removing {crit} changes the leader. Verify that evidence first.",
|
|
35
|
+
"w_all_refuted": "Every hypothesis exceeds the refutation threshold: the correct hypothesis is probably missing.",
|
|
36
|
+
"w_catch_all_alive": ("{id} (catch-all) is not refuted: 'something else' cannot be ruled out. "
|
|
37
|
+
"Treat the leader as a working hypothesis, not a conclusion."),
|
|
38
|
+
# --- render
|
|
39
|
+
"h_title": "ACH: {title}",
|
|
40
|
+
"question": "**Question:** {q}",
|
|
41
|
+
"h_conclusion": "Conclusion",
|
|
42
|
+
"v_no-discrimination": "No discrimination: the observed evidence does not separate the hypotheses.",
|
|
43
|
+
"v_single-leader": "One hypothesis has fewer inconsistencies than the rest.",
|
|
44
|
+
"v_tied-leaders": "Tie: several hypotheses share the lowest inconsistency score.",
|
|
45
|
+
"leaders": "Leader(s): {ids}",
|
|
46
|
+
"margin": " (margin over the next: {m})",
|
|
47
|
+
"fragile_flag": "⚠ **Fragile** conclusion (see Sensitivity).",
|
|
48
|
+
"not_probability": "This is a ranking of inconsistencies, **not a probability**.",
|
|
49
|
+
"h_ranking": "Hypothesis ranking (lower inconsistency = better)",
|
|
50
|
+
"col_hyp": "Hypothesis", "col_incons": "Inconsistency", "col_state": "State", "col_contra": "Contradicted by",
|
|
51
|
+
"st_catch_all": "catch-all", "st_refuted": "refuted", "st_alive": "alive",
|
|
52
|
+
"h_matrix": "Matrix", "col_evidence": "Evidence", "col_weight": "weight", "no_ref": "(no ref)",
|
|
53
|
+
"h_diag": "Evidence diagnosticity", "col_type": "Type", "col_spread": "Spread", "col_spread_w": "Spread×weight",
|
|
54
|
+
"non_diag": ("Evidence that does **not discriminate** under ACH logic: {ids}. "
|
|
55
|
+
"Consistent with several hypotheses ≠ proof of any."),
|
|
56
|
+
"kind_diagnostic": "diagnostic", "kind_supports-only": "supports-only", "kind_non-diagnostic": "non-diagnostic",
|
|
57
|
+
"h_sens": "Sensitivity (what if this evidence is wrong?)",
|
|
58
|
+
"sens_item": "Without **{eid}** the leader becomes: {ids}",
|
|
59
|
+
"sens_none": "No single evidence item changes the leader.",
|
|
60
|
+
"h_next": "Recommended next test",
|
|
61
|
+
"col_test": "Test", "col_priority": "Priority", "col_for": "Favors", "col_against": "Against",
|
|
62
|
+
"no_next": ("No proposed tests separate the live hypotheses. "
|
|
63
|
+
"Propose observations that some hypotheses predict and others rule out."),
|
|
64
|
+
"h_warnings": "Warnings",
|
|
65
|
+
"footer": "_Generated by Clarent · ACH method (Heuer, CIA). Weights and thresholds are Clarent's parametrization._",
|
|
66
|
+
# --- cli
|
|
67
|
+
"t_title": "Describe the problem", "t_question": "What is the root cause of ...?",
|
|
68
|
+
"t_h1": "First candidate cause", "t_h2": "Second candidate cause", "t_h3": "Something else I am not considering",
|
|
69
|
+
"t_e1": "Concrete, verifiable observation",
|
|
70
|
+
"t_e1_ref": "command run, file:line or log excerpt",
|
|
71
|
+
"t_t1": "A test not yet run; ratings = what each hypothesis predicts",
|
|
72
|
+
"err_no_file": "file not found: {path}", "err_bad_json": "invalid JSON in {path}: {e}",
|
|
73
|
+
"err_exists": "{path} already exists (use --force)", "template_created": "template created: {path}",
|
|
74
|
+
"warn_prefix": "warning: {w}",
|
|
75
|
+
"validate_ok": "ok: {h} hypotheses, {o} observed evidence items, {p} proposed tests",
|
|
76
|
+
"report_written": "report written to {path}", "no_tests": "no proposed tests separate the live hypotheses",
|
|
77
|
+
"next_line": "{id} priority={p} for={f} against={a}",
|
|
78
|
+
},
|
|
79
|
+
"es": {
|
|
80
|
+
"root_not_object": "la raíz del archivo debe ser un objeto JSON",
|
|
81
|
+
"need_2_hyp": "se requieren al menos 2 hipótesis en 'hypotheses'",
|
|
82
|
+
"need_1_ev": "se requiere al menos 1 evidencia en 'evidence'",
|
|
83
|
+
"missing_field": "{where}: falta el campo obligatorio '{key}'",
|
|
84
|
+
"dup_id": "{where}: id duplicado {id!r}",
|
|
85
|
+
"bad_status": "{where}: 'status' debe ser uno de {allowed}",
|
|
86
|
+
"ratings_not_obj": "{where}: 'ratings' debe ser un objeto {{hipótesis: rating}}",
|
|
87
|
+
"unknown_hyp": "{where}: rating para hipótesis inexistente {hid!r}",
|
|
88
|
+
"bad_rating": "{where}: rating {r!r} inválido; usa {allowed}",
|
|
89
|
+
"bad_level": "{where}: '{key}' debe ser uno de {allowed} (recibido: {v!r})",
|
|
90
|
+
"all_catch_all": "al menos una hipótesis debe ser específica (no catch_all)",
|
|
91
|
+
"strict_fail": "modo estricto, advertencias:",
|
|
92
|
+
"w_missing_rating": "{eid}: sin rating para {ids} (se asume N)",
|
|
93
|
+
"w_uncited": ("{eid}: evidencia observada sin 'ref' (comando, archivo:línea o log). "
|
|
94
|
+
"Sin cita no es verificable; no la aceptes si la infirió un LLM."),
|
|
95
|
+
"w_two_hyp": "Solo 2 hipótesis: ACH funciona mejor con un conjunto amplio que incluya una hipótesis comodín (\"catch_all\": true).",
|
|
96
|
+
"w_no_catch_all": "Falta una hipótesis comodín ('otra causa'): marca una con \"catch_all\": true.",
|
|
97
|
+
"w_few_obs": "Solo {n} evidencias observadas: el ranking es poco confiable.",
|
|
98
|
+
"w_only_confirms": ("Ninguna evidencia observada es inconsistente con alguna hipótesis: "
|
|
99
|
+
"la matriz solo confirma. ACH busca refutar, no confirmar."),
|
|
100
|
+
"w_no_discrim": "La evidencia observada no discrimina entre hipótesis: reúne evidencia diagnóstica (ver 'next').",
|
|
101
|
+
"w_fragile": "Conclusión frágil: quitar {crit} cambia al líder. Verifica esa evidencia primero.",
|
|
102
|
+
"w_all_refuted": "Todas las hipótesis superan el umbral de refutación: probablemente falta la hipótesis correcta.",
|
|
103
|
+
"w_catch_all_alive": ("{id} (comodín) no está refutada: no puede descartarse 'otra causa'. "
|
|
104
|
+
"Trata al líder como hipótesis de trabajo, no como conclusión."),
|
|
105
|
+
"h_title": "ACH: {title}",
|
|
106
|
+
"question": "**Pregunta:** {q}",
|
|
107
|
+
"h_conclusion": "Conclusión",
|
|
108
|
+
"v_no-discrimination": "Sin discriminación: la evidencia observada no separa a las hipótesis.",
|
|
109
|
+
"v_single-leader": "Hay una hipótesis con menos inconsistencias que el resto.",
|
|
110
|
+
"v_tied-leaders": "Empate: varias hipótesis comparten el menor puntaje de inconsistencia.",
|
|
111
|
+
"leaders": "Líder(es): {ids}",
|
|
112
|
+
"margin": " (margen sobre el siguiente: {m})",
|
|
113
|
+
"fragile_flag": "⚠ Conclusión **frágil** (ver Sensibilidad).",
|
|
114
|
+
"not_probability": "Esto es un ranking de inconsistencias, **no una probabilidad**.",
|
|
115
|
+
"h_ranking": "Ranking de hipótesis (menor inconsistencia = mejor)",
|
|
116
|
+
"col_hyp": "Hipótesis", "col_incons": "Inconsistencia", "col_state": "Estado", "col_contra": "Contradicha por",
|
|
117
|
+
"st_catch_all": "comodín", "st_refuted": "refutada", "st_alive": "viva",
|
|
118
|
+
"h_matrix": "Matriz", "col_evidence": "Evidencia", "col_weight": "peso", "no_ref": "(sin ref)",
|
|
119
|
+
"h_diag": "Diagnosticidad de la evidencia", "col_type": "Tipo", "col_spread": "Spread", "col_spread_w": "Spread×peso",
|
|
120
|
+
"non_diag": ("Evidencia que **no discrimina** bajo la lógica ACH: {ids}. "
|
|
121
|
+
"Consistente con varias hipótesis ≠ prueba de ninguna."),
|
|
122
|
+
"kind_diagnostic": "diagnóstica", "kind_supports-only": "solo-apoya", "kind_non-diagnostic": "no-diagnóstica",
|
|
123
|
+
"h_sens": "Sensibilidad (¿y si esta evidencia está mal?)",
|
|
124
|
+
"sens_item": "Sin **{eid}** el líder pasa a: {ids}",
|
|
125
|
+
"sens_none": "Ninguna evidencia individual cambia al líder.",
|
|
126
|
+
"h_next": "Próxima prueba recomendada",
|
|
127
|
+
"col_test": "Prueba", "col_priority": "Prioridad", "col_for": "A favor de", "col_against": "En contra de",
|
|
128
|
+
"no_next": ("No hay pruebas propuestas que separen a las hipótesis vivas. "
|
|
129
|
+
"Propón observaciones que unas hipótesis predigan y otras descarten."),
|
|
130
|
+
"h_warnings": "Advertencias",
|
|
131
|
+
"footer": "_Generado por Clarent · método ACH (Heuer, CIA). Pesos y umbrales son parametrización de Clarent._",
|
|
132
|
+
"t_title": "Describe el problema", "t_question": "¿Cuál es la causa raíz de ...?",
|
|
133
|
+
"t_h1": "Primera causa candidata", "t_h2": "Segunda causa candidata", "t_h3": "Otra causa que no estoy considerando",
|
|
134
|
+
"t_e1": "Observación concreta y verificable",
|
|
135
|
+
"t_e1_ref": "comando ejecutado, archivo:línea o extracto de log",
|
|
136
|
+
"t_t1": "Prueba que aún no hice; ratings = lo que cada hipótesis predice",
|
|
137
|
+
"err_no_file": "no existe el archivo: {path}", "err_bad_json": "JSON inválido en {path}: {e}",
|
|
138
|
+
"err_exists": "{path} ya existe (usa --force)", "template_created": "plantilla creada: {path}",
|
|
139
|
+
"warn_prefix": "advertencia: {w}",
|
|
140
|
+
"validate_ok": "ok: {h} hipótesis, {o} evidencias observadas, {p} pruebas propuestas",
|
|
141
|
+
"report_written": "reporte escrito en {path}", "no_tests": "no hay pruebas propuestas que separen a las hipótesis vivas",
|
|
142
|
+
"next_line": "{id} prioridad={p} a favor={f} en contra={a}",
|
|
143
|
+
},
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def set_lang(lang: str) -> None:
|
|
148
|
+
global _LANG
|
|
149
|
+
if lang not in M:
|
|
150
|
+
raise ValueError(f"unsupported language {lang!r}; use one of {sorted(M)}")
|
|
151
|
+
_LANG = lang
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def get_lang() -> str:
|
|
155
|
+
return _LANG
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def t(key: str, /, **kw) -> str:
|
|
159
|
+
s = M[_LANG][key]
|
|
160
|
+
return s.format(**kw) if kw else s
|