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,306 @@
|
|
|
1
|
+
"""TRIZ matrix tests. Stdlib only: `python -m unittest discover -s methods/triz-matrix/tests` (from any directory)."""
|
|
2
|
+
import io
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
import unittest
|
|
9
|
+
from contextlib import redirect_stderr, redirect_stdout
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # run from any directory
|
|
13
|
+
|
|
14
|
+
from clarent_triz import TrizError, engine, i18n, load, main, resolve # noqa: E402
|
|
15
|
+
from clarent_triz.model import DATA_DIR # noqa: E402
|
|
16
|
+
|
|
17
|
+
EXAMPLES = Path(__file__).resolve().parent.parent / "examples"
|
|
18
|
+
M = load()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def setUpModule():
|
|
22
|
+
i18n.set_lang("en")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def run(*argv):
|
|
26
|
+
out, err = io.StringIO(), io.StringIO()
|
|
27
|
+
with redirect_stdout(out), redirect_stderr(err):
|
|
28
|
+
try:
|
|
29
|
+
code = main(list(argv))
|
|
30
|
+
except SystemExit as e:
|
|
31
|
+
code = e.code
|
|
32
|
+
i18n.set_lang("en")
|
|
33
|
+
return code, out.getvalue(), err.getvalue()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class DataIntegrity(unittest.TestCase):
|
|
37
|
+
def test_catalog_is_complete_and_bilingual(self):
|
|
38
|
+
self.assertEqual(sorted(M.params), list(range(1, 40)))
|
|
39
|
+
self.assertEqual(sorted(M.principles), list(range(1, 41)))
|
|
40
|
+
for p in M.params.values():
|
|
41
|
+
for text in (p.en, p.es, p.sw_en, p.sw_es):
|
|
42
|
+
self.assertTrue(text.strip(), f"parameter {p.id} has an empty field")
|
|
43
|
+
for p in M.principles.values():
|
|
44
|
+
for text in (p.en, p.es, p.desc_en, p.desc_es, p.sw_en, p.sw_es):
|
|
45
|
+
self.assertTrue(text.strip(), f"principle {p.id} has an empty field")
|
|
46
|
+
self.assertEqual(len({p.sw_en for p in M.principles.values()}), 40, "software examples must be distinct")
|
|
47
|
+
|
|
48
|
+
def test_cells_are_classical_shape(self):
|
|
49
|
+
for (i, j), c in M.cells.items():
|
|
50
|
+
self.assertNotEqual(i, j)
|
|
51
|
+
self.assertTrue(1 <= len(c.principles) <= 4, f"cell {i},{j} has {len(c.principles)} principles")
|
|
52
|
+
self.assertEqual(len(set(c.principles)), len(c.principles))
|
|
53
|
+
|
|
54
|
+
def test_documented_counts_match_the_data(self):
|
|
55
|
+
counts = M.meta["counts"]
|
|
56
|
+
self.assertEqual(counts["filled_cells"], len(M.cells))
|
|
57
|
+
self.assertEqual(len(M.cells), 1248) # matches the filled-cell count of 4 of the 5 independent sources
|
|
58
|
+
for status in ("verified", "contested", "consensus"):
|
|
59
|
+
self.assertEqual(counts[status], sum(1 for c in M.cells.values() if c.status == status))
|
|
60
|
+
self.assertEqual(counts["contested"], 29)
|
|
61
|
+
|
|
62
|
+
def test_contested_cells_carry_a_different_1973_reading(self):
|
|
63
|
+
contested = [c for c in M.cells.values() if c.status == "contested"]
|
|
64
|
+
self.assertTrue(contested)
|
|
65
|
+
for c in contested:
|
|
66
|
+
self.assertIsNotNone(c.alt)
|
|
67
|
+
self.assertNotEqual(set(c.alt), set(c.principles))
|
|
68
|
+
for c in M.cells.values():
|
|
69
|
+
if c.status != "contested":
|
|
70
|
+
self.assertIsNone(c.alt)
|
|
71
|
+
|
|
72
|
+
def test_anchor_cells(self):
|
|
73
|
+
"""Cells present, unanimous and equal to the 1973 table in every source we cross-checked."""
|
|
74
|
+
anchors = {(1, 3): (15, 8, 29, 34), (1, 5): (29, 17, 38, 34), (9, 36): (10, 28, 4, 34), (9, 27): (11, 35, 27, 28)}
|
|
75
|
+
for cell, expected in anchors.items():
|
|
76
|
+
self.assertEqual(M.cells[cell].principles, expected)
|
|
77
|
+
self.assertEqual(M.cells[cell].status, "verified")
|
|
78
|
+
self.assertNotIn((1, 2), M.cells) # genuinely empty in the classical matrix
|
|
79
|
+
|
|
80
|
+
def test_provenance_is_recorded(self):
|
|
81
|
+
meta = M.meta
|
|
82
|
+
self.assertEqual(len(meta["voting_sources"]), 5)
|
|
83
|
+
for s in meta["voting_sources"]:
|
|
84
|
+
self.assertRegex(s["commit"], r"^[0-9a-f]{40}$")
|
|
85
|
+
self.assertRegex(s["sha256"], r"^[0-9a-f]{64}$")
|
|
86
|
+
self.assertIn("MIT", s["license"])
|
|
87
|
+
self.assertTrue(s["repo"].startswith("https://github.com/"))
|
|
88
|
+
self.assertIn("altshuller.ru", meta["reference_source"]["url"])
|
|
89
|
+
self.assertRegex(meta["reference_source"]["sha256"], r"^[0-9a-f]{64}$")
|
|
90
|
+
|
|
91
|
+
def test_data_license_file_names_every_source_and_copyright_holder(self):
|
|
92
|
+
text = (DATA_DIR / "DATA_LICENSE.md").read_text(encoding="utf-8")
|
|
93
|
+
for s in M.meta["voting_sources"]:
|
|
94
|
+
self.assertIn(s["repo"].replace("https://github.com/", ""), text)
|
|
95
|
+
for holder in ("useful-skills contributors", "triz-engine contributors", "DoGyeong Seo", "magery.ai", "luchi2333"):
|
|
96
|
+
self.assertIn(holder, text)
|
|
97
|
+
self.assertIn("Permission is hereby granted", text)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class Resolve(unittest.TestCase):
|
|
101
|
+
def test_by_number_name_and_language(self):
|
|
102
|
+
self.assertEqual(resolve(M, "9")[0].id, 9)
|
|
103
|
+
self.assertEqual(resolve(M, "Speed"), (M.params[9], "name"))
|
|
104
|
+
self.assertEqual(resolve(M, "velocidad")[0].id, 9)
|
|
105
|
+
self.assertEqual(resolve(M, "FIABILIDAD")[0].id, 27)
|
|
106
|
+
self.assertEqual(resolve(M, "Complejidad del dispositivo")[0].id, 36)
|
|
107
|
+
|
|
108
|
+
def test_accents_case_and_punctuation_are_ignored(self):
|
|
109
|
+
self.assertEqual(resolve(M, "perdida de informacion")[0].id, 24)
|
|
110
|
+
self.assertEqual(resolve(M, " device COMPLEXITY ")[0].id, 36)
|
|
111
|
+
|
|
112
|
+
def test_aliases_and_unique_substrings(self):
|
|
113
|
+
self.assertEqual(resolve(M, "Force")[0].id, 10)
|
|
114
|
+
self.assertEqual(resolve(M, "composition")[0].id, 13)
|
|
115
|
+
|
|
116
|
+
def test_software_words(self):
|
|
117
|
+
p, how = resolve(M, "latency")
|
|
118
|
+
self.assertEqual((p.id, how), (9, "software"))
|
|
119
|
+
|
|
120
|
+
def test_ambiguous_is_an_error_that_lists_candidates(self):
|
|
121
|
+
with self.assertRaises(TrizError) as cm:
|
|
122
|
+
resolve(M, "weight")
|
|
123
|
+
self.assertIn("1 Weight of moving object", str(cm.exception))
|
|
124
|
+
self.assertIn("2 Weight of stationary object", str(cm.exception))
|
|
125
|
+
with self.assertRaises(TrizError):
|
|
126
|
+
resolve(M, "memory") # matches the software readings of 1 and 11
|
|
127
|
+
|
|
128
|
+
def test_unknown_and_out_of_range(self):
|
|
129
|
+
for bad in ("zzzz", "", "0", "40", "-1"):
|
|
130
|
+
with self.assertRaises(TrizError, msg=bad):
|
|
131
|
+
resolve(M, bad)
|
|
132
|
+
with self.assertRaises(TrizError) as cm:
|
|
133
|
+
resolve(M, "reliabilty") # typo -> suggestions
|
|
134
|
+
self.assertIn("Reliability", str(cm.exception))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class Lookup(unittest.TestCase):
|
|
138
|
+
def test_principles_keep_the_matrix_order(self):
|
|
139
|
+
lk = engine.lookup(M, "Speed", "Device complexity")
|
|
140
|
+
self.assertEqual(lk.kind, "principles")
|
|
141
|
+
self.assertEqual([p.id for p in lk.principles], [10, 28, 4, 34])
|
|
142
|
+
self.assertEqual(lk.status, "verified")
|
|
143
|
+
|
|
144
|
+
def test_reverse_cell_is_reported(self):
|
|
145
|
+
lk = engine.lookup(M, "Speed", "Device complexity")
|
|
146
|
+
self.assertEqual([p.id for p in lk.reverse], [m for m in M.cells[(36, 9)].principles])
|
|
147
|
+
|
|
148
|
+
def test_same_parameter_is_a_physical_contradiction(self):
|
|
149
|
+
lk = engine.lookup(M, "Speed", "9")
|
|
150
|
+
self.assertEqual(lk.kind, "same-parameter")
|
|
151
|
+
self.assertEqual(lk.principles, ())
|
|
152
|
+
|
|
153
|
+
def test_empty_cell(self):
|
|
154
|
+
lk = engine.lookup(M, 1, 2)
|
|
155
|
+
self.assertEqual((lk.kind, lk.principles), ("empty", ()))
|
|
156
|
+
|
|
157
|
+
def test_contested_cell_exposes_both_readings(self):
|
|
158
|
+
lk = engine.lookup(M, "Speed", "Weight of moving object")
|
|
159
|
+
self.assertEqual(lk.status, "contested")
|
|
160
|
+
self.assertEqual([p.id for p in lk.principles], [2, 28, 13, 38])
|
|
161
|
+
self.assertEqual([p.id for p in lk.alt], [8, 28, 13, 38])
|
|
162
|
+
|
|
163
|
+
def test_contested_cell_with_empty_1973_reading(self):
|
|
164
|
+
lk = engine.lookup(M, "Adaptability or versatility", "Difficulty of detecting and measuring")
|
|
165
|
+
self.assertEqual(lk.status, "contested")
|
|
166
|
+
self.assertEqual(lk.alt, ())
|
|
167
|
+
md = __import__("clarent_triz.render", fromlist=["x"]).lookup_markdown(lk)
|
|
168
|
+
self.assertIn("no principles", md)
|
|
169
|
+
|
|
170
|
+
def test_deterministic(self):
|
|
171
|
+
self.assertEqual(engine.lookup(M, "Speed", "Reliability"), engine.lookup(M, "Speed", "Reliability"))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class Rank(unittest.TestCase):
|
|
175
|
+
PAIRS = [("Speed", "Device complexity"), ("Speed", "Reliability"), ("Adaptability or versatility", "Device complexity")]
|
|
176
|
+
|
|
177
|
+
def test_principle_in_every_contradiction_ranks_first(self):
|
|
178
|
+
a = engine.rank(M, self.PAIRS)
|
|
179
|
+
self.assertEqual((a.ranking[0].principle.id, a.ranking[0].count, a.ranking[0].pairs), (28, 3, (1, 2, 3)))
|
|
180
|
+
|
|
181
|
+
def test_order_is_stable_and_counts_add_up(self):
|
|
182
|
+
a = engine.rank(M, self.PAIRS)
|
|
183
|
+
self.assertEqual(sum(r.count for r in a.ranking), sum(len(lk.principles) for lk in a.lookups))
|
|
184
|
+
self.assertEqual(a.ranking, engine.rank(M, self.PAIRS).ranking)
|
|
185
|
+
keys = [(-r.count, r.mean_position, r.principle.id) for r in a.ranking]
|
|
186
|
+
self.assertEqual(keys, sorted(keys))
|
|
187
|
+
|
|
188
|
+
def test_contested_flag_propagates(self):
|
|
189
|
+
a = engine.rank(M, [("Speed", "Weight of moving object"), ("Speed", "Reliability")])
|
|
190
|
+
flags = {r.principle.id: r.contested for r in a.ranking}
|
|
191
|
+
self.assertTrue(flags[2]) # only in the contested cell
|
|
192
|
+
self.assertFalse(flags[27]) # only in a verified cell
|
|
193
|
+
|
|
194
|
+
def test_empty_and_same_pairs_contribute_nothing(self):
|
|
195
|
+
a = engine.rank(M, [(1, 2), ("Speed", "Speed")])
|
|
196
|
+
self.assertEqual(a.ranking, ())
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class Cli(unittest.TestCase):
|
|
200
|
+
def test_lookup_markdown(self):
|
|
201
|
+
code, out, _ = run("lookup", "Speed", "Device complexity")
|
|
202
|
+
self.assertEqual(code, 0)
|
|
203
|
+
for s in ("## Principles", "Preliminary action", "Cell verified", "prompts for ideas", "Reverse cell"):
|
|
204
|
+
self.assertIn(s, out)
|
|
205
|
+
|
|
206
|
+
def test_lookup_json_is_stable(self):
|
|
207
|
+
code, out, _ = run("lookup", "latency", "complexity", "--format", "json")
|
|
208
|
+
self.assertEqual(code, 0)
|
|
209
|
+
d = json.loads(out)
|
|
210
|
+
self.assertEqual([p["id"] for p in d["principles"]], [10, 28, 4, 34])
|
|
211
|
+
self.assertEqual((d["improving"]["resolved_by"], d["worsening"]["resolved_by"]), ("software", "name"))
|
|
212
|
+
self.assertEqual(d["status"], "verified")
|
|
213
|
+
self.assertIsNone(d["alternative_1973"])
|
|
214
|
+
|
|
215
|
+
def test_spanish_changes_text_not_numbers(self):
|
|
216
|
+
_, en, _ = run("--lang", "en", "lookup", "9", "36", "--format", "json")
|
|
217
|
+
_, es, _ = run("--lang", "es", "lookup", "9", "36", "--format", "json")
|
|
218
|
+
e, s = json.loads(en), json.loads(es)
|
|
219
|
+
self.assertEqual([p["id"] for p in e["principles"]], [p["id"] for p in s["principles"]])
|
|
220
|
+
self.assertNotEqual(e["principles"][0]["name"], s["principles"][0]["name"])
|
|
221
|
+
self.assertEqual(s["principles"][0]["name"], "Acción previa")
|
|
222
|
+
_, md, _ = run("--lang", "es", "lookup", "9", "36")
|
|
223
|
+
self.assertIn("## Principios", md)
|
|
224
|
+
|
|
225
|
+
def test_analyze_example_en_and_es_agree(self):
|
|
226
|
+
c1, en, _ = run("analyze", str(EXAMPLES / "search-api.json"), "--format", "json")
|
|
227
|
+
c2, es, _ = run("--lang", "es", "analyze", str(EXAMPLES / "search-api.es.json"), "--format", "json")
|
|
228
|
+
self.assertEqual((c1, c2), (0, 0))
|
|
229
|
+
ids = lambda o: [(r["principle"]["id"], r["count"]) for r in json.loads(o)["ranking"]]
|
|
230
|
+
self.assertEqual(ids(en), ids(es))
|
|
231
|
+
self.assertEqual(ids(en)[0], (28, 3))
|
|
232
|
+
|
|
233
|
+
def test_analyze_markdown_has_one_section_per_contradiction(self):
|
|
234
|
+
_, out, _ = run("analyze", str(EXAMPLES / "search-api.json"))
|
|
235
|
+
self.assertEqual(len(re.findall(r"^## Contradiction \d", out, re.M)), 3)
|
|
236
|
+
self.assertIn("SYNTHETIC EXAMPLE", out)
|
|
237
|
+
|
|
238
|
+
def test_rank_with_pairs(self):
|
|
239
|
+
code, out, _ = run("rank", "--pair", "Speed:Device complexity", "--pair", "Speed:Reliability", "--format", "json")
|
|
240
|
+
self.assertEqual(code, 0)
|
|
241
|
+
self.assertEqual(json.loads(out)["ranking"][0]["principle"]["id"], 28)
|
|
242
|
+
|
|
243
|
+
def test_errors_are_clean(self):
|
|
244
|
+
for argv in (("lookup", "weight", "speed"), ("lookup", "nope", "speed"), ("analyze", "no-such.json"),
|
|
245
|
+
("rank", "--pair", "SpeedReliability")):
|
|
246
|
+
code, _, err = run(*argv)
|
|
247
|
+
self.assertEqual(code, 2, argv)
|
|
248
|
+
self.assertTrue(err.startswith("error:"), argv)
|
|
249
|
+
|
|
250
|
+
def test_bad_analyze_inputs(self):
|
|
251
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
252
|
+
bad = Path(tmp) / "bad.json"
|
|
253
|
+
for content in ("{not json", '{"pairs": []}', '{"pairs": [{"improving": "Speed"}]}', "[]"):
|
|
254
|
+
bad.write_text(content, encoding="utf-8")
|
|
255
|
+
self.assertEqual(run("analyze", str(bad))[0], 2, content)
|
|
256
|
+
|
|
257
|
+
def test_params_and_principles_listings(self):
|
|
258
|
+
_, out, _ = run("params", "--format", "json")
|
|
259
|
+
self.assertEqual(len(json.loads(out)), 39)
|
|
260
|
+
_, out, _ = run("principles", "--format", "json")
|
|
261
|
+
self.assertEqual(len(json.loads(out)), 40)
|
|
262
|
+
self.assertIn("39", run("params")[1])
|
|
263
|
+
|
|
264
|
+
def test_init_does_not_overwrite(self):
|
|
265
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
266
|
+
p = str(Path(tmp) / "a" / "t.json")
|
|
267
|
+
self.assertEqual(run("init", p)[0], 0)
|
|
268
|
+
self.assertEqual(run("init", p)[0], 2)
|
|
269
|
+
self.assertEqual(run("init", p, "--force")[0], 0)
|
|
270
|
+
self.assertEqual(run("analyze", p)[0], 0) # the template itself is analyzable
|
|
271
|
+
|
|
272
|
+
def test_info_lists_sources(self):
|
|
273
|
+
code, out, _ = run("info")
|
|
274
|
+
self.assertEqual(code, 0)
|
|
275
|
+
self.assertIn("1218 verified", out)
|
|
276
|
+
self.assertIn("MIT", out)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
class CustomData(unittest.TestCase):
|
|
280
|
+
"""Users who do not want to rely on the bundled matrix can supply their own."""
|
|
281
|
+
|
|
282
|
+
def setUp(self):
|
|
283
|
+
self.tmp = Path(tempfile.mkdtemp())
|
|
284
|
+
self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True)
|
|
285
|
+
|
|
286
|
+
def test_own_matrix_with_bundled_catalog(self):
|
|
287
|
+
(self.tmp / "matrix.json").write_text(json.dumps({"cells": {"9,36": {"p": [1, 2], "n": 1, "s": "consensus"}}}), encoding="utf-8")
|
|
288
|
+
code, out, _ = run("lookup", "Speed", "Device complexity", "--format", "json", "--data", str(self.tmp))
|
|
289
|
+
self.assertEqual(code, 0)
|
|
290
|
+
self.assertEqual([p["id"] for p in json.loads(out)["principles"]], [1, 2])
|
|
291
|
+
|
|
292
|
+
def test_invalid_custom_data_is_rejected(self):
|
|
293
|
+
for cells in ({"9,36": {"p": [99]}}, {"9,9": {"p": [1]}}, {"40,1": {"p": [1]}}, {"9,36": {"p": [1, 1]}},
|
|
294
|
+
{"9,36": {"p": [1], "s": "made-up"}}, {"x": {"p": [1]}}):
|
|
295
|
+
(self.tmp / "matrix.json").write_text(json.dumps({"cells": cells}), encoding="utf-8")
|
|
296
|
+
self.assertEqual(run("lookup", "9", "36", "--data", str(self.tmp))[0], 2, cells)
|
|
297
|
+
|
|
298
|
+
def test_bundled_data_is_untouched_by_custom_runs(self):
|
|
299
|
+
before = (DATA_DIR / "matrix.json").read_bytes()
|
|
300
|
+
(self.tmp / "matrix.json").write_text(json.dumps({"cells": {}}), encoding="utf-8")
|
|
301
|
+
run("lookup", "9", "36", "--data", str(self.tmp))
|
|
302
|
+
self.assertEqual((DATA_DIR / "matrix.json").read_bytes(), before)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
if __name__ == "__main__":
|
|
306
|
+
unittest.main()
|
clarent/cli.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""`clarent` command: list methods, check their health, and delegate to a method's own CLI.
|
|
2
|
+
|
|
3
|
+
clarent list [--format json]
|
|
4
|
+
clarent doctor [method ...]
|
|
5
|
+
clarent [--lang en|es] <method> <args...> e.g. clarent ach score analysis.json
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from . import __version__, registry
|
|
14
|
+
|
|
15
|
+
USAGE = """usage: clarent [--lang en|es] {list,doctor,<method>} ...
|
|
16
|
+
|
|
17
|
+
commands:
|
|
18
|
+
list [--format json] show the available methods
|
|
19
|
+
doctor [method ...] [--fail-on-stale]
|
|
20
|
+
validate manifests, cards, skills and sources
|
|
21
|
+
<method> ... run a method's own CLI (try: clarent list)
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _pop_lang(argv: list[str]) -> list[str]:
|
|
26
|
+
out, i = [], 0
|
|
27
|
+
while i < len(argv):
|
|
28
|
+
if argv[i] == "--lang" and i + 1 < len(argv):
|
|
29
|
+
os.environ["CLARENT_LANG"] = argv[i + 1]
|
|
30
|
+
i += 2
|
|
31
|
+
else:
|
|
32
|
+
out.append(argv[i])
|
|
33
|
+
i += 1
|
|
34
|
+
return out
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _list(args: list[str]) -> int:
|
|
38
|
+
methods = registry.discover()
|
|
39
|
+
if args[:2] == ["--format", "json"]:
|
|
40
|
+
print(json.dumps([{"id": m.id, "status": m.manifest.get("status"), "family": m.manifest.get("family"),
|
|
41
|
+
"summary": m.manifest.get("summary")} for m in methods], indent=2))
|
|
42
|
+
return 0
|
|
43
|
+
if not methods:
|
|
44
|
+
print("no methods found (set CLARENT_METHODS_DIR?)", file=sys.stderr)
|
|
45
|
+
return 1
|
|
46
|
+
width = max(len(m.id) for m in methods)
|
|
47
|
+
for m in methods:
|
|
48
|
+
print(f"{m.id:<{width}} {m.manifest.get('status', '?'):<9} {m.manifest.get('summary', '')}")
|
|
49
|
+
return 0
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _doctor(args: list[str]) -> int:
|
|
53
|
+
fail_on_stale = "--fail-on-stale" in args
|
|
54
|
+
args = [a for a in args if a != "--fail-on-stale"]
|
|
55
|
+
methods = registry.discover()
|
|
56
|
+
if args:
|
|
57
|
+
methods = [m for m in methods if m.id in args]
|
|
58
|
+
unknown = set(args) - {m.id for m in methods}
|
|
59
|
+
if unknown:
|
|
60
|
+
print(f"error: unknown method(s): {', '.join(sorted(unknown))}", file=sys.stderr)
|
|
61
|
+
return 2
|
|
62
|
+
bad = 0
|
|
63
|
+
for m in methods:
|
|
64
|
+
problems, stale = registry.doctor(m), registry.stale_claims(m)
|
|
65
|
+
print(f"{'FAIL' if problems or (stale and fail_on_stale) else 'ok '} {m.id}")
|
|
66
|
+
for p in problems:
|
|
67
|
+
print(f" - {p}")
|
|
68
|
+
for w in stale:
|
|
69
|
+
print(f" ! {w}")
|
|
70
|
+
bad += bool(problems) or (bool(stale) and fail_on_stale)
|
|
71
|
+
return 1 if bad else 0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def main(argv: list[str] | None = None) -> int:
|
|
75
|
+
argv = _pop_lang(list(sys.argv[1:] if argv is None else argv))
|
|
76
|
+
if not argv or argv[0] in ("-h", "--help"):
|
|
77
|
+
print(USAGE)
|
|
78
|
+
return 0
|
|
79
|
+
if argv[0] == "--version":
|
|
80
|
+
print(__version__)
|
|
81
|
+
return 0
|
|
82
|
+
cmd, rest = argv[0], argv[1:]
|
|
83
|
+
if cmd == "list":
|
|
84
|
+
return _list(rest)
|
|
85
|
+
if cmd == "doctor":
|
|
86
|
+
return _doctor(rest)
|
|
87
|
+
for m in registry.discover():
|
|
88
|
+
if m.id == cmd:
|
|
89
|
+
return registry.get_main(m)(rest)
|
|
90
|
+
print(f"error: unknown command or method {cmd!r}\n{USAGE}", file=sys.stderr)
|
|
91
|
+
return 2
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
if __name__ == "__main__":
|
|
95
|
+
sys.exit(main())
|
clarent/registry.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Method discovery and validation.
|
|
2
|
+
|
|
3
|
+
A *method* is a self-contained folder `methods/<id>/` with:
|
|
4
|
+
method.toml manifest (see methods/ach/method.toml)
|
|
5
|
+
CARD.md methodology card (sections listed in CARD_SECTIONS)
|
|
6
|
+
<module>/ importable Python package exposing main(argv) -> int
|
|
7
|
+
skill/ optional SKILL.md for Claude Code
|
|
8
|
+
tests/ unittest tests examples/ runnable examples
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import datetime as _dt
|
|
13
|
+
import importlib
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
import tomllib
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
REQUIRED_KEYS = ("id", "name", "version", "family", "status", "summary")
|
|
22
|
+
FAMILIES = ("military", "lean", "soviet", "systems", "decision", "extra")
|
|
23
|
+
STATUSES = ("spec", "beta", "stable", "reference")
|
|
24
|
+
VERIFICATION = ("read", "exists", "blocked", "unverified")
|
|
25
|
+
NOVELTY = ("none", "exists-but-weak", "exists-but-abandoned", "well-covered")
|
|
26
|
+
SURFACES = ("cli", "skill", "agent", "hook", "mcp", "action")
|
|
27
|
+
CARD_SECTIONS = (
|
|
28
|
+
"Origin", "Sources", "Problem it solves", "When to use / when NOT to use",
|
|
29
|
+
"How it maps to software work", "Inputs and outputs", "Algorithm (what is deterministic)",
|
|
30
|
+
"Limitations", "Prior art (GitHub scan)", "Worked example", "Evaluation",
|
|
31
|
+
)
|
|
32
|
+
NOVELTY_MAX_AGE_DAYS = 90
|
|
33
|
+
SKILL_DESCRIPTION_MAX = 300
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class Method:
|
|
38
|
+
id: str
|
|
39
|
+
dir: Path
|
|
40
|
+
manifest: dict
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def module(self) -> str:
|
|
44
|
+
return self.manifest.get("python", {}).get("module", "")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def methods_dir() -> Path:
|
|
48
|
+
"""$CLARENT_METHODS_DIR, else <repo>/methods (editable install), else packaged copy."""
|
|
49
|
+
env = os.environ.get("CLARENT_METHODS_DIR")
|
|
50
|
+
if env:
|
|
51
|
+
return Path(env)
|
|
52
|
+
here = Path(__file__).resolve()
|
|
53
|
+
for cand in (here.parents[2] / "methods", here.parent / "_methods"):
|
|
54
|
+
if cand.is_dir():
|
|
55
|
+
return cand
|
|
56
|
+
return here.parents[2] / "methods"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def load_manifest(path: Path) -> dict:
|
|
60
|
+
with open(path, "rb") as f:
|
|
61
|
+
return tomllib.load(f)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def discover(base: Path | None = None) -> list[Method]:
|
|
65
|
+
base = base or methods_dir()
|
|
66
|
+
out = []
|
|
67
|
+
if base.is_dir():
|
|
68
|
+
for d in sorted(p for p in base.iterdir() if p.is_dir()):
|
|
69
|
+
mf = d / "method.toml"
|
|
70
|
+
if mf.is_file():
|
|
71
|
+
m = load_manifest(mf)
|
|
72
|
+
out.append(Method(str(m.get("id", d.name)), d, m))
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_main(method: Method):
|
|
77
|
+
"""Import the method's package (lazily) and return its main(argv)."""
|
|
78
|
+
p = str(method.dir)
|
|
79
|
+
if p not in sys.path:
|
|
80
|
+
sys.path.insert(0, p)
|
|
81
|
+
return importlib.import_module(method.module).main
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# ---------------------------------------------------------------- doctor
|
|
85
|
+
def _frontmatter(text: str) -> dict:
|
|
86
|
+
if not text.startswith("---"):
|
|
87
|
+
return {}
|
|
88
|
+
end = text.find("\n---", 3)
|
|
89
|
+
if end < 0:
|
|
90
|
+
return {}
|
|
91
|
+
fm = {}
|
|
92
|
+
for line in text[3:end].splitlines():
|
|
93
|
+
m = re.match(r"^([A-Za-z_-]+):\s*(.*)$", line)
|
|
94
|
+
if m:
|
|
95
|
+
fm[m.group(1)] = m.group(2).strip()
|
|
96
|
+
return fm
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def stale_claims(method: Method, today: _dt.date | None = None) -> list[str]:
|
|
100
|
+
"""Novelty claims older than NOVELTY_MAX_AGE_DAYS. A warning, not a failure (see `doctor --fail-on-stale`)."""
|
|
101
|
+
today = today or _dt.date.today()
|
|
102
|
+
try:
|
|
103
|
+
age = (today - _dt.date.fromisoformat(str(method.manifest.get("novelty", {}).get("checked_on")))).days
|
|
104
|
+
except ValueError:
|
|
105
|
+
return []
|
|
106
|
+
if age > NOVELTY_MAX_AGE_DAYS:
|
|
107
|
+
return [f"novelty claim is {age} days old (> {NOVELTY_MAX_AGE_DAYS}): re-run tools/github_scan2.py and update method.toml"]
|
|
108
|
+
return []
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def doctor(method: Method) -> list[str]:
|
|
112
|
+
"""Return a list of problems (empty = healthy). Pure: reads files, never writes."""
|
|
113
|
+
m, d, problems = method.manifest, method.dir, []
|
|
114
|
+
|
|
115
|
+
for k in REQUIRED_KEYS:
|
|
116
|
+
if not m.get(k):
|
|
117
|
+
problems.append(f"manifest: missing '{k}'")
|
|
118
|
+
if m.get("id") and m["id"] != d.name:
|
|
119
|
+
problems.append(f"manifest: id {m['id']!r} must equal folder name {d.name!r}")
|
|
120
|
+
if m.get("family") and m["family"] not in FAMILIES:
|
|
121
|
+
problems.append(f"manifest: family must be one of {FAMILIES}")
|
|
122
|
+
if m.get("status") and m["status"] not in STATUSES:
|
|
123
|
+
problems.append(f"manifest: status must be one of {STATUSES}")
|
|
124
|
+
|
|
125
|
+
sources = m.get("sources", [])
|
|
126
|
+
if not sources:
|
|
127
|
+
problems.append("manifest: at least one [[sources]] entry is required")
|
|
128
|
+
for i, s in enumerate(sources):
|
|
129
|
+
if s.get("verification") not in VERIFICATION:
|
|
130
|
+
problems.append(f"sources[{i}]: verification must be one of {VERIFICATION}")
|
|
131
|
+
if s.get("verification") in ("read", "blocked") and not s.get("url"):
|
|
132
|
+
problems.append(f"sources[{i}]: '{s.get('verification')}' requires a url")
|
|
133
|
+
if s.get("verification") != "unverified" and not (s.get("url") or s.get("citation")):
|
|
134
|
+
problems.append(f"sources[{i}]: needs a url or a citation")
|
|
135
|
+
|
|
136
|
+
nov = m.get("novelty", {})
|
|
137
|
+
if nov.get("status") not in NOVELTY:
|
|
138
|
+
problems.append(f"novelty: status must be one of {NOVELTY}")
|
|
139
|
+
try:
|
|
140
|
+
_dt.date.fromisoformat(str(nov.get("checked_on")))
|
|
141
|
+
except ValueError:
|
|
142
|
+
problems.append("novelty: checked_on must be an ISO date (YYYY-MM-DD)")
|
|
143
|
+
|
|
144
|
+
card = d / "CARD.md"
|
|
145
|
+
if not card.is_file():
|
|
146
|
+
problems.append("CARD.md is missing (copy templates/methodology-card.md)")
|
|
147
|
+
else:
|
|
148
|
+
heads = {h.strip().lower() for h in re.findall(r"^##\s+(.+)$", card.read_text(encoding="utf-8"), re.M)}
|
|
149
|
+
for sec in CARD_SECTIONS:
|
|
150
|
+
if sec.lower() not in heads:
|
|
151
|
+
problems.append(f"CARD.md: missing section '## {sec}'")
|
|
152
|
+
|
|
153
|
+
surfaces = m.get("surfaces", {})
|
|
154
|
+
for k in surfaces:
|
|
155
|
+
if k not in SURFACES:
|
|
156
|
+
problems.append(f"surfaces: unknown surface {k!r}")
|
|
157
|
+
if surfaces.get("cli"):
|
|
158
|
+
if not method.module or not (d / method.module).is_dir():
|
|
159
|
+
problems.append("surfaces.cli: [python].module must be a package folder inside the method")
|
|
160
|
+
if surfaces.get("skill"):
|
|
161
|
+
sk = d / "skill" / "SKILL.md"
|
|
162
|
+
if not sk.is_file():
|
|
163
|
+
problems.append("surfaces.skill: skill/SKILL.md is missing")
|
|
164
|
+
else:
|
|
165
|
+
fm = _frontmatter(sk.read_text(encoding="utf-8"))
|
|
166
|
+
if not fm.get("name") or not fm.get("description"):
|
|
167
|
+
problems.append("SKILL.md: frontmatter needs 'name' and 'description'")
|
|
168
|
+
elif len(fm["description"]) > SKILL_DESCRIPTION_MAX:
|
|
169
|
+
problems.append(f"SKILL.md: description is {len(fm['description'])} chars (max {SKILL_DESCRIPTION_MAX}); "
|
|
170
|
+
"descriptions cost context tokens in every session")
|
|
171
|
+
if not any((d / "tests").glob("test_*.py")):
|
|
172
|
+
problems.append("tests/: at least one test_*.py is required")
|
|
173
|
+
if not (d / "examples").is_dir() or not any((d / "examples").iterdir()):
|
|
174
|
+
problems.append("examples/: at least one runnable example is required")
|
|
175
|
+
return problems
|