Upload folder using huggingface_hub
Browse filesFiles changed (26)
- README.md+98-11
- fixtures/pattern_lab/src/guards.pyAdded+18
- fixtures/pattern_lab/src/notes.pyAdded+18
- fixtures/pattern_lab/src/registry.pyAdded+43
- fixtures/pattern_lab/src/slugify.pyAdded+15
- fixtures/pattern_lab/src/tokens.pyAdded+23
- fixtures/pattern_lab/tests/test_guards.pyAdded+21
- fixtures/pattern_lab/tests/test_notes.pyAdded+16
- fixtures/pattern_lab/tests/test_registry.pyAdded+22
- fixtures/pattern_lab/tests/test_slugify.pyAdded+13
- fixtures/pattern_lab/tests/test_tokens.pyAdded+16
- lgpython/__init__.py+36
- lgpython/cli.py+78
- lgpython/patterns.pyAdded+410
- lgpython/rules.pyAdded+1030
- lgpython/session.py+184
- patterns/coverage.jsonAdded+95
- patterns/pattern_cases.jsonlAdded+10
- results/gates.json+22-1
- tests/conftest.py+9
- tests/test_pattern_session.pyAdded+127
- tests/test_patterns.pyAdded+209
- tests/test_rules.pyAdded+255
- tools/build_patterns.pyAdded+223
- tools/publish_dataset.py+35-19
- tools/run_gates.py+112
19 unmodified lines202122232425262723242526272829303132333434353637373839404110 unmodified lines52535455565758596061626356646558666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271283 unmodified lines13213313413513613713813914014114214314414514614714814915011 unmodified lines162163164165166167168169170171172173174175176177178179180181182183184989918518618718818919 unmodified linesAn external Python programming package and six-node topology built on top of the LingoLOGOS
`codex` kernel, a kernel this folder neither modifies nor carries. This dataset is that folder
published as it stands: the package under `lgpython/`, the six node folders with their grammar,
ontology and seed envelope, the one executable the six roles share, the fixture package under
`fixtures/`, the tests, the gate runner and the publisher, and this card in place of the folder
README. The kernel is a separate dataset, https://huggingface.co/datasets/tailot/lingologos-codex,
and the section "What this bundle needs from the codex kernel" below says how the two find each
other.
ontology and seed envelope, the one executable the six roles share, the two fixtures under
`fixtures/` (a small package, and the pattern laboratory the catalog is measured on), the generated
cases under `patterns/`, the tests, the gate runner and the publisher, and this card in place of the
folder README. The kernel is a separate dataset at
https://huggingface.co/datasets/tailot/lingologos-codex, and the section
"What this bundle needs from the codex kernel" below says how the two find each other.
It provides everything needed to inspect, edit, test, and transactionally commit changes in a
Python repository through the `codex` assurance rules (`VERIFIED`, `SINGLE_PROVER`, `UNKNOWN`).
```
python -B tools/run_gates.py
GATES: CONFIRMED (6 gates: 6 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
GATES: CONFIRMED (9 gates: 9 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
```
The gate runner is where this bundle states its numbers out loud: 6 gates, 26 tests across 5 files,
The gate runner is where this bundle states its numbers out loud: 9 gates, 64 tests across 8 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.10 unmodified lines- `lgpython/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.
- `lgpython/rules.py`: five 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`).
- `lgpython/patterns.py`: the catalog above the rules. A card states the shape it claims, why that
shape is worth changing, what must hold before the rule runs, what test locks the change, and the
reason codes it answers with when it refuses (`PATTERNS`, `pattern_card`, `scan_pattern`,
`plan_pattern`).
- `lgpython/session.py`: `PythonWorkspaceSession` for safe staged verification and atomic disk
commits via `lgcodex.fsadapter` (`verify`, `edit_file`, `create_file`, `delete_file`,
`run_retry_loop`, and `run_topology_subprocesses`).
`apply_pattern`, `run_retry_loop`, and `run_topology_subprocesses`).
- `lgpython/cli.py`: `lgpython` CLI (`verify`, `edit`, `create`, `symbols`, `select-tests`,
`check-adapter`).
`patterns list|show|scan|apply`, `check-adapter`).
- `fixtures/pattern_lab/`: a small package with one function planted in the shape of each card and
one planted to be refused, used by the tests and by the coverage counts.
- `patterns/pattern_cases.jsonl`, `patterns/coverage.json`: the generated case corpus (one accepted
and one refused case per card) and the coverage statement, whose denominator is that fixture.
- `topology.json`, `agents/python_agent.py`, `nodes/<role>/`: external six-node topology using the
`codex` kernel as its base. The six executables it names are written relative to `datasets/`, so in
a standalone copy that leading name is simply the folder you are standing in.
- `codex.python.json`: declarative `CommandLanguageAdapter` template for Python projects.
## The pattern catalog
Five cards, one per shape this bundle can actually carry out:
| Card | Shape it claims | Family |
|---|---|---|
| `annotate-literal-defaults` | a default that is a string, number or `None` literal and states no type | typing |
| `mutable-default-to-none` | a `[]` or `{}` default, which is one object shared by every call | mutation |
| `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 |
A card is not a prompt: it names a syntax-tree shape, and `lgpython/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.
Every change this bundle makes is a pair. The rule returns two edits, the change in the source file
and a lock test appended to the test file paired with it, and `apply_pattern` puts both in one
transaction: the pair commits together, or nothing is written. The lock test is what makes the
second 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 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 the
result by another path, and the arbiter returns `VERIFIED` with assurance 3 only when both trusted
roles agree. `--dry-run` runs all of that against a copy and leaves the workspace byte for byte as it
was. A card that refuses never reaches the nodes, and a path policy that blocks the lock test blocks
the source edit with it.
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
`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)
```
Each row is a work case in the schema `lgcodex/casecorpus.py` defines, so the kernel can check the
shape of a claim about a Python file without reading a byte of Python: `case_id`, the language tag,
the family, the intent tags, the edits, the verdict the run must reach, and for a refusal the reason
code. `patterns/` is a generated folder, so edit `tools/build_patterns.py` and let `--check` say so.
## Running
From the folder of this dataset, with `LGCODEX_ROOT` pointing at the folder of the kernel dataset:3 unmodified linespython -B tools/run_gates.py
python -B -m lgpython check-adapter --workspace fixtures/sample_pkg
python -B -m lgpython verify --workspace fixtures/sample_pkg --file src/mathops.py
python -B -m lgpython patterns list
python -B -m lgpython patterns show --pattern chain-to-registry
python -B -m lgpython patterns scan --workspace fixtures/pattern_lab --pattern chain-to-registry
python -B -m lgpython patterns apply --workspace fixtures/pattern_lab \
--pattern chain-to-registry --target src/registry.py::render --dry-run
```
`patterns apply` without `--dry-run` commits, and only on a verdict the kernel accepts: it commits
when the assurance reaches the higher of the session floor and the card's own floor, and reports a
refusal with the reason code of the rule that stopped it. `fixtures/pattern_lab/` is a copy
candidate: the commands above run against it, and the tests copy it to a temporary folder first, so
the folder as published stays the shape the coverage numbers were counted on.
## What this bundle needs from the codex kernel
11 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
`patterns/pattern_cases.jsonl` holds 10 rows, one accepted and one refused for each of the five 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 in
`lgcodex/casecorpus.py`, so its shape is checkable without a Python file in sight.
`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
written for this bundle, and nothing here counts coverage of real repositories.
## Rights
The dataset is published by the author of LingoLOGOS under the same account, `tailot`. The source tree
is the `codex-python/` folder of https://github.com/tailot/LingoLOGOS, where the project states its own
terms. Neither that repository root nor this folder carries a `LICENSE` file, so no license is claimed
here beyond what the publisher states on the repository and on this dataset page; ask there before
reusing the code. The fixture package under `fixtures/sample_pkg/` was written for this dataset and is
not taken from a third-party project.
reusing the code. The fixture package under `fixtures/sample_pkg/` and the pattern laboratory under
`fixtures/pattern_lab/` were written for this dataset and are not taken from a third-party project.
## Citation
123456789101112131415161718"""Input checks carried over from a command line wrapper.
One function opens with a bare assert, which is the shape the explicit raise patternrewrites. The other asserts further down, where rewriting it would change what thefunction checks first, so the pattern refuses it."""
def open_ticket(queue_name): assert queue_name, "queue name is required" return {"queue": queue_name, "opened": True}
def close_ticket(ticket): ticket = dict(ticket) ticket["opened"] = False assert ticket.get("queue"), "queue name is required" return ticket123456789101112131415161718"""Reading and writing plain text notes on disk.
One function opens a file and closes it by hand, which is the shape the context managerpattern rewrites. The other already scopes its handle, and the pattern says so."""
def read_note(path): handle = open(path, "r", encoding="utf-8") body = handle.read() handle.close() return body
def write_note(path, body): with open(path, "w", encoding="utf-8") as handle: handle.write(body) return len(body)12345678910111213141516171819202122232425262728293031323334353637383940414243"""Formatting handlers picked by a kind name.
The first dispatcher is a chain of equality tests that each return a call, which is theshape the registry pattern rewrites. The second one is not: its branches do not take thesame arguments, and its last branch returns instead of raising, so the pattern has torefuse it."""
def format_short(item): return str(item)
def format_long(item): return "%s (%s)" % (item, type(item).__name__)
def format_json(item): return sorted(str(part) for part in item)
def format_labelled(item, label): return "%s: %s" % (label, item)
def render(kind, item): if kind == "short": return format_short(item) elif kind == "long": return format_long(item) elif kind == "json": return format_json(item) else: raise ValueError("unsupported kind")
def render_pair(kind, item, label): if kind == "short": return format_short(item) elif kind == "labelled": return format_labelled(item, label) else: return None123456789101112131415"""Building slugs from a list of segments.
One function here carries a list as a default argument, which is the shape the mutabledefault pattern refuses to leave in place. The other carries a tuple, which is adefault the pattern leaves alone."""
def add_tag(name, tags=[]): tags.append(name) return tags
def join_parts(parts=("root",), sep="-"): return sep.join(parts)1234567891011121314151617181920212223"""Counting words and lines in plain text notes.
The module is deliberately untyped at the edges: some of its parameters carry aliteral default and no annotation, which is the shape the annotation pattern of thisbundle is allowed to touch."""
def count_words(text="", unit="word"): parts = text.split() if unit == "word": return len(parts) if unit == "line": return len(text.splitlines()) return 0
def count_lines(text: str = "") -> int: return len(text.splitlines())
def summarize(text, unit="word"): return count_words(text, unit)123456789101112131415161718192021"""Tests for src.guards."""
import pytest
from src.guards import close_ticket, open_ticket
def test_open_ticket_records_the_queue() -> None: assert open_ticket("builds") == {"queue": "builds", "opened": True}
def test_open_ticket_refuses_an_empty_queue() -> None: with pytest.raises(AssertionError): open_ticket("")
def test_close_ticket_clears_the_flag() -> None: closed = close_ticket(open_ticket("builds")) assert closed["opened"] is False with pytest.raises(AssertionError): close_ticket({"queue": ""})12345678910111213141516"""Tests for src.notes."""
from src.notes import read_note, write_note
def test_write_then_read_round_trip(tmp_path) -> None: path = tmp_path / "note.txt" body = "first line\nsecond line\n" assert write_note(path, body) == len(body) assert read_note(path) == body
def test_read_note_of_an_empty_file(tmp_path) -> None: path = tmp_path / "empty.txt" write_note(path, "") assert read_note(path) == ""12345678910111213141516171819202122"""Tests for src.registry."""
import pytest
from src.registry import render
def test_render_short_stringifies() -> None: assert render("short", 5) == "5"
def test_render_long_names_the_type() -> None: assert render("long", 5) == "5 (int)"
def test_render_json_sorts_parts() -> None: assert render("json", [3, 1, 2]) == ["1", "2", "3"]
def test_render_rejects_an_unknown_kind() -> None: with pytest.raises(ValueError): render("yaml", 5)12345678910111213"""Tests for src.slugify."""
from src.slugify import add_tag, join_parts
def test_add_tag_collects_one_name_by_default() -> None: assert add_tag("alpha") == ["alpha"] assert add_tag("beta", ["gamma"]) == ["gamma", "beta"]
def test_join_parts_uses_its_tuple_default() -> None: assert join_parts() == "root" assert join_parts(("a", "b"), sep="/") == "a/b"12345678910111213141516"""Tests for src.tokens."""
from src.tokens import count_lines, count_words, summarize
def test_count_words_counts_words_by_default() -> None: assert count_words("one two three") == 3
def test_count_words_counts_lines_when_asked() -> None: assert count_words("one\ntwo", unit="line") == 2
def test_summarize_follows_the_unit() -> None: assert summarize("a b", unit="word") == 2 assert count_lines("a\nb") == 214 unmodified lines15161718192021222324252627282930313233343536373839408 unmodified lines4950515253545556575859606162636465666768691 unmodified line717273747576777879808114 unmodified lines extract_python_graph, module_names_for_file,)from lgpython.patterns import ( # noqa: E402 FAMILIES, PATTERNS, PATTERN_IDS, PatternPlan, PatternSpec, pattern_card, plan_pattern, render_card, scan_pattern,)from lgpython.rules import ( # noqa: E402 RULES, RULE_IDS, Edit, RuleHit, RuleMiss, Target, open_target,)from lgpython.session import ( # noqa: E402 PythonWorkspaceSession, SessionResult,8 unmodified lines__all__ = [ "ADAPTER_NAME", "ADAPTER_VERSION", "Edit", "FAMILIES", "PATTERNS", "PATTERN_IDS", "PythonLanguageAdapter", "PythonWorkspaceSession", "RULES", "RULE_IDS", "PatternPlan", "PatternSpec", "RuleHit", "RuleMiss", "SessionResult", "StrictPythonLanguageAdapter", "Target", "discover_python_files", "discover_test_files", "ensure_codex_on_path",1 unmodified line "find_codex_root", "is_test_file", "module_names_for_file", "open_target", "pattern_card", "plan_pattern", "render_card", "run_topology_subprocesses", "scan_pattern", "select_python_tests",]4 unmodified lines5678910116 unmodified lines1819202122232447 unmodified lines7273747576777879808182838485868788899090 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482494 unmodified linesimport argparseimport jsonimport sysfrom dataclasses import asdictfrom pathlib import Pathfrom typing import List, Optional, Sequence
6 unmodified lines
from lgpython.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter # noqa: E402from lgpython.ast_graph import discover_python_files, extract_python_graph # noqa: E402from lgpython.patterns import PATTERNS, pattern_card, render_card, scan_pattern # noqa: E402from lgpython.session import PythonWorkspaceSession # noqa: E402from lgpython.test_selector import select_python_tests # noqa: E402
47 unmodified lines p_tests.add_argument("--files", nargs="+", required=True, help="Changed relative Python files.") p_tests.add_argument("--json", action="store_true", help="Print JSON output.")
# patterns p_pat = sub.add_parser( "patterns", help="List, show, scan or apply the verified Python pattern catalog.", ) p_pat.add_argument("action", choices=("list", "show", "scan", "apply")) p_pat.add_argument("--pattern", default=None, help="Pattern id from the catalog.") p_pat.add_argument("--workspace", default=None, help="Target Python workspace for scan and apply.") p_pat.add_argument("--target", default=None, help="Target as path/to/file.py::function_name.") p_pat.add_argument("--dry-run", action="store_true", help="Verify the pair without committing.") p_pat.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") p_pat.add_argument("--json", action="store_true", help="Print JSON output.")
# check-adapter p_check = sub.add_parser("check-adapter", help="Validate PythonLanguageAdapter against the codex contract.") p_check.add_argument("--workspace", required=True, help="Target Python workspace directory.")90 unmodified lines print(item) return 0
if args.command == "patterns": if args.action in ("scan", "apply") and not args.workspace: print("scan and apply need --workspace", file=sys.stderr) return 2 if args.action in ("show", "apply", "scan") and not args.pattern: print("this action needs --pattern", file=sys.stderr) return 2 if args.action == "list": rows = [ { "pattern_id": spec.pattern_id, "family": spec.family, "intent_tags": list(spec.intent_tags), "min_assurance": spec.min_assurance, "rule": spec.rule, "companions": list(spec.companions), } for spec in PATTERNS ] if args.json: print(json.dumps({"patterns": rows}, indent=2, sort_keys=True)) else: for spec in PATTERNS: print( "%-28s %-10s %s" % (spec.pattern_id, spec.family, ", ".join(spec.intent_tags)) ) return 0 if args.action == "show": try: spec = pattern_card(args.pattern) except KeyError as exc: print(str(exc).strip("'"), file=sys.stderr) return 2 if args.json: print(json.dumps(asdict(spec), indent=2, sort_keys=True)) else: print(render_card(spec)) return 0 root = Path(args.workspace).resolve() if args.action == "scan": found = scan_pattern(root, args.pattern) if args.json: print(json.dumps({"pattern": args.pattern, "targets": found}, indent=2)) else: for item in found: print(item) if not found: print("no function in this workspace has the shape of this card") return 0 session = PythonWorkspaceSession(args.workspace, strict_tools=args.strict_tools) res = session.apply_pattern(args.pattern, target=args.target, commit=not args.dry_run) if args.json: print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) else: print( "%s (assurance %s, committed=%s) %s: %s" % (res.verdict, res.assurance, res.committed, res.reason, res.detail) ) if res.verdict == "REFUSED" and not args.json: print("nothing was written; the card named this reason before any node ran") return 0 if res.accepted else 1
if args.command == "check-adapter": root = Path(args.workspace).resolve() adapter = (123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410"""The catalog: which patterns this bundle teaches, and exactly what each one claims.
A card here is not a snippet to paste. Every card names a rule in ``lgpython.rules`` thatdecides whether the shape is really present in a given function and writes the text forit, plus the lock test that rule appends to the matching test file. The card is what aperson reads before applying anything; the rule is what runs; ``patterns/`` holds the rowsthat prove the card and the rule still say the same thing.
Three limits are written into the cards rather than assumed:
* A card claims one shape. It says what has to be true for the pattern to apply, and the reason codes the rule answers with when it is not, so a refusal is a result with a name and not a stack trace.* A card claims a companion, not a wish. The lock test is part of the pattern because a rewrite nobody checks is a claim nobody verified, and the lock is written so that it fails when the primary edit did not land.* A card claims a minimum assurance. Applying a pattern is a commit, and the commit needs the number of independent provers the card asks for."""
from __future__ import annotations
import astfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Callable, Dict, List, Optional, Sequence, Tuple
from lgpython import rulesfrom lgpython.ast_graph import discover_python_files
# Target syntax: a workspace-relative path, then the module level function, split by "::".TARGET_SEPARATOR = "::"
FAMILIES: Tuple[str, ...] = ("contracts", "mutation", "resources", "shape", "typing")
@dataclass(frozen=True)class PatternSpec: """One card: the shape, the rule that recognises it, and what applying it claims."""
pattern_id: str family: str intent_tags: Tuple[str, ...] rule: str shape: str rationale: str preconditions: Tuple[str, ...] companions: Tuple[str, ...] lock_claims: str refuses_as: Tuple[str, ...] min_assurance: int = 3
def target_of(self, rel_posix: str, symbol: str) -> str: return "%s%s%s" % (rel_posix.replace("\\", "/"), TARGET_SEPARATOR, symbol)
def to_row(self, case_id: str, target: str, edits: Sequence[rules.Edit], expect: str, reason_code: str = "") -> Dict[str, object]: """The corpus row for one run of this card against one target."""
row: Dict[str, object] = { "case_id": case_id, "language": "python", "family": self.family, "intent_tags": list(self.intent_tags), "edits": [ {"file": edit.file, "search": edit.search, "replace": edit.replace, "label": edit.label} for edit in edits ], "expect": expect, "note": self.shape, "pattern_id": self.pattern_id, "rule": self.rule, "targets": [target], "min_assurance": self.min_assurance, } if reason_code: row["reason_code"] = reason_code return row
def _card( pattern_id: str, family: str, intent_tags: Sequence[str], shape: str, rationale: str, preconditions: Sequence[str], companions: Sequence[str], lock_claims: str, refuses_as: Sequence[str],) -> PatternSpec: return PatternSpec( pattern_id=pattern_id, family=family, intent_tags=tuple(intent_tags), rule=pattern_id, shape=shape, rationale=rationale, preconditions=tuple(preconditions), companions=tuple(companions), lock_claims=lock_claims, refuses_as=tuple(refuses_as), )
# Every card writes its companion in the same place: the test file this layout pairs with# the source file by name. Which function goes there differs per card, and that is what# the lock claim states.LOCK_COMPANION = ( "one test function appended to the test file paired by name, tests/test_<module>.py, " "in the same run as the source change")
PATTERNS: Dict[str, PatternSpec] = { spec.pattern_id: spec for spec in ( _card( "annotate-literal-defaults", "typing", ("annotate", "defaults", "types"), "a module level function whose parameter has a literal default and no annotation", "the default already states the type, and a caller reading the signature has to guess it. " "Writing it down is what lets a type checker see the boundary of the module.", ( "the function is defined at module level, not nested", "the parameter is not annotated already", "the default is a str, int, float or bool literal, so the type is readable from it", "the file is ASCII text with LF endings and spaces for indentation", ), (LOCK_COMPANION,), "the signature of the function carries the annotation the pattern added and the default it started with", (rules.ALREADY_ANNOTATED, rules.NOT_A_MODULE_FUNCTION, rules.NOT_ASCII_TARGET, rules.CRLF_TARGET), ), _card( "mutable-default-to-none", "mutation", ("defaults", "aliasing", "mutation"), "a module level function whose parameter defaults to a list, dict or set built at definition time", "one default object is created once and handed to every call that omits the argument, so a call " "that mutates it changes what the next caller sees. The rewrite makes the absence explicit.", ( "the function is defined at module level, not nested", "the default is an empty list, dict or set literal, or a bare list(), dict() or set() call", "that parameter carries no annotation, because widening an annotation is a second change", "the guard is not already the first line of the body", "the file is ASCII text with LF endings and spaces for indentation", ), (LOCK_COMPANION,), "the default is None, the guard is in the source, and two calls that omit the argument answer differently", ( rules.NOT_A_MUTABLE_DEFAULT, rules.ANNOTATED_MUTABLE_DEFAULT, rules.GUARD_ALREADY_PRESENT, rules.NOT_A_MODULE_FUNCTION, ), ), _card( "chain-to-registry", "shape", ("dispatch", "registry", "extension"), "a module level function that dispatches an if/elif chain of one name compared to text literals", "adding a kind means editing the middle of a chain, and a missing branch silently falls through. " "A mapping of kind to handler makes the set of kinds one visible object and the refusal one place.", ( "every branch tests the same parameter against a text literal and returns one call", "each branch is a call of a name defined in the same module, taking plain parameters", "the last branch raises, so an unknown kind is refused rather than answered with None", "the function takes plain positional parameters only", ), (LOCK_COMPANION,), "the source holds the mapping and no elif, each kind still answers as the chain answered, and an " "unknown kind is still refused", (rules.NO_DISPATCH_CHAIN, rules.BRANCH_SHAPE_MISMATCH, rules.NOT_A_MODULE_FUNCTION), ), _card( "open-to-context-manager", "resources", ("files", "lifetime", "resources"), "a module level function that opens a file into a name and closes that name itself", "a close that is not tied to the scope is skipped by the one path that raises on the way out, and " "the reader has to trace every exit to believe the handle is closed.", ( "the assignment is open(...) directly, with no wrapper between the call and the name", "the name is closed by an expression statement whose target is that name", "the name is used only inside that function and never stored or returned", "the function does not already open the handle inside a with block", ), (LOCK_COMPANION,), "the source opens inside a with block and never calls close, and a file written in a temporary " "directory is read back through the rewritten function", (rules.ALREADY_SCOPED, rules.NO_BARE_OPEN, rules.HANDLE_ESCAPE, rules.NOT_A_MODULE_FUNCTION), ), _card( "bare-assert-to-explicit-raise", "contracts", ("preconditions", "errors", "contracts"), "a module level function whose first statement is an assert guarding its arguments", "an assert is a development check that a normal run may switch off, so a precondition written with " "it is a contract that stops holding when someone passes -O. The rewrite keeps the same exception.", ( "the assert is the first statement of the function, so it is a precondition and not a check in the middle", "the message text, when there is one, is kept word for word", "the function still raises AssertionError, so a caller that catches it keeps catching it", ), (LOCK_COMPANION,), "the source carries the raise and no assert line, and the call still refuses the argument the check " "refused, with the message it carried", (rules.NOT_THE_FIRST_STATEMENT, rules.NOT_A_MODULE_FUNCTION, rules.CRLF_TARGET), ), )}
PATTERN_IDS: Tuple[str, ...] = tuple(sorted(PATTERNS))
def pattern_card(pattern_id: str) -> PatternSpec: spec = PATTERNS.get(pattern_id) if spec is None: raise KeyError("unknown pattern: '%s'" % pattern_id) return spec
def split_target(target: str) -> Tuple[str, str]: """Split ``path::function`` into a workspace-relative path and a function name."""
if TARGET_SEPARATOR not in target: raise ValueError("target must be written as 'path/to/file.py::function': '%s'" % target) rel_posix, symbol = target.split(TARGET_SEPARATOR, 1) rel_posix = rel_posix.replace("\\", "/").strip() symbol = symbol.strip() if not rel_posix or not symbol: raise ValueError("target must name both a file and a function: '%s'" % target) return rel_posix, symbol
@dataclass(frozen=True)class PatternPlan: """What applying a card to one target would write, or why it refuses to."""
pattern_id: str target: str edits: Tuple[rules.Edit, ...] evidence: Tuple[str, ...] min_assurance: int refused: bool = False reason_code: str = "" detail: str = ""
@property def files(self) -> Tuple[str, ...]: return tuple(edit.file for edit in self.edits)
def primary(self) -> rules.Edit: if not self.edits: raise ValueError("a refused plan writes nothing") return self.edits[0]
def companions(self) -> Tuple[rules.Edit, ...]: return self.edits[1:]
def to_row(self, case_id: str) -> Dict[str, object]: spec = pattern_card(self.pattern_id) expect = "REFUSED" if self.refused else "VERIFIED" return spec.to_row( case_id, self.target, () if self.refused else self.edits, expect, self.reason_code if self.refused else "", )
def summary(self) -> str: if self.refused: return "%s refuses %s: %s (%s)" % (self.pattern_id, self.target, self.detail, self.reason_code) return "%s applies to %s and writes %s" % (self.pattern_id, self.target, ", ".join(self.files))
def _workspace_reader(root: Path) -> Callable[[str], Optional[str]]: def read(rel_posix: str) -> Optional[str]: path = root / Path(*rel_posix.split("/")) if not path.is_file(): return None return path.read_text(encoding="utf-8", newline="")
return read
def module_level_functions(text: str) -> Tuple[str, ...]: """Names defined at module level, the only functions a card in this catalog claims."""
try: tree = ast.parse(text) except SyntaxError: return () return tuple(node.name for node in tree.body if isinstance(node, ast.FunctionDef))
def scan_pattern(root: str | Path, pattern_id: str, *, files: Optional[Sequence[str]] = None) -> List[Tuple[str, rules.RuleHit]]: """Every target under one root a card applies to, as ``path::function`` labels."""
spec = pattern_card(pattern_id) rule = rules.RULES[spec.rule] workspace = Path(root).resolve() reader = _workspace_reader(workspace) found: List[Tuple[str, rules.RuleHit]] = [] for rel in sorted(files if files is not None else discover_python_files(workspace)): text = reader(rel) if text is None: continue for symbol in module_level_functions(text): target, miss = rules.open_target(rel, symbol, reader) if target is None: continue outcome = rule(target) if isinstance(outcome, rules.RuleHit): found.append((rules.target_label(rel, symbol), outcome)) return found
def plan_pattern(root: str | Path, pattern_id: str, target: Optional[str] = None) -> PatternPlan: """Decide what a card would write in a real workspace, or why it refuses.
Without an explicit target the catalog scans the workspace, and more than one match is a refusal: the caller has to choose, because applying a pattern everywhere it happens to fit is not what a card claims. """
spec = pattern_card(pattern_id) rule = rules.RULES[spec.rule] workspace = Path(root).resolve() reader = _workspace_reader(workspace)
if target is None: found = scan_pattern(workspace, pattern_id) if not found: return PatternPlan( pattern_id=pattern_id, target="", edits=(), evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code=rules.NO_SUCH_FUNCTION, detail="no module level function under '%s' is in the shape this card claims" % workspace, ) if len(found) > 1: return PatternPlan( pattern_id=pattern_id, target="", edits=(), evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code="AMBIGUOUS_TARGET", detail="this card fits %d targets, name one: %s" % (len(found), ", ".join(label for label, _hit in found)), ) target = found[0][0]
rel_posix, symbol = split_target(target) opened, miss = rules.open_target(rel_posix, symbol, reader) if opened is None and miss is not None: return PatternPlan( pattern_id=pattern_id, target=rules.target_label(rel_posix, symbol), edits=(), evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code=miss.reason_code, detail=miss.detail, ) assert opened is not None outcome = rule(opened) if isinstance(outcome, rules.RuleMiss): return PatternPlan( pattern_id=pattern_id, target=outcome.target, edits=(), evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code=outcome.reason_code, detail=outcome.detail, ) return PatternPlan( pattern_id=pattern_id, target=outcome.target, edits=outcome.edits, evidence=outcome.evidence, min_assurance=spec.min_assurance, )
def render_card(spec: PatternSpec) -> str: """The card as a person reads it in a terminal."""
lines = [ spec.pattern_id, " family %s" % spec.family, " intent %s" % ", ".join(spec.intent_tags), " shape %s" % spec.shape, " why %s" % spec.rationale, " needs", ] lines += [" - %s" % item for item in spec.preconditions] lines.append(" companion") lines += [" - %s" % item for item in spec.companions] lines.append(" lock %s" % spec.lock_claims) lines.append(" refuses %s" % ", ".join(spec.refuses_as)) lines.append(" needs assurance >= %d to commit" % spec.min_assurance) return "\n".join(lines)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030"""Structural rules: where a pattern applies in a real file, and what text it writes.
A pattern in this bundle is not a snippet to paste. It is a predicate over the syntaxtree plus a text transform that has to survive the kernel patcher, so this module doestwo things and nothing else: it decides whether a named function is in the shape apattern claims to improve, and it builds the exact search and replace pair for it. Whenthe shape is not there it says why with a code, and that code is what a negative row of``patterns/pattern_cases.jsonl`` claims, which is what the ``pattern_round_trip`` gatere-checks by running the rule again.
Four boundaries are stated rather than assumed.
* Offsets. A syntax tree column is a byte offset. Anchors here are built from those offsets, so a target file that is not ASCII is refused instead of patched at the wrong place, and a file indented with a tab is refused instead of getting spaces mixed into one block.* Endings. The catalog anchors on LF text, so a CRLF target is refused with ``CRLF_TARGET``. A hand written edit through the kernel patcher still preserves the endings of a CRLF file; that guarantee is the kernel's and is untouched here.* Shape. A rule refuses the shapes it has not read: a handle that is stored or returned, a chain that falls through instead of raising, a check that is not the first statement. Refusing is a result, not an error, and a refusal writes nothing.* Evidence. A rule never runs the code it reads. The lock test it appends to a test file is for the test gate of a run to execute, and it is written so that it fails when the primary edit did not land. That coupling is the whole reason a companion exists."""
from __future__ import annotations
import astfrom dataclasses import dataclassfrom typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
# Refusal codes. A negative row names one of these and the gate re-runs the rule to check# that the rule still answers with exactly that code for exactly that target.MISSING_TARGET_FILE = "MISSING_TARGET_FILE"NO_SUCH_FUNCTION = "NO_SUCH_FUNCTION"NOT_A_MODULE_FUNCTION = "NOT_A_MODULE_FUNCTION"NOT_PARSEABLE = "NOT_PARSEABLE"NOT_ASCII_TARGET = "NOT_ASCII_TARGET"TAB_INDENTED_TARGET = "TAB_INDENTED_TARGET"CRLF_TARGET = "CRLF_TARGET"NO_TEST_FILE = "NO_TEST_FILE"NO_TEST_ANCHOR = "NO_TEST_ANCHOR"AMBIGUOUS_TEST_ANCHOR = "AMBIGUOUS_TEST_ANCHOR"ALREADY_ANNOTATED = "ALREADY_ANNOTATED"NOT_A_MUTABLE_DEFAULT = "NOT_A_MUTABLE_DEFAULT"ANNOTATED_MUTABLE_DEFAULT = "ANNOTATED_MUTABLE_DEFAULT"GUARD_ALREADY_PRESENT = "GUARD_ALREADY_PRESENT"NO_DISPATCH_CHAIN = "NO_DISPATCH_CHAIN"BRANCH_SHAPE_MISMATCH = "BRANCH_SHAPE_MISMATCH"ALREADY_SCOPED = "ALREADY_SCOPED"NO_BARE_OPEN = "NO_BARE_OPEN"HANDLE_ESCAPE = "HANDLE_ESCAPE"NOT_THE_FIRST_STATEMENT = "NOT_THE_FIRST_STATEMENT"
INDENT = " "_MUTABLE_LITERALS = (ast.List, ast.Dict, ast.Set)_MUTABLE_CALLS = ("list", "dict", "set")
@dataclass(frozen=True)class Target: """One function a caller wants a pattern looked at, read from a workspace."""
rel_posix: str symbol: str text: str tree: ast.Module read: Callable[[str], Optional[str]]
@dataclass(frozen=True)class Edit: """One file the pattern would write, as a search and replace pair."""
file: str search: str replace: str label: str
@dataclass(frozen=True)class RuleHit: """The pattern applies: ``edits`` is the function change first, the lock test second."""
rule: str target: str edits: Tuple[Edit, ...] evidence: Tuple[str, ...] reason_code: str = ""
@dataclass(frozen=True)class RuleMiss: """The pattern does not apply, with the reason a corpus row is allowed to claim."""
reason_code: str detail: str target: str = ""
Outcome = Union[RuleHit, RuleMiss]
def target_label(rel_posix: str, symbol: str) -> str: return "%s::%s" % (rel_posix, symbol)
def _miss(rel_posix: str, symbol: str, code: str, detail: str) -> RuleMiss: return RuleMiss(reason_code=code, detail=detail, target=target_label(rel_posix, symbol))
def _no_companion(target: Target, companion: Optional[RuleMiss]) -> RuleMiss: if companion is not None: return companion return _miss(target.rel_posix, target.symbol, NO_TEST_FILE, "no lock test could be written")
# ---------------------------------------------------------------------------# Offsets, so that an anchor is the file and not an impression of it.# ---------------------------------------------------------------------------
def line_starts(text: str) -> List[int]: """Absolute character offset of every line, numbered like the syntax tree."""
starts = [0] for index, char in enumerate(text): if char == "\n": starts.append(index + 1) return starts
def node_span(text: str, starts: Sequence[int], node: ast.AST) -> Tuple[int, int]: """Absolute start and end offsets of a node, or (-1, -1) when it has no position."""
lineno = getattr(node, "lineno", None) end_lineno = getattr(node, "end_lineno", None) if lineno is None or end_lineno is None or end_lineno > len(starts): return -1, -1 start = starts[lineno - 1] + int(getattr(node, "col_offset", 0)) end = starts[end_lineno - 1] + int(getattr(node, "end_col_offset", 0)) if start < 0 or end < start or end > len(text): return -1, -1 return start, end
def segment_of(text: str, starts: Sequence[int], node: ast.AST) -> str: """The exact text a node covers in the file it was parsed from."""
start, end = node_span(text, starts, node) if start < 0: return "" return text[start:end]
@dataclass(frozen=True)class _Splice: start: int end: int text: str
def apply_splices(text: str, start: int, end: int, splices: Sequence[_Splice]) -> str: """Rewrite ``text[start:end]`` out of spans, leaving everything else byte for byte."""
out: List[str] = [] cursor = start for splice in sorted(splices, key=lambda item: (item.start, item.end)): if splice.start < cursor or splice.end > end: raise ValueError("a splice does not fit inside the span it belongs to") out.append(text[cursor:splice.start]) out.append(splice.text) cursor = splice.end out.append(text[cursor:end]) return "".join(out)
def _shifted(text: str, starts: Sequence[int], node: ast.AST, indent: str) -> str: """The text of a statement placed at ``indent``, with its own lines moved with it.
A slice of a node starts at the first token of its first line and carries the original indentation of every line after that, so the first line gets the whole target indent and the others get the one level this block is being pushed by. """
raw = segment_of(text, starts, node) lines = raw.split("\n") moved = [indent + lines[0]] for line in lines[1:]: moved.append(INDENT + line if line.strip() else line) return "\n".join(moved)
def _gap(text: str, start: int, end: int) -> str: """The blank lines between two statements, never more than one of them."""
return "\n\n" if text[start:end].count("\n") > 1 else "\n"
# ---------------------------------------------------------------------------# Reading a target, and the shapes this module refuses to anchor on.# ---------------------------------------------------------------------------
_SHAPE_DETAIL = { NOT_ASCII_TARGET: "the file is not ASCII, so a byte offset anchor is not trusted here", CRLF_TARGET: "the file ends its lines with CRLF and this catalog anchors on LF text", TAB_INDENTED_TARGET: "the file indents with a tab and the transform adds space indent",}
def _shape_rejection(text: str) -> str: if not text.isascii(): return NOT_ASCII_TARGET if "\r\n" in text: return CRLF_TARGET for line in text.split("\n"): if line.lstrip(" ").startswith("\t"): return TAB_INDENTED_TARGET return ""
def open_target(rel_posix: str, symbol: str, read: Callable[[str], Optional[str]]) -> Tuple[Optional[Target], Optional[RuleMiss]]: """Read and parse one target, with every refusal a corpus row may claim about it."""
text = read(rel_posix) if text is None: return None, _miss(rel_posix, symbol, MISSING_TARGET_FILE, "no such file: '%s'" % rel_posix) code = _shape_rejection(text) if code: return None, _miss(rel_posix, symbol, code, _SHAPE_DETAIL[code]) try: tree = ast.parse(text) except SyntaxError as exc: return None, _miss(rel_posix, symbol, NOT_PARSEABLE, "the file does not parse: %s" % exc.msg) return Target(rel_posix=rel_posix, symbol=symbol, text=text, tree=tree, read=read), None
def module_function(target: Target) -> Tuple[Optional[ast.FunctionDef], Optional[RuleMiss]]: """The module level function the target names, or the refusal that says why not."""
for node in target.tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol: return node, None for node in ast.walk(target.tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol: return None, _miss( target.rel_posix, target.symbol, NOT_A_MODULE_FUNCTION, "'%s' is not a module level function of this file" % target.symbol, ) return None, _miss( target.rel_posix, target.symbol, NO_SUCH_FUNCTION, "no function named '%s' in '%s'" % (target.symbol, target.rel_posix), )
# ---------------------------------------------------------------------------# The lock test that goes with a change.# ---------------------------------------------------------------------------
def test_file_for(rel_posix: str) -> str: """The test file this layout pairs with a source file, by name."""
parts = [part for part in rel_posix.split("/") if part] stem = parts[-1][:-3] if parts[-1].endswith(".py") else parts[-1] return "tests/test_%s.py" % stem
def import_statement_for(rel_posix: str) -> Tuple[str, str]: """The import that reaches a module without running anything, and the alias it binds."""
parts = [part for part in rel_posix.split("/") if part] stem = parts[-1][:-3] if parts[-1].endswith(".py") else parts[-1] package = [part for part in parts[:-1] if part != "__init__.py"] if package: return "from %s import %s" % (".".join(package), stem), stem return "import %s" % stem, stem
def lock_source( rel_posix: str, test_name: str, docstring: str, statements: Sequence[str], headers: Sequence[str] = (),) -> str: """One test function of ASCII, space indented text: imports, then the checks."""
import_statement, _alias = import_statement_for(rel_posix) lines = ["def test_%s() -> None:" % test_name, ' """%s"""' % docstring, " import inspect"] lines.extend(" %s" % line for line in headers) lines.append("") lines.append(" %s" % import_statement) for statement in statements: for line in statement.split("\n"): lines.append(" %s" % line if line.strip() else "") return "\n".join(lines) + "\n"
def _append_lock(target: Target, test_rel: str, test_name: str, lock_text: str) -> Tuple[Optional[Edit], Optional[RuleMiss]]: """Append one test function after the last test function of a test file."""
text = target.read(test_rel) if text is None: return None, _miss(test_rel, target.symbol, NO_TEST_FILE, "no test file: '%s'" % test_rel) try: tree = ast.parse(text) except SyntaxError as exc: return None, _miss(test_rel, target.symbol, NOT_PARSEABLE, "the test file does not parse: %s" % exc.msg) last: Optional[ast.FunctionDef] = None for node in tree.body: if isinstance(node, ast.FunctionDef) and node.name.startswith("test_"): last = node if last is None: return None, _miss(test_rel, target.symbol, NO_TEST_ANCHOR, "no top level test function to append after") anchor = segment_of(text, line_starts(text), last) if not anchor: return None, _miss(test_rel, target.symbol, NO_TEST_ANCHOR, "no text for the anchor of the last test") times = text.count(anchor) if times != 1: return None, _miss( test_rel, target.symbol, AMBIGUOUS_TEST_ANCHOR, "the anchor text appears %d times in '%s'" % (times, test_rel), ) return ( Edit( file=test_rel, search=anchor, replace=anchor.rstrip("\n") + "\n\n\n" + lock_text, label="lock test 'test_%s' appended after '%s'" % (test_name, last.name), ), None, )
def _hit(rule: str, target: Target, edit: Edit, companion: Edit, evidence: Sequence[str]) -> RuleHit: return RuleHit( rule=rule, target=target_label(target.rel_posix, target.symbol), edits=(edit, companion), evidence=tuple(evidence), )
def _rewrite_function(target: Target, starts: Sequence[int], function: ast.FunctionDef, splices: Sequence[_Splice], label: str) -> Edit: start, end = node_span(target.text, starts, function) return Edit( file=target.rel_posix, search=target.text[start:end], replace=apply_splices(target.text, start, end, splices), label=label, )
def _parameters(function: ast.FunctionDef) -> List[ast.arg]: return list(function.args.posonlyargs) + list(function.args.args) + list(function.args.kwonlyargs)
def _defaults_by_name(function: ast.FunctionDef) -> Dict[str, ast.expr]: """Map each plain parameter to the default expression it carries, when it has one."""
positional = list(function.args.posonlyargs) + list(function.args.args) defaults: Dict[str, ast.expr] = {} offset = len(positional) - len(function.args.defaults) for index, argument in enumerate(positional): position = index - offset if position >= 0: defaults[argument.arg] = function.args.defaults[position] for argument, default in zip(function.args.kwonlyargs, function.args.kw_defaults): if default is not None: defaults[argument.arg] = default return defaults
# ---------------------------------------------------------------------------# Rule 1: write down the type a literal default already states.# ---------------------------------------------------------------------------
def _literal_type(node: ast.expr) -> Optional[str]: if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)): return _literal_type(node.operand) if not isinstance(node, ast.Constant): return None value = node.value if isinstance(value, bool): return "bool" if isinstance(value, int): return "int" if isinstance(value, float): return "float" if isinstance(value, str): return "str" return None
def rule_annotate_literal_defaults(target: Target) -> Outcome: """Annotate a parameter with the type of the literal default it already carries.
A parameter whose default is ``None`` is left alone on purpose: the honest annotation for it is an Optional, and that needs an import this transform will not add. """
function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text) annotated = {argument.arg for argument in _parameters(function) if argument.annotation is not None} defaults = _defaults_by_name(function) position_of = {argument.arg: argument for argument in _parameters(function)}
splices: List[_Splice] = [] touched: List[Tuple[str, str, str]] = [] for name in sorted(defaults): if name in annotated: continue inferred = _literal_type(defaults[name]) if inferred is None: continue argument = position_of[name] name_end = starts[argument.lineno - 1] + argument.col_offset + len(argument.arg) default_start, _default_end = node_span(target.text, starts, defaults[name]) splices.append(_Splice(start=name_end, end=default_start, text=": %s = " % inferred)) literal = repr(defaults[name].value) if isinstance(defaults[name], ast.Constant) else segment_of(target.text, starts, defaults[name]) touched.append((name, inferred, literal)) if not splices: return _miss( target.rel_posix, target.symbol, ALREADY_ANNOTATED, "no parameter of '%s' carries a literal default without an annotation" % target.symbol, )
alias = import_statement_for(target.rel_posix)[1] statements = ["parameters = inspect.signature(%s.%s).parameters" % (alias, target.symbol)] for name, inferred, literal in touched: statements.append("assert parameters[%r].annotation is %s" % (name, inferred)) statements.append("assert parameters[%r].default == %s" % (name, literal)) test_name = "%s_parameters_keep_their_defaults" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the annotations this pattern added and the defaults it had to leave alone.", 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("parameter '%s' takes its type from its own default %s" % (name, literal) for name, _inferred, literal in touched) return _hit( "annotate-literal-defaults", target, _rewrite_function(target, starts, function, splices, "signature of '%s'" % target.symbol), companion, evidence, )
# ---------------------------------------------------------------------------# Rule 2: a mutable default stops being shared.# ---------------------------------------------------------------------------
def _is_mutable_default(node: ast.expr) -> bool: if isinstance(node, _MUTABLE_LITERALS): return True return ( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _MUTABLE_CALLS and not node.args and not node.keywords )
def rule_mutable_default_to_none(target: Target) -> Outcome: """Replace a mutable default with ``None`` and rebuild the value inside the call.
This is a behaviour change by design, and the only one in the catalog: the default stops being shared between calls. The guard reuses the literal that was written as the default, so the value each call starts from is the one the author wrote. """
function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text) named = {argument.arg: argument for argument in _parameters(function)} mutable = {name: node for name, node in _defaults_by_name(function).items() if _is_mutable_default(node)} if not mutable: return _miss( target.rel_posix, target.symbol, NOT_A_MUTABLE_DEFAULT, "no default of '%s' is a list, dict or set, so there is nothing shared to break" % target.symbol, ) for name in sorted(mutable): if named[name].annotation is not None: return _miss( target.rel_posix, target.symbol, ANNOTATED_MUTABLE_DEFAULT, "parameter '%s' of '%s' carries an annotation this rule would have to widen" % (name, target.symbol), )
body_start = starts[function.body[0].lineno - 1] guard_indent = " " * function.body[0].col_offset for name in sorted(mutable): literal = segment_of(target.text, starts, mutable[name]) guard = "%sif %s is None:\n%s%s%s = %s\n" % (guard_indent, name, guard_indent, INDENT, name, literal) if target.text[body_start:body_start + len(guard)] == guard: return _miss( target.rel_posix, target.symbol, GUARD_ALREADY_PRESENT, "'%s' already rebuilds '%s' on its first line" % (target.symbol, name), )
splices: List[_Splice] = [] for name in sorted(mutable): start, end = node_span(target.text, starts, mutable[name]) splices.append(_Splice(start=start, end=end, text="None")) for name in sorted(mutable): literal = segment_of(target.text, starts, mutable[name]) splices.append( _Splice( start=body_start, end=body_start, text="%sif %s is None:\n%s%s%s = %s\n" % (guard_indent, name, guard_indent, INDENT, name, literal), ) )
alias = import_statement_for(target.rel_posix)[1] statements = [ "signature = inspect.signature(%s.%s)" % (alias, target.symbol), "source = inspect.getsource(%s.%s)" % (alias, target.symbol), ] for name in sorted(mutable): statements.append("assert signature.parameters[%r].default is None" % name) statements.append("assert 'if %s is None:' in source" % name) test_name = "%s_has_no_shared_default" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the default this pattern unshared, the guard that replaced it, and the call that no longer shares state.", statements + [ "first = %s.%s(%s)" % (alias, target.symbol, _probe_arguments(function, mutable, "alpha")), "second = %s.%s(%s)" % (alias, target.symbol, _probe_arguments(function, mutable, "beta")), "assert first != second", ], ) 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 default of '%s' is a value every call would share" % name for name in sorted(mutable)) return _hit( "mutable-default-to-none", target, _rewrite_function(target, starts, function, splices, "shared default of '%s'" % target.symbol), companion, evidence, )
def _probe_arguments(function: ast.FunctionDef, mutable: Dict[str, ast.expr], word: str) -> str: """Arguments of one call that reaches the guard, carrying ``word`` for the rest.
These values are placeholders, not claims about the domain. They differ between the two calls of the lock, so a default shared between calls cannot pass it, and the round trip gate runs the lock before it believes a pattern applies anywhere. """
needed = [ argument.arg for argument in function.args.args if argument.arg not in mutable and argument.arg not in _defaults_by_name(function) ] return ", ".join(repr(word) for _ in needed)
# ---------------------------------------------------------------------------# Rule 3: an equality chain that returns calls becomes a registry.# ---------------------------------------------------------------------------
def _refusal_name(node: ast.Raise) -> str: """The exception type a raise statement names, with or without its arguments."""
if isinstance(node.exc, ast.Name): return node.exc.id if isinstance(node.exc, ast.Call) and isinstance(node.exc.func, ast.Name): return node.exc.func.id return ""
def _chain_branches(node: ast.If) -> Optional[Tuple[List[Tuple[str, str, List[str]]], ast.Raise]]: """Read an if or elif chain of ``name == literal`` tests that each return one call.
Every branch has to take exactly the same arguments and the chain has to end by raising: a chain that falls through returns something a registry would not, and this rule does not guess what the fall through was meant to produce. """
branches: List[Tuple[str, str, List[str]]] = [] current: Optional[ast.If] = node shared: Optional[List[str]] = None while current is not None: test = current.test if not isinstance(test, ast.Compare) or len(test.ops) != 1 or not isinstance(test.ops[0], ast.Eq): return None if not isinstance(test.left, ast.Name) or len(test.comparators) != 1: return None key = test.comparators[0] if not isinstance(key, ast.Constant) or not isinstance(key.value, str): return None if len(current.body) != 1 or not isinstance(current.body[0], ast.Return) or current.body[0].value is None: return None value = current.body[0].value if not isinstance(value, ast.Call) or not isinstance(value.func, ast.Name) or value.keywords: return None arguments = [argument.id for argument in value.args if isinstance(argument, ast.Name)] if len(arguments) != len(value.args): return None if shared is None: shared = arguments elif shared != arguments: return None branches.append((str(key.value), value.func.id, arguments)) if len(current.orelse) != 1: return None follower = current.orelse[0] if isinstance(follower, ast.If): current = follower continue if isinstance(follower, ast.Raise) and _refusal_name(follower) and not follower.cause: return branches, follower return None return None
def _module_level_names(tree: ast.Module) -> set: """Names a caller reaches as an attribute of this module, read from its top level."""
names: set = set() for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): names.add(node.name) elif isinstance(node, ast.Assign): names.update(target.id for target in node.targets if isinstance(target, ast.Name)) elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): names.add(node.target.id) elif isinstance(node, (ast.Import, ast.ImportFrom)): for alias in node.names: names.add(alias.asname or alias.name.split(".")[0]) return names
def rule_chain_to_registry(target: Target) -> Outcome: """Turn a chain of ``kind == literal`` returns into a dictionary and one lookup."""
function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text) if len(function.body) != 1 or not isinstance(function.body[0], ast.If): return _miss(target.rel_posix, target.symbol, NO_DISPATCH_CHAIN, "the body of '%s' is not one if or elif chain" % target.symbol) chain = function.body[0] read = _chain_branches(chain) if read is None: return _miss( target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "the chain in '%s' tests more than one name against text literals, its branches do not " "take the same arguments, or its last branch does not raise" % target.symbol, ) branches, tail = read keys = [key for key, _handler, _arguments in branches] if len(set(keys)) != len(keys): return _miss(target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "two branches of '%s' test the same literal" % target.symbol) assert isinstance(chain.test, ast.Compare) and isinstance(chain.test.left, ast.Name) subject = chain.test.left.id if subject not in {argument.arg for argument in function.args.args + function.args.posonlyargs}: return _miss(target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "'%s' is compared but is not a parameter" % subject) reachable = _module_level_names(target.tree) parameters = {argument.arg for argument in function.args.args} if function.args.vararg or function.args.kwarg or function.args.kwonlyargs or function.args.posonlyargs: return _miss( target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "'%s' takes arguments this catalog does not know how to pass, so no lock could compare the answers" % target.symbol, ) for _key, _handler, arguments in branches: if not set(arguments) <= parameters: return _miss( target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "a branch of '%s' passes something that is not a plain parameter of the chain" % target.symbol, ) for _key, handler, _arguments in branches: if handler not in reachable: return _miss( target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "a branch of '%s' returns '%s', which is not a name of this module, so no lock could compare the answers" % (target.symbol, handler), )
raise_text = "raise " + segment_of(target.text, starts, tail.exc)
indent = " " * chain.col_offset entries = ", ".join('"%s": %s' % (key, handler) for key, handler, _arguments in branches) arguments = ", ".join(branches[0][2]) block = ( "handlers = {%s}\n" % entries + "%shandled = handlers.get(%s)\n" % (indent, subject) + "%sif handled is None:\n" % indent + "%s%s%s\n" % (indent, INDENT, raise_text) + "%sreturn handled(%s)" % (indent, arguments) ) start, end = node_span(target.text, starts, chain) edit = _rewrite_function(target, starts, function, [_Splice(start=start, end=end, text=block)], "dispatch registry of '%s'" % target.symbol)
alias = import_statement_for(target.rel_posix)[1] statements = ["source = inspect.getsource(%s.%s)" % (alias, target.symbol)] statements.append("assert 'handlers = {' in source") for key, handler, _arguments in branches: statements.append('assert \'"%s": %s\' in source' % (key, handler)) statements.append("assert 'handlers.get(%s)' in source" % subject) statements.append("assert 'elif' not in source") for key, handler, arguments in branches: statements.append( "assert %s.%s(%s) == %s.%s(%s)" % (alias, target.symbol, _call(function, _values(function, key)), alias, handler, _call_for(function, arguments, _values(function, key))) ) refusal = _refusal_name(tail) statements.append( "\n".join( ( "try:", " %s.%s(%s)" % (alias, target.symbol, _call(function, _values(function, "~no such kind~"))), "except %s:" % refusal, " pass", "else:", " raise AssertionError('%s accepted a kind no branch carries')" % target.symbol, ) ) ) test_name = "%s_dispatches_through_a_registry" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the registry the chain became, and the answers the chain used to give.", 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 branch for '%s' returns %s" % (key, handler) for key, handler, _arguments in branches) return _hit("chain-to-registry", target, edit, companion, evidence)
def _chain_subject(function: ast.FunctionDef) -> str: """The name every branch of the chain is compared against."""
first = function.body[0] if isinstance(first, ast.If) and isinstance(first.test, ast.Compare) and isinstance(first.test.left, ast.Name): return first.test.left.id return ""
def _values(function: ast.FunctionDef, kind: str) -> Dict[str, str]: """One literal per parameter: the tested name carries ``kind``, the rest carry a placeholder.
The placeholder says nothing about the domain; it only has to be a value the handler accepts without complaint. The round trip gate runs the call, so a target where a placeholder is not accepted is a target this catalog does not claim. """
subject = _chain_subject(function) return {argument.arg: (repr(kind) if argument.arg == subject else '""') for argument in function.args.args}
def _call(function: ast.FunctionDef, values: Dict[str, str]) -> str: return ", ".join(values[argument.arg] for argument in function.args.args)
def _call_for(function: ast.FunctionDef, names: Sequence[str], values: Dict[str, str]) -> str: return ", ".join(values[name] for name in names)
# ---------------------------------------------------------------------------# Rule 4: a handle opened by hand gets a scope.# ---------------------------------------------------------------------------
def _open_call(node: ast.AST) -> Optional[ast.Call]: if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "open" and node.args: return node return None
def _closes_handle(statement: ast.stmt, handle: str) -> bool: return ( isinstance(statement, ast.Expr) and isinstance(statement.value, ast.Call) and isinstance(statement.value.func, ast.Attribute) and statement.value.func.attr == "close" and isinstance(statement.value.func.value, ast.Name) and statement.value.func.value.id == handle and not statement.value.args )
def rule_open_to_context_manager(target: Target) -> Outcome: """Give a hand opened file a ``with`` scope and drop the close it makes redundant.
The handle may only be used by statements in the run of lines below the assignment. A handle that is returned, stored in another name, or used above the assignment escapes the scope this rule can build, and the rule says so instead of narrowing a lifetime quietly. """
function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text)
for node in ast.walk(function): if isinstance(node, ast.With): for item in node.items: if _open_call(item.context_expr) is not None: return _miss( target.rel_posix, target.symbol, ALREADY_SCOPED, "'%s' already opens its handle inside a with block" % target.symbol, )
position = None handle = "" opened: Optional[ast.Call] = None for index, statement in enumerate(function.body): if ( isinstance(statement, ast.Assign) and len(statement.targets) == 1 and isinstance(statement.targets[0], ast.Name) and _open_call(statement.value) is not None ): position = index handle = statement.targets[0].id opened = _open_call(statement.value) break if position is None or opened is None: return _miss(target.rel_posix, target.symbol, NO_BARE_OPEN, "'%s' opens no handle into a plain name" % target.symbol)
def uses(node: ast.AST) -> bool: return any(isinstance(item, ast.Name) and item.id == handle for item in ast.walk(node))
if any(uses(statement) for statement in function.body[:position]): return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is used before it is opened" % handle)
block: List[ast.stmt] = [function.body[position]] for statement in function.body[position + 1:]: if not uses(statement): break block.append(statement) last_use = max(index for index, statement in enumerate(function.body) if uses(statement)) if any(uses(statement) for statement in function.body[last_use + 1:]): return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is used after the run this rule can scope" % handle)
for statement in block[1:]: if isinstance(statement, ast.Return): return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is used by a return, which outlives the scope" % handle) if isinstance(statement, ast.Assign) and any(isinstance(item, ast.Name) and item.id == handle for item in ast.walk(statement.value)): if isinstance(statement.value, ast.Name): return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is stored in another name" % handle) elif not isinstance(statement, (ast.Assign, ast.Expr)): return _miss( target.rel_posix, target.symbol, HANDLE_ESCAPE, "a %s statement uses the handle in a way this rule cannot scope" % type(statement).__name__, )
drop = [statement for statement in block if _closes_handle(statement, handle)] kept = [statement for statement in block if statement is not block[0] and statement not in drop] indent = " " * block[0].col_offset pieces: List[str] = ["with %s as %s:" % (segment_of(target.text, starts, opened), handle)] previous_end = None for statement in kept: start, end = node_span(target.text, starts, statement) if previous_end is not None: pieces.append(_gap(target.text, previous_end, start)) pieces.append(_shifted(target.text, starts, statement, indent + INDENT)) previous_end = end block_text = "\n".join(pieces)
function_start, function_end = node_span(target.text, starts, function) block_start, block_end = node_span(target.text, starts, block[0]) _unused, last_end = node_span(target.text, starts, block[-1]) edit = Edit( file=target.rel_posix, search=target.text[function_start:function_end], replace=apply_splices(target.text, function_start, function_end, [_Splice(start=block_start, end=last_end, text=block_text)]), label="scoped handle of '%s'" % target.symbol, )
alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s.%s)" % (alias, target.symbol), "assert 'with open(' in source", "assert '.close()' not in source", "assert '%s = open(' not in source" % handle, "directory = tempfile.mkdtemp()", "try:", ' path = os.path.join(directory, "lock note.txt")', ' with open(path, "w", encoding="utf-8") as writer:', ' writer.write("alpha")', " assert %s.%s(path) == 'alpha'" % (alias, target.symbol), "finally:", " shutil.rmtree(directory, ignore_errors=True)", ] test_name = "%s_scopes_its_handle" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the scope the pattern gave the handle, the close it made redundant, and the read still working.", statements, headers=("import os", "import shutil", "import tempfile"), ) 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 = ("the handle '%s' is opened outside any with block" % handle,) + tuple( "the close of '%s' becomes redundant inside the scope" % handle for _ in drop ) return _hit("open-to-context-manager", target, edit, companion, evidence)
# ---------------------------------------------------------------------------# Rule 5: a precondition states its own failure.# ---------------------------------------------------------------------------
def rule_bare_assert_to_explicit_raise(target: Target) -> Outcome: """Rewrite the first statement of a function from an assert into a raise.
The exception type is kept, because an assert raises ``AssertionError`` and a caller that catches it has to keep catching it. Only the first statement is considered: a check further down is not a precondition, and moving it changes what the function does before it refuses. """
function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text) first = function.body[0] check = first.value if isinstance(first, ast.Expr) else first if not isinstance(check, ast.Assert): return _miss( target.rel_posix, target.symbol, NOT_THE_FIRST_STATEMENT, "the first statement of '%s' is not an assert, so it is not a precondition" % target.symbol, ) indent = " " * first.col_offset test_text = segment_of(target.text, starts, check.test) arguments = "" message_evidence = "no message was written, so the raise carries none either" if check.msg is not None: arguments = segment_of(target.text, starts, check.msg) message_evidence = "the message text is kept word for word" replacement = "if not %s:\n%sraise AssertionError(%s)" % (test_text, indent + INDENT, arguments) start, end = node_span(target.text, starts, first) edit = _rewrite_function(target, starts, function, [_Splice(start=start, end=end, text=replacement)], "explicit raise of '%s'" % target.symbol)
alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s.%s)" % (alias, target.symbol), "assert 'raise AssertionError(' in source", "assert not [line for line in source.splitlines() if line.strip().startswith('assert ')]", "try:", ' %s.%s("")' % (alias, target.symbol), "except AssertionError as caught:", " pass" if check.msg is None else " assert %s in str(caught)" % arguments, "else:", " raise AssertionError('%s accepted an argument its check rejects')" % target.symbol, ] test_name = "%s_raises_in_stead_of_asserting" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the raise that replaced the assert, and the refusal the function still carries.", 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 = ("the first statement is an assert on '%s'" % test_text, message_evidence) return _hit("bare-assert-to-explicit-raise", 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,}
RULE_IDS: Tuple[str, ...] = tuple(sorted(RULES))42 unmodified lines43444546474849344 unmodified lines39439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158242 unmodified lines)
from lgpython.ast_graph import IGNORED_DIRS, discover_python_files # noqa: E402from lgpython.patterns import PatternPlan, plan_pattern # noqa: E402
PYTHON_ROOT = Path(__file__).resolve().parent.parentDEFAULT_AGENT_SCRIPT = PYTHON_ROOT / "agents" / "python_agent.py"344 unmodified lines dossier=dossier, )
def apply_pattern( self, pattern_id: str, *, target: Optional[str] = None, case_id: Optional[str] = None, note: Optional[str] = None, commit: bool = True, patch_config: FuzzyPatchConfig = FuzzyPatchConfig(), ) -> SessionResult: """Apply one catalog card to one target, primary edit and lock test together.
Both files of the pair land in the same staged copy, so the test gate runs against the rewritten source and the lock test that can only pass once the rewrite landed. The kernel claim stays the primary edit, because that is the edit the six nodes are asked to judge, and the companion paths are announced on the same case. The commit is one transaction: the source replaced and the test file replaced, or neither.
A card that refuses is not a failed run. It reports the reason code the rule named and never reaches the six nodes, because there is nothing there to verify. A card that applies but whose anchors do not apply writes nothing either: a pattern that would have to edit one file of its pair and skip the other is a pattern this session does not run. """ chosen_case_id = case_id or "pattern-%s" % pattern_id plan = plan_pattern(self.workspace_root, pattern_id, target) if plan.refused: return SessionResult( case_id=chosen_case_id, verdict="REFUSED", assurance=0, reason=plan.reason_code, detail=plan.detail, committed=False, touched_files=(), dossier={ "pattern": pattern_id, "target": plan.target, "refusal": plan.reason_code, "decision": { "verdict": "REFUSED", "assurance": 0, "reason": plan.reason_code, "detail": plan.detail, }, "gates": [], "checkers": [], }, )
primary = plan.primary() guard = PathGuard(self.policy()) try: planned = guard.plan_transaction( [PlannedOp(op=OP_WRITE, rel_posix=edit.file, content="") for edit in plan.edits] ) except PathSecurityError: case = { "case_id": chosen_case_id, "workspace": str(self.workspace_root), "file": primary.file, "text": "", "search": primary.search, "replace": primary.replace, "note": note or plan.summary(), "required_gates": list(self.required_gates), "policy": self.policy_dict(), "pattern": pattern_id, "companionFiles": [edit.file for edit in plan.companions()], **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) return SessionResult( case_id=chosen_case_id, verdict=str(decision.get("verdict", "UNKNOWN")), assurance=int(decision.get("assurance", 0)), reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=False, touched_files=plan.files, trace=tuple(trace), dossier=dossier, )
originals: Dict[str, str] = {} patched: Dict[str, str] = {} unapplied: List[str] = [] for edit in plan.edits: source = self.workspace_root / Path(*edit.file.split("/")) original = source.read_text(encoding="utf-8", newline="") if source.is_file() else "" originals[edit.file] = original outcome = apply_controlled_fuzzy_patch( original, SearchReplaceBlock(edit.search, edit.replace), patch_config ) if not outcome.applied: unapplied.append(edit.file) patched[edit.file] = outcome.updated_text if planned.rejected or unapplied: # Nothing of the pair is written: a half pair is exactly the state the lock # test exists to prevent, and staging it would judge a change nobody proposed. return SessionResult( case_id=chosen_case_id, verdict="REFUSED", assurance=0, reason="PATH_POLICY" if planned.rejected else "PATCH_NOT_APPLIED", detail=( "the path policy rejected the pair: " + ", ".join(plan.files) if planned.rejected else "the anchor of this card did not apply in: " + ", ".join(unapplied) ), committed=False, touched_files=plan.files, dossier={ "pattern": pattern_id, "target": plan.target, "refusal": "PATH_POLICY" if planned.rejected else "PATCH_NOT_APPLIED", "decision": {"verdict": "REFUSED", "assurance": 0}, "gates": [], "checkers": [], }, )
needed = max(self.min_assurance, plan.min_assurance) with tempfile.TemporaryDirectory(prefix="lgpython_pattern_stage_") as tmp_dir: staged_root = Path(tmp_dir).resolve() _copy_workspace_for_staging(self.workspace_root, staged_root) staged_fs = self._os_fs(staged_root) tx = staged_fs.begin_transaction() for edit in plan.edits: staged_fs.stage_write_text(tx, edit.file, patched[edit.file]) staged_fs.commit_transaction(tx)
case = { "case_id": chosen_case_id, "workspace": str(staged_root), "file": primary.file, "text": originals[primary.file], "search": primary.search, "replace": primary.replace, "note": note or plan.summary(), "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), "options": { "min_similarity": patch_config.min_similarity, "ambiguity_margin": patch_config.ambiguity_margin, }, "attemptSignatures": [], "pattern": pattern_id, "companionFiles": [edit.file for edit in plan.companions()], **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case)
decision = dict(dossier.get("decision", {})) verdict = str(decision.get("verdict", "UNKNOWN")) assurance = int(decision.get("assurance", 0)) committed = False
if commit and assurance >= needed: real_fs = self._os_fs(self.workspace_root) tx = real_fs.begin_transaction() for edit in plan.edits: real_fs.stage_write_text(tx, edit.file, patched[edit.file]) real_fs.commit_transaction(tx) committed = True
dossier["pattern"] = pattern_id dossier["target"] = plan.target dossier["companionFiles"] = [edit.file for edit in plan.companions()] dossier["requiredAssurance"] = needed return SessionResult( case_id=chosen_case_id, verdict=verdict, assurance=assurance, reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=committed, touched_files=plan.files, trace=tuple(trace), dossier=dossier, )
def create_file( self, rel_path: str,1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495{ "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_by_file": { "src/guards.py": 2, "src/notes.py": 2, "src/registry.py": 6, "src/slugify.py": 2, "src/tokens.py": 3 }, "patterns": [ { "family": "typing", "min_assurance": 3, "negative_rows": 1, "pattern_id": "annotate-literal-defaults", "positive_rows": 1, "refusals_recorded": [ "ALREADY_ANNOTATED" ], "targets_in_shape": [ "src/slugify.py::join_parts", "src/tokens.py::count_words", "src/tokens.py::summarize" ], "targets_planted_in_shape": 3 }, { "family": "contracts", "min_assurance": 3, "negative_rows": 1, "pattern_id": "bare-assert-to-explicit-raise", "positive_rows": 1, "refusals_recorded": [ "NOT_THE_FIRST_STATEMENT" ], "targets_in_shape": [ "src/guards.py::open_ticket" ], "targets_planted_in_shape": 1 }, { "family": "shape", "min_assurance": 3, "negative_rows": 1, "pattern_id": "chain-to-registry", "positive_rows": 1, "refusals_recorded": [ "BRANCH_SHAPE_MISMATCH" ], "targets_in_shape": [ "src/registry.py::render" ], "targets_planted_in_shape": 1 }, { "family": "mutation", "min_assurance": 3, "negative_rows": 1, "pattern_id": "mutable-default-to-none", "positive_rows": 1, "refusals_recorded": [ "NOT_A_MUTABLE_DEFAULT" ], "targets_in_shape": [ "src/slugify.py::add_tag" ], "targets_planted_in_shape": 1 }, { "family": "resources", "min_assurance": 3, "negative_rows": 1, "pattern_id": "open-to-context-manager", "positive_rows": 1, "refusals_recorded": [ "ALREADY_SCOPED" ], "targets_in_shape": [ "src/notes.py::read_note" ], "targets_planted_in_shape": 1 } ], "rows": 10, "schema": "lingologos-python-pattern-coverage-1", "source_files": [ "src/guards.py", "src/notes.py", "src/registry.py", "src/slugify.py", "src/tokens.py" ]}12345678910{"case_id": "pat-annotate-literal-defaults-positive", "edits": [{"file": "src/tokens.py", "label": "signature of 'count_words'", "replace": "def count_words(text: str = \"\", unit: str = \"word\"):\n parts = text.split()\n if unit == \"word\":\n return len(parts)\n if unit == \"line\":\n return len(text.splitlines())\n return 0", "search": "def count_words(text=\"\", unit=\"word\"):\n parts = text.split()\n if unit == \"word\":\n return len(parts)\n if unit == \"line\":\n return len(text.splitlines())\n return 0"}, {"file": "tests/test_tokens.py", "label": "lock test 'test_count_words_parameters_keep_their_defaults' appended after 'test_summarize_follows_the_unit'", "replace": "def test_summarize_follows_the_unit() -> None:\n assert summarize(\"a b\", unit=\"word\") == 2\n assert count_lines(\"a\\nb\") == 2\n\n\ndef test_count_words_parameters_keep_their_defaults() -> None:\n \"\"\"Lock the annotations this pattern added and the defaults it had to leave alone.\"\"\"\n import inspect\n\n from src import tokens\n parameters = inspect.signature(tokens.count_words).parameters\n assert parameters['text'].annotation is str\n assert parameters['text'].default == ''\n assert parameters['unit'].annotation is str\n assert parameters['unit'].default == 'word'\n", "search": "def test_summarize_follows_the_unit() -> None:\n assert summarize(\"a b\", unit=\"word\") == 2\n assert count_lines(\"a\\nb\") == 2"}], "expect": "VERIFIED", "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", "rule": "annotate-literal-defaults", "targets": ["src/tokens.py::count_words"]}{"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-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-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-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"]}1 unmodified line2345567839 unmodified lines4849505152535455565758596061626364656667686970717273741 unmodified line "schema": "lingologos-python-gates-1",
"verdict": "CONFIRMED",
"counts": {
"CONFIRMED": 6,
"CONFIRMED": 9,
"REJECTED": 0,
"ABSTAIN": 0
},39 unmodified lines "check": "external topology.json, node folders, and six subprocess turns",
"note": "6 node folders valid, 7 subprocess envelopes reached VERIFIED (3)",
"failed_targets": []
},
{
"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",
"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",
"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",
"failed_targets": []
}
]
}25 unmodified lines26272829303132333435363725 unmodified lines dst = tmp_path / "sample_pkg" shutil.copytree(src, dst) return dst
@pytest.fixturedef pattern_lab(tmp_path: Path) -> Path: """A private copy of the pattern fixture, for tests that write into it.""" src = PYTHON_ROOT / "fixtures" / "pattern_lab" dst = tmp_path / "pattern_lab" shutil.copytree(src, dst) return dst123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""Tests for applying a catalog card end to end: pair staged, six nodes judging, one commit."""
from __future__ import annotations
import hashlibimport subprocessimport sysfrom pathlib import Pathfrom typing import Dict
from lgpython.patterns import PATTERNS, plan_patternfrom lgpython.session import DEFAULT_PROTECTED_PATTERNS, PythonWorkspaceSession
POSITIVE = { "annotate-literal-defaults": "src/tokens.py::count_words", "bare-assert-to-explicit-raise": "src/guards.py::open_ticket", "chain-to-registry": "src/registry.py::render", "mutable-default-to-none": "src/slugify.py::add_tag", "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"), "chain-to-registry": ("src/registry.py::render_pair", "BRANCH_SHAPE_MISMATCH"), "mutable-default-to-none": ("src/slugify.py::join_parts", "NOT_A_MUTABLE_DEFAULT"), "open-to-context-manager": ("src/notes.py::write_note", "ALREADY_SCOPED"),}
def _tree_state(root: Path) -> Dict[str, str]: state: Dict[str, str] = {} for path in sorted(root.rglob("*")): if path.is_file(): digest = hashlib.sha256(path.read_bytes()).hexdigest() state[str(path.relative_to(root).as_posix())] = digest return state
def _pytest_return_code(root: Path) -> int: return subprocess.run( [sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider"], cwd=str(root), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ).returncode
def test_every_card_lands_on_its_target_and_the_six_nodes_confirm_it(pattern_lab: Path) -> None: session = PythonWorkspaceSession(pattern_lab) for pattern_id in sorted(POSITIVE): result = session.apply_pattern(pattern_id, target=POSITIVE[pattern_id]) assert result.verdict == "VERIFIED", "%s: %s %s" % (pattern_id, result.verdict, result.detail) assert result.assurance == 3 assert result.committed is True assert len(result.touched_files) == 2 assert result.dossier["pattern"] == pattern_id assert result.dossier["companionFiles"] == [result.touched_files[1]] assert _pytest_return_code(pattern_lab) == 0 source = (pattern_lab / "src" / "notes.py").read_text(encoding="utf-8") assert "with open(" in source test_text = (pattern_lab / "tests" / "test_notes.py").read_text(encoding="utf-8") assert "def test_read_note_scopes_its_handle() -> None:" in test_text
def test_the_lock_test_fails_until_the_change_it_locks_lands(pattern_lab: Path) -> None: assert _pytest_return_code(pattern_lab) == 0 plan = plan_pattern(pattern_lab, "chain-to-registry", POSITIVE["chain-to-registry"]) assert not plan.refused companion = plan.companions()[0] target = pattern_lab / "tests" / "test_registry.py" original = target.read_text(encoding="utf-8", newline="") assert companion.search in original target.write_text(original.replace(companion.search, companion.replace, 1), encoding="utf-8", newline="") assert _pytest_return_code(pattern_lab) != 0 target.write_text(original, encoding="utf-8", newline="") assert _pytest_return_code(pattern_lab) == 0
def test_a_card_that_refuses_never_reaches_the_nodes_and_writes_nothing(pattern_lab: Path) -> None: session = PythonWorkspaceSession(pattern_lab) before = _tree_state(pattern_lab) for pattern_id in sorted(NEGATIVE): target, code = NEGATIVE[pattern_id] result = session.apply_pattern(pattern_id, target=target) assert result.verdict == "REFUSED" assert result.assurance == 0 assert result.reason == code assert result.committed is False assert result.touched_files == () assert result.dossier["gates"] == [] assert _tree_state(pattern_lab) == before
def test_a_dry_run_verifies_the_pair_and_touches_no_file(pattern_lab: Path) -> None: session = PythonWorkspaceSession(pattern_lab) before = _tree_state(pattern_lab) result = session.apply_pattern("open-to-context-manager", target=POSITIVE["open-to-context-manager"], commit=False) assert result.verdict == "VERIFIED" assert result.assurance == 3 assert result.committed is False assert _tree_state(pattern_lab) == before
def test_applying_a_card_twice_is_a_refusal_and_not_a_second_change(pattern_lab: Path) -> None: session = PythonWorkspaceSession(pattern_lab) pattern_id = "open-to-context-manager" first = session.apply_pattern(pattern_id, target=POSITIVE[pattern_id]) assert first.committed is True after_first = _tree_state(pattern_lab) second = session.apply_pattern(pattern_id, target=POSITIVE[pattern_id]) assert second.verdict == "REFUSED" assert second.reason in PATTERNS[pattern_id].refuses_as assert second.committed is False assert _tree_state(pattern_lab) == after_first
def test_a_policy_that_blocks_the_lock_test_blocks_the_source_edit_too(pattern_lab: Path) -> None: session = PythonWorkspaceSession( pattern_lab, protected_patterns=DEFAULT_PROTECTED_PATTERNS + ("tests/test_notes.py",), ) before = _tree_state(pattern_lab) result = session.apply_pattern("open-to-context-manager", target=POSITIVE["open-to-context-manager"]) assert result.verdict == "REFUSED" assert result.reason == "PATH_POLICY" assert result.committed is False assert _tree_state(pattern_lab) == before123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209"""Tests for the pattern catalog: what a card claims, and what a plan reports."""
from __future__ import annotations
import jsonimport subprocessimport sysfrom pathlib import Pathfrom typing import Dict, List
from lgcodex.casecorpus import read_rows, validate_case_rows
from lgpython.patterns import ( FAMILIES, PATTERNS, PATTERN_IDS, PatternSpec, pattern_card, plan_pattern, render_card, scan_pattern, split_target, TARGET_SEPARATOR,)from lgpython.rules import RULE_IDS
ROOT = Path(__file__).resolve().parents[1]LAB = ROOT / "fixtures" / "pattern_lab"CASES = ROOT / "patterns" / "pattern_cases.jsonl"COVERAGE = ROOT / "patterns" / "coverage.json"
POSITIVE = { "annotate-literal-defaults": "src/tokens.py::count_words", "bare-assert-to-explicit-raise": "src/guards.py::open_ticket", "chain-to-registry": "src/registry.py::render", "mutable-default-to-none": "src/slugify.py::add_tag", "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", "chain-to-registry": "src/registry.py::render_pair", "mutable-default-to-none": "src/slugify.py::join_parts", "open-to-context-manager": "src/notes.py::write_note",}
def _card(pattern_id: str) -> PatternSpec: return pattern_card(pattern_id)
def _reason_codes() -> List[str]: from lgpython import rules
return [name for name in dir(rules) if name.isupper() and "_" in name]
def test_each_card_states_the_shape_it_claims_and_the_lock_it_writes() -> None: assert sorted(PATTERNS) == list(PATTERN_IDS) for pattern_id in PATTERN_IDS: spec = _card(pattern_id) assert spec.family in FAMILIES assert spec.rule in RULE_IDS assert spec.shape and spec.rationale and spec.lock_claims assert spec.preconditions, "%s claims a shape with no stated precondition" % pattern_id assert spec.intent_tags and spec.companions assert spec.min_assurance >= 2
def test_the_refusals_a_card_lists_are_codes_its_rule_can_give() -> None: known = set(_reason_codes()) for pattern_id in PATTERN_IDS: spec = _card(pattern_id) assert spec.refuses_as, "%s states no refusal" % pattern_id for code in spec.refuses_as: assert code in known, "%s names %s, which no rule of this bundle gives" % (pattern_id, code)
def test_a_target_label_splits_into_the_file_and_the_function_it_names() -> None: assert split_target("src/notes.py::read_note") == ("src/notes.py", "read_note") assert split_target("src\\notes.py::read_note") == ("src/notes.py", "read_note") for broken in ("src/notes.py", "src/notes.py::", "::read_note"): try: split_target(broken) except ValueError: continue raise AssertionError("'%s' is not a target label" % broken) assert TARGET_SEPARATOR == "::"
def test_a_card_that_is_not_in_the_catalog_is_named_as_missing() -> None: try: pattern_card("rename-the-module") except KeyError as exc: assert "rename-the-module" in str(exc) return raise AssertionError("an unknown card was accepted")
def test_a_plan_that_applies_reports_the_files_it_would_write() -> None: for pattern_id in PATTERN_IDS: plan = plan_pattern(LAB, pattern_id, POSITIVE[pattern_id]) assert not plan.refused, plan.detail assert plan.min_assurance == _card(pattern_id).min_assurance assert plan.evidence, "%s applied without saying why" % pattern_id assert len(plan.edits) == 2 assert plan.primary().file in plan.files assert plan.files == tuple(edit.file for edit in plan.edits) assert plan.target.endswith(TARGET_SEPARATOR + POSITIVE[pattern_id].split(TARGET_SEPARATOR)[1]) summary = plan.summary() assert pattern_id in summary and "writes" in summary
def test_a_plan_that_refuses_reports_the_code_its_rule_gave() -> None: for pattern_id in PATTERN_IDS: plan = plan_pattern(LAB, pattern_id, NEGATIVE[pattern_id]) assert plan.refused assert plan.edits == () assert plan.files == () assert plan.reason_code in _card(pattern_id).refuses_as assert plan.detail, "%s refused without a sentence explaining it" % pattern_id try: plan.primary() except ValueError: pass else: raise AssertionError("a refused plan claimed an edit")
def test_the_catalog_refuses_to_choose_between_two_functions_of_the_same_shape() -> None: plan = plan_pattern(LAB, "annotate-literal-defaults") assert plan.refused assert plan.reason_code == "AMBIGUOUS_TARGET" for target in [label for label, _hit in scan_pattern(LAB, "annotate-literal-defaults")]: assert target in plan.detail
def test_scan_names_every_function_of_a_workspace_a_card_claims() -> None: for pattern_id in PATTERN_IDS: found = [label for label, _hit in scan_pattern(LAB, pattern_id)] assert POSITIVE[pattern_id] in found, "%s does not find the function planted for it" % pattern_id assert NEGATIVE[pattern_id] not in found, "%s finds the function planted to be refused" % pattern_id only_one = scan_pattern(LAB, "open-to-context-manager") assert [label for label, _hit in only_one] == ["src/notes.py::read_note"]
def test_a_card_written_as_a_row_validates_against_the_kernel_schema() -> None: rows: List[Dict[str, object]] = [] for pattern_id in PATTERN_IDS: rows.append(plan_pattern(LAB, pattern_id, POSITIVE[pattern_id]).to_row("pos-%s" % pattern_id)) rows.append(plan_pattern(LAB, pattern_id, NEGATIVE[pattern_id]).to_row("neg-%s" % pattern_id)) assert validate_case_rows(rows) == [] for row in rows[:1] + rows[1:2]: assert row["language"] == "python" assert row["pattern_id"] in PATTERN_IDS assert row["rule"] == row["pattern_id"] assert row["intent_tags"] == sorted(_card(str(row["pattern_id"])).intent_tags) assert row["note"] == _card(str(row["pattern_id"])).shape assert int(row["min_assurance"]) == _card(str(row["pattern_id"])).min_assurance for row in rows: if row["expect"] == "REFUSED": assert row["edits"] == [] assert str(row["reason_code"]) in _card(str(row["pattern_id"])).refuses_as else: assert len(row["edits"]) == 2 assert row.get("reason_code", "") == ""
def test_a_card_renders_as_a_card_a_person_can_read() -> None: text = render_card(_card("chain-to-registry")) assert text.startswith("chain-to-registry") for part in ("family", "shape", "why", "needs", "companion", "lock", "refuses", "assurance"): assert part in text assert "adding a kind means editing the middle of a chain" in text
def test_the_corpus_on_disk_is_what_the_rules_generate() -> None: proc = subprocess.run( [sys.executable, "-B", str(ROOT / "tools" / "build_patterns.py"), "--check"], cwd=str(ROOT), capture_output=True, text=True, ) assert proc.returncode == 0, proc.stdout + proc.stderr assert "PATTERNS: CONFIRMED" in proc.stdout
def test_the_corpus_holds_one_pair_for_every_card_and_validates() -> None: rows = read_rows(CASES) assert validate_case_rows(rows) == [] assert len(rows) == 2 * len(PATTERNS) for pattern_id in PATTERN_IDS: positive = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "VERIFIED"] negative = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED"] assert [str(row["targets"][0]) for row in positive] == [POSITIVE[pattern_id]] assert [str(row["targets"][0]) for row in negative] == [NEGATIVE[pattern_id]]
def test_coverage_states_the_fixture_as_its_denominator() -> None: payload = json.loads(COVERAGE.read_text(encoding="utf-8")) assert payload["fixture"] == "fixtures/pattern_lab" assert "not over Python" in payload["denominator"] assert payload["rows"] == len(read_rows(CASES)) assert sorted(str(entry["pattern_id"]) for entry in payload["patterns"]) == list(PATTERN_IDS) for entry in payload["patterns"]: assert entry["positive_rows"] == 1 and entry["negative_rows"] == 1 assert POSITIVE[str(entry["pattern_id"])] in entry["targets_in_shape"] assert len(entry["refusals_recorded"]) == 1 assert entry["refusals_recorded"][0] in _card(str(entry["pattern_id"])).refuses_as123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""Tests for the five rules of the Python pattern catalog."""
from __future__ import annotations
from pathlib import Pathfrom typing import Callable, Dict, Optional
from lgcodex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch
from lgpython import rulesfrom lgpython.patterns import PATTERNS
ROOT = Path(__file__).resolve().parents[1]LAB = ROOT / "fixtures" / "pattern_lab"
def _reader(root: Path) -> Callable[[str], Optional[str]]: def read(rel_posix: str) -> Optional[str]: path = root / Path(*rel_posix.split("/")) return path.read_text(encoding="utf-8", newline="") if path.is_file() else None
return read
def _write(path: Path, text: str) -> None: """Write LF text on any host: the catalog anchors on LF, and Path.write_text would translate it."""
path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8", newline="\n") as handle: handle.write(text)
def _outcome(rel_posix: str, symbol: str, rule_id: str, root: Path = LAB) -> rules.Outcome: target, miss = rules.open_target(rel_posix, symbol, _reader(root)) if target is None: assert miss is not None return miss return rules.RULES[rule_id](target)
def _plan(rel_posix: str, symbol: str, rule_id: str) -> rules.RuleHit: outcome = _outcome(rel_posix, symbol, rule_id) assert isinstance(outcome, rules.RuleHit), "expected a hit, got %r" % (outcome,) return outcome
def _miss_code(rel_posix: str, symbol: str, rule_id: str) -> str: outcome = _outcome(rel_posix, symbol, rule_id) assert isinstance(outcome, rules.RuleMiss), "expected a refusal, got %r" % (outcome,) return outcome.reason_code
def _patched(hit: rules.RuleHit) -> Dict[str, str]: """Every file of a hit after its edit is applied to the fixture text."""
patched: Dict[str, str] = {} for edit in hit.edits: original = (LAB / Path(*edit.file.split("/"))).read_text(encoding="utf-8", newline="") result = apply_controlled_fuzzy_patch( original, SearchReplaceBlock(edit.search, edit.replace), FuzzyPatchConfig() ) assert result.applied, "the anchor for '%s' does not apply" % edit.file patched[edit.file] = result.updated_text return patched
def test_every_card_asks_for_a_rule_this_bundle_holds() -> None: assert sorted(PATTERNS) == sorted(rules.RULE_IDS) for pattern_id, spec in PATTERNS.items(): assert spec.rule == pattern_id assert pattern_id in rules.RULES
def test_annotating_a_literal_default_touches_the_signature_and_nothing_else() -> None: hit = _plan("src/tokens.py", "count_words", "annotate-literal-defaults") patched = _patched(hit)["src/tokens.py"] compile(patched, "tokens.py", "exec") original = (LAB / "src" / "tokens.py").read_text(encoding="utf-8", newline="") assert patched == original.replace( 'def count_words(text="", unit="word"):', 'def count_words(text: str = "", unit: str = "word"):', )
def test_a_default_that_already_states_its_type_is_left_alone() -> None: assert _miss_code("src/tokens.py", "count_lines", "annotate-literal-defaults") == rules.ALREADY_ANNOTATED
def test_a_tuple_default_is_not_the_shared_kind_a_rule_refuses() -> None: assert _miss_code("src/slugify.py", "join_parts", "mutable-default-to-none") == rules.NOT_A_MUTABLE_DEFAULT
def test_a_shared_default_moves_out_of_the_signature_into_the_body() -> None: hit = _plan("src/slugify.py", "add_tag", "mutable-default-to-none") source = hit.edits[0].replace assert "tags=None" in source assert "if tags is None:" in source assert "tags=[]" not in source compile(_patched(hit)["src/slugify.py"], "slugify.py", "exec")
def test_a_chain_of_one_name_becomes_one_visible_mapping() -> None: hit = _plan("src/registry.py", "render", "chain-to-registry") source = hit.edits[0].replace assert '"short": format_short' in source assert "handlers.get(kind)" in source assert "elif" not in source compile(_patched(hit)["src/registry.py"], "registry.py", "exec")
def test_a_chain_whose_branches_answer_differently_stays_a_chain() -> None: assert _miss_code("src/registry.py", "render_pair", "chain-to-registry") == rules.BRANCH_SHAPE_MISMATCH
def test_a_handle_that_escapes_its_function_is_placed_in_a_with_block() -> None: hit = _plan("src/notes.py", "read_note", "open-to-context-manager") source = hit.edits[0].replace assert "with open(" in source assert ".close()" not in source assert "body = handle.read()" in source compile(_patched(hit)["src/notes.py"], "notes.py", "exec")
def test_a_function_that_already_scopes_its_handle_is_not_touched() -> None: assert _miss_code("src/notes.py", "write_note", "open-to-context-manager") == rules.ALREADY_SCOPED
def test_a_bare_assert_becomes_a_raise_that_says_the_same_thing() -> None: hit = _plan("src/guards.py", "open_ticket", "bare-assert-to-explicit-raise") source = hit.edits[0].replace assert "raise AssertionError(" in source assert '"queue name is required"' in source assert "\n assert " not in source compile(_patched(hit)["src/guards.py"], "guards.py", "exec")
def test_an_assert_that_is_not_the_guard_of_the_function_stays() -> None: assert _miss_code("src/guards.py", "close_ticket", "bare-assert-to-explicit-raise") == rules.NOT_THE_FIRST_STATEMENT
def test_every_hit_hangs_its_lock_on_the_test_file_of_its_target() -> None: pairs = [ ("src/tokens.py", "count_words", "annotate-literal-defaults"), ("src/slugify.py", "add_tag", "mutable-default-to-none"), ("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"), ] for rel_posix, symbol, rule_id in pairs: hit = _plan(rel_posix, symbol, rule_id) assert len(hit.edits) == 2 assert hit.edits[1].file == rules.test_file_for(rel_posix) compile(_patched(hit)[hit.edits[1].file], hit.edits[1].file, "exec")
def test_a_rule_that_cannot_place_its_lock_refuses_the_whole_change(tmp_path: Path) -> None: root = tmp_path / "ws" (root / "src").mkdir(parents=True) (root / "tests").mkdir(parents=True) _write(root / "src" / "widget.py", "def pick(items=[]):\n return items\n") twice = ( "from src.widget import pick\n\n\n" "def test_pick_defaults() -> None:\n assert pick() == []\n\n\n" "def test_pick_defaults() -> None:\n assert pick() == []\n" ) _write(root / "tests" / "test_widget.py", twice) outcome = _outcome("src/widget.py", "pick", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.AMBIGUOUS_TEST_ANCHOR
def test_a_module_with_no_test_file_beside_it_is_left_as_it_is(tmp_path: Path) -> None: root = tmp_path / "ws" (root / "src").mkdir(parents=True) _write(root / "src" / "widget.py", "def pick(items=[]):\n return items\n") outcome = _outcome("src/widget.py", "pick", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.NO_TEST_FILE
def test_a_mutable_default_that_carries_an_annotation_is_outside_the_claim(tmp_path: Path) -> None: root = tmp_path / "ws" (root / "src").mkdir(parents=True) (root / "tests").mkdir(parents=True) _write(root / "src" / "widget.py", "def pick(items: list = []):\n return items\n") _write( root / "tests" / "test_widget.py", "from src.widget import pick\n\n\ndef test_pick_defaults() -> None:\n assert pick() == []\n", ) outcome = _outcome("src/widget.py", "pick", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.ANNOTATED_MUTABLE_DEFAULT
def test_a_function_that_already_rebuilds_its_default_is_not_done_twice(tmp_path: Path) -> None: root = tmp_path / "ws" (root / "src").mkdir(parents=True) (root / "tests").mkdir(parents=True) _write(root / "src" / "widget.py", "def pick(items=[]):\n if items is None:\n items = []\n return items\n") _write( root / "tests" / "test_widget.py", "from src.widget import pick\n\n\ndef test_pick_defaults() -> None:\n assert pick() == []\n", ) outcome = _outcome("src/widget.py", "pick", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.GUARD_ALREADY_PRESENT
def test_a_target_that_is_not_there_is_named_instead_of_guessed(tmp_path: Path) -> None: root = tmp_path / "ws" (root / "src").mkdir(parents=True) (root / "tests").mkdir(parents=True) _write(root / "src" / "widget.py", "def pick(items=[]):\n return items\n") _write( root / "tests" / "test_widget.py", "from src.widget import pick\n\n\ndef test_pick_defaults() -> None:\n assert pick() == []\n", ) missing_file = _outcome("src/nothing.py", "pick", "mutable-default-to-none", root) assert isinstance(missing_file, rules.RuleMiss) assert missing_file.reason_code == rules.MISSING_TARGET_FILE missing_symbol = _outcome("src/widget.py", "absent", "mutable-default-to-none", root) assert isinstance(missing_symbol, rules.RuleMiss) assert missing_symbol.reason_code == rules.NO_SUCH_FUNCTION
def test_a_handle_that_outlives_its_function_is_left_to_a_larger_change(tmp_path: Path) -> None: root = tmp_path / "ws" (root / "src").mkdir(parents=True) (root / "tests").mkdir(parents=True) _write( root / "src" / "keep.py", 'def take(path):\n handle = open(path, "r", encoding="utf-8")\n return handle\n', ) _write( root / "tests" / "test_keep.py", "from src.keep import take\n\n\ndef test_take_exists() -> None:\n assert callable(take)\n", ) outcome = _outcome("src/keep.py", "take", "open-to-context-manager", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.HANDLE_ESCAPE
def test_a_rule_that_anchors_on_text_refuses_text_it_cannot_anchor(tmp_path: Path) -> None: root = tmp_path / "ws" (root / "src").mkdir(parents=True) (root / "tests").mkdir(parents=True) with (root / "src" / "crlf.py").open("w", encoding="utf-8", newline="") as handle: handle.write("def pick(items=[]):\r\n return items\r\n") _write( root / "tests" / "test_crlf.py", "from src.crlf import pick\n\n\ndef test_pick_defaults() -> None:\n assert pick() == []\n", ) outcome = _outcome("src/crlf.py", "pick", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.CRLF_TARGET123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""Generate the pattern corpus and its coverage table for this bundle.
Run from inside the folder:
python tools/build_patterns.py # write the two generated files python tools/build_patterns.py --check # rebuild and compare bytes, change nothing
Both files under `patterns/` are generated here and nowhere else. A row is not written by hand andthen checked against the rules; it is the plan a rule produced for one named function of`fixtures/pattern_lab`, handed to `lgcodex.casecorpus` for validation before it reaches the file.That is what makes the corpus more than a description of the code beside it: if a rule changes andthe plan it produces changes with it, the file changes because the plan changed, and if the corpusis edited by hand the `--check` mode stops, because rebuilding no longer reproduces the bytes.
A positive row is a plan that applied. A negative row is a refusal the rule itself named, with thereason code the rule gave, and an empty `edits`. The pairs are declared below: each pattern has onefunction of the fixture written in the shape it claims and one function beside it written so thatthe claim does not hold. The gate runner re-derives both halves from the fixture on every run, sothe pairs below are checked, not trusted."""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Pathfrom typing import Dict, List, Sequence, Tuple
ROOT = Path(__file__).resolve().parents[1]if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))sys.dont_write_bytecode = True
from lgpython._codex_bridge import ensure_codex_on_path # noqa: E402
ensure_codex_on_path(ROOT)
from lgcodex.casecorpus import read_rows, validate_case_rows, write_rows # noqa: E402
from lgpython.ast_graph import discover_python_files # noqa: E402from lgpython.patterns import ( # noqa: E402 PATTERNS, module_level_functions, plan_pattern, scan_pattern,)
LAB = ROOT / "fixtures" / "pattern_lab"CASES_PATH = ROOT / "patterns" / "pattern_cases.jsonl"COVERAGE_PATH = ROOT / "patterns" / "coverage.json"COVERAGE_SCHEMA = "lingologos-python-pattern-coverage-1"
# One pair per card: a function of the fixture in the shape, and a function beside it that is not.# The right column states the reason code the rule is expected to give, so a rule that stops# refusing for the reason the card claims is caught here rather than in a reader's session.PAIRS: Dict[str, Tuple[str, str, str]] = { "annotate-literal-defaults": ( "src/tokens.py::count_words", "src/tokens.py::count_lines", "ALREADY_ANNOTATED", ), "bare-assert-to-explicit-raise": ( "src/guards.py::open_ticket", "src/guards.py::close_ticket", "NOT_THE_FIRST_STATEMENT", ), "chain-to-registry": ( "src/registry.py::render", "src/registry.py::render_pair", "BRANCH_SHAPE_MISMATCH", ), "mutable-default-to-none": ( "src/slugify.py::add_tag", "src/slugify.py::join_parts", "NOT_A_MUTABLE_DEFAULT", ), "open-to-context-manager": ( "src/notes.py::read_note", "src/notes.py::write_note", "ALREADY_SCOPED", ),}
def build_rows() -> List[Dict[str, object]]: """Every row of the corpus, in the order it belongs in the file."""
rows: List[Dict[str, object]] = [] for pattern_id in sorted(PATTERNS): positive_target, negative_target, expected_code = PAIRS[pattern_id] applied = plan_pattern(LAB, pattern_id, positive_target) if applied.refused: raise SystemExit( "the card '%s' refuses the target built for it: %s (%s)" % (pattern_id, applied.detail, applied.reason_code) ) if len(applied.edits) < 2: raise SystemExit( "the card '%s' planned %d edits, and a card without its lock test does not belong " "in this corpus" % (pattern_id, len(applied.edits)) ) rows.append(applied.to_row("pat-%s-positive" % pattern_id))
refusal = plan_pattern(LAB, pattern_id, negative_target) if not refusal.refused: raise SystemExit( "the card '%s' applied to the target built to be refused: %s" % (pattern_id, negative_target) ) if refusal.reason_code != expected_code: raise SystemExit( "the card '%s' refused '%s' with '%s', this tool expects '%s'" % (pattern_id, negative_target, refusal.reason_code, expected_code) ) rows.append(refusal.to_row("pat-%s-negative" % pattern_id))
problems = validate_case_rows(rows) if problems: raise SystemExit("casecorpus rejected the generated corpus: " + "; ".join(problems)) return rows
def build_coverage(rows: Sequence[Dict[str, object]]) -> Dict[str, object]: """The table that states what the corpus covers, and over what."""
source_files = [name for name in discover_python_files(LAB) if not name.startswith("tests/")] functions: Dict[str, int] = {} for rel in source_files: text = (LAB / Path(*rel.split("/"))).read_text(encoding="utf-8", newline="") functions[rel] = len(module_level_functions(text)) per_pattern: List[Dict[str, object]] = [] for pattern_id in sorted(PATTERNS): spec = PATTERNS[pattern_id] shapes = [label for label, _hit in scan_pattern(LAB, pattern_id)] positive = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "VERIFIED"] negative = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED"] per_pattern.append( { "pattern_id": pattern_id, "family": spec.family, "min_assurance": spec.min_assurance, "positive_rows": len(positive), "negative_rows": len(negative), "targets_planted_in_shape": len(shapes), "targets_in_shape": shapes, "refusals_recorded": sorted(str(row.get("reason_code", "")) for row in negative), } ) return { "schema": COVERAGE_SCHEMA, "fixture": "fixtures/pattern_lab", "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." ), "source_files": source_files, "module_level_functions_by_file": functions, "module_level_functions": sum(functions.values()), "patterns": per_pattern, "rows": len(rows), }
def _render_coverage(payload: Dict[str, object]) -> str: return json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=True) + "\n"
def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument( "--check", action="store_true", help="rebuild both files, compare them with what is on disk, and write nothing", ) args = parser.parse_args(argv)
rows = build_rows() coverage = build_coverage(rows) cases_text = "".join( json.dumps(row, sort_keys=True, ensure_ascii=True) + "\n" for row in rows ) coverage_text = _render_coverage(coverage)
if args.check: drift: List[str] = [] for path, text in ((CASES_PATH, cases_text), (COVERAGE_PATH, coverage_text)): if not path.is_file(): drift.append("%s is missing" % path.relative_to(ROOT)) elif path.read_text(encoding="utf-8", newline="") != text: drift.append("%s is not what the rules produce" % path.relative_to(ROOT)) on_disk = read_rows(CASES_PATH) if CASES_PATH.is_file() else [] if on_disk: bad = validate_case_rows(on_disk) if bad: drift.append("patterns/pattern_cases.jsonl is not a valid case-1 corpus: " + "; ".join(bad)) if drift: print("PATTERNS: REJECTED (%s)" % "; ".join(drift)) return 1 print( "PATTERNS: CONFIRMED (%d rows over %d cards, %d module level functions in the fixture)" % (len(rows), len(PATTERNS), coverage["module_level_functions"]) ) return 0
CASES_PATH.parent.mkdir(parents=True, exist_ok=True) write_rows(CASES_PATH, rows) COVERAGE_PATH.write_text(coverage_text, encoding="utf-8", newline="\n") print( "wrote %s (%d rows) and %s (%d cards)" % ( CASES_PATH.relative_to(ROOT), len(rows), COVERAGE_PATH.relative_to(ROOT), len(PATTERNS), ) ) return 0
if __name__ == "__main__": raise SystemExit(main())10 unmodified lines11121314151614151617181920202122232414 unmodified lines3940414142434445424344454647474849505129 unmodified lines81828383848586878485868788899091909293929495969730 unmodified lines12812913013113213313413513613713813914014114214314414514614714814915013513615115215315415510 unmodified linessiblings) and deliberately avoids `publish_to_hub.py`: that name belongs to the release builder ofthe multilingual track.
This bundle carries no corpora and no kernel. It is the Python layer over `lgcodex`, so the card hasto say how the two find each other on the hub, and every number the card states (6 gates, 26 tests,18 node files, the staged file count) is re-derived from this tree before a single object isThis bundle carries no kernel. It carries one corpus of its own, the ten 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,64 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.
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 three sections are added for readers who metthat only make sense inside a LingoLOGOS checkout, and four sections are added for readers who metthe bundle on the hub. Every pair has to match the README exactly, or the tool stops.
Nothing here runs during a test, and the token is never a command line argument, only the name of an14 unmodified linesROOT = Path(__file__).resolve().parents[1]
REPO = "tailot/codex-python"EXPECTED_FILES = 47 # the staged tree: 47 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 48 # those 47 plus the .gitattributes the hub addsEXPECTED_GATES = 6EXPECTED_TESTS = 26EXPECTED_TEST_FILES = 5EXPECTED_FILES = 65 # the staged tree: 65 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 66 # those 65 plus the .gitattributes the hub addsEXPECTED_GATES = 9EXPECTED_TESTS = 64EXPECTED_TEST_FILES = 8EXPECTED_NODE_FILES = 18EXPECTED_GATE_LINE = "GATES: CONFIRMED (6 gates: 6 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"EXPECTED_GATE_LINE = "GATES: CONFIRMED (9 gates: 9 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"ROLES = ("planner", "retriever", "executor", "gate_checker", "adversary", "arbiter")ENVELOPE_KIND = "lingologos-codex-envelope-1"IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git", ".venv", ".venv-train"}29 unmodified lines "An external Python programming package and six-node topology built on top of the LingoLOGOS\n" "`codex` kernel, a kernel this folder neither modifies nor carries. This dataset is that folder\n" "published as it stands: the package under `lgpython/`, the six node folders with their grammar,\n" "ontology and seed envelope, the one executable the six roles share, the fixture package under\n" "`fixtures/`, the tests, the gate runner and the publisher, and this card in place of the folder\n" "README. The kernel is a separate dataset, https://huggingface.co/datasets/tailot/lingologos-codex,\n" "and the section \"What this bundle needs from the codex kernel\" below says how the two find each\n" "other.", "ontology and seed envelope, the one executable the six roles share, the two fixtures under\n" "`fixtures/` (a small package, and the pattern laboratory the catalog is measured on), the generated\n" "cases under `patterns/`, the tests, the gate runner and the publisher, and this card in place of the\n" "folder README. The kernel is a separate dataset at\n" "https://huggingface.co/datasets/tailot/lingologos-codex, and the section\n" "\"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: 6 gates, 26 tests across 5 files,\n" "The gate runner is where this bundle states its numbers out loud: 9 gates, 64 tests across 8 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: 6 gates, 26 tests across 5 files,\n" "The gate runner is where this bundle states its numbers out loud: 9 gates, 64 tests across 8 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.",30 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
`patterns/pattern_cases.jsonl` holds 10 rows, one accepted and one refused for each of the five 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 in`lgcodex/casecorpus.py`, so its shape is checkable without a Python file in sight.
`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 waswritten for this bundle, and nothing here counts coverage of real repositories.
## Rights
The dataset is published by the author of LingoLOGOS under the same account, `tailot`. The source treeis the `codex-python/` folder of https://github.com/tailot/LingoLOGOS, where the project states its ownterms. Neither that repository root nor this folder carries a `LICENSE` file, so no license is claimedhere beyond what the publisher states on the repository and on this dataset page; ask there beforereusing the code. The fixture package under `fixtures/sample_pkg/` was written for this dataset and isnot taken from a third-party project.reusing the code. The fixture package under `fixtures/sample_pkg/` and the pattern laboratory under`fixtures/pattern_lab/` were written for this dataset and are not taken from a third-party project.
## Citation
20 unmodified lines21222324252627282930313233343536373839404142127 unmodified lines1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772781 unmodified line28028128228328428528628728820 unmodified lines
from lgcodex.adapter_contract import check_adapter_contract # noqa: E402from lgcodex.agents import ROLES # noqa: E402from lgcodex.casecorpus import read_rows, validate_case_rows # noqa: E402from lgcodex.decision import dossier_from_dict # noqa: E402from lgcodex.envelope import ENVELOPE_KIND # noqa: E402from lgcodex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch # noqa: E402from lgcodex.types import ABSTAIN, CONFIRMED, REJECTED, VERDICTS, GateResult # noqa: E402
from lgpython.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter # noqa: E402from lgpython.ast_graph import discover_python_files, extract_python_graph # noqa: E402from lgpython.patterns import PATTERNS, module_level_functions, plan_pattern # noqa: E402from lgpython.session import PythonWorkspaceSession # noqa: E402from lgpython.test_selector import select_python_tests # noqa: E402
FIXTURE_PKG = ROOT / "fixtures" / "sample_pkg"PATTERN_LAB = ROOT / "fixtures" / "pattern_lab"PATTERN_CASES = ROOT / "patterns" / "pattern_cases.jsonl"PATTERN_COVERAGE = ROOT / "patterns" / "coverage.json"
def _confirmed(check: str, note: str) -> GateResult:127 unmodified lines return _confirmed(check, "6 node folders valid, 7 subprocess envelopes reached VERIFIED (3)")
def gate_pattern_corpus_schema() -> GateResult: check = "patterns/pattern_cases.jsonl is a valid case-1 corpus with one pair per card" if not PATTERN_CASES.is_file(): return _rejected(check, "patterns/pattern_cases.jsonl is missing") rows = read_rows(PATTERN_CASES) problems = validate_case_rows(rows) if problems: return _rejected(check, "; ".join(problems), problems) unknown = sorted({str(row["pattern_id"]) for row in rows} - set(PATTERNS)) if unknown: return _rejected(check, f"rows name patterns this bundle does not hold: {unknown}", unknown) short: List[str] = [] for pattern_id in sorted(PATTERNS): positive = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "VERIFIED"] negative = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED"] if len(positive) != 1 or len(negative) != 1: short.append("%s has %d positive and %d negative rows" % (pattern_id, len(positive), len(negative))) elif len(positive[0]["edits"]) < 2: short.append("%s claims a companion test but its row holds %d edits" % (pattern_id, len(positive[0]["edits"]))) if short: return _rejected(check, "; ".join(short), short) return _confirmed(check, f"{len(rows)} rows over {len(PATTERNS)} cards, each with its lock test and its refusal")
def gate_pattern_round_trip() -> GateResult: 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") failures: List[str] = [] for row in read_rows(PATTERN_CASES): case_id = str(row["case_id"]) pattern_id = str(row["pattern_id"]) targets = [str(item) for item in row["targets"]] if not targets: failures.append("%s names no target" % case_id) continue plan = plan_pattern(PATTERN_LAB, pattern_id, targets[0]) if row["expect"] == "REFUSED": if not plan.refused: failures.append("%s was refused by the corpus and re-planned as a change" % case_id) elif plan.reason_code != str(row.get("reason_code", "")): failures.append( "%s refused with '%s', the corpus states '%s'" % (case_id, plan.reason_code, row.get("reason_code", "")) ) continue if plan.refused: failures.append("%s applied in the corpus and re-plans as a refusal: %s" % (case_id, plan.detail)) continue for edit in plan.edits: path = PATTERN_LAB / Path(*edit.file.split("/")) if not path.is_file(): failures.append("%s edits '%s', which the fixture does not hold" % (case_id, edit.file)) continue original = path.read_text(encoding="utf-8", newline="") outcome = apply_controlled_fuzzy_patch( original, SearchReplaceBlock(edit.search, edit.replace), FuzzyPatchConfig() ) if not outcome.applied: failures.append("%s: the anchor for '%s' does not apply" % (case_id, edit.file)) continue try: compile(outcome.updated_text, edit.file, "exec") except SyntaxError as exc: 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")
def gate_pattern_coverage() -> GateResult: check = "patterns/coverage.json states a denominator this fixture still supports" if not PATTERN_COVERAGE.is_file(): return _rejected(check, "patterns/coverage.json is missing") payload = json.loads(PATTERN_COVERAGE.read_text(encoding="utf-8")) source_files = [name for name in discover_python_files(PATTERN_LAB) if not name.startswith("tests/")] if payload.get("source_files") != source_files: return _rejected(check, f"the fixture holds {source_files}, the table states {payload.get('source_files')}") functions = payload.get("module_level_functions_by_file") or {} stated = int(payload.get("module_level_functions", -1)) by_file = {rel: len(module_level_functions((PATTERN_LAB / Path(*rel.split("/"))).read_text(encoding="utf-8", newline=""))) for rel in source_files} if by_file != functions or sum(by_file.values()) != stated: return _rejected(check, f"the functions of the fixture are {by_file}, the table states {functions} totaling {stated}") if int(payload.get("rows", -1)) != len(read_rows(PATTERN_CASES)): return _rejected(check, f"the corpus holds {len(read_rows(PATTERN_CASES))} rows, the table states {payload.get('rows')}") entries = payload.get("patterns") or [] if sorted(str(entry["pattern_id"]) for entry in entries) != sorted(PATTERNS): return _rejected(check, "the table does not list exactly the cards this bundle holds") wrong = [ str(entry["pattern_id"]) for entry in entries if int(entry["min_assurance"]) != PATTERNS[str(entry["pattern_id"])].min_assurance or str(entry["family"]) != PATTERNS[str(entry["pattern_id"])].family ] if wrong: return _rejected(check, f"family or assurance differs from the card for: {wrong}", wrong) return _confirmed( check, "%d cards over %d source files and %d module level functions, denominator stated as the fixture" % (len(entries), len(source_files), stated), )
GATES: Tuple[Tuple[str, Callable[[], GateResult]], ...] = ( ("adapter_contract", gate_adapter_contract), ("ast_symbol_graph", gate_ast_graph),1 unmodified line ("strict_abstain_control", gate_strict_abstain_control), ("session_transactions", gate_session_transactions), ("external_topology", gate_external_topology), ("pattern_corpus_schema", gate_pattern_corpus_schema), ("pattern_round_trip", gate_pattern_round_trip), ("pattern_coverage", gate_pattern_coverage),)
README.md+98-11
fixtures/pattern_lab/src/guards.pyAdded+18
fixtures/pattern_lab/src/notes.pyAdded+18
fixtures/pattern_lab/src/registry.pyAdded+43
fixtures/pattern_lab/src/slugify.pyAdded+15
fixtures/pattern_lab/src/tokens.pyAdded+23
fixtures/pattern_lab/tests/test_guards.pyAdded+21
fixtures/pattern_lab/tests/test_notes.pyAdded+16
fixtures/pattern_lab/tests/test_registry.pyAdded+22
fixtures/pattern_lab/tests/test_slugify.pyAdded+13
fixtures/pattern_lab/tests/test_tokens.pyAdded+16
lgpython/__init__.py+36
lgpython/cli.py+78
lgpython/patterns.pyAdded+410
lgpython/rules.pyAdded+1030
lgpython/session.py+184
patterns/coverage.jsonAdded+95
patterns/pattern_cases.jsonlAdded+10
results/gates.json+22-1
tests/conftest.py+9
tests/test_pattern_session.pyAdded+127
tests/test_patterns.pyAdded+209
tests/test_rules.pyAdded+255
tools/build_patterns.pyAdded+223
tools/publish_dataset.py+35-19
tools/run_gates.py+112