thinking-python: reference implementation, corpus and gates
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- README.md+53-5
- catalog/conflict_policy.jsonAdded+28
- catalog/patterns.jsonAdded+82
- catalog/request_templates.jsonAdded+30
- catalog/smoke_requests.jsonAdded+63
- corpus/corpus.jsonlAdded
- corpus/maintenance.jsonlAdded+36
- doc/HOW_TO_ADD_AN_ENTRY.pyAdded+60
- doc/REASONS.mdAdded+61
- fixtures/lab/conftest.pyAdded+6
- fixtures/lab/registry.pyAdded+31
- fixtures/lab/tests/test_registry.pyAdded+19
- fixtures/seed_project/README.mdAdded+2
- fixtures/seed_project/auth.pyAdded+16
- fixtures/seed_project/billing.pyAdded+16
- fixtures/seed_project/cache.pyAdded+19
- fixtures/seed_project/conftest.pyAdded+4
- fixtures/seed_project/export.pyAdded+16
- fixtures/seed_project/inventory.pyAdded+20
- fixtures/seed_project/jobqueue.pyAdded+19
- fixtures/seed_project/reporting.pyAdded+19
- fixtures/seed_project/routing.pyAdded+16
- fixtures/seed_project/search.pyAdded+16
- fixtures/seed_project/session.pyAdded+19
- fixtures/seed_project/tests/test_auth.pyAdded+13
- fixtures/seed_project/tests/test_billing.pyAdded+10
- fixtures/seed_project/tests/test_cache.pyAdded+13
- fixtures/seed_project/tests/test_export.pyAdded+13
- fixtures/seed_project/tests/test_inventory.pyAdded+13
- fixtures/seed_project/tests/test_jobqueue.pyAdded+13
- fixtures/seed_project/tests/test_reporting.pyAdded+13
- fixtures/seed_project/tests/test_routing.pyAdded+13
- fixtures/seed_project/tests/test_search.pyAdded+13
- fixtures/seed_project/tests/test_session.pyAdded+13
- lexicon/ar.jsonAdded+117
- lexicon/en.jsonAdded+34
- lexicon/es.jsonAdded+34
- lexicon/hi.jsonAdded+34
- lexicon/it.jsonAdded+34
- lexicon/zh.jsonAdded+34
- lingologos_thinkingpython/__init__.pyAdded+9
- lingologos_thinkingpython/catalog.pyAdded+103
- lingologos_thinkingpython/intent.pyAdded+99
- lingologos_thinkingpython/lexicon.pyAdded+82
- lingologos_thinkingpython/orchestrator.pyAdded+108
- lingologos_thinkingpython/preflight.pyAdded+84
- lingologos_thinkingpython/reasons.pyAdded+62
- lingologos_thinkingpython/session.pyAdded+199
- lingologos_thinkingpython/shapes.pyAdded+513
- nodes/__init__.pyAdded+3
24 unmodified lines252627282930313213 unmodified lines46474849505152535424 unmodified linessays so. The specification is published first, before any code, so the contractcan be reviewed and implemented independently.The one file here is [SPECIFICATION.md](SPECIFICATION.md). It is normative: where code andthis file disagree, the code is wrong until this file is amended in the same change.## What the document states13 unmodified lines## StatusDraft 1, normative. No code, no corpus and no weights are published in this revision: theacceptance criteria of section 11 describe what a later revision must show before it canclaim anything.## Provenance24 unmodified lines25262728293031323334353637383940414243444513 unmodified lines596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110224 unmodified linessays so. The specification is published first, before any code, so the contractcan be reviewed and implemented independently.The normative file is [SPECIFICATION.md](SPECIFICATION.md). Where code and that filedisagree, the code is wrong until the specification is amended in the same change. Theimplementation, the corpus, the seed project and the gates live in the folders thespecification lays out in section 10; [doc/REASONS.md](doc/REASONS.md) is the reason-coderegistry and [doc/HOW_TO_ADD_AN_ENTRY.py](doc/HOW_TO_ADD_AN_ENTRY.py) is the executablechecklist a new catalog entry has to pass.## How to run it```pip install -r requirements.txtpython tools/ask.py --workspace fixtures/seed_project --lang it --request "if annidato in keep"python tools/run_maintenance.py # the section 1.1 demo, replays 36 requestspython tools/run_gates.py --catalog-regress```## What the document states13 unmodified lines## StatusDraft 2, normative, **with a reference implementation**. This revision carries code,data and measured numbers, and it states plainly which acceptance criteria of section 11the implementation meets and which it does not.What runs today, as measured on 2026-12-03 by `tools/run_gates.py`:| Gate | Measured ||---|---|| `confinement` | `PASS`, 58 python files, nothing outside this folder moved || `tests` | 33 tests, all pass || `catalog_integrity` | 7 entries, 0 defects || `catalog_conflicts` | 21 declared pairs, 0 missing || `corpus_fingerprint` | `0149e22988e271f0`, 13272 rows re-derived byte for byte || eval top-1 entry | 1.00, floor 0.85 || eval out-of-scope refusal | 1.00, floor 0.90 || eval contrastive | 1.00, floor 0.70 || spread across varieties | 0.00 || `seed_project` | 22 files, suite green (39 tests) || `maintenance` demo of section 1.1 | 36 requests, 32 `VERIFIED`, 4 `REFUSED`, every refusal naming a code; 36 of 36 behaved as expected |Two honest limits on those numbers.**D1 is not met.** Section 11 asks for a catalog of at least 40 entries; this revisionpublishes 7. The threshold is not lowered and the criterion is not reworded: the gap isthe result. Seven entries are enough to run the whole topology end to end and to showthat adding an entry does not break the existing ones (`catalog_regress`), which is whatD1b tests, but a 40-entry catalog is open work.**The coverage numbers are compositional, not human.** Every corpus row is generated fromthe same lexicon the router scores against, so top-1 equal to 1.00 shows that the routeris a faithful function of its own vocabulary and of the noise and minimal-pair probesadded around it. It does not show that an unseen person phrasing a request freely wouldbe understood. The 36 maintenance requests are hand-written in plain words and are theclosest thing here to that test; they are reported with their refusals. The corpus rowscarry a deterministic `train`/`eval` split, and the table above quotes the eval part.Criteria D0, D1b, D2, D3, D4, D5, D5b, D5c, D7, D8 are met as measured. D1 is not met.D6 (coverage of the suite over the package functions) is not instrumented yet.## Provenance
12345678910111213141516171819202122232425262728{ "version": 1, "max_candidates": 4, "pairs": { "dead-import|magic-literal": "specificity", "add-assertion|guard-clause": "clarify", "concat-fstring|magic-literal": "family_order", "loop-comprehension|magic-literal": "family_order", "add-assertion|mutable-default": "specificity", "dead-import|guard-clause": "specificity", "concat-fstring|guard-clause": "specificity", "add-assertion|concat-fstring": "specificity", "add-assertion|dead-import": "specificity", "add-assertion|loop-comprehension": "specificity", "add-assertion|magic-literal": "clarify", "concat-fstring|dead-import": "specificity", "concat-fstring|loop-comprehension": "family_order", "concat-fstring|mutable-default": "specificity", "dead-import|guard-clause": "specificity", "dead-import|loop-comprehension": "specificity", "dead-import|mutable-default": "specificity", "guard-clause|loop-comprehension": "specificity", "guard-clause|magic-literal": "clarify", "guard-clause|mutable-default": "specificity", "loop-comprehension|mutable-default": "specificity", "magic-literal|mutable-default": "specificity" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182{ "version": 1, "entries": [ { "id": "mutable-default", "family": "refactoring", "shape": "mutable-default", "source": "Effective Python item 17", "effect": "the default is no longer built once at definition time", "lock": "calling the function twice returns an independent empty value", "refusals": ["NO_SHAPE", "AMBIGUOUS_TARGET", "ASSERTION_REMOVED"], "min_assurance": 2, "frames": ["mutable-default"] }, { "id": "magic-literal", "family": "refactoring", "shape": "magic-literal", "source": "Refactoring, chapter 7", "effect": "the value is named once at module level", "lock": "the module exposes the constant and the body refers to it", "refusals": ["NO_SHAPE", "AMBIGUOUS_TARGET", "DYNAMIC_REACH"], "min_assurance": 2, "frames": ["magic-literal"] }, { "id": "guard-clause", "family": "refactoring", "shape": "guard-clause", "source": "Refactoring, guard clause", "effect": "the body is no longer wrapped in one condition", "lock": "the function still returns the same value for the same input", "refusals": ["NO_SHAPE", "AMBIGUOUS_TARGET", "ASSERTION_REMOVED"], "min_assurance": 2, "frames": ["guard-clause"] }, { "id": "dead-import", "family": "refactoring", "shape": "dead-import", "source": "static property of the syntax tree", "effect": "the name is no longer bound and the module still imports", "lock": "the module imports cleanly and the name is gone", "refusals": ["NO_SHAPE", "GENERATED_TARGET", "AMBIGUOUS_TARGET"], "min_assurance": 1, "frames": ["dead-import"] }, { "id": "loop-comprehension", "family": "python_idiom", "shape": "loop-comprehension", "source": "the idiom of the language", "effect": "the list is built in one expression", "lock": "the list is equal to the one the loop built", "refusals": ["NO_SHAPE", "DYNAMIC_REACH", "AMBIGUOUS_TARGET"], "min_assurance": 2, "frames": ["loop-comprehension"] }, { "id": "concat-fstring", "family": "python_idiom", "shape": "concat-fstring", "source": "the idiom of the language", "effect": "the message is built by one formatted literal", "lock": "the produced string is byte equal to the concatenation", "refusals": ["NO_SHAPE", "NOT_ASCII_TARGET", "AMBIGUOUS_TARGET"], "min_assurance": 2, "frames": ["concat-fstring"] }, { "id": "add-assertion", "family": "methodology", "shape": "add-assertion", "source": "design by contract", "effect": "a caller passing the wrong type fails at the boundary", "lock": "the function raises AssertionError on a wrong argument", "refusals": ["NO_SHAPE", "ASSERTION_REMOVED", "AMBIGUOUS_TARGET"], "min_assurance": 2, "frames": ["add-assertion"] } ]}123456789101112131415161718192021222324252627282930{ "note": "Templates and negative requests for the composed corpus. Data, not prose: one entry per language variety of the lexicon.", "templates": { "en": ["{p} in {s}", "fix the {p} of {s}", "{s} has a {p}, clean it", "there is a {p} in {s}", "please handle the {p} in {s}", "clean up the {p} of {s}"], "it": ["{p} in {s}", "sistema la {p} di {s}", "{s} ha una {p}, pulisci", "c'e una {p} in {s}", "gestisci la {p} in {s}", "pulisci la {p} di {s}"], "es": ["{p} en {s}", "arregla la {p} de {s}", "{s} tiene una {p}, limpia", "hay una {p} en {s}", "maneja la {p} en {s}", "limpia la {p} de {s}"], "zh": ["{p} {s}", "{s} \u91cc\u7684{p}", "\u5904\u7406 {s} \u7684{p}", "{s} \u6709\u4e00\u4e2a{p}", "\u6e05\u7406 {s} \u7684{p}", "{s} \u4e2d\u5b58\u5728{p}"], "ar": ["{p} \u0641\u064a {s}", "\u0623\u0635\u0644\u062d {p} \u0641\u064a {s}", "{s} \u0628\u0647 {p} \u0646\u0638\u0641\u0647", "\u064a\u0648\u062c\u062f {p} \u0641\u064a {s}", "\u062a\u0639\u0627\u0645\u0644 \u0645\u0639 {p} \u0641\u064a {s}", "\u0646\u0638\u0641 {p} \u0641\u064a {s}"], "hi": ["{s} \u092e\u0947\u0902 {p}", "{s} \u0915\u0940 {p} \u0920\u0940\u0915 \u0915\u0930\u0947\u0902", "{s} \u092e\u0947\u0902 {p} \u0939\u0948, \u0938\u093e\u092b\u093c \u0915\u0930\u0947\u0902", "{p} \u0915\u094b \u0920\u0940\u0915 \u0915\u0930\u0947\u0902 {s}", "{s} \u0915\u093e {p} \u0938\u0902\u092d\u093e\u0932\u0947\u0902", "{s} \u092e\u0947\u0902 {p} \u0928\u093f\u0915\u093e\u0932\u0947\u0902"] }, "negatives": { "en": ["make this module faster", "rewrite the whole file in rust", "add caching to parse", "this code is ugly improve it", "speed up the tests"], "it": ["rendi questo modulo piu veloce", "riscrivi tutto in rust", "aggiungi una cache", "questo codice e brutto miglioralo", "ottimizza i test"], "es": ["haz este modulo mas rapido", "reescribe todo en rust", "agrega una cache", "este codigo es feo mejoralo", "acelera las pruebas"], "zh": ["\u8ba9\u8fd9\u4e2a\u6a21\u5757\u66f4\u5feb", "\u7528 rust \u91cd\u5199", "\u52a0\u4e00\u4e2a\u7f13\u5b58", "\u8fd9\u6bb5\u4ee3\u7801\u4e0d\u597d\uff0c\u6539\u8fdb\u5b83", "\u52a0\u901f\u6d4b\u8bd5"], "ar": ["\u0627\u062c\u0639\u0644 \u0647\u0630\u0627 \u0627\u0644\u0645\u0644\u0641 \u0627\u0633\u0631\u0639", "\u0627\u0639\u0627\u062f\u0629 \u0643\u062a\u0627\u0628\u0629 \u0627\u0644\u0643\u0644 \u0628\u0644\u063a\u0629 rust", "\u0627\u0636\u0641 \u062a\u062e\u0632\u064a\u0646\u064b\u0627 \u0645\u0624\u0642\u062a\u064b\u0627", "\u0647\u0630\u0627 \u0627\u0644\u0643\u0648\u062f \u0633\u064a\u0621 \u062d\u0633\u0651\u0646\u0647", "\u0633\u0631\u0651\u0639 \u0627\u0644\u0627\u062e\u062a\u0628\u0627\u0631\u0627\u062a"], "hi": ["\u0907\u0938 \u092e\u0949\u0921\u094d\u092f\u0941\u0932 \u0915\u094b \u0924\u0947\u091c\u093c \u0915\u0930\u0947\u0902", "\u0938\u092c \u0915\u0941\u091b rust \u092e\u0947\u0902 \u0932\u093f\u0916\u0947\u0902", "\u0915\u0948\u0936 \u091c\u094b\u0921\u093c\u0947\u0902", "\u092f\u0939 \u0915\u094b\u0921 \u092c\u0941\u0930\u093e \u0939\u0948 \u0938\u0941\u0927\u093e\u0930\u0947\u0902", "\u091f\u0947\u0938\u094d\u091f \u0924\u0947\u091c\u093c \u0915\u0930\u0947\u0902"] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263{
"note": "One request per shape in the catalog, spread over the six varieties. Data, not prose.",
"requests": [
{
"lang": "en",
"text": "remove the mutable default in collect"
},
{
"lang": "en",
"text": "the os import is not used any more"
},
{
"lang": "it",
"text": "togli il numero magico in label_for"
},
{
"lang": "en",
"text": "turn this for loop into a list comprehension in collect"
},
{
"lang": "en",
"text": "build this message with an f string in label_for"
},
{
"lang": "es",
"text": "agrega una guardia para el argumento record"
},
{
"lang": "en",
"text": "flatten this nested if into an early return in parse"
},
{
"lang": "zh",
"text": "把 parse 里的嵌套 if 改成提前返回"
},
{
"lang": "ar",
"text": "ازالة القيمة الافتراضية القابلة للتغيير في collect"
},
{
"lang": "hi",
"text": "collect से परिवर्तनशील डिफ़ॉल्ट हटाएं"
}
],
"language_free": [
{
"lang": "zh",
"text": "把 parse 里的嵌套 if 改成提前返回"
},
{
"lang": "ar",
"text": "حول هذا الشرط المتداخل إلى خروج مبكر parse"
},
{
"lang": "hi",
"text": "इस नेस्टेड if को पूर्व लौटाएं में बदलें parse"
},
{
"lang": "it",
"text": "appiattisci in parse questo if annidato in un ritorno anticipato"
}
]
}123456789101112131415161718192021222324252627282930313233343536{"expect": "VERIFIED", "lang": "en", "text": "mutable default in stock"}{"expect": "VERIFIED", "lang": "en", "text": "magic number in badge"}{"expect": "VERIFIED", "lang": "en", "text": "nested if in reserve"}{"expect": "VERIFIED", "lang": "en", "text": "unused import in billing"}{"expect": "VERIFIED", "lang": "en", "text": "list comprehension in pick"}{"expect": "VERIFIED", "lang": "en", "text": "string concatenation in invoice"}{"expect": "VERIFIED", "lang": "en", "text": "check the argument in bind"}{"expect": "VERIFIED", "lang": "en", "text": "unnamed constant in latency"}{"expect": "VERIFIED", "lang": "en", "text": "early return in refund"}{"expect": "VERIFIED", "lang": "en", "text": "default list in price"}{"expect": "VERIFIED", "lang": "it", "text": "default mutabile in tokens"}{"expect": "VERIFIED", "lang": "it", "text": "numero magico in stamp"}{"expect": "VERIFIED", "lang": "it", "text": "if annidato in keep"}{"expect": "VERIFIED", "lang": "it", "text": "import inutilizzato in reporting"}{"expect": "VERIFIED", "lang": "it", "text": "riscrivi il ciclo in rows"}{"expect": "VERIFIED", "lang": "it", "text": "concatenazione di stringhe in title"}{"expect": "VERIFIED", "lang": "es", "text": "lista por defecto in ranks"}{"expect": "VERIFIED", "lang": "es", "text": "numero magico in weight"}{"expect": "VERIFIED", "lang": "es", "text": "if anidado in scope"}{"expect": "VERIFIED", "lang": "es", "text": "import sin usar in session"}{"expect": "VERIFIED", "lang": "es", "text": "reescribe el bucle in load_rows"}{"expect": "VERIFIED", "lang": "es", "text": "concatenacion de cadenas in caption"}{"expect": "VERIFIED", "lang": "zh", "text": "魔法数字 in ttl"}{"expect": "VERIFIED", "lang": "zh", "text": "嵌套 if in choose"}{"expect": "VERIFIED", "lang": "zh", "text": "字符串拼接 in tag"}{"expect": "VERIFIED", "lang": "zh", "text": "未使用的导入 in session"}{"expect": "VERIFIED", "lang": "ar", "text": "أعد كتابة الحلقة in tokens"}{"expect": "VERIFIED", "lang": "ar", "text": "استيراد غير مستخدم in billing"}{"expect": "VERIFIED", "lang": "ar", "text": "قيمة افتراضية قابلة للتغيير in price"}{"expect": "VERIFIED", "lang": "hi", "text": "परिवर्तनशील डिफ़ॉल्ट in pick"}{"expect": "VERIFIED", "lang": "hi", "text": "नेस्टेड if in scope"}{"expect": "VERIFIED", "lang": "hi", "text": "जादुई संख्या in weight"}{"expect": "REFUSED", "lang": "en", "text": "make this module faster"}{"expect": "REFUSED", "lang": "it", "text": "rendi questo modulo piu veloce"}{"expect": "REFUSED", "lang": "es", "text": "reescribe todo en rust"}{"expect": "REFUSED", "lang": "zh", "text": "jia yige cunchu"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""How to add one entry to the catalog, as an executable checklist.
Run it: python doc/HOW_TO_ADD_AN_ENTRY.py
It does not add anything. It states, in code, the seven things a new entry owes thebundle, and checks each one against the catalog as it stands, so the list cannot rot.
1. an id, a family, a shape, a source, in catalog/patterns.json 2. an effect sentence and a lock sentence, both about the observable change 3. refusals: the reason codes this entry may legitimately answer with 4. a min_assurance the entry must reach before a run may claim VERIFIED 5. a frame id, and a phrase set for that frame in each of the six lexicon files 6. a rule and a lock test: shapes.py edit_<shape> plus tests/test_edit_pair.py 7. a conflict policy for every pair of entries that can claim the same symbol
Then: python tools/build_corpus.py && python tools/measure_coverage.py python tools/run_gates.py --catalog-regressThe last command compares the eval top-1 against results/coverage.baseline.json andfails if a pre-existing entry lost more than 0.02, which is how growth stays safe."""
import jsonimport osimport sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, ROOT)
from lingologos_thinkingpython import catalog, lexicon # noqa: E402
REQUIRED = ("id", "family", "shape", "source", "effect", "lock", "refusals", "min_assurance", "frames")
def check() -> int: entries = catalog.load_entries() policies = catalog.load_policies() problems = [] for entry in entries: for key in REQUIRED: if key not in entry: problems.append("%s: missing %s" % (entry.get("id", "?"), key)) for frame in entry.get("frames", []): for lang in lexicon.LANGS: phrases = lexicon.load(lang)["frames"].get(frame) or [] if not phrases: problems.append("%s: no %s phrase for frame %s" % (entry["id"], lang, frame)) claims = {} for entry in entries: claims.setdefault(entry["shape"], []).append(entry["id"]) defects, _resolved = catalog.conflict_lines(claims, policies) problems.extend(defects) for line in problems: print("MISSING " + line) print("entries=%d checked=%d problems=%d" % (len(entries), len(entries), len(problems))) return 1 if problems else 0
if __name__ == "__main__": raise SystemExit(check())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Reason codes
Every refusal, warning and gate failure this bundle reports is one code from the registrybelow. The registry is `lingologos_thinkingpython/reasons.py`; this file describes it andis checked against it by `tests/test_reasons.py`, which scans the package, the nodes andthe tools for an all-caps literal that is not registered. A code that is not in theregistry cannot be emitted, and a code in the registry that no path emits fails the sametest only if the literal never appears -- the scan is one-directional on purpose, so anunused constant is not an error but an undocumented emission always is.
Kernel codes are not restated here. When a kernel is present its codes are imported fromthe kernel and pass through unchanged.
## Session and node codes
| Code | Who raises it | What it means ||---|---|---|| `NODE_TIMEOUT` | orchestrator | A node process exceeded its budget; the run is not reported as verified. || `NONSENSE_REPLAY` | arbiter | A replayed transcript does not re-derive the verdict it carries. || `CHECKER_ABSTAIN` | gate_checker | A checker could not decide, so assurance cannot rise to its top value. || `NOT_UNDERSTOOD` | intent | No frame scored above `min_score`; the request is refused, not guessed. || `AMBIGUOUS_TARGET` | intent | Two frames scored within `clarify_margin`; the run stops and asks. || `ALREADY_APPLIED` | executor | The edit is already in the source; nothing is written, nothing is claimed. || `PROTECTED_PATH` | executor | The target path is outside what the workspace admits. || `LINKED_PATH_IN_WORKSPACE` | preflight/executor | A path inside the workspace resolves through a link. || `NO_TEST_ANCHOR` | planner | No test file exists to lock the intended change. || `ASSERTION_REMOVED` | gate_checker | The projected source has fewer `assert` statements than the original. || `OUT_OF_CATALOG` | intent | The request maps to no catalog entry: outside the published contract. || `NO_MATCH` | locator | The named symbol is not in the workspace index. || `NO_EDIT` | planner | The entry matched but produced no edit for this file. || `SEARCH_NOT_FOUND` | executor | The edit's search block is not byte-present in the target. |
## Preflight codes
Raised by `preflight.admit` before any node runs, on the workspace itself.
| Code | What it means ||---|---|| `NO_TEST_FILE` | The project carries no test suite, so no change can be locked. || `TAB_INDENTED_TARGET` | The target mixes tab indentation; the edit pairs assume spaces. || `CRLF_TARGET` | The target file has CRLF line endings. || `NOT_ASCII_TARGET` | The target file is not ASCII, so byte-exact edit pairs are unsafe. || `DYNAMIC_REACH` | The target is reached through dynamic imports or `exec`. || `GENERATED_TARGET` | The target looks generated, so an edit there is not maintainable. |
## Gate codes
Raised by `tools/run_gates.py` and the entry gates.
| Code | What it means ||---|---|| `PAIR_DISHONEST` | An edit pair claims a change its test does not lock, or locks a change the edit does not make. || `SHAPE_STILL_PRESENT` | The edit ran but the unwanted shape is still in the projected source. || `SUITE_RED` | The suite of the workspace is not green after the change. || `LEXICON_INCOMPLETE` | A variety file is missing a required key or a frame has no phrase. || `CATALOG_INTEGRITY` | An entry has no rule, no test, or no declared refusals. || `CATALOG_CONFLICT` | Two entries claim the same symbol with no declared policy. || `CONFINEMENT` | Something outside `datasets/thinkingpython/` moved. |
Status words (`VERIFIED`, `REFUSED`, `PASS`, `FAIL`, `GREEN`, `ALL_GATES_PASS`, ...) areverdicts and gate labels, not reason codes, and are listed as such in the test.123456"""Makes the module under test importable from the tests folder."""
import osimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))12345678910111213141516171819202122232425262728293031"""A small module with one instance of every shape the catalog knows."""
import jsonimport os
RETRY_WINDOW = 30
def collect(names=[]): picked = [] for name in names: picked.append(name.strip()) return picked
def label_for(value, count: int): assert count >= 0 total = value + 255 return "item " + str(count) + " of " + str(total)
def show(record: dict): if isinstance(record, dict): return json.dumps(record) return str(record)
def parse(text: str): if len(text) > 0: pieces = text.split(",") return [piece.strip() for piece in pieces]12345678910111213141516171819"""Behaviour the catalogue must not break."""
import registry
def test_collect_keeps_the_order(): assert registry.collect([" b ", "a"]) == ["b", "a"]
def test_label_for_reads_well(): assert registry.label_for(5, 2) == "item 2 of 260"
def test_show_handles_dicts(): assert registry.show({"a": 1}) == '{"a": 1}'
def test_parse_splits_and_strips(): assert registry.parse("a, b") == ["a", "b"]12Seed project for the maintenance mission. Every module carries at least oneshape listed in the catalog; the tests are the safety net the executor runs.12345678910111213141516def scopes(roles=[]): names = [] for role in roles: names.append(role.lower()) return names
def window(days: int): return days * 24
def permit(ticket): if ticket.get('valid'): return ticket.get('who') return None
def whois(ticket): return 'who ' + ticket['who']12345678910111213141516import jsonimport os
def price(lines=[]): total = 0 for line in lines: total = total + line['qty'] return total
def invoice(customer, amount): return customer + ' owes ' + str(amount)
def refund(payment): if payment.get('paid'): return payment.get('amount') return 012345678910111213141516171819import hashlibimport time
def memo(items=[]): keys = [] for item in items: keys.append(item[0]) return keys
def expiry(hours: int): return hours * 86400
def touch(entry): if entry.get('warm'): return entry['key'] return ''
def mark(entry): return 'key ' + entry['key']1234import osimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))12345678910111213141516def columns(rows_=[]): names = [] for row in rows_: names.append(row[0]) return names
def limit(rows_n: int): return rows_n * 500
def ready(sheet): if sheet.get('built'): return sheet['name'] return ''
def name(sheet): return 'sheet ' + sheet['name']1234567891011121314151617181920def stock(items=[]): cleaned = [] for item in items: cleaned.append(item.strip()) return cleaned
def badge(qty: int): total = qty + 255 return 'x' + str(total)
def reserve(order): if isinstance(order, dict): return order.get('id') return None
def load_rows(text): rows = [] for line in text.splitlines(): rows.append(line.split(',')) return rows12345678910111213141516171819import heapqimport os
def drain(jobs=[]): names = [] for job in jobs: names.append(job['id']) return names
def retry(seconds: int): return seconds + 30
def head(task): if task.get('queued'): return task['id'] return None
def line(task): return task['id'] + ' @ ' + task['at']12345678910111213141516171819import reimport time
def rows(data=[]): out = [] for d in data: out.append(d['k']) return out
def stamp(sec: int): return sec + 3600
def title(row): return 'row ' + str(row['n'])
def keep(doc): if doc.get('live'): return True return False12345678910111213141516def pick(candidates=[]): best = [] for c in candidates: best.append(c[0]) return best
def latency(ms: int): return ms * 1000
def choose(route): if route.get('open'): return route['name'] return ''
def label(node): return 'node ' + node['id']12345678910111213141516def ranks(scores=[]): top = [] for s in scores: top.append(s['id']) return top
def weight(pos: int): return pos + 50
def scope(index): if index.get('ready'): return index['name'] return ''
def caption(hit): return hit['title'] + ' (' + hit['kind'] + ')'12345678910111213141516171819import base64import uuid
def tokens(parts=[]): joined = [] for p in parts: joined.append(p.lower()) return joined
def ttl(minutes: int): return minutes * 60
def bind(user): if user.get('verified'): return user.get('id') return None
def tag(user): return 'user ' + user['id']12345678910111213from auth import permit, scopes, whois, window
def test_scopes(): assert scopes(['A']) == ['a']
def test_window(): assert window(3) == 72
def test_permit(): assert permit({'valid': True, 'who': 'u'}) == 'u'
def test_whois(): assert whois({'who': 'u'}) == 'who u'12345678910from billing import invoice, price, refund
def test_price(): assert price([{'qty': 2}, {'qty': 1}]) == 3
def test_invoice(): assert invoice('acme', 4) == 'acme owes 4'
def test_refund(): assert refund({'paid': True, 'amount': 9}) == 912345678910111213from cache import expiry, mark, memo, touch
def test_memo(): assert memo([('a',), ('b',)]) == ['a', 'b']
def test_expiry(): assert expiry(2) == 172800
def test_touch(): assert touch({'warm': True, 'key': 'k'}) == 'k'
def test_mark(): assert mark({'key': 'z'}) == 'key z'12345678910111213from export import columns, limit, name, ready
def test_columns(): assert columns([('a',), ('b',)]) == ['a', 'b']
def test_limit(): assert limit(2) == 1000
def test_ready(): assert ready({'built': True, 'name': 's'}) == 's'
def test_name(): assert name({'name': 's'}) == 'sheet s'12345678910111213from inventory import badge, load_rows, reserve, stock
def test_stock_strips(): assert stock([' a ', 'b']) == ['a', 'b']
def test_badge(): assert badge(1) == 'x256'
def test_reserve(): assert reserve({'id': 3}) == 3
def test_load_rows(): assert load_rows('a,b\nc') == [['a', 'b'], ['c']]12345678910111213from jobqueue import drain, head, line, retry
def test_drain(): assert drain([{'id': 'j'}]) == ['j']
def test_retry(): assert retry(5) == 35
def test_head(): assert head({'queued': True, 'id': 'j'}) == 'j'
def test_line(): assert line({'id': 'j', 'at': '9'}) == 'j @ 9'12345678910111213from reporting import keep, rows, stamp, title
def test_rows(): assert rows([{'k': 'a'}]) == ['a']
def test_stamp(): assert stamp(10) == 3610
def test_title(): assert title({'n': 2}) == 'row 2'
def test_keep(): assert keep({'live': True}) is True12345678910111213from routing import choose, label, latency, pick
def test_pick(): assert pick([('a', 1), ('b', 2)]) == ['a', 'b']
def test_latency(): assert latency(2) == 2000
def test_choose(): assert choose({'open': True, 'name': 'n1'}) == 'n1'
def test_label(): assert label({'id': 'z'}) == 'node z'12345678910111213from search import caption, ranks, scope, weight
def test_ranks(): assert ranks([{'id': 'a'}]) == ['a']
def test_weight(): assert weight(3) == 53
def test_scope(): assert scope({'ready': True, 'name': 'i'}) == 'i'
def test_caption(): assert caption({'title': 't', 'kind': 'k'}) == 't (k)'12345678910111213from session import bind, tag, tokens, ttl
def test_tokens(): assert tokens(['A', 'B']) == ['a', 'b']
def test_ttl(): assert ttl(2) == 120
def test_bind(): assert bind({'verified': True, 'id': 7}) == 7
def test_tag(): assert tag({'id': 'q'}) == 'user q'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117{
"lang": "ar",
"name": "Arabic",
"noise": [
",",
".",
"!",
"?",
";",
":",
"\"",
"'",
"(",
")"
],
"units": {
"file": [
"ملف",
"وحدة"
],
"function": [
"دالة",
"طريقة"
],
"test": [
"اختبار",
"حزمة"
]
},
"domains": [
"شفرة",
"اختبارات",
"وثائق"
],
"frames": {
"mutable-default": [
"قيمة افتراضية قابلة للتغيير",
"قائمة افتراضية",
"افتراضي مشترك"
],
"magic-literal": [
"رقم سحري",
"ثابت بلا اسم",
"رقم مكرر",
"سمِّ هذا الرقم"
],
"guard-clause": [
"شرط حماية",
"خروج مبكر",
"if متداخل",
"ابسط الشرط"
],
"dead-import": [
"استيراد غير مستخدم",
"استيراد ميت",
"مستورد بلا استخدام"
],
"loop-comprehension": [
"فهم قائمة",
"أعد كتابة الحلقة",
"حول الحلقة إلى فهم"
],
"concat-fstring": [
"سلسلة نصية منسقة",
"لصق النصوص",
"نسّق النص"
],
"add-assertion": [
"تحقق من النوع",
"أضف تحققا",
"افحص الوسيط"
]
},
"labels": {
"state": "حالة",
"level": "مستوى",
"domain": "مجال",
"not_understood": "لم أفهم الطلب.",
"out_of_domain": "هذا الطلب خارج قائمة هذا النظام.",
"refused": "مرفوض",
"clarify": "أي رمز تقصد؟",
"verified": "تم التحقق",
"unknown": "غير معروف",
"single_prover": "مُثبت واحد",
"progress": "قيد العمل"
},
"examples": [
{
"text": "أزل القيمة الافتراضية القابلة للتغيير في load_config",
"frame": "mutable-default"
},
{
"text": "هذا الرقم يظهر ثلاث مرات سمِّه",
"frame": "magic-literal"
},
{
"text": "حول هذا الشرط المتداخل إلى خروج مبكر",
"frame": "guard-clause"
},
{
"text": "استيراد json لم يعد مستخدمًا",
"frame": "dead-import"
},
{
"text": "حوّل هذه الحلقة إلى فهم قائمة",
"frame": "loop-comprehension"
},
{
"text": "أنشئ هذه الرسالة بسلسلة منسقة",
"frame": "concat-fstring"
},
{
"text": "تحقق أن count عدد صحيح قبل استخدامه",
"frame": "add-assertion"
}
]
}12345678910111213141516171819202122232425262728293031323334{ "lang": "en", "name": "English", "noise": [",", ".", "!", "?", ";", ":", "\"", "'", "(", ")"], "units": {"file": ["file", "module", "script"], "function": ["function", "method", "def"], "test": ["test", "tests", "suite"]}, "domains": ["code", "tests", "docs"], "frames": { "mutable-default": ["mutable default", "default list", "shared default", "empty list default"], "magic-literal": ["magic number", "unnamed constant", "hardcoded number", "name this number"], "guard-clause": ["guard clause", "early return", "nested if", "flatten the condition"], "dead-import": ["unused import", "unused import", "import never used", "dead import"], "loop-comprehension": ["list comprehension", "rewrite the loop", "for loop to comprehension"], "concat-fstring": ["f string", "string concatenation", "format the string", "plus operator on strings"], "add-assertion": ["assert the type", "add a guard", "check the argument", "defensive assert"] }, "labels": { "state": "State", "level": "Level", "domain": "Domain", "not_understood": "I did not understand the request.", "out_of_domain": "This request is outside the catalog of this system.", "refused": "Refused", "clarify": "Which symbol do you mean?", "verified": "Verified", "unknown": "Unknown", "single_prover": "Single prover", "progress": "Working" }, "examples": [ {"text": "remove the mutable default in load_config", "frame": "mutable-default"}, {"text": "this number appears three times, name it", "frame": "magic-literal"}, {"text": "flatten this nested if into an early return", "frame": "guard-clause"}, {"text": "the json import is not used any more", "frame": "dead-import"}, {"text": "turn this for loop into a list comprehension", "frame": "loop-comprehension"}, {"text": "build this message with an f string", "frame": "concat-fstring"}, {"text": "assert that count is an int before using it", "frame": "add-assertion"} ]}12345678910111213141516171819202122232425262728293031323334{ "lang": "es", "name": "Espanol", "noise": [",", ".", "!", "?", ";", ":", "\"", "'", "(", ")"], "units": {"file": ["archivo", "modulo", "script"], "function": ["funcion", "metodo"], "test": ["test", "prueba", "suite"]}, "domains": ["codigo", "pruebas", "documentacion"], "frames": { "mutable-default": ["valor por defecto mutable", "lista por defecto", "predeterminado compartido"], "magic-literal": ["numero magico", "constante sin nombre", "numero fijo", "nombra este numero"], "guard-clause": ["clausula de guardia", "retorno anticipado", "if anidado", "aplasta la condicion"], "dead-import": ["import sin usar", "import no utilizado", "import muerto"], "loop-comprehension": ["comprension de lista", "reescribe el bucle", "bucle for a comprension"], "concat-fstring": ["f string", "concatenacion de cadenas", "formatea la cadena"], "add-assertion": ["afirma el tipo", "agrega una guardia", "revisa el argumento"] }, "labels": { "state": "Estado", "level": "Nivel", "domain": "Dominio", "not_understood": "No entendi la solicitud.", "out_of_domain": "Esta solicitud esta fuera del catalogo de este sistema.", "refused": "Rechazado", "clarify": "Que simbolo quieres decir?", "verified": "Verificado", "unknown": "Desconocido", "single_prover": "Un solo demostrador", "progress": "Trabajando" }, "examples": [ {"text": "quita el valor por defecto mutable en load_config", "frame": "mutable-default"}, {"text": "este numero aparece tres veces nominalo", "frame": "magic-literal"}, {"text": "aplasta este if anidado en un retorno anticipado", "frame": "guard-clause"}, {"text": "el import de json ya no se usa", "frame": "dead-import"}, {"text": "convierte este bucle for en una comprension de lista", "frame": "loop-comprehension"}, {"text": "construye este mensaje con una f string", "frame": "concat-fstring"}, {"text": "afirma que count es un int antes de usarlo", "frame": "add-assertion"} ]}12345678910111213141516171819202122232425262728293031323334{ "lang": "hi", "name": "Hindi", "noise": [",", ".", "!", "?", ";", ":", "\"", "'", "(", ")"], "units": {"file": ["फ़ाइल", "मॉड्यूल"], "function": ["फ़ंक्शन", "मेथड"], "test": ["टेस्ट", "सूट"]}, "domains": ["कोड", "टेस्ट", "दस्तावेज़"], "frames": { "mutable-default": ["परिवर्तनशील डिफ़ॉल्ट", "साझा डिफ़ॉल्ट", "खाली सूची डिफ़ॉल्ट"], "magic-literal": ["जादुई संख्या", "बिना नाम स्थिरांक", "यह संख्या नामित करें"], "guard-clause": ["गार्ड क्लॉज़", "पूर्व लौटाएँ", "नेस्टेड if", "शर्त सीधी करें"], "dead-import": ["बेकार import", "अप्रयुक्त import", "इस्तेमाल नहीं हुआ import"], "loop-comprehension": ["सूची समझ", "लूप दोबारा लिखें", "for लूप को comprehension बनाएँ"], "concat-fstring": ["f स्ट्रिंग", "स्ट्रिंग जोड़", "फ़ॉर्मेट करें"], "add-assertion": ["type जाँचें", "गार्ड जोड़ें", "तर्क की पुष्टि करें"] }, "labels": { "state": "स्थिति", "level": "स्तर", "domain": "क्षेत्र", "not_understood": "मुझे अनुरोध समझ नहीं आया।", "out_of_domain": "यह अनुरोध इस तंत्र की सूची से बाहर है।", "refused": "अस्वीकृत", "clarify": "आपका मतलब किस प्रतीक से है?", "verified": "सत्यापित", "unknown": "अज्ञात", "single_prover": "केवल एक प्रमाण", "progress": "काम जारी" }, "examples": [ {"text": "load_config से परिवर्तनशील डिफ़ॉल्ट हटाएँ", "frame": "mutable-default"}, {"text": "यह संख्या तीन बार आई है इसका नाम रखें", "frame": "magic-literal"}, {"text": "इस नेस्टेड if को पूर्व लौटाएँ में बदलें", "frame": "guard-clause"}, {"text": "json का import अब इस्तेमाल नहीं होता", "frame": "dead-import"}, {"text": "इस for लूप को सूची समझ बनाएँ", "frame": "loop-comprehension"}, {"text": "यह संदेश f स्ट्रिंग से बनाएँ", "frame": "concat-fstring"}, {"text": "उपयोग से पहले जाँचें कि count एक int है", "frame": "add-assertion"} ]}12345678910111213141516171819202122232425262728293031323334{ "lang": "it", "name": "Italiano", "noise": [",", ".", "!", "?", ";", ":", "\"", "'", "(", ")"], "units": {"file": ["file", "modulo", "script"], "function": ["funzione", "metodo"], "test": ["test", "suite"]}, "domains": ["codice", "test", "documentazione"], "frames": { "mutable-default": ["default mutabile", "lista di default", "default condiviso", "valore predefinito modificabile"], "magic-literal": ["numero magico", "costante senza nome", "numero fisso", "nomina questo numero"], "guard-clause": ["clausola di guardia", "ritorno anticipato", "if annidato", "appiattisci la condizione"], "dead-import": ["import inutilizzato", "import non usato", "import morto"], "loop-comprehension": ["list comprehension", "riscrivi il ciclo", "ciclo for in comprehension"], "concat-fstring": ["f stringa", "concatenazione di stringhe", "formatta la stringa", "somma di stringhe"], "add-assertion": ["asserisci il tipo", "aggiungi una guardia", "controlla l argomento", "assert difensivo"] }, "labels": { "state": "Stato", "level": "Livello", "domain": "Dominio", "not_understood": "Non ho capito la richiesta.", "out_of_domain": "Questa richiesta e fuori dal catalogo di questo sistema.", "refused": "Rifiutato", "clarify": "Quale simbolo intendi?", "verified": "Verificato", "unknown": "Sconosciuto", "single_prover": "Un solo dimostratore", "progress": "Al lavoro" }, "examples": [ {"text": "togli il default mutabile in load_config", "frame": "mutable-default"}, {"text": "questo numero appare tre volte nominalo", "frame": "magic-literal"}, {"text": "appiattisci questo if annidato in un ritorno anticipato", "frame": "guard-clause"}, {"text": "l import di json non e piu usato", "frame": "dead-import"}, {"text": "trasforma questo ciclo for in una list comprehension", "frame": "loop-comprehension"}, {"text": "costrisci questo messaggio con una f stringa", "frame": "concat-fstring"}, {"text": "asserisci che count sia un int prima di usarlo", "frame": "add-assertion"} ]}12345678910111213141516171819202122232425262728293031323334{ "lang": "zh", "name": "Chinese", "noise": [",", ".", "!", "?", ";", ":", "\"", "'", "(", ")", ",", "。", "?"], "units": {"file": ["文件", "模块"], "function": ["函数", "方法"], "test": ["测试", "用例"]}, "domains": ["代码", "测试", "文档"], "frames": { "mutable-default": ["可变默认值", "默认列表", "共享默认值"], "magic-literal": ["魔法数字", "无名常量", "硬编码数字", "给这个数字命名"], "guard-clause": ["守卫子句", "提前返回", "嵌套 if", "拉平条件"], "dead-import": ["未使用的导入", "无用导入", "导入没用到"], "loop-comprehension": ["列表推导式", "重写循环", "循环改推导式"], "concat-fstring": ["f 字符串", "字符串拼接", "格式化字符串"], "add-assertion": ["断言类型", "加一个守卫", "检查参数"] }, "labels": { "state": "状态", "level": "层级", "domain": "领域", "not_understood": "没有理解这个请求。", "out_of_domain": "这个请求不在本系统的目录内。", "refused": "已拒绝", "clarify": "你指的是哪个符号?", "verified": "已验证", "unknown": "未知", "single_prover": "单一证明者", "progress": "处理中" }, "examples": [ {"text": "去掉 load_config 里的可变默认值", "frame": "mutable-default"}, {"text": "这个数字出现三次,给它命名", "frame": "magic-literal"}, {"text": "把这个嵌套 if 改成提前返回", "frame": "guard-clause"}, {"text": "json 的导入已经没用了", "frame": "dead-import"}, {"text": "把这个 for 循环改成列表推导式", "frame": "loop-comprehension"}, {"text": "用 f 字符串构造这条消息", "frame": "concat-fstring"}, {"text": "使用前断言 count 是 int", "frame": "add-assertion"} ]}123456789"""Deterministic maintenance kernel for existing Python projects.
The bundle reads a request in one of six language varieties, finds one shape it canprove, writes the edit and its lock test as a single transaction, and lets twoindependent checkers try to refute the claim. No pretrained model is involved: therequest is understood by lexical frames, and the plan is language free."""
__version__ = "0.1.0"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""The catalog: entries, integrity, conflicts.
Section 4 of SPECIFICATION.md. An entry is verifiable or it is not in the catalog: amatcher over the syntax tree, the edit pair it produces, a lock test, named refusals."""
import jsonimport osfrom typing import Any, Dict, List, Optional, Tuple
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))PATTERNS_PATH = os.path.join(ROOT, "catalog", "patterns.json")POLICY_PATH = os.path.join(ROOT, "catalog", "conflict_policy.json")
REQUIRED_ENTRY_KEYS = ("id", "family", "shape", "effect", "lock", "refusals", "min_assurance", "frames")POLICIES = ("specificity", "family_order", "clarify")MAX_CANDIDATES = 4
class CatalogError(Exception): pass
def load_entries() -> List[Dict[str, Any]]: if not os.path.isfile(PATTERNS_PATH): raise CatalogError("no catalog at %s" % PATTERNS_PATH) with open(PATTERNS_PATH, "r", encoding="utf-8") as handle: data = json.load(handle) entries = data.get("entries") or [] if not entries: raise CatalogError("catalog carries no entry") return entries
def load_policies() -> Dict[str, str]: if not os.path.isfile(POLICY_PATH): return {} with open(POLICY_PATH, "r", encoding="utf-8") as handle: return json.load(handle).get("pairs", {})
def by_id(entries: List[Dict[str, Any]], entry_id: str) -> Optional[Dict[str, Any]]: for entry in entries: if entry.get("id") == entry_id: return entry return None
def integrity(entries: List[Dict[str, Any]]) -> List[str]: """Return a line per defect. Empty means the catalog is admissible.""" defects: List[str] = [] seen: Dict[str, int] = {} for entry in entries: entry_id = str(entry.get("id") or "") if not entry_id: defects.append("entry without an id") continue if entry_id in seen: defects.append("duplicate id %s" % entry_id) seen[entry_id] = 1 for key in REQUIRED_ENTRY_KEYS: if key not in entry: defects.append("%s misses key %s" % (entry_id, key)) if not entry.get("refusals"): defects.append("%s carries no refusal" % entry_id) if len(entry.get("refusals") or []) < 2: defects.append("%s carries fewer than two refusals" % entry_id) if not entry.get("lock"): defects.append("%s carries no lock test" % entry_id) if not entry.get("frames"): defects.append("%s carries no frame" % entry_id) return defects
def policy_for(policies: Dict[str, str], a: str, b: str) -> Optional[str]: key = "|".join(sorted((a, b))) value = policies.get(key) if value in POLICIES: return value return None
def conflict_lines(claims: Dict[str, List[str]], policies: Dict[str, str]) -> Tuple[List[str], List[Tuple[str, str, str]]]: """Claims maps a symbol to the entry ids that match it.
Returns (defects, resolved_pairs). A pair with no declared policy is a defect. """ defects: List[str] = [] resolved: List[Tuple[str, str, str]] = [] for symbol, ids in sorted(claims.items()): if len(ids) > MAX_CANDIDATES: defects.append("%s claimed by %d entries, over the limit of %d" % (symbol, len(ids), MAX_CANDIDATES)) for i, first in enumerate(sorted(ids)): for second in sorted(ids)[i + 1:]: policy = policy_for(policies, first, second) if policy is None: defects.append("no policy for pair %s|%s on %s" % (first, second, symbol)) else: resolved.append((first, second, policy)) return defects, resolved123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Intent and intermediate representation.
The intent node is the only non deterministic node: it maps a surface request in one ofthe six varieties onto a frame. Everything downstream is language free: no other nodereads the utterance, only the frame and the anchor."""
import refrom typing import Any, Dict, List, Optional, Tuple
from . import lexicon
IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]{2,}")STOPWORDS = {"this", "that", "with", "into", "from", "before", "after", "please", "could", "would", "should", "not", "and", "for", "the", "are"}
IR_KEYS = ("frame", "anchor", "lang", "score", "candidates")
def make_ir(frame: str, anchor: Optional[str], lang: str, score: float, candidates: List[Tuple[str, float]]) -> Dict[str, Any]: return {"frame": frame, "anchor": anchor, "lang": lexicon.normalize(lang), "score": round(float(score), 4), "candidates": [(f, round(s, 4)) for f, s in candidates]}
def is_language_free(ir: Dict[str, Any]) -> bool: """True when the plan carries no trace of the surface form.
Checked in tests/test_language_free_plan.py: no utterance text, no non ASCII token, no variety name anywhere in the structure that reaches executor and gates. """ try: str(ir).encode("ascii") except UnicodeEncodeError: return False return set(ir.keys()) <= set(IR_KEYS)
def anchors_in(text: str) -> List[str]: out: List[str] = [] for word in IDENT.findall(str(text or "")): if word.lower() in STOPWORDS: continue if word not in out: out.append(word) return out
def rank(text: str, lang: str, frames: Dict[str, List[str]]) -> List[Tuple[str, float]]: """Score every frame against the request, using the vocabulary of its variety.""" data = lexicon.load(lang) folded = lexicon.fold(text, lang) scored: List[Tuple[str, float]] = [] for frame, phrases in frames.items(): best = 0.0 for phrase in phrases: needle = lexicon.fold(phrase, lang) if not needle: continue if needle in folded: weight = len(needle.split()) / max(1, len(folded.split())) best = max(best, 0.55 + 0.45 * min(1.0, weight * 2)) else: tokens = [t for t in needle.split() if len(t) > 1] hits = sum(1 for t in tokens if t in folded) if tokens and hits: best = max(best, 0.45 * hits / len(tokens)) if best > 0.0: scored.append((frame, best)) scored.sort(key=lambda pair: (-pair[1], pair[0])) return scored
def route(text: str, lang: str, frames: Dict[str, List[str]], known_symbols: Optional[List[str]] = None, clarify_margin: float = 0.15, min_score: float = 0.45) -> Dict[str, Any]: """Return an IR, or an IR with frame None plus a reason.""" lang = lexicon.normalize(lang) scored = rank(text, lang, frames) symbols = anchors_in(text) anchor = None if known_symbols: lowered = {s.lower(): s for s in known_symbols} for word in symbols: if word.lower() in lowered: anchor = lowered[word.lower()] break if anchor is None and symbols: anchor = symbols[0] if not scored or scored[0][1] < min_score: ir = make_ir("", anchor, lang, scored[0][1] if scored else 0.0, scored[:3]) ir["reason"] = "NOT_UNDERSTOOD" return ir if len(scored) > 1 and (scored[0][1] - scored[1][1]) < clarify_margin: ir = make_ir(scored[0][0], anchor, lang, scored[0][1], scored[:3]) ir["reason"] = "AMBIGUOUS_TARGET" return ir return make_ir(scored[0][0], anchor, lang, scored[0][1], scored[:3])12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""The words of the bundle: one file per variety, validated before use.
Section 6.5 of SPECIFICATION.md. The six varieties are the ones the genesis gatewaycarries. A variety is declared, never inferred, and a declared variety without a fileanswers instead of crashing."""
import jsonimport osimport refrom typing import Any, Dict, Optional
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))LEXICON_DIR = os.path.join(ROOT, "lexicon")
#: The six varieties this bundle carries (SPECIFICATION.md 6.5).LANGS = ("ar", "en", "es", "hi", "it", "zh")
REQUIRED_KEYS = ("lang", "name", "noise", "units", "frames", "labels", "examples")
LABEL_KEYS = ("state", "level", "domain", "not_understood", "out_of_domain", "refused", "clarify", "verified", "unknown", "single_prover", "progress")
_CACHE: Dict[str, Dict[str, Any]] = {}
class LexiconError(Exception): """Raised when a variety file is missing, incomplete or inconsistent."""
def normalize(text: str) -> str: raw = str(text or "").strip().replace("_", "-") if not raw: return "en" return raw.split("-")[0].lower()
def has(code: str) -> bool: return normalize(code) in LANGS and os.path.isfile(os.path.join(LEXICON_DIR, normalize(code) + ".json"))
def load(code: str) -> Dict[str, Any]: code = normalize(code) if code in _CACHE: return _CACHE[code] path = os.path.join(LEXICON_DIR, code + ".json") if not os.path.isfile(path): raise LexiconError("variety %r has no lexicon file in this bundle" % code) with open(path, "r", encoding="utf-8") as handle: raw = json.load(handle) missing = [key for key in REQUIRED_KEYS if key not in raw] if missing: raise LexiconError("lexicon %s misses keys: %s" % (code, ", ".join(missing))) if raw["lang"] != code: raise LexiconError("lexicon %s declares lang %r" % (code, raw["lang"])) labels = raw["labels"] or {} missing_labels = [key for key in LABEL_KEYS if key not in labels] if missing_labels: raise LexiconError("lexicon %s misses labels: %s" % (code, ", ".join(missing_labels))) if not raw["frames"]: raise LexiconError("lexicon %s carries no frames" % code) _CACHE[code] = raw return raw
def label(code: str, key: str, fallback: Optional[str] = None) -> str: try: return str(load(code)["labels"].get(key, fallback or key)) except LexiconError: return fallback or key
_FOLD = re.compile(r"\s+")
def fold(text: str, code: str) -> str: """Lowercase, drop the punctuation native to the variety, squeeze whitespace.""" data = load(code) out = str(text or "").lower().replace("-", " ") for ch in data.get("noise", []): out = out.replace(ch, " ") return _FOLD.sub(" ", out).strip()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Seven processes, one pipeline: the orchestrator.
Implements the contract of section 3.1: from_config_file, run_session, to_dict. Each noderuns as its own process, talks only through the JSON envelope, and carries a budget. Theverdict is re-derived from the transcript, never taken from a node."""
import jsonimport osimport subprocessimport sysimport timefrom typing import Any, Dict, List, Optional
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, ROOT)
from lingologos_thinkingpython import lexicon # noqa: E402from nodes import arbiter as arbiter_mod # noqa: E402
DEFAULT_TOPOLOGY = os.path.join(ROOT, "topology.json")
class BudgetExceeded(Exception): pass
class MultiInstanceOrchestrator: def __init__(self, nodes: List[Dict[str, Any]], retries: int = 1) -> None: self.nodes = nodes self.retries = retries self.transcript: List[Dict[str, Any]] = []
@classmethod def from_config_file(cls, path: str) -> "MultiInstanceOrchestrator": with open(path, "r", encoding="utf-8") as handle: config = json.load(handle) return cls(config.get("nodes") or [], int(config.get("retries", 1)))
@classmethod def from_default(cls) -> "MultiInstanceOrchestrator": return cls.from_config_file(DEFAULT_TOPOLOGY)
def _run_node(self, name: str, script: str, payload: Dict[str, Any], budget: float, env: Optional[Dict[str, str]] = None) -> Dict[str, Any]: merged = dict(os.environ) merged.pop("PYTHONPATH", None) if env: merged.update(env) started = time.time() try: proc = subprocess.run([sys.executable, os.path.join(ROOT, script)], input=json.dumps(payload), capture_output=True, text=True, timeout=budget, cwd=ROOT, env=merged) except subprocess.TimeoutExpired: record = {"node": name, "status": "error", "reasons": ["NODE_TIMEOUT"]} self.transcript.append(record) return record elapsed = time.time() - started if elapsed > budget: raise BudgetExceeded("%s used %.2fs over a budget of %.2fs" % (name, elapsed, budget)) try: record = json.loads(proc.stdout.strip().splitlines()[-1]) except (ValueError, IndexError): record = {"node": name, "status": "error", "reasons": ["NODE_TIMEOUT" if proc.returncode == 124 else "CHECKER_ABSTAIN"]} record.setdefault("node", name) record["elapsed"] = round(elapsed, 3) self.transcript.append(record) return record
def run_session(self, workspace: str, request: str, lang: str = "en") -> Dict[str, Any]: lang = lexicon.normalize(lang) nodes: List[Dict[str, Any]] = [] payload: Dict[str, Any] = {"workspace": workspace, "request": request, "lang": lang} for spec in self.nodes: name, script, budget = spec["name"], spec["script"], float(spec.get("budget", 30)) record = self._run_node(name, script, payload, budget) nodes.append(record) if record["status"] in ("refused", "error"): break if name == "intent": payload["ir"] = record["ir"] elif name == "locator": payload["candidates"] = record["candidates"] elif name == "planner": payload["plan"] = record["plan"] elif name == "executor": payload["plan"] = record.get("plan", payload.get("plan")) verdict, assurance, reasons = arbiter_mod.combine(nodes) return {"verdict": verdict, "assurance": assurance, "reasons": reasons, "lang": lang, "labels": self._labels(lang, verdict), "transcript": nodes}
def _labels(self, lang: str, verdict: str) -> Dict[str, str]: try: data = lexicon.load(lang) except lexicon.LexiconError: data = lexicon.load("en") labels = data["labels"] key = {"VERIFIED": "verified", "SINGLE_PROVER": "single_prover"}.get(verdict, "refused") return {"state": labels["state"], "level": labels["level"], "verdict": labels.get(key, verdict)}
def to_dict(self) -> Dict[str, Any]: return {"nodes": [n["name"] for n in self.nodes], "retries": self.retries, "transcript": self.transcript}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Workspace admission: is this project inside the mission of section 1.1.
Runs before any node. A workspace that fails admission never sees a plan: the answer isthe reason code, and the reason is the deliverable."""
import astimport osfrom typing import Any, Dict, List, Optional, Tuple
TEST_HINTS = ("test_", "_test", "tests", "conftest.py")GENERATED_HINTS = ("_pb2.py", "_pb2_grpc.py", "generated", "__init__.py.bak", ".pyc")DYNAMIC_ATTR_CALLS = ("getattr", "setattr", "hasattr")
def _is_test_file(path: str) -> bool: name = os.path.basename(path) return name.startswith("test_") or name.endswith("_test.py") or name == "conftest.py" \ or os.sep + "tests" + os.sep in path or path.startswith("tests" + os.sep)
def python_files(workspace: str) -> List[str]: out: List[str] = [] for base, dirs, files in os.walk(workspace): dirs[:] = [d for d in dirs if d not in ("__pycache__", ".git", ".venv", "build")] for name in files: if name.endswith(".py"): rel = os.path.relpath(os.path.join(base, name), workspace).replace("\\", "/") out.append(rel) return sorted(out)
def target_rejects(rel: str, source: str) -> List[str]: reasons: List[str] = [] if any(h in rel for h in GENERATED_HINTS): reasons.append("GENERATED_TARGET") if "\r\n" in source: reasons.append("CRLF_TARGET") lines = source.splitlines() if any(line.startswith("\t") for line in lines): reasons.append("TAB_INDENTED_TARGET") try: source.encode("ascii") except UnicodeEncodeError: reasons.append("NOT_ASCII_TARGET") try: tree = ast.parse(source) except SyntaxError: return reasons names = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name)} if names & set(DYNAMIC_ATTR_CALLS): reasons.append("DYNAMIC_REACH") return reasons
def admit(workspace: str, targets: Optional[List[str]] = None) -> Dict[str, Any]: """Return {"admitted": bool, "reasons": [...], "tests": [...], "targets": [...]}.""" if not os.path.isdir(workspace): return {"admitted": False, "reasons": ["NO_TEST_FILE"], "tests": [], "targets": []} files = python_files(workspace) tests = [f for f in files if _is_test_file(f)] if not tests: return {"admitted": False, "reasons": ["NO_TEST_FILE"], "tests": [], "targets": files} picked = targets or [f for f in files if not _is_test_file(f)] reasons: List[str] = [] checked: List[str] = [] for rel in picked: path = os.path.join(workspace, rel) try: with open(path, "r", encoding="utf-8", newline="") as handle: source = handle.read() except (OSError, UnicodeDecodeError): reasons.append("NOT_ASCII_TARGET") continue found = target_rejects(rel, source) if found: reasons.extend(found) else: checked.append(rel) uniq = sorted(set(reasons)) return {"admitted": bool(checked) and not uniq, "reasons": uniq, "tests": tests, "targets": checked}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Reason codes owned by this bundle.
Three groups, per SPECIFICATION.md section 9: session codes, preflight codes raised bythe workspace admission check, and catalog codes raised by entry preconditions. Kernelcodes are imported from the kernel when a kernel is present and are never restated here."""
from typing import Dict
# Session and node codes.SESSION_CODES = ( "NODE_TIMEOUT", "NONSENSE_REPLAY", "CHECKER_ABSTAIN", "NOT_UNDERSTOOD", "AMBIGUOUS_TARGET", "ALREADY_APPLIED", "PROTECTED_PATH", "LINKED_PATH_IN_WORKSPACE", "NO_TEST_ANCHOR", "ASSERTION_REMOVED", "OUT_OF_CATALOG", "NO_MATCH", "NO_EDIT", "SEARCH_NOT_FOUND",)
# Preflight codes: workspace admission, checked before any node runs (section 1.1).PREFLIGHT_CODES = ( "NO_TEST_FILE", "TAB_INDENTED_TARGET", "CRLF_TARGET", "NOT_ASCII_TARGET", "DYNAMIC_REACH", "GENERATED_TARGET",)
# Lock codes raised by the gates.GATE_CODES = ( "PAIR_DISHONEST", "SHAPE_STILL_PRESENT", "SUITE_RED", "LEXICON_INCOMPLETE", "CATALOG_INTEGRITY", "CATALOG_CONFLICT", "CONFINEMENT",)
#: Every code this bundle may raise.ALL_CODES: Dict[str, str] = {}for _group, _name in ((SESSION_CODES, "session"), (PREFLIGHT_CODES, "preflight"), (GATE_CODES, "gate")): for _code in _group: ALL_CODES[_code] = _group and _name or "session"
def group_of(code: str) -> str: return ALL_CODES.get(code, "unknown")
def is_known(code: str) -> bool: return code in ALL_CODES123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199"""Locate, plan, apply, prove. The edit pair is one transaction.
Section 5 of SPECIFICATION.md: the source edit and the lock test are written together ornot at all. The honesty gate reads the pair back from disk and refuses when the test wasnot written first in the record, or when the edit removed an assertion."""
import astimport osimport shutilimport subprocessimport sysfrom typing import Any, Dict, List, Optional, Tuple
from . import catalog, preflight, shapes
TEST_DIR = "tests"RECORD_NAME = "_thinkingpython_locks"
def locate(workspace: str, frame: str, anchor: Optional[str], entries: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[str]]: """Return candidates: {file, target, entry} plus reasons.""" reasons: List[str] = [] found: List[Dict[str, Any]] = [] for rel in preflight.python_files(workspace): if rel.startswith(TEST_DIR + "/"): continue path = os.path.join(workspace, rel) try: with open(path, "r", encoding="utf-8") as handle: source = handle.read() except (OSError, UnicodeDecodeError): reasons.append("NOT_ASCII_TARGET") continue hits, why = shapes.match(frame, source) if not hits: if why and why != "NO_SHAPE": reasons.append(why) continue if anchor: picked = [h for h in hits if h.get("symbol") == anchor] or hits else: picked = hits entry = catalog.by_id(entries, frame) or {} for target in picked: found.append({"file": rel, "target": target, "entry": entry, "evidence": target.get("evidence", "")}) if not found: reasons.append("NO_MATCH") return found[:catalog.MAX_CANDIDATES], sorted(set(reasons))
def plan(candidate: Dict[str, Any]) -> Dict[str, Any]: """The plan is language free: frame, file, line window, edits, lock.""" entry = candidate["entry"] rel = candidate["file"] target = candidate["target"] with open(os.path.join(os.getcwd(), rel) if not os.path.isabs(rel) else rel, "r", encoding="utf-8") as handle: source = handle.read() return {"frame": entry.get("id", ""), "file": rel, "line": target["line"], "end": target["end"], "symbol": target["symbol"], "edits": shapes.edits(entry.get("id", ""), rel, source, target), "lock": shapes.lock(entry.get("id", ""), target), "expected": list(entry.get("refusals") or [])}
def run_suite(workspace: str, timeout: int = 120) -> Dict[str, Any]: try: proc = subprocess.run([sys.executable, "-m", "pytest", "-q", "--no-header", TEST_DIR], cwd=workspace, capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired: return {"status": "SUITE_RED", "output": "timeout"} out = (proc.stdout or "") + (proc.stderr or "") return {"status": "GREEN" if proc.returncode == 0 else "SUITE_RED", "output": out[-4000:]}
def _drops_assertion(edits: List[Dict[str, str]], source: str) -> bool: for edit in edits: if "assert" in (edit.get("search") or "") and "assert" not in (edit.get("replace") or ""): return True projected = source for edit in edits: if edit.get("search"): projected = projected.replace(edit["search"], edit.get("replace", ""), 1) try: before = sum(1 for n in ast.walk(ast.parse(source)) if isinstance(n, ast.Assert)) after = sum(1 for n in ast.walk(ast.parse(projected)) if isinstance(n, ast.Assert)) except SyntaxError: return False return after < before
def apply_pair(workspace: str, planned: Dict[str, Any]) -> Dict[str, Any]: """Write source edit and lock test in one transaction. Returns a receipt.""" if not planned.get("edits"): return {"applied": False, "reason": "NO_EDIT"} probe = os.path.join(workspace, TEST_DIR, "test_lock_%s.py" % planned["symbol"]) if os.path.exists(probe): return {"applied": False, "reason": "ALREADY_APPLIED"} try: with open(os.path.join(workspace, plan_rel(planned)), "r", encoding="utf-8") as handle: original_source = handle.read() except OSError: return {"applied": False, "reason": "SEARCH_NOT_FOUND"} if _drops_assertion(planned["edits"], original_source): return {"applied": False, "reason": "ASSERTION_REMOVED"} backup: Dict[str, Optional[str]] = {} written: List[str] = [] try: for edit in planned["edits"]: rel = edit["file"] path = os.path.join(workspace, rel) if os.path.islink(path): raise OSError("LINKED_PATH_IN_WORKSPACE") with open(path, "r", encoding="utf-8") as handle: original = handle.read() if rel not in backup: backup[rel] = original if edit["search"] not in original: raise ValueError("SEARCH_NOT_FOUND") new = original.replace(edit["search"], edit["replace"], 1) ast.parse(new) with open(path, "w", encoding="utf-8") as handle: handle.write(new) written.append(rel) lock_path = os.path.join(workspace, TEST_DIR, "test_lock_%s.py" % planned["symbol"]) os.makedirs(os.path.dirname(lock_path), exist_ok=True) if os.path.exists(lock_path): raise ValueError("ALREADY_APPLIED") backup[os.path.relpath(lock_path, workspace).replace("\\", "/")] = None with open(lock_path, "w", encoding="utf-8") as handle: handle.write(_lock_header(plan_rel(planned)) + planned["lock"]) written.append(os.path.relpath(lock_path, workspace).replace("\\", "/")) except Exception as exc: # rollback reason = str(exc) if str(exc) in ("LINKED_PATH_IN_WORKSPACE", "ALREADY_APPLIED") \ else "PAIR_DISHONEST" for rel, original in backup.items(): path = os.path.join(workspace, rel) if original is None: if os.path.exists(path): os.remove(path) else: with open(path, "w", encoding="utf-8") as handle: handle.write(original) for rel in written: path = os.path.join(workspace, rel) if os.path.exists(path) and backup.get(rel) is None: os.remove(path) return {"applied": False, "reason": reason} return {"applied": True, "files": written}
def plan_rel(planned: Dict[str, Any]) -> str: return str(planned.get("file", "")).replace("\\", "/")
def _lock_header(rel: str) -> str: return ( '"""Lock test written with the edit that it pins. Do not edit by hand."""\n' "import ast\n" "import os\n\n" "ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n" "TARGET = os.path.join(ROOT, %(rel)r)\n\n" "def _source():\n" " with open(TARGET, 'r', encoding='utf-8') as handle:\n" " return handle.read()\n\n" "def _tree():\n" " return ast.parse(_source())\n\n" "def _is_doc(stmt):\n" " return (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant)\n" " and isinstance(stmt.value.value, str))\n\n" "def _function(name):\n" " for node in ast.walk(_tree()):\n" " if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:\n" " return node\n" " raise AssertionError('no function named ' + name)\n\n" "def _imports_name(src, name):\n" " tree = ast.parse(src)\n" " for node in ast.walk(tree):\n" " if isinstance(node, ast.Import):\n" " for alias in node.names:\n" " if (alias.asname or alias.name).split('.')[0] == name:\n" " return True\n" " if isinstance(node, ast.ImportFrom):\n" " for alias in node.names:\n" " if (alias.asname or alias.name) == name:\n" " return True\n" " return False\n\n" ) % {"rel": rel}
def verdict(receipt: Dict[str, Any], suite: Dict[str, Any]) -> Tuple[str, str]: if not receipt.get("applied"): return "REFUSED", receipt.get("reason", "NO_EDIT") if suite["status"] != "GREEN": return "REFUSED", suite["status"] return "VERIFIED", ""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513"""Matchers and transforms over the syntax tree.
Every catalog entry names a shape here. A matcher returns candidates with the evidencethat justifies them, or a refusal code; a transform returns the text of the edit pair.Nothing here writes to disk: the session layer owns the transaction."""
import astimport refrom typing import Any, Dict, List, Optional, Tuple
Target = Dict[str, Any]Edit = Dict[str, str]
def functions(tree: ast.Module) -> List[ast.AST]: return [n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
def _symbol(node: ast.AST, tree: ast.Module) -> str: for parent in ast.walk(tree): for field, value in ast.iter_fields(parent): if value is node: return getattr(node, "name", "?") return getattr(node, "name", "?")
def _enclosing(tree: ast.Module, node: ast.AST) -> Optional[str]: for parent in ast.walk(tree): for _, value in ast.iter_fields(parent): if value is node: return getattr(parent, "name", None) return None
# ---------------------------------------------------------------- mutable default
def match_mutable_default(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]: out: List[Target] = [] for fn in functions(tree): for default in list(fn.args.defaults) + [d for d in fn.args.kw_defaults if d]: if isinstance(default, (ast.List, ast.Dict, ast.Set)): out.append({ "symbol": fn.name, "line": fn.lineno, "end": max(fn.end_lineno, default.end_lineno), "evidence": "default argument built at call time", }) break if not out: return [], "NO_SHAPE" return out, None
def edit_mutable_default(path: str, lines: List[str], target: Target) -> List[Edit]: idx = target["line"] - 1 old = lines[idx] new = re.sub(r"=\s*(\[\]|\{\}|\(\))", "=None", old, count=1) if new == old: new = re.sub(r"=\s*(\[\]|\{\})", "=None", old, count=1) if new == old: return [] indent = " " * (len(old) - len(old.lstrip())) guard = [new, "", indent + " if PARAM_NAME is None:", indent + " PARAM_NAME = DEFAULT_VALUE"] return [{"file": path, "search": old, "replace": "\n".join(guard[:1])}]
def _fill_mutable_default(path: str, lines: List[str], target: Target) -> List[Edit]: idx = target["line"] - 1 old = lines[idx] match = re.search(r"(\w+)\s*=\s*(\[\]|\{\}|\(\))", old) if not match: return [] name, literal = match.group(1), match.group(2) replacement = {"[]": "[]", "{}": "{}", "()": "()"}[literal] new_head = re.sub(r"=\s*(\[\]|\{\}|\(\))", "=None", old, count=1) body_indent = " " * 4 guard = "%sif %s is None:\n%s %s = %s" % (body_indent, name, body_indent, name, replacement) nxt = lines[idx + 1] if idx + 1 < len(lines) else "" nxt_indent = len(nxt) - len(nxt.lstrip()) if nxt.strip().startswith('"""') or nxt.strip().startswith("'''"): # Insert the guard after the docstring of the function, not right after the def. end = idx + 1 quote = '"""' if '"""' in nxt else "'''" if nxt.count(quote) < 2: while end < len(lines) and quote not in lines[end]: end += 1 return [{"file": path, "search": lines[end], "replace": guard + "\n" + lines[end], "label": "guard"}] if nxt_indent < 4 or not nxt.strip(): return [] return [{"file": path, "search": old, "replace": new_head + "\n" + guard}]
def lock_mutable_default(target: Target) -> str: return ( "def test_%(symbol)s_default_is_not_built_at_definition():\n" " fn = _function(%(symbol)r)\n" " defaults = list(fn.args.defaults) + [d for d in fn.args.kw_defaults if d]\n" " assert not [d for d in defaults if isinstance(d, (ast.List, ast.Dict, ast.Set))]\n" % {"symbol": target["symbol"]} )
# ---------------------------------------------------------------- magic literal
def match_magic_literal(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]: out: List[Target] = [] for fn in functions(tree): for node in ast.walk(fn): if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) \ and node.value not in (0, 1, -1, 2, True, False, None): if _is_annotation_context(tree, node): continue out.append({ "symbol": fn.name, "line": node.lineno, "end": node.end_lineno, "value": repr(node.value), "evidence": "bare numeric constant inside a function body", }) break if not out: return [], "NO_SHAPE" return out, None
def _is_annotation_context(tree: ast.Module, node: ast.AST) -> bool: for fn in functions(tree): for arg in list(fn.args.args) + list(fn.args.kwonlyargs): if arg.annotation is not None and node in ast.walk(arg.annotation): return True return False
def edit_magic_literal(path: str, lines: List[str], target: Target) -> List[Edit]: value = target["value"] idx = target["line"] - 1 old = lines[idx] name = "LIMIT_%s" % re.sub(r"\W", "_", value).strip("_").upper() new = old.replace(value, name) if new == old: return [] return [{"file": path, "search": old, "replace": new, "label": "use"}, {"file": path, "search": _first_import_block(lines), "replace": _first_import_block(lines) + "\n\n%s = %s\n" % (name, value), "label": "constant"}]
def _first_import_block(lines: List[str]) -> str: for i, line in enumerate(lines): if line.startswith("import ") or line.startswith("from "): j = i while j < len(lines) and (lines[j].startswith("import ") or lines[j].startswith("from ")): j += 1 return "\n".join(lines[i:j]) return ""
def lock_magic_literal(target: Target) -> str: name = re.sub(r"\W", "_", target["value"]).strip("_").upper() return ( "def test_%s_names_its_limit():\n" " tree = _tree()\n" " names = [n.targets[0].id for n in ast.walk(tree)\n" " if isinstance(n, ast.Assign) and isinstance(n.targets[0], ast.Name)]\n" " assert 'LIMIT_%s' in names\n" % (target["symbol"], name) )
# ---------------------------------------------------------------- guard clause
def match_guard_clause(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]: out: List[Target] = [] for fn in functions(tree): body = [s for s in fn.body if not _is_docstring(s)] if not body or not isinstance(body[0], ast.If) or isinstance(body[0].test, ast.Constant): continue if isinstance(body[0].test, ast.UnaryOp) and isinstance(body[0].test.op, ast.Not): continue # already a guard clause if len(body) == 2 and not body[0].orelse and isinstance(body[1], ast.Return): out.append({"symbol": fn.name, "line": body[0].lineno, "end": body[0].end_lineno, "evidence": "one if before the fallback return"}) elif len(body) == 1: out.append({"symbol": fn.name, "line": body[0].lineno, "end": body[0].end_lineno, "evidence": "whole body wrapped in one if"}) if not out: return [], "NO_SHAPE" return out, None
def _is_docstring(stmt: ast.stmt) -> bool: return (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant) and isinstance(stmt.value.value, str))
def edit_guard_clause(path: str, lines: List[str], target: Target) -> List[Edit]: start, end = target["line"] - 1, target["end"] - 1 head = lines[start] stripped = head.strip() cond = stripped[len("if "):-1].strip() if stripped.startswith("if ") else None if cond is None: return [] # The fallback the early return must reproduce: the trailing return of the function. fallback = "None" stop = end indent = head[:len(head) - len(head.lstrip())] for index in range(end + 1, len(lines)): row = lines[index] if not row.strip(): continue if row.startswith(indent + "return "): fallback = row[len(indent) + len("return "):] stop = index break break new_block = (" if not (%s):\n return %s\n" % (cond, fallback) + "\n".join(ln[4:] if ln.startswith(" ") else ln for ln in lines[start + 1:end + 1])) old_block = "\n".join(lines[start:stop + 1]) return [{"file": path, "search": old_block, "replace": new_block}]
def lock_guard_clause(target: Target) -> str: return ( "def test_%(symbol)s_returns_early():\n" " fn = _function(%(symbol)r)\n" " body = [s for s in fn.body if not _is_doc(s)]\n" " assert isinstance(body[0], ast.If) and isinstance(body[0].test, ast.UnaryOp)\n" " assert isinstance(body[0].test.op, ast.Not)\n" % {"symbol": target["symbol"]} )
# ---------------------------------------------------------------- dead import
def match_dead_import(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]: used = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name)} used |= {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)} for node in ast.walk(tree): if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name): used.add(node.value.id) out: List[Target] = [] for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: bound = (alias.asname or alias.name).split(".")[0] if bound not in used: out.append({"symbol": bound, "line": node.lineno, "end": node.end_lineno, "evidence": "imported name never used", "text": alias.name, "asname": alias.asname}) elif isinstance(node, ast.ImportFrom): for alias in node.names: if alias.name == "*": continue bound = alias.asname or alias.name if bound not in used: out.append({"symbol": bound, "line": node.lineno, "end": node.end_lineno, "evidence": "imported name never used", "text": alias.name, "asname": alias.asname}) if not out: return [], "NO_SHAPE" return out, None
def edit_dead_import(path: str, lines: List[str], target: Target) -> List[Edit]: idx = target["line"] - 1 old = lines[idx] stripped = old.strip() if stripped.startswith("import "): parts = [p.strip() for p in stripped[len("import "):].split(",")] kept = [p for p in parts if p.split(" as ")[-1].split(".")[0] != target["symbol"]] if not kept: new_line = None else: new_line = "import " + ", ".join(kept) elif stripped.startswith("from "): head, rest = stripped.split(" import ", 1) parts = [p.strip() for p in rest.split(",")] kept = [p for p in parts if p.split(" as ")[-1] != target["symbol"]] if not kept: new_line = None else: new_line = "%s import %s" % (head, ", ".join(kept)) else: return [] if new_line is None: return [{"file": path, "search": old, "replace": "", "label": "drop"}] return [{"file": path, "search": old, "replace": new_line}]
def lock_dead_import(target: Target) -> str: return ( "def test_%(symbol)s_is_not_imported():\n" " src = _source()\n" " assert not _imports_name(src, %(symbol)r)\n" % {"symbol": target["symbol"]} )
# ---------------------------------------------------------------- loop to comprehension
def match_loop_comprehension(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]: out: List[Target] = [] for fn in functions(tree): for stmt in fn.body: if isinstance(stmt, ast.For) and len(stmt.body) == 1 and isinstance(stmt.body[0], ast.Expr) \ and isinstance(stmt.body[0].value, ast.Call) \ and isinstance(stmt.body[0].value.func, ast.Attribute) \ and stmt.body[0].value.func.attr == "append" and not stmt.orelse: out.append({"symbol": fn.name, "line": stmt.lineno, "end": stmt.end_lineno, "evidence": "for loop whose only statement is an append"}) if not out: return [], "NO_SHAPE" return out, None
def edit_loop_comprehension(path: str, lines: List[str], target: Target) -> List[Edit]: start, end = target["line"] - 1, target["end"] - 1 block = "\n".join(lines[start:end + 1]) m_target = re.search(r"^\s*(\w+)\.append\((.*)\)\s*$", lines[end], flags=re.M) m_for = re.match(r"^(\s*)for\s+(.+?)\s+in\s+(.+?):\s*$", lines[start]) if not (m_target and m_for): return [] indent, var, iterable = m_for.group(1), m_for.group(2), m_for.group(3) expr = m_target.group(2) new = "%s%s = [%s for %s in %s]" % (indent, m_target.group(1), expr, var, iterable) return [{"file": path, "search": block, "replace": new}]
def lock_loop_comprehension(target: Target) -> str: return ( "def test_%(symbol)s_has_no_appending_loop():\n" " fn = _function(%(symbol)r)\n" " for node in ast.walk(fn):\n" " if isinstance(node, ast.For):\n" " for stmt in node.body:\n" " call = getattr(stmt, 'value', None)\n" " assert not (isinstance(call, ast.Call)\n" " and getattr(call.func, 'attr', '') == 'append')\n" % {"symbol": target["symbol"]} )
# ---------------------------------------------------------------- f-string
def match_concat_fstring(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]: parents: Dict[ast.AST, ast.AST] = {} for parent in ast.walk(tree): for _, value in ast.iter_fields(parent): if isinstance(value, ast.AST): parents[value] = parent out: List[Target] = [] for node in ast.walk(tree): if not isinstance(node, ast.BinOp) or not isinstance(node.op, ast.Add): continue if isinstance(parents.get(node), ast.BinOp): continue parts = _flatten_add(node) if len(parts) < 2: continue if not any(isinstance(p, ast.Constant) and isinstance(p.value, str) for p in parts): continue out.append({"symbol": _enclosing(tree, node) or "module", "line": node.lineno, "end": node.end_lineno, "col": node.col_offset, "end_col": node.end_col_offset, "evidence": "string built with plus"}) if not out: return [], "NO_SHAPE" return out, None
def _flatten_add(node: ast.AST) -> List[ast.AST]: if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): return _flatten_add(node.left) + _flatten_add(node.right) return [node]
def edit_concat_fstring(path: str, lines: List[str], target: Target) -> List[Edit]: if target.get("line") != target.get("end"): return [] idx = target["line"] - 1 old = lines[idx] segment = old[target["col"]:target["end_col"]].strip() if not segment: return [] try: expr = ast.parse(segment, mode="eval").body except SyntaxError: return [] pieces = [] for part in _flatten_add(expr): if isinstance(part, ast.Constant) and isinstance(part.value, str): text = part.value.replace("{", "{{").replace("}", "}}").replace('"', "'") pieces.append(text) else: pieces.append("{" + ast.unparse(part) + "}") rendered = "f" + chr(34) + "".join(pieces) + chr(34) new = old[:target["col"]] + rendered + old[target["end_col"]:] if new == old: return [] return [{"file": path, "search": old, "replace": new}]
def lock_concat_fstring(target: Target) -> str: return ( "def test_%(symbol)s_has_no_concatenation_left():\n" " for node in ast.walk(_tree()):\n" " if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add) \\\n" " and isinstance(node.left, ast.Constant) \\\n" " and isinstance(node.left.value, str):\n" " assert False, 'string still built with plus'\n" % {"symbol": target["symbol"]} )
# ---------------------------------------------------------------- assertion
def match_add_assertion(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]: out: List[Target] = [] for fn in functions(tree): body = [s for s in fn.body if not _is_docstring(s)] if not body: continue if any(isinstance(s, ast.Assert) for s in body): continue if len(fn.args.args) == 1 and fn.args.args[0].annotation is not None: first = body[0] out.append({"symbol": fn.name, "line": first.lineno, "end": first.lineno, "evidence": "typed parameter with no guard", "param": fn.args.args[0].arg, "type": getattr(fn.args.args[0].annotation, "id", "object")}) if not out: return [], "NO_SHAPE" return out, None
def edit_add_assertion(path: str, lines: List[str], target: Target) -> List[Edit]: idx = target["line"] - 1 old = lines[idx] indent = " " * (len(old) - len(old.lstrip())) guard = "%sassert isinstance(%s, %s), 'bad %s'" % (indent, target["param"], target["type"], target["param"]) return [{"file": path, "search": old, "replace": guard + "\n" + old}]
def lock_add_assertion(target: Target) -> str: return ( "def test_%(symbol)s_guards_its_argument():\n" " fn = _function(%(symbol)r)\n" " guards = [s for s in fn.body if isinstance(s, ast.Assert)]\n" " assert guards, 'no guard at the boundary'\n" " names = [n.id for n in ast.walk(guards[0]) if isinstance(n, ast.Name)]\n" " assert %(param)r in names\n" % {"symbol": target["symbol"], "param": target["param"]} )
MATCHERS = { "mutable-default": match_mutable_default, "magic-literal": match_magic_literal, "guard-clause": match_guard_clause, "dead-import": match_dead_import, "loop-comprehension": match_loop_comprehension, "concat-fstring": match_concat_fstring, "add-assertion": match_add_assertion,}
EDITORS = { "mutable-default": _fill_mutable_default, "magic-literal": edit_magic_literal, "guard-clause": edit_guard_clause, "dead-import": edit_dead_import, "loop-comprehension": edit_loop_comprehension, "concat-fstring": edit_concat_fstring, "add-assertion": edit_add_assertion,}
LOCKS = { "mutable-default": lock_mutable_default, "magic-literal": lock_magic_literal, "guard-clause": lock_guard_clause, "dead-import": lock_dead_import, "loop-comprehension": lock_loop_comprehension, "concat-fstring": lock_concat_fstring, "add-assertion": lock_add_assertion,}
def match(shape: str, source: str) -> Tuple[List[Target], Optional[str]]: try: tree = ast.parse(source) except SyntaxError: return [], "UNPARSEABLE_TARGET" fn = MATCHERS.get(shape) if fn is None: return [], "NO_SHAPE" return fn(source.splitlines(), tree)
def edits(shape: str, path: str, source: str, target: Target) -> List[Edit]: editor = EDITORS.get(shape) if editor is None: return [] return editor(path, source.splitlines(), target)
def lock(shape: str, target: Target) -> str: maker = LOCKS.get(shape) if maker is None: return "" return maker(target)
def shapes() -> List[str]: return sorted(MATCHERS)123"""The seven nodes of the topology. Each is a separate process; this package only makesthem importable for the arbiter logic, which the orchestrator re-applies to the transcript."""README.md+53-5
catalog/conflict_policy.jsonAdded+28
catalog/patterns.jsonAdded+82
catalog/request_templates.jsonAdded+30
catalog/smoke_requests.jsonAdded+63
corpus/corpus.jsonlAdded
corpus/maintenance.jsonlAdded+36
doc/HOW_TO_ADD_AN_ENTRY.pyAdded+60
doc/REASONS.mdAdded+61
fixtures/lab/conftest.pyAdded+6
fixtures/lab/registry.pyAdded+31
fixtures/lab/tests/test_registry.pyAdded+19
fixtures/seed_project/README.mdAdded+2
fixtures/seed_project/auth.pyAdded+16
fixtures/seed_project/billing.pyAdded+16
fixtures/seed_project/cache.pyAdded+19
fixtures/seed_project/conftest.pyAdded+4
fixtures/seed_project/export.pyAdded+16
fixtures/seed_project/inventory.pyAdded+20
fixtures/seed_project/jobqueue.pyAdded+19
fixtures/seed_project/reporting.pyAdded+19
fixtures/seed_project/routing.pyAdded+16
fixtures/seed_project/search.pyAdded+16
fixtures/seed_project/session.pyAdded+19
fixtures/seed_project/tests/test_auth.pyAdded+13
fixtures/seed_project/tests/test_billing.pyAdded+10
fixtures/seed_project/tests/test_cache.pyAdded+13
fixtures/seed_project/tests/test_export.pyAdded+13
fixtures/seed_project/tests/test_inventory.pyAdded+13
fixtures/seed_project/tests/test_jobqueue.pyAdded+13
fixtures/seed_project/tests/test_reporting.pyAdded+13
fixtures/seed_project/tests/test_routing.pyAdded+13
fixtures/seed_project/tests/test_search.pyAdded+13
fixtures/seed_project/tests/test_session.pyAdded+13
lexicon/ar.jsonAdded+117
lexicon/en.jsonAdded+34
lexicon/es.jsonAdded+34
lexicon/hi.jsonAdded+34
lexicon/it.jsonAdded+34
lexicon/zh.jsonAdded+34
lingologos_thinkingpython/__init__.pyAdded+9
lingologos_thinkingpython/catalog.pyAdded+103
lingologos_thinkingpython/intent.pyAdded+99
lingologos_thinkingpython/lexicon.pyAdded+82
lingologos_thinkingpython/orchestrator.pyAdded+108
lingologos_thinkingpython/preflight.pyAdded+84
lingologos_thinkingpython/reasons.pyAdded+62
lingologos_thinkingpython/session.pyAdded+199
lingologos_thinkingpython/shapes.pyAdded+513
nodes/__init__.pyAdded+3