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,103 @@
1
+ """Matrix lookup and principle ranking. Pure and deterministic: same input and data -> same output.
2
+
3
+ This engine does NOT generate solutions. It returns the principles the classical matrix associates with a pair of
4
+ parameters, tells you how far the cell can be trusted, and ranks principles across several contradictions.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+
10
+ from .model import Cell, Matrix, Param, Principle, resolve
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Lookup:
15
+ improving: Param
16
+ worsening: Param
17
+ how: tuple[str, str] # how each query was resolved: id | name | software
18
+ kind: str # principles | empty | same-parameter
19
+ principles: tuple[Principle, ...]
20
+ status: str | None # verified | contested | consensus (None if no cell)
21
+ agree: int | None
22
+ alt: tuple[Principle, ...] | None # the 1973 table's reading when contested
23
+ reverse: tuple[Principle, ...] # principles of the reverse cell (worsen, improve)
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class RankedPrinciple:
28
+ principle: Principle
29
+ count: int
30
+ pairs: tuple[int, ...] # 1-based indexes of the contradictions that list it
31
+ mean_position: float
32
+ contested: bool
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Analysis:
37
+ lookups: tuple[Lookup, ...]
38
+ ranking: tuple[RankedPrinciple, ...]
39
+
40
+
41
+ def _cell(m: Matrix, i: int, j: int) -> Cell | None:
42
+ return m.cells.get((i, j))
43
+
44
+
45
+ def lookup(m: Matrix, improving: str, worsening: str) -> Lookup:
46
+ pi, hi = resolve(m, improving)
47
+ pw, hw = resolve(m, worsening)
48
+ if pi.id == pw.id:
49
+ return Lookup(pi, pw, (hi, hw), "same-parameter", (), None, None, None, ())
50
+ cell = _cell(m, pi.id, pw.id)
51
+ back = _cell(m, pw.id, pi.id)
52
+ reverse = tuple(m.principles[x] for x in back.principles) if back else ()
53
+ if cell is None or not cell.principles:
54
+ # A contested empty cell can still carry a 1973 reading in `alt`.
55
+ alt = tuple(m.principles[x] for x in cell.alt) if cell and cell.alt else None
56
+ return Lookup(pi, pw, (hi, hw), "empty", (), cell.status if cell else None, cell.agree if cell else None, alt, reverse)
57
+ alt = tuple(m.principles[x] for x in cell.alt) if cell.alt is not None else None
58
+ return Lookup(pi, pw, (hi, hw), "principles", tuple(m.principles[x] for x in cell.principles),
59
+ cell.status, cell.agree, alt, reverse)
60
+
61
+
62
+ def rank(m: Matrix, pairs: list[tuple[str, str]]) -> Analysis:
63
+ """Look up every pair and rank principles by how many contradictions list them (then by mean position)."""
64
+ lookups = tuple(lookup(m, a, b) for a, b in pairs)
65
+ seen: dict[int, list[tuple[int, int, bool]]] = {}
66
+ for n, lk in enumerate(lookups, start=1):
67
+ for pos, pr in enumerate(lk.principles, start=1):
68
+ seen.setdefault(pr.id, []).append((n, pos, lk.status == "contested"))
69
+ ranked = [
70
+ RankedPrinciple(m.principles[pid], len(v), tuple(n for n, _, _ in v),
71
+ round(sum(p for _, p, _ in v) / len(v), 2), any(c for _, _, c in v))
72
+ for pid, v in seen.items()
73
+ ]
74
+ ranked.sort(key=lambda r: (-r.count, r.mean_position, r.principle.id))
75
+ return Analysis(lookups, tuple(ranked))
76
+
77
+
78
+ # ---------------------------------------------------------------- stable serialization
79
+ def principle_dict(p: Principle) -> dict:
80
+ return {"id": p.id, "name": p.name(), "description": p.description(), "software_example": p.example()}
81
+
82
+
83
+ def lookup_dict(lk: Lookup) -> dict:
84
+ return {
85
+ "improving": {"id": lk.improving.id, "name": lk.improving.name(), "software_reading": lk.improving.software(),
86
+ "resolved_by": lk.how[0]},
87
+ "worsening": {"id": lk.worsening.id, "name": lk.worsening.name(), "software_reading": lk.worsening.software(),
88
+ "resolved_by": lk.how[1]},
89
+ "kind": lk.kind,
90
+ "status": lk.status,
91
+ "sources_agreeing": lk.agree,
92
+ "principles": [principle_dict(p) for p in lk.principles],
93
+ "alternative_1973": [principle_dict(p) for p in lk.alt] if lk.alt is not None else None,
94
+ "reverse_cell": [p.id for p in lk.reverse],
95
+ }
96
+
97
+
98
+ def analysis_dict(a: Analysis) -> dict:
99
+ return {
100
+ "contradictions": [lookup_dict(lk) for lk in a.lookups],
101
+ "ranking": [{"principle": principle_dict(r.principle), "count": r.count, "contradictions": list(r.pairs),
102
+ "mean_position": r.mean_position, "contested": r.contested} for r in a.ranking],
103
+ }
@@ -0,0 +1,134 @@
1
+ """UI messages in English (default) and Spanish. Language: --lang, or CLARENT_LANG, or 'en'.
2
+
3
+ Data text (parameter and principle names, descriptions, software examples) lives in data/catalog.json in both languages.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import os
8
+
9
+ _LANG = os.environ.get("CLARENT_LANG", "en")
10
+
11
+ M: dict[str, dict[str, str]] = {
12
+ "en": {
13
+ # errors
14
+ "err_param_not_found": "no parameter matches {q!r}. Closest: {close}. Run 'params' to list all 39.",
15
+ "err_param_ambiguous": "{q!r} is ambiguous; it matches: {cands}. Use the number or a more specific name.",
16
+ "err_param_id": "parameter number must be 1-39 (got {q})",
17
+ "err_principle_id": "principle number must be 1-40 (got {q})",
18
+ "err_no_file": "file not found: {path}",
19
+ "err_bad_json": "invalid JSON in {path}: {e}",
20
+ "err_bad_input": "{path}: {msg}",
21
+ "err_need_pairs": "'pairs' must be a non-empty list of {{improving, worsening}} objects",
22
+ "err_pair_fields": "pairs[{i}]: both 'improving' and 'worsening' are required",
23
+ "err_pair_syntax": "--pair must look like IMPROVING:WORSENING (got {p!r})",
24
+ "err_data": "data problem in {where}: {msg}",
25
+ # lookup
26
+ "h_lookup": "TRIZ contradiction: improve «{imp}» without worsening «{wor}»",
27
+ "improving": "Improving", "worsening": "Worsening", "sw_reading": "software reading",
28
+ "interpreted": "«{q}» was interpreted as parameter {id} ({name}) by {how}",
29
+ "how_id": "number", "how_name": "name", "how_software": "software-reading match",
30
+ "same_param": ("Improving and worsening are the same parameter. That is a physical contradiction "
31
+ "(one property must take opposite values), not a technical one, so the matrix does not apply. "
32
+ "Consider separation in space, in time, between the whole and its parts, or on condition."),
33
+ "empty_cell": ("The classical matrix lists no principles for this pair. Try: swapping the direction "
34
+ "(reverse cell below), restating the parameters more generally or more specifically, "
35
+ "or browsing the 40 principles directly."),
36
+ "reverse": "Reverse cell (improve «{wor}», worsen «{imp}»): {ids}",
37
+ "reverse_none": "Reverse cell (improve «{wor}», worsen «{imp}»): no principles listed",
38
+ "st_verified": "Cell verified: the consensus of {n} independent transcriptions equals the Altshuller Foundation 1973 table.",
39
+ "st_contested": ("Cell CONTESTED: the consensus of {n} transcriptions differs from the Altshuller Foundation 1973 table, "
40
+ "which lists {alt}. Treat both lists as candidates."),
41
+ "st_contested_empty": "no principles",
42
+ "st_consensus": "Cell from the consensus of {n} transcriptions; the 1973 table could not be read for this cell.",
43
+ "col_principle": "Principle", "col_meaning": "What it means", "col_example": "Software example",
44
+ "h_principles": "Principles (in the order the matrix lists them)",
45
+ "idea_note": ("Principles are prompts for ideas, not solutions. Check every candidate against the original "
46
+ "contradiction: a good idea improves «{imp}» without bringing back the worsening of «{wor}»."),
47
+ # rank / analyze
48
+ "h_rank": "Principles across all contradictions",
49
+ "rank_note": "Ranked by how many contradictions list the principle, then by average position in the cells.",
50
+ "col_count": "In", "col_pairs": "Contradictions",
51
+ "h_pair": "Contradiction {n}: improve «{imp}» / worsen «{wor}»",
52
+ "h_analysis": "TRIZ analysis: {title}",
53
+ "contested_in_rank": "contested cell involved",
54
+ # params / principles
55
+ "h_params": "The 39 engineering parameters",
56
+ "params_note": "For «Loss of …» parameters, improving means reducing the loss. The software reading is Clarent's adaptation, not Altshuller's.",
57
+ "h_all_principles": "The 40 inventive principles",
58
+ "col_id": "#", "col_name": "Name", "col_desc": "Description",
59
+ # info
60
+ "info_line": "Matrix: {filled} filled cells ({verified} verified against the 1973 table, {contested} contested, {consensus} consensus-only). Built {built}.",
61
+ "info_sources": "Voting sources: {n} MIT-licensed transcriptions. Reference: Altshuller Foundation 1973 table. See DATA_LICENSE.md.",
62
+ "footer": "_Matrix data: consensus of independent transcriptions of Altshuller's table (see DATA_LICENSE.md). Descriptions and software examples are Clarent's own adaptation._",
63
+ "data_override": "Using custom data from {dir}",
64
+ # cli
65
+ "t_title": "Describe your system and the trade-off",
66
+ "t_context": "What are you trying to improve, and what gets worse when you do?",
67
+ },
68
+ "es": {
69
+ "err_param_not_found": "ningún parámetro coincide con {q!r}. Más cercanos: {close}. Usa 'params' para ver los 39.",
70
+ "err_param_ambiguous": "{q!r} es ambiguo; coincide con: {cands}. Usa el número o un nombre más específico.",
71
+ "err_param_id": "el número de parámetro debe estar entre 1 y 39 (recibido: {q})",
72
+ "err_principle_id": "el número de principio debe estar entre 1 y 40 (recibido: {q})",
73
+ "err_no_file": "no existe el archivo: {path}",
74
+ "err_bad_json": "JSON inválido en {path}: {e}",
75
+ "err_bad_input": "{path}: {msg}",
76
+ "err_need_pairs": "'pairs' debe ser una lista no vacía de objetos {{improving, worsening}}",
77
+ "err_pair_fields": "pairs[{i}]: se requieren 'improving' y 'worsening'",
78
+ "err_pair_syntax": "--pair debe tener la forma MEJORA:EMPEORA (recibido: {p!r})",
79
+ "err_data": "problema de datos en {where}: {msg}",
80
+ "h_lookup": "Contradicción TRIZ: mejorar «{imp}» sin empeorar «{wor}»",
81
+ "improving": "Mejora", "worsening": "Empeora", "sw_reading": "lectura en software",
82
+ "interpreted": "«{q}» se interpretó como el parámetro {id} ({name}) por {how}",
83
+ "how_id": "número", "how_name": "nombre", "how_software": "coincidencia con la lectura en software",
84
+ "same_param": ("Lo que mejora y lo que empeora es el mismo parámetro. Es una contradicción física "
85
+ "(una propiedad debe tomar valores opuestos), no técnica, así que la matriz no aplica. "
86
+ "Considera separar en el espacio, en el tiempo, entre el todo y sus partes, o según una condición."),
87
+ "empty_cell": ("La matriz clásica no lista principios para este par. Prueba: invertir el sentido "
88
+ "(celda inversa abajo), reformular los parámetros de forma más general o más específica, "
89
+ "o revisar directamente los 40 principios."),
90
+ "reverse": "Celda inversa (mejora «{wor}», empeora «{imp}»): {ids}",
91
+ "reverse_none": "Celda inversa (mejora «{wor}», empeora «{imp}»): sin principios listados",
92
+ "st_verified": "Celda verificada: el consenso de {n} transcripciones independientes coincide con la tabla de 1973 de la Fundación Altshuller.",
93
+ "st_contested": ("Celda EN DISPUTA: el consenso de {n} transcripciones difiere de la tabla de 1973 de la Fundación Altshuller, "
94
+ "que lista {alt}. Trata ambas listas como candidatas."),
95
+ "st_contested_empty": "ningún principio",
96
+ "st_consensus": "Celda tomada del consenso de {n} transcripciones; no se pudo leer la tabla de 1973 para esta celda.",
97
+ "col_principle": "Principio", "col_meaning": "Qué significa", "col_example": "Ejemplo en software",
98
+ "h_principles": "Principios (en el orden en que los lista la matriz)",
99
+ "idea_note": ("Los principios son disparadores de ideas, no soluciones. Contrasta cada candidato con la "
100
+ "contradicción original: una buena idea mejora «{imp}» sin traer de vuelta el empeoramiento de «{wor}»."),
101
+ "h_rank": "Principios en el conjunto de contradicciones",
102
+ "rank_note": "Ordenados por cuántas contradicciones listan el principio y luego por posición media en las celdas.",
103
+ "col_count": "En", "col_pairs": "Contradicciones",
104
+ "h_pair": "Contradicción {n}: mejora «{imp}» / empeora «{wor}»",
105
+ "h_analysis": "Análisis TRIZ: {title}",
106
+ "contested_in_rank": "interviene una celda en disputa",
107
+ "h_params": "Los 39 parámetros de ingeniería",
108
+ "params_note": "En los parámetros «Pérdida de …», mejorar significa reducir la pérdida. La lectura en software es una adaptación de Clarent, no de Altshuller.",
109
+ "h_all_principles": "Los 40 principios inventivos",
110
+ "col_id": "#", "col_name": "Nombre", "col_desc": "Descripción",
111
+ "info_line": "Matriz: {filled} celdas con principios ({verified} verificadas contra la tabla de 1973, {contested} en disputa, {consensus} solo por consenso). Construida el {built}.",
112
+ "info_sources": "Fuentes con voto: {n} transcripciones con licencia MIT. Referencia: tabla de 1973 de la Fundación Altshuller. Ver DATA_LICENSE.md.",
113
+ "footer": "_Datos de la matriz: consenso de transcripciones independientes de la tabla de Altshuller (ver DATA_LICENSE.md). Las descripciones y los ejemplos en software son adaptación propia de Clarent._",
114
+ "data_override": "Usando datos propios de {dir}",
115
+ "t_title": "Describe tu sistema y el compromiso",
116
+ "t_context": "¿Qué quieres mejorar y qué empeora al hacerlo?",
117
+ },
118
+ }
119
+
120
+
121
+ def set_lang(lang: str) -> None:
122
+ global _LANG
123
+ if lang not in M:
124
+ raise ValueError(f"unsupported language {lang!r}; use one of {sorted(M)}")
125
+ _LANG = lang
126
+
127
+
128
+ def get_lang() -> str:
129
+ return _LANG
130
+
131
+
132
+ def t(key: str, /, **kw) -> str:
133
+ s = M[_LANG][key]
134
+ return s.format(**kw) if kw else s
@@ -0,0 +1,179 @@
1
+ """Data model, loading and validation for the TRIZ contradiction matrix. Stdlib only.
2
+
3
+ Data files (see data/ and DATA_LICENSE.md):
4
+ catalog.json 39 parameters and 40 principles, in English and Spanish, with software readings and examples
5
+ matrix.json cells "i,j" -> {p: [principle ids in order], n: sources agreeing, s: status, alt: 1973 reading}
6
+
7
+ Convention: i = parameter to IMPROVE (row), j = parameter that WORSENS (column).
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import difflib
12
+ import json
13
+ import re
14
+ import unicodedata
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+
18
+ from .i18n import get_lang, t
19
+
20
+ DATA_DIR = Path(__file__).resolve().parent / "data"
21
+ N_PARAMS, N_PRINCIPLES = 39, 40
22
+ STATUSES = ("verified", "contested", "consensus")
23
+
24
+
25
+ class TrizError(ValueError):
26
+ """Invalid input or data (reported to the user without a traceback)."""
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Param:
31
+ id: int
32
+ en: str
33
+ es: str
34
+ sw_en: str
35
+ sw_es: str
36
+ aliases: tuple[str, ...] = ()
37
+
38
+ def name(self, lang: str | None = None) -> str:
39
+ return self.es if (lang or get_lang()) == "es" else self.en
40
+
41
+ def software(self, lang: str | None = None) -> str:
42
+ return self.sw_es if (lang or get_lang()) == "es" else self.sw_en
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Principle:
47
+ id: int
48
+ en: str
49
+ es: str
50
+ desc_en: str
51
+ desc_es: str
52
+ sw_en: str
53
+ sw_es: str
54
+
55
+ def name(self, lang: str | None = None) -> str:
56
+ return self.es if (lang or get_lang()) == "es" else self.en
57
+
58
+ def description(self, lang: str | None = None) -> str:
59
+ return self.desc_es if (lang or get_lang()) == "es" else self.desc_en
60
+
61
+ def example(self, lang: str | None = None) -> str:
62
+ return self.sw_es if (lang or get_lang()) == "es" else self.sw_en
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Cell:
67
+ principles: tuple[int, ...]
68
+ agree: int
69
+ status: str
70
+ alt: tuple[int, ...] | None = None
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class Matrix:
75
+ params: dict[int, Param]
76
+ principles: dict[int, Principle]
77
+ cells: dict[tuple[int, int], Cell]
78
+ meta: dict = field(default_factory=dict)
79
+ source_dir: Path = DATA_DIR
80
+
81
+
82
+ def norm(s: str) -> str:
83
+ """Lowercase, strip accents and punctuation, collapse spaces."""
84
+ s = unicodedata.normalize("NFKD", s)
85
+ s = "".join(c for c in s if not unicodedata.combining(c)).lower()
86
+ return re.sub(r"\s+", " ", re.sub(r"[^a-z0-9]+", " ", s)).strip()
87
+
88
+
89
+ def _read_json(path: Path) -> dict:
90
+ try:
91
+ return json.loads(path.read_text(encoding="utf-8"))
92
+ except FileNotFoundError:
93
+ raise TrizError(t("err_no_file", path=path))
94
+ except json.JSONDecodeError as e:
95
+ raise TrizError(t("err_bad_json", path=path, e=e))
96
+
97
+
98
+ def load(data_dir: Path | None = None) -> Matrix:
99
+ """Load and validate the catalog and the matrix. `data_dir` may hold either or both files; missing ones fall back
100
+ to the bundled data, so a user can supply only their own matrix.json."""
101
+ d = Path(data_dir) if data_dir else DATA_DIR
102
+ cat_path = d / "catalog.json" if (d / "catalog.json").is_file() else DATA_DIR / "catalog.json"
103
+ mat_path = d / "matrix.json" if (d / "matrix.json").is_file() else DATA_DIR / "matrix.json"
104
+ cat, raw = _read_json(cat_path), _read_json(mat_path)
105
+
106
+ try:
107
+ params = {p["id"]: Param(p["id"], p["en"], p["es"], p["sw_en"], p["sw_es"], tuple(p.get("aliases", ())))
108
+ for p in cat["parameters"]}
109
+ principles = {p["id"]: Principle(p["id"], p["en"], p["es"], p["desc_en"], p["desc_es"], p["sw_en"], p["sw_es"])
110
+ for p in cat["principles"]}
111
+ except (KeyError, TypeError) as e:
112
+ raise TrizError(t("err_data", where=cat_path, msg=f"missing field {e}"))
113
+ if sorted(params) != list(range(1, N_PARAMS + 1)):
114
+ raise TrizError(t("err_data", where=cat_path, msg="parameters must have ids 1..39"))
115
+ if sorted(principles) != list(range(1, N_PRINCIPLES + 1)):
116
+ raise TrizError(t("err_data", where=cat_path, msg="principles must have ids 1..40"))
117
+
118
+ cells: dict[tuple[int, int], Cell] = {}
119
+ for key, c in raw.get("cells", {}).items():
120
+ try:
121
+ i, j = (int(x) for x in key.split(","))
122
+ p = tuple(int(x) for x in c["p"])
123
+ alt = tuple(int(x) for x in c["alt"]) if "alt" in c else None
124
+ cell = Cell(p, int(c.get("n", 0)), c.get("s", "consensus"), alt)
125
+ except (ValueError, KeyError, TypeError) as e:
126
+ raise TrizError(t("err_data", where=f"{mat_path} cell {key!r}", msg=str(e)))
127
+ if not (1 <= i <= N_PARAMS and 1 <= j <= N_PARAMS) or i == j:
128
+ raise TrizError(t("err_data", where=mat_path, msg=f"cell {key!r} is outside the 39x39 off-diagonal grid"))
129
+ if any(x not in principles for x in cell.principles + (cell.alt or ())):
130
+ raise TrizError(t("err_data", where=mat_path, msg=f"cell {key!r} lists an unknown principle"))
131
+ if len(set(cell.principles)) != len(cell.principles):
132
+ raise TrizError(t("err_data", where=mat_path, msg=f"cell {key!r} repeats a principle"))
133
+ if cell.status not in STATUSES:
134
+ raise TrizError(t("err_data", where=mat_path, msg=f"cell {key!r} has unknown status {cell.status!r}"))
135
+ cells[(i, j)] = cell
136
+ return Matrix(params, principles, cells, raw.get("meta", {}), d)
137
+
138
+
139
+ def resolve(m: Matrix, query: str) -> tuple[Param, str]:
140
+ """Map a user string to a parameter. Returns (param, how) with how in {'id','name','software'}.
141
+
142
+ Order: number; exact name (either language, or alias); unique substring of a name; unique substring of the
143
+ software reading. Anything ambiguous is an error that lists the candidates (never a silent guess).
144
+ """
145
+ q = str(query).strip()
146
+ if q.isdigit():
147
+ n = int(q)
148
+ if n not in m.params:
149
+ raise TrizError(t("err_param_id", q=q))
150
+ return m.params[n], "id"
151
+ nq = norm(q)
152
+ if not nq:
153
+ raise TrizError(t("err_param_not_found", q=q, close="-"))
154
+
155
+ def names(p: Param) -> set[str]:
156
+ return {norm(p.en), norm(p.es), *(norm(a) for a in p.aliases)}
157
+
158
+ exact = [p for p in m.params.values() if nq in names(p)]
159
+ if len(exact) == 1:
160
+ return exact[0], "name"
161
+
162
+ def pick(cands: list[Param], how: str):
163
+ if len(cands) == 1:
164
+ return cands[0], how
165
+ if len(cands) > 1:
166
+ raise TrizError(t("err_param_ambiguous", q=q, cands="; ".join(f"{p.id} {p.name()}" for p in cands)))
167
+ return None
168
+
169
+ sub = [p for p in m.params.values() if any(nq in n for n in names(p))]
170
+ r = pick(sub, "name")
171
+ if r:
172
+ return r
173
+ sw = [p for p in m.params.values() if nq in norm(p.sw_en) or nq in norm(p.sw_es)]
174
+ r = pick(sw, "software")
175
+ if r:
176
+ return r
177
+ pool = {norm(p.en): p for p in m.params.values()} | {norm(p.es): p for p in m.params.values()}
178
+ close = [f"{pool[c].id} {pool[c].name()}" for c in difflib.get_close_matches(nq, pool, n=3, cutoff=0.4)]
179
+ raise TrizError(t("err_param_not_found", q=q, close="; ".join(close) or "-"))
@@ -0,0 +1,101 @@
1
+ """Markdown rendering for the TRIZ matrix tool (meant to be pasted into an ADR, issue or PR)."""
2
+ from __future__ import annotations
3
+
4
+ from .engine import Analysis, Lookup
5
+ from .i18n import t
6
+ from .model import Matrix
7
+
8
+
9
+ def _cell(s: str) -> str:
10
+ return s.replace("|", "\\|").replace("\n", " ")
11
+
12
+
13
+ def _ids(ps) -> str:
14
+ return ", ".join(str(p.id) for p in ps) if ps else t("st_contested_empty")
15
+
16
+
17
+ def _resolved(lk: Lookup, queries: tuple[str, str] | None) -> list[str]:
18
+ if not queries:
19
+ return []
20
+ out = []
21
+ for q, p, how in ((queries[0], lk.improving, lk.how[0]), (queries[1], lk.worsening, lk.how[1])):
22
+ if how != "id" and q.strip().lower() not in (p.en.lower(), p.es.lower()):
23
+ out.append("- " + t("interpreted", q=q, id=p.id, name=p.name(), how=t("how_" + how)))
24
+ return out
25
+
26
+
27
+ def lookup_body(lk: Lookup, queries: tuple[str, str] | None = None, level: str = "##") -> list[str]:
28
+ L = [f"- **{t('improving')}:** {lk.improving.id}. {lk.improving.name()} — _{t('sw_reading')}: {lk.improving.software()}_",
29
+ f"- **{t('worsening')}:** {lk.worsening.id}. {lk.worsening.name()} — _{t('sw_reading')}: {lk.worsening.software()}_"]
30
+ L += _resolved(lk, queries)
31
+ L.append("")
32
+ if lk.kind == "same-parameter":
33
+ return L + [t("same_param"), ""]
34
+ if lk.status == "verified":
35
+ L += [f"> {t('st_verified', n=lk.agree)}", ""]
36
+ elif lk.status == "contested":
37
+ L += [f"> **{t('st_contested', n=lk.agree, alt=_ids(lk.alt or ()))}**", ""]
38
+ elif lk.status == "consensus":
39
+ L += [f"> {t('st_consensus', n=lk.agree)}", ""]
40
+ if lk.kind == "empty":
41
+ L += [t("empty_cell"), ""]
42
+ if lk.alt:
43
+ L += [f"> **{t('st_contested', n=lk.agree, alt=_ids(lk.alt))}**", ""]
44
+ else:
45
+ L += [f"{level} {t('h_principles')}", "",
46
+ f"| # | {t('col_principle')} | {t('col_meaning')} | {t('col_example')} |", "|--:|---|---|---|"]
47
+ for p in lk.principles:
48
+ L.append(f"| {p.id} | **{_cell(p.name())}** | {_cell(p.description())} | {_cell(p.example())} |")
49
+ L += ["", t("idea_note", imp=lk.improving.name(), wor=lk.worsening.name()), ""]
50
+ L.append(t("reverse", wor=lk.worsening.name(), imp=lk.improving.name(), ids=_ids(lk.reverse))
51
+ if lk.reverse else t("reverse_none", wor=lk.worsening.name(), imp=lk.improving.name()))
52
+ L.append("")
53
+ return L
54
+
55
+
56
+ def lookup_markdown(lk: Lookup, queries: tuple[str, str] | None = None) -> str:
57
+ L = [f"# {t('h_lookup', imp=lk.improving.name(), wor=lk.worsening.name())}", ""]
58
+ L += lookup_body(lk, queries)
59
+ L += ["---", t("footer"), ""]
60
+ return "\n".join(L)
61
+
62
+
63
+ def ranking_table(a: Analysis, limit: int | None = None) -> list[str]:
64
+ L = [t("rank_note"), "", f"| {t('col_count')} | # | {t('col_principle')} | {t('col_pairs')} |", "|--:|--:|---|---|"]
65
+ for r in a.ranking[:limit]:
66
+ flag = f" ⚠ {t('contested_in_rank')}" if r.contested else ""
67
+ L.append(f"| {r.count}/{len(a.lookups)} | {r.principle.id} | **{_cell(r.principle.name())}** — "
68
+ f"{_cell(r.principle.example())} | {', '.join(map(str, r.pairs))}{flag} |")
69
+ L.append("")
70
+ return L
71
+
72
+
73
+ def analysis_markdown(a: Analysis, title: str = "", context: str = "", notes: list[str] | None = None,
74
+ queries: list[tuple[str, str]] | None = None) -> str:
75
+ L = [f"# {t('h_analysis', title=title or '-')}", ""]
76
+ if context:
77
+ L += [context, ""]
78
+ L += [f"## {t('h_rank')}", ""] + ranking_table(a)
79
+ for n, lk in enumerate(a.lookups, start=1):
80
+ L += [f"## {t('h_pair', n=n, imp=lk.improving.name(), wor=lk.worsening.name())}", ""]
81
+ if notes and notes[n - 1]:
82
+ L += [f"_{notes[n - 1]}_", ""]
83
+ L += lookup_body(lk, queries[n - 1] if queries else None, level="###")
84
+ L += ["---", t("footer"), ""]
85
+ return "\n".join(L)
86
+
87
+
88
+ def params_markdown(m: Matrix) -> str:
89
+ L = [f"# {t('h_params')}", "", t("params_note"), "",
90
+ f"| {t('col_id')} | {t('col_name')} | {t('sw_reading')} |", "|--:|---|---|"]
91
+ for p in m.params.values():
92
+ L.append(f"| {p.id} | {_cell(p.name())} | {_cell(p.software())} |")
93
+ return "\n".join(L + [""])
94
+
95
+
96
+ def principles_markdown(m: Matrix) -> str:
97
+ L = [f"# {t('h_all_principles')}", "",
98
+ f"| {t('col_id')} | {t('col_name')} | {t('col_desc')} | {t('col_example')} |", "|--:|---|---|---|"]
99
+ for p in m.principles.values():
100
+ L.append(f"| {p.id} | **{_cell(p.name())}** | {_cell(p.description())} | {_cell(p.example())} |")
101
+ return "\n".join(L + [""])
@@ -0,0 +1,9 @@
1
+ {
2
+ "title": "Acelerar la API de búsqueda sin volverla más difícil de operar (EJEMPLO SINTÉTICO)",
3
+ "context": "La latencia p95 de /search es 900 ms y la meta es 300 ms. Cada arreglo que probamos (más cachés, más réplicas, más casos especiales) añade piezas móviles, perjudica la fiabilidad o vuelve rígido el sistema.",
4
+ "pairs": [
5
+ {"improving": "latencia", "worsening": "Complejidad del dispositivo", "note": "Respuestas más rápidas, pero cada aceleración añade componentes y rutas de código."},
6
+ {"improving": "Velocidad", "worsening": "Fiabilidad", "note": "El caché agresivo y los atajos hicieron más frecuentes los incidentes."},
7
+ {"improving": "Adaptabilidad o versatilidad", "worsening": "Complejidad del dispositivo", "note": "Producto quiere muchas variantes de ranking sin una maraña de casos especiales."}
8
+ ]
9
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "title": "Make the search API faster without making it harder to run (SYNTHETIC EXAMPLE)",
3
+ "context": "p95 latency of /search is 900 ms and the target is 300 ms. Every fix we tried (more caches, more replicas, more special cases) adds moving parts, hurts reliability, or makes the system rigid.",
4
+ "pairs": [
5
+ {"improving": "latency", "worsening": "Device complexity", "note": "Faster responses, but each speed-up adds components and code paths."},
6
+ {"improving": "Speed", "worsening": "Reliability", "note": "Aggressive caching and shortcuts made incidents more frequent."},
7
+ {"improving": "Adaptability or versatility", "worsening": "Device complexity", "note": "Product wants many ranking variants without a tangle of special cases."}
8
+ ]
9
+ }
@@ -0,0 +1,58 @@
1
+ id = "triz-matrix"
2
+ name = "TRIZ Contradiction Matrix"
3
+ version = "0.1.0"
4
+ family = "soviet"
5
+ status = "beta" # spec | beta | stable | reference
6
+ summary = "Given a parameter you want to improve and one that gets worse, return Altshuller's inventive principles with software examples; every cell is checked against the 1973 table."
7
+
8
+ [python]
9
+ module = "clarent_triz" # importable package inside this folder; exposes register(subparsers) and main(argv)
10
+
11
+ [surfaces]
12
+ cli = true
13
+ skill = true
14
+ agent = false
15
+ hook = false
16
+ mcp = false
17
+ action = false
18
+
19
+ # verification: read = opened and read | exists = confirmed to exist | blocked = exists, server blocks scripts | unverified = from memory
20
+ [[sources]]
21
+ title = "G.S. Altshuller Foundation: table of principles for technical contradictions (cites Altshuller, Algorithm of Invention, Moscow, 1973, Appendix 1). Parsed cell by cell for verification only."
22
+ url = "https://www.altshuller.ru/triz/technique2.asp"
23
+ verification = "read"
24
+
25
+ [[sources]]
26
+ title = "Altshuller, Creativity as an Exact Science (Gordon and Breach, 1984), ISBN 0-677-21230-5"
27
+ url = "https://searchworks.stanford.edu/view/1223823"
28
+ verification = "exists"
29
+
30
+ [[sources]]
31
+ title = "Voting transcription A: Antropocosmist/triz-engineering-solver (MIT)"
32
+ url = "https://github.com/Antropocosmist/triz-engineering-solver/tree/251084f171508e774507c36140af55096213ad30"
33
+ verification = "read"
34
+
35
+ [[sources]]
36
+ title = "Voting transcription B: SharathSPhD/triz-engine (MIT)"
37
+ url = "https://github.com/SharathSPhD/triz-engine/tree/17d48dc0273c23bc8456e7369f2a298bd44131a3"
38
+ verification = "read"
39
+
40
+ [[sources]]
41
+ title = "Voting transcription C: seogineer/triz-solver (MIT)"
42
+ url = "https://github.com/seogineer/triz-solver/tree/32c8278eb7ded45a6f2a19eadc0ea9bb4144711d"
43
+ verification = "read"
44
+
45
+ [[sources]]
46
+ title = "Voting transcription D: magery-ai/triz-skill (MIT)"
47
+ url = "https://github.com/magery-ai/triz-skill/tree/ba773ce3785ddd8b12f2f2af3b9537c4aaf13549"
48
+ verification = "read"
49
+
50
+ [[sources]]
51
+ title = "Voting transcription E: luchi2333/triz-worker-innovation-research (MIT)"
52
+ url = "https://github.com/luchi2333/triz-worker-innovation-research/tree/ba796e2b06b941bb6e970e9a472de9ab29e69bfb"
53
+ verification = "read"
54
+
55
+ [novelty]
56
+ checked_on = "2026-11-24"
57
+ status = "exists-but-weak" # none | exists-but-weak | exists-but-abandoned | well-covered
58
+ evidence = "At least 8 small repos (mostly MIT) ship a TRIZ matrix lookup as an agent skill or tool; the most-starred are ironyjk/strategy-frameworks (47 stars, TRIZ among 30 frameworks) and Antropocosmist/triz-engineering-solver (24). None found with a stdlib engine, tests, per-cell verification against the 1973 table, or software readings of the parameters. The space is crowded: this method is not novel in itself."
@@ -0,0 +1,50 @@
1
+ ---
2
+ name: triz-matrix
3
+ description: Resolve a design trade-off (improving A worsens B) with TRIZ's contradiction matrix. Returns inventive principles with software examples and says how far each matrix cell can be trusted. Use when a design is stuck between two competing properties.
4
+ disable-model-invocation: true
5
+ argument-hint: [trade-off in one sentence]
6
+ ---
7
+
8
+ # TRIZ contradiction matrix
9
+
10
+ You are helping resolve a **technical contradiction**: improving one property of a system worsens another. A bundled script looks up the classical matrix; your job is to state the contradiction precisely and turn the principles into concrete, checkable design candidates.
11
+
12
+ Trade-off: $ARGUMENTS
13
+
14
+ ## Tooling
15
+
16
+ Stdlib-only Python. Use whichever of `python3` / `python` exists:
17
+
18
+ ```bash
19
+ python3 "${CLAUDE_SKILL_DIR}/scripts/run.py" params # the 39 parameters with their software readings
20
+ python3 "${CLAUDE_SKILL_DIR}/scripts/run.py" lookup "<improving>" "<worsening>"
21
+ python3 "${CLAUDE_SKILL_DIR}/scripts/run.py" rank --pair "A:B" --pair "C:D"
22
+ python3 "${CLAUDE_SKILL_DIR}/scripts/run.py" principles # the 40 principles
23
+ python3 "${CLAUDE_SKILL_DIR}/scripts/run.py" info # data provenance
24
+ ```
25
+
26
+ Add `--lang es` before the subcommand for Spanish, and `--format json` to parse the output.
27
+
28
+ ## Procedure
29
+
30
+ 1. **State the contradiction in one sentence:** "If we improve X, then Y gets worse." Both X and Y must be properties of the *same* system, and you must be able to say how you would notice each.
31
+ 2. **Map X and Y to the 39 parameters.** Run `params` and read the *software reading* column. Pass a number or exact name to `lookup`. If the tool reports an ambiguous or unknown name, choose from the candidates it lists; do not guess. For "Loss of …" parameters, improving means *reducing* the loss.
32
+ 3. **Look up the pair.** Read the cell status first:
33
+ - `verified`: the consensus matches the 1973 table.
34
+ - `contested`: the sources and the 1973 table disagree; consider the principles from **both** lists.
35
+ - empty cell: say so, then try the reverse cell the tool reports, or restate the parameters more generally or more specifically.
36
+ - same parameter on both sides: it is a *physical* contradiction (one property needs opposite values); say so and consider separation in space, time, condition or between whole and parts instead.
37
+ 4. **For each principle returned (top 2–4), write one concrete candidate for THIS system:** what exactly would change, in which component. A candidate that only repeats the software example from the table is not done.
38
+ 5. **Test each candidate against the original contradiction.** Keep it only if it improves X *without* bringing back the worsening of Y, or if you can state what it costs and why that is acceptable. Discard the rest and say why.
39
+ 6. **If you have several related contradictions,** use `rank`: principles that appear in more than one are worth the first look.
40
+
41
+ ## Reporting
42
+
43
+ For each kept candidate give: the principle (number and name), the concrete change, the effect on X, the effect on Y, and how you would verify both. Quote the cell status. Offer the data caveat (`info`) if the user asks about trust.
44
+
45
+ ## Rules
46
+
47
+ - The matrix returns **prompts for ideas, not solutions**. Never present a principle as proven to work.
48
+ - Software readings and examples are an adaptation of a physical-patent method; say when a principle maps loosely.
49
+ - Do not invent parameters or principles; use only what the tool returns.
50
+ - A candidate you did not check against the contradiction is a suggestion, not a result.