Upload folder using huggingface_hub
Browse filesFiles changed (18)
- README.md+30-19
- fixtures/pattern_lab/src/baskets.pyAdded+17
- fixtures/pattern_lab/src/labels.pyAdded+18
- fixtures/pattern_lab/src/retries.pyAdded+20
- fixtures/pattern_lab/tests/test_baskets.pyAdded+13
- fixtures/pattern_lab/tests/test_labels.pyAdded+14
- fixtures/pattern_lab/tests/test_retries.pyAdded+16
- lingologos_python/patterns.py+59
- lingologos_python/rules.py+295
- patterns/coverage.json+50-2
- patterns/pattern_cases.jsonl+6
- results/gates.json+3-3
- tests/test_pattern_session.py+6
- tests/test_patterns.py+6
- tests/test_rules.py+72-1
- tools/build_patterns.py+15
- tools/publish_dataset.py+14-13
- tools/run_gates.py+9-2
34 unmodified lines353637383839404111 unmodified lines535455565657585917 unmodified lines77787980808182832 unmodified lines868788899091929394959694959798991001011021031041054 unmodified lines1101111121131141151161171184 unmodified lines1231241251161261271281291301311321231331341351368 unmodified lines145146147138139140141142143148149150151152153154155156147157158159160114 unmodified lines27527627726827827928028128215 unmodified lines2982993002903013022923033043053061 unmodified line30830931030030131131231331431534 unmodified linesGATES: CONFIRMED (9 gates: 9 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
```
The gate runner is where this bundle states its numbers out loud: 9 gates, 90 tests across 9 files,
The gate runner is where this bundle states its numbers out loud: 9 gates, 99 tests across 9 files,
18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives every
one of those numbers from the tree it is standing in and stops the upload when the card and the code
beside it disagree.11 unmodified lines- `lingologos_python/gates.py`: bytecode-free `ast.parse` + in-memory `compile` gate, optional static
checkers (`mypy`, `ruff`, `pyright`, `flake8`) that return `ABSTAIN` when missing, and `pytest`
/ `unittest` test runner with failed-target parsing.
- `lingologos_python/rules.py`: five shape rules over a named function. Each rule reads the function
- `lingologos_python/rules.py`: eight shape rules over a named function. Each rule reads the function
through its syntax tree, refuses with a named reason code when the shape is not the one it claims, and
returns the edit texts when it is (`RULES`, `RULE_IDS`, `open_target`).
- `lingologos_python/patterns.py`: the catalog above the rules. A card states the shape it claims, why17 unmodified lines
## The pattern catalog
Five cards, one per shape this bundle can actually carry out:
Eight cards, one per shape this bundle can actually carry out:
| Card | Shape it claims | Family |
|---|---|---|2 unmodified lines| `chain-to-registry` | an `if`/`elif` chain dispatching on one name, ending in a refusal | shape |
| `open-to-context-manager` | a file handle opened in a function body and closed by hand | resources |
| `bare-assert-to-explicit-raise` | a bare `assert` as the guard of a function, which vanishes under `-O` | contracts |
| `bare-except-to-narrow-exception` | an `except:` that names no class, so it also catches the exits of the interpreter | contracts |
| `none-comparison-to-identity` | a test against `None` written with `==` or `!=`, which asks agreement and not identity | shape |
| `empty-len-to-truthiness` | an emptiness test that counts the collection with `len` and compares to zero | shape |
A card is not a prompt: it names a syntax-tree shape, and `lingologos_python/rules.py` refuses anything
that is not that shape. `chain-to-registry` refuses a chain whose branches take different kinds of
arguments (`BRANCH_SHAPE_MISMATCH`), `open-to-context-manager` refuses a handle that escapes the function
it opened (`HANDLE_ESCAPE`), `mutable-default-to-none` refuses a default that already carries an
annotation (`ANNOTATED_MUTABLE_DEFAULT`). A refusal is an answer, not a failure: it names the reason code
and writes nothing. Each card also lists the refusals the plan around a rule shares: a target that is not
annotation (`ANNOTATED_MUTABLE_DEFAULT`), `bare-except-to-narrow-exception` refuses a bare handler that
re-raises what it caught (`BARE_EXCEPT_RE_RAISES`), `none-comparison-to-identity` refuses a test against
`None` inside a chained comparison (`NONE_COMPARISON_IS_CHAINED`), and `empty-len-to-truthiness` refuses
a count of something that is not a plain name (`LEN_TARGET_IS_NOT_A_NAME`). A refusal is an answer, not
a failure: it names the reason code and writes nothing. Each card also lists the refusals the plan around
a rule shares: a target that is not
there (`MISSING_TARGET_FILE`), a test file that cannot carry the lock (`NO_TEST_FILE`, `CRLF_TARGET`,
`INVALID_COMPANION_PATH`), a coroutine the lock tests could not call directly (`ASYNC_TARGET`), an assert
whose message is built at call time (`NON_LITERAL_ASSERT_MESSAGE`), and anchors that collide (`ANCHOR_OVERLAP`).4 unmodified linessecond run honest. Run `chain-to-registry` on `src/registry.py::render` and the lock asserts that
the mapping is there, that each kind reaches its handler, that the chain is gone, and that the
refusal still refuses; take only the lock test and leave the source alone, and the test suite fails.
The three newest cards write their lock as a reading rather than a call: the test opens the function
with `inspect` and asserts on the text the rewrite leaves behind and the text it removes, so the lock
still fails while the old shape stands, but it answers about the source and not about a behavior.
The pair then goes through the six nodes of the kernel as any other change does: the proposing roles
claim it, `gate_checker` runs the syntax gate and the selected tests, `adversary` reproduces the4 unmodified lines
This is a catalog of patterns this bundle has carried out and can re-derive, not a claim that it can
change Python in general. `patterns/coverage.json` says what has been shown and names its denominator:
the five cards over the five source files and fifteen module level functions of
the eight cards over the eight source files and twenty-one module level functions of
`fixtures/pattern_lab/`, not over Python and not over any corpus of real repositories.
The corpus is generated, like the kernel's own:
```
python -B tools/build_patterns.py --check
PATTERNS: CONFIRMED (10 rows over 5 cards, 15 module level functions in the fixture)
PATTERNS: CONFIRMED (16 rows over 8 cards, 21 module level functions in the fixture)
```
Each row is a work case in the schema `lingologos_codex/casecorpus.py` defines, so the kernel can check8 unmodified lines
```
$ python -B -m lingologos_python symbols --workspace fixtures/pattern_lab --limit 5
files=10 symbols=29 edges=29
0.0942 src/registry.py::render
0.0838 src/tokens.py::count_words
0.0669 src/guards.py::open_ticket
0.0572 src/registry.py::format_short
0.0481 src/registry.py::format_json
files=16 symbols=43 edges=40
0.0669 src/registry.py::render
0.0594 src/tokens.py::count_words
0.0475 src/guards.py::open_ticket
0.0406 src/registry.py::format_short
0.0341 src/registry.py::format_json
```
The ranking is PageRank over the call and import graph, and the three highest ranked functions here are
three of the five the catalog claims: the dispatcher, the annotatable default, the bare guard. To know
three of the eight the catalog claims: the dispatcher, the annotatable default, the bare guard. To know
which tests a change is answerable to:
```114 unmodified linescommand line is `python -B -m lingologos_python`, the same name the console script of `pyproject.toml`
carries. What did not move: the five adapter methods, the envelope kind string, the entry point group
`lingologos.codex.adapters`, the work case schema version, and the ten rows of
`patterns/pattern_cases.jsonl`, which are byte for byte what that revision published. The six seed
`patterns/pattern_cases.jsonl` that the earlier revision published, which this revision kept byte for
byte while adding one pair for each of its three new cards. The six seed
envelopes under `nodes/` do carry the adapter under its new dotted path, because naming a module that no
longer exists would make those files disagree with the code beside them. The dataset keeps its name,
`tailot/codex-python`.15 unmodified linesnever imports this folder, so the dependency has exactly one direction, and one copy of the kernel can
serve any number of workspaces.
## The ten pattern cases
## The sixteen pattern cases
`patterns/pattern_cases.jsonl` holds 10 rows, one accepted and one refused for each of the five cards
`patterns/pattern_cases.jsonl` holds 16 rows, one accepted and one refused for each of the eight cards
of the catalog: `case_id`, `language`, `family`, `intent_tags`, the `edits` the rule returned (the
source edit and the test that locks it), the verdict the run must reach, and for a refusal the
`reason_code` the rule answered with. A row is a work case in the schema the kernel dataset defines in1 unmodified line
`tools/build_patterns.py` derives the rows by running each rule over `fixtures/pattern_lab/`, and
`--check` re-derives them and compares the bytes: a row is never edited by hand. The same tool writes
`patterns/coverage.json`, which states what the ten rows cover and names its own denominator, the
fixture. Ten rows are five cards carried end to end, not a benchmark: the fixture is small and was
`patterns/coverage.json`, which states what the sixteen rows cover and names its own denominator, the
fixture. Sixteen rows are eight cards carried end to end, not a benchmark: the fixture is small and was
written for this bundle, and nothing here counts coverage of real repositories.
## Rights1234567891011121314151617"""Reporting what a basket holds.
One function counts the basket to ask whether it is empty, and that is the shape thetruthiness pattern rewrites. The other already asks directly, and the pattern says so."""
def describe(items): if len(items) == 0: return "empty" return "full"
def first_or_none(items): if not items: return None return items[0]123456789101112131415161718"""Naming a value by what it holds.
One function asks whether a value is None with the equality operators, and that is theshape the identity comparison pattern rewrites. The other already asks with identity,and the pattern says so."""
def label_for(value): if value == None: return "none" if value != None and value == "": return "blank" return "given"
def is_missing(value): return value is None1234567891011121314151617181920"""Failure handling around an object that reads.
One handler catches every exception the interpreter can raise, and that is the shapethe narrow exception pattern rewrites. The other handler already names its exception,and the pattern says so."""
def call_or_none(source): try: return source.read() except: return ""
def call_or_note(source): try: return source.read() except ValueError: return "no source"12345678910111213"""Tests for the two emptiness shapes in src.baskets."""
from src.baskets import describe, first_or_none
def test_describe_reports_whether_the_basket_holds_anything() -> None: assert describe([]) == "empty" assert describe([1, 2]) == "full"
def test_first_or_none_gives_the_head_or_nothing() -> None: assert first_or_none([7]) == 7 assert first_or_none([]) is None1234567891011121314"""Tests for the two comparison shapes in src.labels."""
from src.labels import is_missing, label_for
def test_label_for_names_a_given_value() -> None: assert label_for("note") == "given" assert label_for(None) == "none" assert label_for("") == "blank"
def test_is_missing_answers_for_none() -> None: assert is_missing(None) assert not is_missing("")12345678910111213141516"""Tests for the two retry shapes in src.retries."""
from src.retries import call_or_none, call_or_note
class _BrokenSource: def read(self): raise ValueError("the source is closed")
def test_call_or_note_reports_a_broken_source() -> None: assert call_or_note(_BrokenSource()) == "no source"
def test_call_or_none_falls_back_when_reading_fails() -> None: assert call_or_none(_BrokenSource()) == ""229 unmodified lines230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294229 unmodified lines "refused, with the message it carried", (rules.NOT_THE_FIRST_STATEMENT, rules.NOT_A_MODULE_FUNCTION, rules.CRLF_TARGET), ), _card( "bare-except-to-narrow-exception", "contracts", ("errors", "exceptions", "contracts"), "a module level function with an except handler that names no exception class", "a bare handler also answers the exits the interpreter raises, so the one path that means to " "leave the program is answered with the fallback the handler was written for. Naming the " "class keeps the fallback and lets the exits pass.", ( "the handler carries the bare header text the rule anchors on, 'except:'", "the handler body does not end by re-raising what it caught, which is a second change", "the function text holds no other 'except:' the lock could confuse with a header", ), (LOCK_COMPANION,), "the source names Exception in every handler that was bare and carries no bare header left; " "the lock reads the function back with inspect, so it answers about the text, not about a call", ( rules.NO_BARE_EXCEPT, rules.BARE_EXCEPT_RE_RAISES, rules.EXCEPT_HANDLER_UNREADABLE, rules.NOT_A_MODULE_FUNCTION, ), ), _card( "none-comparison-to-identity", "shape", ("equality", "identity", "none"), "a module level function that asks whether a value is None with == or !=", "None is one object, and an equality against it is a question most objects answer by their own " "agreement: a type with a custom equality turns a presence check into whatever that equality " "happens to say. Identity asks the question that was meant.", ( "the comparison is a single equality test against None, not a chained comparison", "None is written as the plain literal on one side of the test", "the file is ASCII text with LF endings and spaces for indentation", ), (LOCK_COMPANION,), "every test the pattern touched reads with is or is not, and the source carries no == None or " "!= None left; the lock reads the function back with inspect, so it answers about the text", (rules.NO_NONE_COMPARISON, rules.NONE_COMPARISON_IS_CHAINED, rules.NOT_A_MODULE_FUNCTION), ), _card( "empty-len-to-truthiness", "shape", ("collections", "truthiness", "emptiness"), "a module level function that counts a value with len and compares the count to zero", "counting a collection only to ask whether it is empty does work the answer does not need, and " "it stops working for collections that answer emptiness without giving a length. The rewrite " "asks the question directly.", ( "the value counted is a plain name, so the rewrite evaluates it no more than before", "the comparison is a single test against the number 0, not against False or a chain", "the file is ASCII text with LF endings and spaces for indentation", ), (LOCK_COMPANION,), "each check the pattern touched became a truthiness test, and its counted comparison is gone " "from the source; the lock reads the function back with inspect, so it answers about the text", (rules.NO_EMPTY_LEN_CHECK, rules.LEN_TARGET_IS_NOT_A_NAME, rules.NOT_A_MODULE_FUNCTION), ), )}
57 unmodified lines585960616263646566676869701029 unmodified lines11001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139957 unmodified linesNON_LITERAL_ASSERT_MESSAGE = "NON_LITERAL_ASSERT_MESSAGE"INVALID_COMPANION_PATH = "INVALID_COMPANION_PATH"ANCHOR_OVERLAP = "ANCHOR_OVERLAP"NO_BARE_EXCEPT = "NO_BARE_EXCEPT"BARE_EXCEPT_RE_RAISES = "BARE_EXCEPT_RE_RAISES"EXCEPT_HANDLER_UNREADABLE = "EXCEPT_HANDLER_UNREADABLE"NO_NONE_COMPARISON = "NO_NONE_COMPARISON"NONE_COMPARISON_IS_CHAINED = "NONE_COMPARISON_IS_CHAINED"NO_EMPTY_LEN_CHECK = "NO_EMPTY_LEN_CHECK"LEN_TARGET_IS_NOT_A_NAME = "LEN_TARGET_IS_NOT_A_NAME"
INDENT = " "_MUTABLE_LITERALS = (ast.List, ast.Dict, ast.Set)1029 unmodified lines return _hit("bare-assert-to-explicit-raise", target, edit, companion, evidence)
# ---------------------------------------------------------------------------# Rule 6: a bare handler names the class it answers to.# ---------------------------------------------------------------------------
def rule_bare_except_to_narrow_exception(target: Target) -> Outcome: """Name ``Exception`` in every bare ``except:`` header of the function.
A handler that names no class also answers the exits the interpreter raises, so the one path that means to leave the program is answered with the fallback written for an ordinary failure. Naming the class keeps the fallback and lets the exits pass. """
function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text) handlers = [ node for node in ast.walk(function) if isinstance(node, ast.ExceptHandler) and node.type is None ] if not handlers: return _miss( target.rel_posix, target.symbol, NO_BARE_EXCEPT, "no handler of '%s' leaves out the exception class" % target.symbol, ) splices: List[_Splice] = [] for handler in sorted(handlers, key=lambda node: node.lineno): if any(isinstance(node, ast.Raise) and node.exc is None for node in ast.walk(handler)): return _miss( target.rel_posix, target.symbol, BARE_EXCEPT_RE_RAISES, "a bare handler of '%s' re-raises what it caught, so naming the class would also " "change which exits the re-raise can still pass" % target.symbol, ) start = starts[handler.lineno - 1] + handler.col_offset if target.text[start : start + len("except:")] != "except:": return _miss( target.rel_posix, target.symbol, EXCEPT_HANDLER_UNREADABLE, "a bare handler of '%s' does not carry the header text 'except:' this rule anchors on" % target.symbol, ) splices.append(_Splice(start=start, end=start + len("except:"), text="except Exception:")) function_start, function_end = node_span(target.text, starts, function) rewritten = apply_splices(target.text, function_start, function_end, splices) if "except:" in rewritten: return _miss( target.rel_posix, target.symbol, EXCEPT_HANDLER_UNREADABLE, "the text of '%s' carries an 'except:' outside a handler header, so the lock test this " "rule writes could not tell the handler from the text around it" % target.symbol, ) edit = Edit( file=target.rel_posix, search=target.text[function_start:function_end], replace=rewritten, label="named handler of '%s'" % target.symbol, )
alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s.%s)" % (alias, target.symbol), "assert 'except Exception:' in source", "assert 'except:' not in source", ] test_name = "%s_answers_named_exceptions" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the class every handler of this function now names.", statements, ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = tuple( "the handler on line %d catches every exception the interpreter can raise" % handler.lineno for handler in sorted(handlers, key=lambda node: node.lineno) ) return _hit("bare-except-to-narrow-exception", target, edit, companion, evidence)
# ---------------------------------------------------------------------------# Rule 7: asking whether a value is None asks with identity.# ---------------------------------------------------------------------------
def _is_none_literal(node: ast.expr) -> bool: return isinstance(node, ast.Constant) and node.value is None
def _none_comparisons(function: ast.FunctionDef) -> Tuple[List[ast.Compare], bool]: """The single equality tests against ``None``, and whether a test against None is chained."""
claimed: List[ast.Compare] = [] chained = False for node in ast.walk(function): if not isinstance(node, ast.Compare): continue operands = [node.left] + list(node.comparators) if not any(isinstance(op, (ast.Eq, ast.NotEq)) for op in node.ops): continue if not any(_is_none_literal(operand) for operand in operands): continue if len(node.ops) != 1 or len(operands) != 2: chained = True continue claimed.append(node) return claimed, chained
def rule_none_comparison_to_identity(target: Target) -> Outcome: """Replace an equality against ``None`` with ``is`` or ``is not``.
None is one object, and an equality against it is a question most objects answer by their own agreement: a type with a custom equality turns a presence check into whatever that equality happens to say. Identity asks the question that was meant. """
function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text) comparisons, chained = _none_comparisons(function) if chained: return _miss( target.rel_posix, target.symbol, NONE_COMPARISON_IS_CHAINED, "a test against None in '%s' is part of a chained comparison, which one identity test " "cannot replace" % target.symbol, ) if not comparisons: return _miss( target.rel_posix, target.symbol, NO_NONE_COMPARISON, "no comparison of '%s' tests a value against None with equality" % target.symbol, ) splices: List[_Splice] = [] touched: List[Tuple[str, str]] = [] for node in comparisons: start, end = node_span(target.text, starts, node) operator = "is not" if isinstance(node.ops[0], ast.NotEq) else "is" left = node.left right = node.comparators[0] if _is_none_literal(right) and not _is_none_literal(left): operand = segment_of(target.text, starts, left) replacement = "%s %s None" % (operand, operator) else: operand = segment_of(target.text, starts, right) replacement = "None %s %s" % (operator, operand) splices.append(_Splice(start=start, end=end, text=replacement)) touched.append((operand, operator)) edit = _rewrite_function( target, starts, function, splices, "identity comparisons of '%s'" % target.symbol )
alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s.%s)" % (alias, target.symbol), "assert '== None' not in source", "assert '!= None' not in source", ] for operand, operator in touched: statements.append("assert %s in source" % repr("%s %s None" % (operand, operator))) test_name = "%s_compares_none_by_identity" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the identity tests that replaced the equality against None.", statements, ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = tuple("the test against None reads '%s %s None'" % (operand, operator) for operand, operator in touched) return _hit("none-comparison-to-identity", target, edit, companion, evidence)
# ---------------------------------------------------------------------------# Rule 8: an emptiness test stops counting the collection.# ---------------------------------------------------------------------------
def _len_call(node: ast.expr) -> bool: return ( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "len" and len(node.args) == 1 and not node.keywords )
def _is_plain_zero(node: ast.expr) -> bool: return ( isinstance(node, ast.Constant) and isinstance(node.value, int) and not isinstance(node.value, bool) and node.value == 0 )
def rule_empty_len_to_truthiness(target: Target) -> Outcome: """Ask whether a collection is empty by truthiness instead of counting it."""
function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text) checks: List[Tuple[ast.Compare, str]] = [] counted_but_not_a_name: List[ast.expr] = [] for node in ast.walk(function): if not isinstance(node, ast.Compare) or len(node.ops) != 1 or not isinstance(node.ops[0], ast.Eq): continue operands = [node.left] + list(node.comparators) if len(operands) != 2: continue if _is_plain_zero(operands[0]) and _len_call(operands[1]): counted = operands[1] elif _is_plain_zero(operands[1]) and _len_call(operands[0]): counted = operands[0] else: continue assert isinstance(counted, ast.Call) and counted.args argument = counted.args[0] if isinstance(argument, ast.Name): checks.append((node, argument.id)) else: counted_but_not_a_name.append(argument) if not checks and not counted_but_not_a_name: return _miss( target.rel_posix, target.symbol, NO_EMPTY_LEN_CHECK, "no comparison of '%s' counts a value with len only to ask whether it is empty" % target.symbol, ) if counted_but_not_a_name: return _miss( target.rel_posix, target.symbol, LEN_TARGET_IS_NOT_A_NAME, "'%s' counts '%s', which is not a plain name, and this rule only rewrites a count of a " "name it can ask about directly" % (target.symbol, segment_of(target.text, starts, counted_but_not_a_name[0])), ) splices: List[_Splice] = [] names: List[str] = [] for node, name in checks: start, end = node_span(target.text, starts, node) splices.append(_Splice(start=start, end=end, text="not %s" % name)) if name not in names: names.append(name) edit = _rewrite_function( target, starts, function, splices, "truthiness emptiness test of '%s'" % target.symbol )
alias = import_statement_for(target.rel_posix)[1] statements = ["source = inspect.getsource(%s.%s)" % (alias, target.symbol)] for name in names: statements.append("assert 'not %s' in source" % name) statements.append("assert 'len(%s) == 0' not in source" % name) test_name = "%s_asks_for_truthiness" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the truthiness test that replaced the counted emptiness.", statements, ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = tuple("'%s' is counted only to ask whether it is empty" % name for name in names) return _hit("empty-len-to-truthiness", target, edit, companion, evidence)
RULES: Dict[str, Callable[[Target], Outcome]] = { "annotate-literal-defaults": rule_annotate_literal_defaults, "mutable-default-to-none": rule_mutable_default_to_none, "chain-to-registry": rule_chain_to_registry, "open-to-context-manager": rule_open_to_context_manager, "bare-assert-to-explicit-raise": rule_bare_assert_to_explicit_raise, "bare-except-to-narrow-exception": rule_bare_except_to_narrow_exception, "none-comparison-to-identity": rule_none_comparison_to_identity, "empty-len-to-truthiness": rule_empty_len_to_truthiness,}
RULE_IDS: Tuple[str, ...] = tuple(sorted(RULES))1234456789101112131428 unmodified lines43444546474849505152535455565758596061628 unmodified lines71727374757677787980818283848586878889908 unmodified lines991001011021031041051061071081091101111121131141151161171189 unmodified lines12812913086131132133134135136137138139140141142{ "denominator": "the counts below are over one fixture of this bundle, not over Python. They say how many of the functions this bundle planted are in a shape the catalog claims, so a reader can see that the catalog is a set of verified cards and not a claim about arbitrary code.", "fixture": "fixtures/pattern_lab", "module_level_functions": 15, "module_level_functions": 21, "module_level_functions_by_file": { "src/baskets.py": 2, "src/guards.py": 2, "src/labels.py": 2, "src/notes.py": 2, "src/registry.py": 6, "src/retries.py": 2, "src/slugify.py": 2, "src/tokens.py": 3 },28 unmodified lines ], "targets_planted_in_shape": 1 }, { "family": "contracts", "min_assurance": 3, "negative_rows": 1, "pattern_id": "bare-except-to-narrow-exception", "positive_rows": 1, "refusals_recorded": [ "NO_BARE_EXCEPT" ], "targets_in_shape": [ "src/retries.py::call_or_none" ], "targets_planted_in_shape": 1 }, { "family": "shape", "min_assurance": 3,8 unmodified lines ], "targets_planted_in_shape": 1 }, { "family": "shape", "min_assurance": 3, "negative_rows": 1, "pattern_id": "empty-len-to-truthiness", "positive_rows": 1, "refusals_recorded": [ "NO_EMPTY_LEN_CHECK" ], "targets_in_shape": [ "src/baskets.py::describe" ], "targets_planted_in_shape": 1 }, { "family": "mutation", "min_assurance": 3,8 unmodified lines ], "targets_planted_in_shape": 1 }, { "family": "shape", "min_assurance": 3, "negative_rows": 1, "pattern_id": "none-comparison-to-identity", "positive_rows": 1, "refusals_recorded": [ "NO_NONE_COMPARISON" ], "targets_in_shape": [ "src/labels.py::label_for" ], "targets_planted_in_shape": 1 }, { "family": "resources", "min_assurance": 3,9 unmodified lines "targets_planted_in_shape": 1 } ], "rows": 10, "rows": 16, "schema": "lingologos-python-pattern-coverage-1", "source_files": [ "src/baskets.py", "src/guards.py", "src/labels.py", "src/notes.py", "src/registry.py", "src/retries.py", "src/slugify.py", "src/tokens.py" ]1 unmodified line23456789101112131415161 unmodified line{"case_id": "pat-annotate-literal-defaults-negative", "edits": [], "expect": "REFUSED", "family": "typing", "intent_tags": ["annotate", "defaults", "types"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter has a literal default and no annotation", "pattern_id": "annotate-literal-defaults", "reason_code": "ALREADY_ANNOTATED", "rule": "annotate-literal-defaults", "targets": ["src/tokens.py::count_lines"]}{"case_id": "pat-bare-assert-to-explicit-raise-positive", "edits": [{"file": "src/guards.py", "label": "explicit raise of 'open_ticket'", "replace": "def open_ticket(queue_name):\n if not queue_name:\n raise AssertionError(\"queue name is required\")\n return {\"queue\": queue_name, \"opened\": True}", "search": "def open_ticket(queue_name):\n assert queue_name, \"queue name is required\"\n return {\"queue\": queue_name, \"opened\": True}"}, {"file": "tests/test_guards.py", "label": "lock test 'test_open_ticket_raises_in_stead_of_asserting' appended after 'test_close_ticket_clears_the_flag'", "replace": "def test_close_ticket_clears_the_flag() -> None:\n closed = close_ticket(open_ticket(\"builds\"))\n assert closed[\"opened\"] is False\n with pytest.raises(AssertionError):\n close_ticket({\"queue\": \"\"})\n\n\ndef test_open_ticket_raises_in_stead_of_asserting() -> None:\n \"\"\"Lock the raise that replaced the assert, and the refusal the function still carries.\"\"\"\n import inspect\n\n from src import guards\n source = inspect.getsource(guards.open_ticket)\n assert 'raise AssertionError(' in source\n assert not [line for line in source.splitlines() if line.strip().startswith('assert ')]\n try:\n guards.open_ticket(\"\")\n except AssertionError as caught:\n assert \"queue name is required\" in str(caught)\n else:\n raise AssertionError('open_ticket accepted an argument its check rejects')\n", "search": "def test_close_ticket_clears_the_flag() -> None:\n closed = close_ticket(open_ticket(\"builds\"))\n assert closed[\"opened\"] is False\n with pytest.raises(AssertionError):\n close_ticket({\"queue\": \"\"})"}], "expect": "VERIFIED", "family": "contracts", "intent_tags": ["preconditions", "errors", "contracts"], "language": "python", "min_assurance": 3, "note": "a module level function whose first statement is an assert guarding its arguments", "pattern_id": "bare-assert-to-explicit-raise", "rule": "bare-assert-to-explicit-raise", "targets": ["src/guards.py::open_ticket"]}{"case_id": "pat-bare-assert-to-explicit-raise-negative", "edits": [], "expect": "REFUSED", "family": "contracts", "intent_tags": ["preconditions", "errors", "contracts"], "language": "python", "min_assurance": 3, "note": "a module level function whose first statement is an assert guarding its arguments", "pattern_id": "bare-assert-to-explicit-raise", "reason_code": "NOT_THE_FIRST_STATEMENT", "rule": "bare-assert-to-explicit-raise", "targets": ["src/guards.py::close_ticket"]}{"case_id": "pat-bare-except-to-narrow-exception-positive", "edits": [{"file": "src/retries.py", "label": "named handler of 'call_or_none'", "replace": "def call_or_none(source):\n try:\n return source.read()\n except Exception:\n return \"\"", "search": "def call_or_none(source):\n try:\n return source.read()\n except:\n return \"\""}, {"file": "tests/test_retries.py", "label": "lock test 'test_call_or_none_answers_named_exceptions' appended after 'test_call_or_none_falls_back_when_reading_fails'", "replace": "def test_call_or_none_falls_back_when_reading_fails() -> None:\n assert call_or_none(_BrokenSource()) == \"\"\n\n\ndef test_call_or_none_answers_named_exceptions() -> None:\n \"\"\"Lock the class every handler of this function now names.\"\"\"\n import inspect\n\n from src import retries\n source = inspect.getsource(retries.call_or_none)\n assert 'except Exception:' in source\n assert 'except:' not in source\n", "search": "def test_call_or_none_falls_back_when_reading_fails() -> None:\n assert call_or_none(_BrokenSource()) == \"\""}], "expect": "VERIFIED", "family": "contracts", "intent_tags": ["errors", "exceptions", "contracts"], "language": "python", "min_assurance": 3, "note": "a module level function with an except handler that names no exception class", "pattern_id": "bare-except-to-narrow-exception", "rule": "bare-except-to-narrow-exception", "targets": ["src/retries.py::call_or_none"]}{"case_id": "pat-bare-except-to-narrow-exception-negative", "edits": [], "expect": "REFUSED", "family": "contracts", "intent_tags": ["errors", "exceptions", "contracts"], "language": "python", "min_assurance": 3, "note": "a module level function with an except handler that names no exception class", "pattern_id": "bare-except-to-narrow-exception", "reason_code": "NO_BARE_EXCEPT", "rule": "bare-except-to-narrow-exception", "targets": ["src/retries.py::call_or_note"]}{"case_id": "pat-chain-to-registry-positive", "edits": [{"file": "src/registry.py", "label": "dispatch registry of 'render'", "replace": "def render(kind, item):\n handlers = {\"short\": format_short, \"long\": format_long, \"json\": format_json}\n handled = handlers.get(kind)\n if handled is None:\n raise ValueError(\"unsupported kind\")\n return handled(item)", "search": "def render(kind, item):\n if kind == \"short\":\n return format_short(item)\n elif kind == \"long\":\n return format_long(item)\n elif kind == \"json\":\n return format_json(item)\n else:\n raise ValueError(\"unsupported kind\")"}, {"file": "tests/test_registry.py", "label": "lock test 'test_render_dispatches_through_a_registry' appended after 'test_render_rejects_an_unknown_kind'", "replace": "def test_render_rejects_an_unknown_kind() -> None:\n with pytest.raises(ValueError):\n render(\"yaml\", 5)\n\n\ndef test_render_dispatches_through_a_registry() -> None:\n \"\"\"Lock the registry the chain became, and the answers the chain used to give.\"\"\"\n import inspect\n\n from src import registry\n source = inspect.getsource(registry.render)\n assert 'handlers = {' in source\n assert '\"short\": format_short' in source\n assert '\"long\": format_long' in source\n assert '\"json\": format_json' in source\n assert 'handlers.get(kind)' in source\n assert 'elif' not in source\n assert registry.render('short', \"\") == registry.format_short(\"\")\n assert registry.render('long', \"\") == registry.format_long(\"\")\n assert registry.render('json', \"\") == registry.format_json(\"\")\n try:\n registry.render('~no such kind~', \"\")\n except ValueError:\n pass\n else:\n raise AssertionError('render accepted a kind no branch carries')\n", "search": "def test_render_rejects_an_unknown_kind() -> None:\n with pytest.raises(ValueError):\n render(\"yaml\", 5)"}], "expect": "VERIFIED", "family": "shape", "intent_tags": ["dispatch", "registry", "extension"], "language": "python", "min_assurance": 3, "note": "a module level function that dispatches an if/elif chain of one name compared to text literals", "pattern_id": "chain-to-registry", "rule": "chain-to-registry", "targets": ["src/registry.py::render"]}{"case_id": "pat-chain-to-registry-negative", "edits": [], "expect": "REFUSED", "family": "shape", "intent_tags": ["dispatch", "registry", "extension"], "language": "python", "min_assurance": 3, "note": "a module level function that dispatches an if/elif chain of one name compared to text literals", "pattern_id": "chain-to-registry", "reason_code": "BRANCH_SHAPE_MISMATCH", "rule": "chain-to-registry", "targets": ["src/registry.py::render_pair"]}{"case_id": "pat-empty-len-to-truthiness-positive", "edits": [{"file": "src/baskets.py", "label": "truthiness emptiness test of 'describe'", "replace": "def describe(items):\n if not items:\n return \"empty\"\n return \"full\"", "search": "def describe(items):\n if len(items) == 0:\n return \"empty\"\n return \"full\""}, {"file": "tests/test_baskets.py", "label": "lock test 'test_describe_asks_for_truthiness' appended after 'test_first_or_none_gives_the_head_or_nothing'", "replace": "def test_first_or_none_gives_the_head_or_nothing() -> None:\n assert first_or_none([7]) == 7\n assert first_or_none([]) is None\n\n\ndef test_describe_asks_for_truthiness() -> None:\n \"\"\"Lock the truthiness test that replaced the counted emptiness.\"\"\"\n import inspect\n\n from src import baskets\n source = inspect.getsource(baskets.describe)\n assert 'not items' in source\n assert 'len(items) == 0' not in source\n", "search": "def test_first_or_none_gives_the_head_or_nothing() -> None:\n assert first_or_none([7]) == 7\n assert first_or_none([]) is None"}], "expect": "VERIFIED", "family": "shape", "intent_tags": ["collections", "truthiness", "emptiness"], "language": "python", "min_assurance": 3, "note": "a module level function that counts a value with len and compares the count to zero", "pattern_id": "empty-len-to-truthiness", "rule": "empty-len-to-truthiness", "targets": ["src/baskets.py::describe"]}{"case_id": "pat-empty-len-to-truthiness-negative", "edits": [], "expect": "REFUSED", "family": "shape", "intent_tags": ["collections", "truthiness", "emptiness"], "language": "python", "min_assurance": 3, "note": "a module level function that counts a value with len and compares the count to zero", "pattern_id": "empty-len-to-truthiness", "reason_code": "NO_EMPTY_LEN_CHECK", "rule": "empty-len-to-truthiness", "targets": ["src/baskets.py::first_or_none"]}{"case_id": "pat-mutable-default-to-none-positive", "edits": [{"file": "src/slugify.py", "label": "shared default of 'add_tag'", "replace": "def add_tag(name, tags=None):\n if tags is None:\n tags = []\n tags.append(name)\n return tags", "search": "def add_tag(name, tags=[]):\n tags.append(name)\n return tags"}, {"file": "tests/test_slugify.py", "label": "lock test 'test_add_tag_has_no_shared_default' appended after 'test_join_parts_uses_its_tuple_default'", "replace": "def test_join_parts_uses_its_tuple_default() -> None:\n assert join_parts() == \"root\"\n assert join_parts((\"a\", \"b\"), sep=\"/\") == \"a/b\"\n\n\ndef test_add_tag_has_no_shared_default() -> None:\n \"\"\"Lock the default this pattern unshared, the guard that replaced it, and the call that no longer shares state.\"\"\"\n import inspect\n\n from src import slugify\n signature = inspect.signature(slugify.add_tag)\n source = inspect.getsource(slugify.add_tag)\n assert signature.parameters['tags'].default is None\n assert 'if tags is None:' in source\n first = slugify.add_tag('alpha')\n second = slugify.add_tag('beta')\n assert first != second\n", "search": "def test_join_parts_uses_its_tuple_default() -> None:\n assert join_parts() == \"root\"\n assert join_parts((\"a\", \"b\"), sep=\"/\") == \"a/b\""}], "expect": "VERIFIED", "family": "mutation", "intent_tags": ["defaults", "aliasing", "mutation"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter defaults to a list, dict or set built at definition time", "pattern_id": "mutable-default-to-none", "rule": "mutable-default-to-none", "targets": ["src/slugify.py::add_tag"]}{"case_id": "pat-mutable-default-to-none-negative", "edits": [], "expect": "REFUSED", "family": "mutation", "intent_tags": ["defaults", "aliasing", "mutation"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter defaults to a list, dict or set built at definition time", "pattern_id": "mutable-default-to-none", "reason_code": "NOT_A_MUTABLE_DEFAULT", "rule": "mutable-default-to-none", "targets": ["src/slugify.py::join_parts"]}{"case_id": "pat-none-comparison-to-identity-positive", "edits": [{"file": "src/labels.py", "label": "identity comparisons of 'label_for'", "replace": "def label_for(value):\n if value is None:\n return \"none\"\n if value is not None and value == \"\":\n return \"blank\"\n return \"given\"", "search": "def label_for(value):\n if value == None:\n return \"none\"\n if value != None and value == \"\":\n return \"blank\"\n return \"given\""}, {"file": "tests/test_labels.py", "label": "lock test 'test_label_for_compares_none_by_identity' appended after 'test_is_missing_answers_for_none'", "replace": "def test_is_missing_answers_for_none() -> None:\n assert is_missing(None)\n assert not is_missing(\"\")\n\n\ndef test_label_for_compares_none_by_identity() -> None:\n \"\"\"Lock the identity tests that replaced the equality against None.\"\"\"\n import inspect\n\n from src import labels\n source = inspect.getsource(labels.label_for)\n assert '== None' not in source\n assert '!= None' not in source\n assert 'value is None' in source\n assert 'value is not None' in source\n", "search": "def test_is_missing_answers_for_none() -> None:\n assert is_missing(None)\n assert not is_missing(\"\")"}], "expect": "VERIFIED", "family": "shape", "intent_tags": ["equality", "identity", "none"], "language": "python", "min_assurance": 3, "note": "a module level function that asks whether a value is None with == or !=", "pattern_id": "none-comparison-to-identity", "rule": "none-comparison-to-identity", "targets": ["src/labels.py::label_for"]}{"case_id": "pat-none-comparison-to-identity-negative", "edits": [], "expect": "REFUSED", "family": "shape", "intent_tags": ["equality", "identity", "none"], "language": "python", "min_assurance": 3, "note": "a module level function that asks whether a value is None with == or !=", "pattern_id": "none-comparison-to-identity", "reason_code": "NO_NONE_COMPARISON", "rule": "none-comparison-to-identity", "targets": ["src/labels.py::is_missing"]}{"case_id": "pat-open-to-context-manager-positive", "edits": [{"file": "src/notes.py", "label": "scoped handle of 'read_note'", "replace": "def read_note(path):\n with open(path, \"r\", encoding=\"utf-8\") as handle:\n body = handle.read()\n return body", "search": "def read_note(path):\n handle = open(path, \"r\", encoding=\"utf-8\")\n body = handle.read()\n handle.close()\n return body"}, {"file": "tests/test_notes.py", "label": "lock test 'test_read_note_scopes_its_handle' appended after 'test_read_note_of_an_empty_file'", "replace": "def test_read_note_of_an_empty_file(tmp_path) -> None:\n path = tmp_path / \"empty.txt\"\n write_note(path, \"\")\n assert read_note(path) == \"\"\n\n\ndef test_read_note_scopes_its_handle() -> None:\n \"\"\"Lock the scope the pattern gave the handle, the close it made redundant, and the read still working.\"\"\"\n import inspect\n import os\n import shutil\n import tempfile\n\n from src import notes\n source = inspect.getsource(notes.read_note)\n assert 'with open(' in source\n assert '.close()' not in source\n assert 'handle = open(' not in source\n directory = tempfile.mkdtemp()\n try:\n path = os.path.join(directory, \"lock note.txt\")\n with open(path, \"w\", encoding=\"utf-8\") as writer:\n writer.write(\"alpha\")\n assert notes.read_note(path) == 'alpha'\n finally:\n shutil.rmtree(directory, ignore_errors=True)\n", "search": "def test_read_note_of_an_empty_file(tmp_path) -> None:\n path = tmp_path / \"empty.txt\"\n write_note(path, \"\")\n assert read_note(path) == \"\""}], "expect": "VERIFIED", "family": "resources", "intent_tags": ["files", "lifetime", "resources"], "language": "python", "min_assurance": 3, "note": "a module level function that opens a file into a name and closes that name itself", "pattern_id": "open-to-context-manager", "rule": "open-to-context-manager", "targets": ["src/notes.py::read_note"]}{"case_id": "pat-open-to-context-manager-negative", "edits": [], "expect": "REFUSED", "family": "resources", "intent_tags": ["files", "lifetime", "resources"], "language": "python", "min_assurance": 3, "note": "a module level function that opens a file into a name and closes that name itself", "pattern_id": "open-to-context-manager", "reason_code": "ALREADY_SCOPED", "rule": "open-to-context-manager", "targets": ["src/notes.py::write_note"]}52 unmodified lines53545556565758596061626363646566676869707071727352 unmodified lines "name": "pattern_corpus_schema", "verdict": "CONFIRMED", "check": "patterns/pattern_cases.jsonl is a valid case-1 corpus with one pair per card", "note": "10 rows over 5 cards, each with its lock test and its refusal", "note": "16 rows over 8 cards, each with its lock test and its refusal", "failed_targets": [] }, { "name": "pattern_round_trip", "verdict": "CONFIRMED", "check": "every row of the pattern corpus re-plans on the fixture as written", "note": "10 rows re-planned: 5 pairs land and compile, 5 refusals repeat with the same code", "note": "16 rows re-planned: 8 pairs land and compile, 8 refusals repeat with the same code", "failed_targets": [] }, { "name": "pattern_coverage", "verdict": "CONFIRMED", "check": "patterns/coverage.json states a denominator this fixture still supports", "note": "5 cards over 5 source files and 15 module level functions, denominator stated as the fixture", "note": "8 cards over 8 source files and 21 module level functions, denominator stated as the fixture", "failed_targets": [] } ]13 unmodified lines14151617181920212223242526272829303132333413 unmodified linesPOSITIVE = { "annotate-literal-defaults": "src/tokens.py::count_words", "bare-assert-to-explicit-raise": "src/guards.py::open_ticket", "bare-except-to-narrow-exception": "src/retries.py::call_or_none", "chain-to-registry": "src/registry.py::render", "empty-len-to-truthiness": "src/baskets.py::describe", "mutable-default-to-none": "src/slugify.py::add_tag", "none-comparison-to-identity": "src/labels.py::label_for", "open-to-context-manager": "src/notes.py::read_note",}NEGATIVE = { "annotate-literal-defaults": ("src/tokens.py::count_lines", "ALREADY_ANNOTATED"), "bare-assert-to-explicit-raise": ("src/guards.py::close_ticket", "NOT_THE_FIRST_STATEMENT"), "bare-except-to-narrow-exception": ("src/retries.py::call_or_note", "NO_BARE_EXCEPT"), "chain-to-registry": ("src/registry.py::render_pair", "BRANCH_SHAPE_MISMATCH"), "empty-len-to-truthiness": ("src/baskets.py::first_or_none", "NO_EMPTY_LEN_CHECK"), "mutable-default-to-none": ("src/slugify.py::join_parts", "NOT_A_MUTABLE_DEFAULT"), "none-comparison-to-identity": ("src/labels.py::is_missing", "NO_NONE_COMPARISON"), "open-to-context-manager": ("src/notes.py::write_note", "ALREADY_SCOPED"),}
32 unmodified lines33343536373839404142434445464748495051525332 unmodified linesPOSITIVE = { "annotate-literal-defaults": "src/tokens.py::count_words", "bare-assert-to-explicit-raise": "src/guards.py::open_ticket", "bare-except-to-narrow-exception": "src/retries.py::call_or_none", "chain-to-registry": "src/registry.py::render", "empty-len-to-truthiness": "src/baskets.py::describe", "mutable-default-to-none": "src/slugify.py::add_tag", "none-comparison-to-identity": "src/labels.py::label_for", "open-to-context-manager": "src/notes.py::read_note",}NEGATIVE = { "annotate-literal-defaults": "src/tokens.py::count_lines", "bare-assert-to-explicit-raise": "src/guards.py::close_ticket", "bare-except-to-narrow-exception": "src/retries.py::call_or_note", "chain-to-registry": "src/registry.py::render_pair", "empty-len-to-truthiness": "src/baskets.py::first_or_none", "mutable-default-to-none": "src/slugify.py::join_parts", "none-comparison-to-identity": "src/labels.py::is_missing", "open-to-context-manager": "src/notes.py::write_note",}
11234140 unmodified lines145146147148149150151152153214 unmodified lines368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438"""Tests for the five rules of the Python pattern catalog.""""""Tests for the eight rules of the Python pattern catalog."""
from __future__ import annotations
140 unmodified lines ("src/registry.py", "render", "chain-to-registry"), ("src/notes.py", "read_note", "open-to-context-manager"), ("src/guards.py", "open_ticket", "bare-assert-to-explicit-raise"), ("src/retries.py", "call_or_none", "bare-except-to-narrow-exception"), ("src/labels.py", "label_for", "none-comparison-to-identity"), ("src/baskets.py", "describe", "empty-len-to-truthiness"), ] for rel_posix, symbol, rule_id in pairs: hit = _plan(rel_posix, symbol, rule_id)214 unmodified lines outcome = _outcome("my-src/tool.py", "pick", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.INVALID_COMPANION_PATH
def test_a_bare_handler_becomes_a_named_one_without_touching_its_body() -> None: hit = _plan("src/retries.py", "call_or_none", "bare-except-to-narrow-exception") patched = _patched(hit)["src/retries.py"] compile(patched, "retries.py", "exec") original = (LAB / "src" / "retries.py").read_text(encoding="utf-8", newline="") assert patched == original.replace(" except:\n", " except Exception:\n") assert "return \"\"" in patched
def test_a_handler_that_already_names_its_class_is_left_alone() -> None: assert _miss_code("src/retries.py", "call_or_note", "bare-except-to-narrow-exception") == rules.NO_BARE_EXCEPT
def test_a_bare_handler_that_re_raises_is_refused_by_name(tmp_path: Path) -> None: root = tmp_path / "ws" _write( root / "src" / "lift.py", "def carry(source):\n try:\n return source.read()\n except:\n raise\n", ) _write(root / "tests" / "test_lift.py", "def test_lift_reads() -> None:\n assert True\n") outcome = _outcome("src/lift.py", "carry", "bare-except-to-narrow-exception", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.BARE_EXCEPT_RE_RAISES
def test_a_count_of_none_becomes_an_identity_test_and_leaves_the_rest_alone() -> None: hit = _plan("src/labels.py", "label_for", "none-comparison-to-identity") patched = _patched(hit)["src/labels.py"] compile(patched, "labels.py", "exec") assert "if value is None:" in patched assert "if value is not None and value == \"\":" in patched assert "== None" not in patched
def test_a_test_that_already_asks_with_identity_is_left_alone() -> None: assert _miss_code("src/labels.py", "is_missing", "none-comparison-to-identity") == rules.NO_NONE_COMPARISON
def test_a_chained_comparison_against_none_is_refused_by_name(tmp_path: Path) -> None: root = tmp_path / "ws" _write(root / "src" / "same.py", "def agrees(one, two):\n return one == two == None\n") _write(root / "tests" / "test_same.py", "def test_agrees_exists() -> None:\n assert True\n") outcome = _outcome("src/same.py", "agrees", "none-comparison-to-identity", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.NONE_COMPARISON_IS_CHAINED
def test_counting_to_ask_for_emptiness_becomes_a_truthiness_test() -> None: hit = _plan("src/baskets.py", "describe", "empty-len-to-truthiness") patched = _patched(hit)["src/baskets.py"] compile(patched, "baskets.py", "exec") original = (LAB / "src" / "baskets.py").read_text(encoding="utf-8", newline="") assert patched == original.replace("if len(items) == 0:", "if not items:")
def test_an_emptiness_test_that_already_asks_directly_is_left_alone() -> None: assert _miss_code("src/baskets.py", "first_or_none", "empty-len-to-truthiness") == rules.NO_EMPTY_LEN_CHECK
def test_a_count_of_something_that_is_not_a_name_is_refused_by_name(tmp_path: Path) -> None: root = tmp_path / "ws" _write(root / "src" / "box.py", "def show(box):\n if len(box.items) == 0:\n return 0\n return 1\n") _write(root / "tests" / "test_box.py", "def test_box_shows() -> None:\n assert True\n") outcome = _outcome("src/box.py", "show", "empty-len-to-truthiness", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.LEN_TARGET_IS_NOT_A_NAME64 unmodified lines6566676869707172737475767778798081828384858687888990919293949564 unmodified lines "src/guards.py::close_ticket", "NOT_THE_FIRST_STATEMENT", ), "bare-except-to-narrow-exception": ( "src/retries.py::call_or_none", "src/retries.py::call_or_note", "NO_BARE_EXCEPT", ), "chain-to-registry": ( "src/registry.py::render", "src/registry.py::render_pair", "BRANCH_SHAPE_MISMATCH", ), "empty-len-to-truthiness": ( "src/baskets.py::describe", "src/baskets.py::first_or_none", "NO_EMPTY_LEN_CHECK", ), "mutable-default-to-none": ( "src/slugify.py::add_tag", "src/slugify.py::join_parts", "NOT_A_MUTABLE_DEFAULT", ), "none-comparison-to-identity": ( "src/labels.py::label_for", "src/labels.py::is_missing", "NO_NONE_COMPARISON", ), "open-to-context-manager": ( "src/notes.py::read_note", "src/notes.py::write_note",10 unmodified lines1112131414151617181617181920212217 unmodified lines4041424243434445454647484940 unmodified lines909192929394949596979831 unmodified lines1301311321321331341341351361371381 unmodified line14014114214214314314414514614710 unmodified linessiblings) and deliberately avoids `publish_to_hub.py`: that name belongs to the release builder ofthe multilingual track.
This bundle carries no kernel. It carries one corpus of its own, the ten pattern cases underThis bundle carries no kernel. It carries one corpus of its own, the sixteen pattern cases under`patterns/`, generated from the rules and the fixture beside them, and the card states theirdenominator rather than letting ten rows look like a benchmark. Every number the card states (9 gates,90 tests, 18 node files, the staged file count) is re-derived from this tree before a single object isuploaded. A card that contradicts the code beside it stops the run instead of publishing.denominator rather than letting sixteen rows look like a benchmark. Every number the card states(9 gates, 99 tests, 18 node files, the staged file count) is re-derived from this tree before asingle object is uploaded. A card that contradicts the code beside it stops the run instead ofpublishing.
The folder README is the body of the dataset card. A short list of wording pairs turns the sentencesthat only make sense inside a LingoLOGOS checkout, and four sections are added for readers who met17 unmodified linesROOT = Path(__file__).resolve().parents[1]
REPO = "tailot/codex-python"EXPECTED_FILES = 66 # the staged tree: 66 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 67 # those 66 plus the .gitattributes the hub addsEXPECTED_FILES = 72 # the staged tree: 72 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 73 # those 72 plus the .gitattributes the hub addsEXPECTED_GATES = 9EXPECTED_TESTS = 90EXPECTED_TESTS = 99EXPECTED_TEST_FILES = 9EXPECTED_NODE_FILES = 18EXPECTED_GATE_LINE = "GATES: CONFIRMED (9 gates: 9 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"40 unmodified lines "\"What this bundle needs from the codex kernel\" below says how the two find each other.", ), ( "The gate runner is where this bundle states its numbers out loud: 9 gates, 90 tests across 9 files,\n" "The gate runner is where this bundle states its numbers out loud: 9 gates, 99 tests across 9 files,\n" "18 files under `nodes/`, and a kernel it does not carry.", "The gate runner is where this bundle states its numbers out loud: 9 gates, 90 tests across 9 files,\n" "The gate runner is where this bundle states its numbers out loud: 9 gates, 99 tests across 9 files,\n" "18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives every\n" "one of those numbers from the tree it is standing in and stops the upload when the card and the code\n" "beside it disagree.",31 unmodified linesnever imports this folder, so the dependency has exactly one direction, and one copy of the kernel canserve any number of workspaces.
## The ten pattern cases## The sixteen pattern cases
`patterns/pattern_cases.jsonl` holds 10 rows, one accepted and one refused for each of the five cards`patterns/pattern_cases.jsonl` holds 16 rows, one accepted and one refused for each of the eight cardsof the catalog: `case_id`, `language`, `family`, `intent_tags`, the `edits` the rule returned (thesource edit and the test that locks it), the verdict the run must reach, and for a refusal the`reason_code` the rule answered with. A row is a work case in the schema the kernel dataset defines in1 unmodified line
`tools/build_patterns.py` derives the rows by running each rule over `fixtures/pattern_lab/`, and`--check` re-derives them and compares the bytes: a row is never edited by hand. The same tool writes`patterns/coverage.json`, which states what the ten rows cover and names its own denominator, thefixture. Ten rows are five cards carried end to end, not a benchmark: the fixture is small and was`patterns/coverage.json`, which states what the sixteen rows cover and names its own denominator, thefixture. Sixteen rows are eight cards carried end to end, not a benchmark: the fixture is small and waswritten for this bundle, and nothing here counts coverage of real repositories.
## Rights197 unmodified lines19819920020120220220320420520631 unmodified lines238239240240241242243244245246247248249250197 unmodified lines check = "every row of the pattern corpus re-plans on the fixture as written" if not PATTERN_CASES.is_file(): return _rejected(check, "patterns/pattern_cases.jsonl is missing") rows = read_rows(PATTERN_CASES) failures: List[str] = [] for row in read_rows(PATTERN_CASES): for row in rows: case_id = str(row["case_id"]) pattern_id = str(row["pattern_id"]) targets = [str(item) for item in row["targets"]]31 unmodified lines failures.append("%s: '%s' stops compiling after the edit (%s)" % (case_id, edit.file, exc.msg)) if failures: return _rejected(check, "; ".join(failures), failures) return _confirmed(check, "10 rows re-planned: 5 pairs land and compile, 5 refusals repeat with the same code") landing = sum(1 for row in rows if row["expect"] == "VERIFIED") refusing = sum(1 for row in rows if row["expect"] == "REFUSED") return _confirmed( check, "%d rows re-planned: %d pairs land and compile, %d refusals repeat with the same code" % (len(rows), landing, refusing), )
def gate_pattern_coverage() -> GateResult:README.md+30-19
fixtures/pattern_lab/src/baskets.pyAdded+17
fixtures/pattern_lab/src/labels.pyAdded+18
fixtures/pattern_lab/src/retries.pyAdded+20
fixtures/pattern_lab/tests/test_baskets.pyAdded+13
fixtures/pattern_lab/tests/test_labels.pyAdded+14
fixtures/pattern_lab/tests/test_retries.pyAdded+16
lingologos_python/patterns.py+59
lingologos_python/rules.py+295
patterns/coverage.json+50-2
patterns/pattern_cases.jsonl+6
results/gates.json+3-3
tests/test_pattern_session.py+6
tests/test_patterns.py+6
tests/test_rules.py+72-1
tools/build_patterns.py+15
tools/publish_dataset.py+14-13
tools/run_gates.py+9-2