Upload folder using huggingface_hub
Browse filesFiles changed (35)
- README.md+63-46
- agents/python_agent.py+5-5
- lingologos_python/__init__.pyAdded+81
- lingologos_python/__main__.pyAdded+6
- lingologos_python/_codex_bridge.pyAdded+59
- lingologos_python/adapter.pyAdded+125
- lingologos_python/ast_graph.pyAdded+298
- lingologos_python/cli.pyAdded+276
- lingologos_python/gates.pyAdded+174
- lingologos_python/patterns.pyAdded+410
- lingologos_python/rules.pyAdded+1030
- lingologos_python/session.pyAdded+755
- lingologos_python/test_selector.pyAdded+140
- nodes/adversary/seed_payload.json+1-1
- nodes/arbiter/grammar.gf+1-1
- nodes/arbiter/seed_payload.json+1-1
- nodes/executor/seed_payload.json+1-1
- nodes/gate_checker/seed_payload.json+1-1
- nodes/planner/seed_payload.json+1-1
- nodes/retriever/seed_payload.json+1-1
- pyproject.toml+3-3
- results/gates.json+74-74
- tests/conftest.py+1-1
- tests/test_adapter.py+7-7
- tests/test_ast_graph.py+1-1
- tests/test_cli.py+3-3
- tests/test_pattern_session.py+2-2
- tests/test_patterns.py+4-4
- tests/test_rules.py+3-3
- tests/test_session.py+1-1
- tests/test_test_selector.py+1-1
- tests/test_topology_and_cli.py+5-5
- tools/build_patterns.py+5-5
- tools/publish_dataset.py+13-12
- tools/run_gates.py+16-16
18 unmodified lines1920212223242516 unmodified lines4243444546474849505152535455565758596061626364656667686915 unmodified lines85868788899091929394959621 unmodified lines1181191201211221231241251261271 unmodified line1291301311321331341357 unmodified lines1431441451461471481491 unmodified line15115215315415515615710 unmodified lines1681691701711721731744 unmodified lines1791801811821831841853 unmodified lines1891901911921931941954 unmodified lines2002012022032042052069 unmodified lines2162172182192202212222232242252262272282292302312323 unmodified lines2362372382392402412422432442452462472482492502512526 unmodified lines25926026126226326426518 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 folderpublished 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 two fixtures under`fixtures/` (a small package, and the pattern laboratory the catalog is measured on), the generatedcases under `patterns/`, the tests, the gate runner and the publisher, and this card in place of the16 unmodified lines## Contents- `lgpython/_codex_bridge.py`: finds the kernel without copying it: an already importable `lgcodex`,then `LGCODEX_ROOT`, then a sibling `codex/` or `datasets/codex/` among the ancestors.- `lgpython/adapter.py`: `PythonLanguageAdapter` and `StrictPythonLanguageAdapter` implementing thefive-method `lgcodex.adapter_contract.LanguageAdapter` contract.- `lgpython/ast_graph.py`: AST symbol, method, inheritance, relative/absolute import, and callgraph extraction (`discover_python_files`, `extract_python_graph`).- `lgpython/test_selector.py`: import-aware Python test selection (`select_python_tests`).- `lgpython/gates.py`: bytecode-free `ast.parse` + in-memory `compile` gate, optional staticcheckers (`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 throughits syntax tree, refuses with a named reason code when the shape is not the one it claims, andreturns 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 thatshape is worth changing, what must hold before the rule runs, what test locks the change, and thereason codes it answers with when it refuses (`PATTERNS`, `pattern_card`, `scan_pattern`,`plan_pattern`).- `lgpython/session.py`: `PythonWorkspaceSession` for safe staged verification and atomic diskcommits via `lgcodex.fsadapter` (`verify`, `edit_file`, `create_file`, `delete_file`,`apply_pattern`, `run_retry_loop`, and `run_topology_subprocesses`).- `lgpython/cli.py`: `lgpython` CLI (`verify`, `edit`, `create`, `symbols`, `select-tests`,`patterns list|show|scan|apply`, `check-adapter`).- `fixtures/pattern_lab/`: a small package with one function planted in the shape of each card andone 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 accepted15 unmodified lines| `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 thatis not that shape. `chain-to-registry` refuses a chain whose branches take different kinds ofarguments (`BRANCH_SHAPE_MISMATCH`), `open-to-context-manager` refuses a handle that escapes thefunction it opened (`HANDLE_ESCAPE`), `mutable-default-to-none` refuses a default that alreadycarries an annotation (`ANNOTATED_MUTABLE_DEFAULT`). A refusal is an answer, not a failure: it namesthe reason code and writes nothing.Every change this bundle makes is a pair. The rule returns two edits, the change in the source fileand a lock test appended to the test file paired with it, and `apply_pattern` puts both in one21 unmodified linesPATTERNS: 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 theshape 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 reasoncode. `patterns/` is a generated folder, so edit `tools/build_patterns.py` and let `--check` say so.## Working the fixture from the command line1 unmodified linecame back. The first one answers before anything is asked to change:```$ python -B -m lgpython symbols --workspace fixtures/pattern_lab --limit 5files=10 symbols=29 edges=290.0942 src/registry.py::render0.0838 src/tokens.py::count_words7 unmodified lineswhich tests a change is answerable to:```$ python -B -m lgpython select-tests --workspace fixtures/pattern_lab --files src/registry.pytests/test_registry.py```1 unmodified lineon, and the two long lines are wrapped here for width:```$ python -B -m lgpython patterns show --pattern open-to-context-manageropen-to-context-managerfamily resourcesshape a module level function that opens a file into a name and closes that name itself10 unmodified linesTo find out whether a workspace really holds the shape, rather than guessing:```$ python -B -m lgpython patterns scan --workspace fixtures/pattern_lab --pattern chain-to-registry```This prints one hit, `src/registry.py::render`, with the two edits it would apply: the chain of `if`4 unmodified linesThe pair, verified and not committed:```$ python -B -m lgpython patterns apply --workspace fixtures/pattern_lab \--pattern chain-to-registry --target src/registry.py::render --dry-runVERIFIED (assurance 3, committed=False) OK_DUAL_CONFIRMATION: confirmed by adversary, gate_checker```3 unmodified linesnot move by a byte:```$ python -B -m lgpython patterns apply --workspace fixtures/pattern_lab \--pattern chain-to-registry --target src/registry.py::render_pair --dry-runREFUSED (assurance 0, committed=False) BRANCH_SHAPE_MISMATCH: the chain in 'render_pair' tests morethan one name against text literals, its branches do not take the same arguments, or its last branch4 unmodified linesA change of your own goes through the same six nodes, as a search and replace you wrote:```bashpython -B -m lgpython edit --workspace repo --file src/x.py \--search "def load(path):" --replace "def load(path: Path) -> dict:" --dry-run```9 unmodified lines## RunningFrom the folder of this dataset, with `LGCODEX_ROOT` pointing at the folder of the kernel dataset:```bashpython -B -m pytest -p no:cacheprovider tests -qpython -B tools/run_gates.pypython -B -m lgpython check-adapter --workspace fixtures/sample_pkgpython -B -m lgpython verify --workspace fixtures/sample_pkg --file src/mathops.pypython -B -m lgpython patterns listpython -B -m lgpython patterns show --pattern chain-to-registrypython -B -m lgpython patterns scan --workspace fixtures/pattern_lab --pattern chain-to-registrypython -B -m lgpython patterns apply --workspace fixtures/pattern_lab \--pattern chain-to-registry --target src/registry.py::render --dry-run```3 unmodified linesthe commands above either read it or verify against a copy, and the tests copy it to a temporary folderbefore writing, so the folder as published keeps the exact shape the coverage numbers were counted on.## What this bundle needs from the codex kernel`lgpython` imports `lgcodex`, and `lgpython/_codex_bridge.py` resolves that import in one step: analready importable `lgcodex`, then the folder named by `LGCODEX_ROOT`, then a sibling `codex/` or a`datasets/codex/` among the ancestors of the package. Downloaded from here the two orders are the samefolder, and the resolution is:pip install -r requirements.txtgit clone https://huggingface.co/datasets/tailot/lingologos-codexLGCODEX_ROOT=/path/to/lingologos-codex python -B -m pytest -p no:cacheprovider tests -qNothing in this bundle downloads anything at run time: the kernel is a second download you make once,and the tests fail with a named reason when it is missing rather than passing without it. The kernel6 unmodified linesof 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 writes18 unmodified lines1920212223242516 unmodified lines424344454647484950515253545556575859606162636465666768697015 unmodified lines86878889909192939495969721 unmodified lines1191201211221231241251261271281 unmodified line1301311321331341351367 unmodified lines1441451461471481491501 unmodified line15215315415515615715810 unmodified lines1691701711721731741751764 unmodified lines1811821831841851861873 unmodified lines1911921931941951961974 unmodified lines2022032042052062072089 unmodified lines2182192202212222232242252262272282292302312322332342352363 unmodified lines2402412422432442452462472482492502512522532542552562572582592602612622632642652662672682696 unmodified lines27627727827928028128218 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 folderpublished as it stands: the package under `lingologos_python/`, the six node folders with their grammar,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 generatedcases under `patterns/`, the tests, the gate runner and the publisher, and this card in place of the16 unmodified lines## Contents- - `lingologos_python/_codex_bridge.py`: finds the kernel without copying it: an already importable`lingologos_codex`, then `LINGOLOGOS_CODEX_ROOT`, then a sibling `codex/` or `datasets/codex/` among theancestors.- - `lingologos_python/adapter.py`: `PythonLanguageAdapter` and `StrictPythonLanguageAdapter`implementing the five-method `lingologos_codex.adapter_contract.LanguageAdapter` contract.- `lingologos_python/ast_graph.py`: AST symbol, method, inheritance, relative/absolute import, and callgraph extraction (`discover_python_files`, `extract_python_graph`).- `lingologos_python/test_selector.py`: import-aware Python test selection (`select_python_tests`).- `lingologos_python/gates.py`: bytecode-free `ast.parse` + in-memory `compile` gate, optional staticcheckers (`mypy`, `ruff`, `pyright`, `flake8`) that return `ABSTAIN` when missing, and `pytest`/ `unittest` test runner with failed-target parsing.- - `lingologos_python/rules.py`: five shape rules over a named function. Each rule reads the functionthrough its syntax tree, refuses with a named reason code when the shape is not the one it claims, andreturns the edit texts when it is (`RULES`, `RULE_IDS`, `open_target`).- - `lingologos_python/patterns.py`: the catalog above the rules. A card states the shape it claims, whythat shape is worth changing, what must hold before the rule runs, what test locks the change, and thereason codes it answers with when it refuses (`PATTERNS`, `pattern_card`, `scan_pattern`,`plan_pattern`).- `lingologos_python/session.py`: `PythonWorkspaceSession` for safe staged verification and atomic diskcommits via `lingologos_codex.fsadapter` (`verify`, `edit_file`, `create_file`, `delete_file`,`apply_pattern`, `run_retry_loop`, and `run_topology_subprocesses`).- - `lingologos_python/cli.py`: `lingologos_python` CLI (`verify`, `edit`, `create`, `symbols`,`select-tests`, `patterns list|show|scan|apply`, `check-adapter`).- `fixtures/pattern_lab/`: a small package with one function planted in the shape of each card andone 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 accepted15 unmodified lines| `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 `lingologos_python/rules.py` refuses anythingthat is not that shape. `chain-to-registry` refuses a chain whose branches take different kinds ofarguments (`BRANCH_SHAPE_MISMATCH`), `open-to-context-manager` refuses a handle that escapes the functionit opened (`HANDLE_ESCAPE`), `mutable-default-to-none` refuses a default that already carries anannotation (`ANNOTATED_MUTABLE_DEFAULT`). A refusal is an answer, not a failure: it names the reason codeand writes nothing.Every change this bundle makes is a pair. The rule returns two edits, the change in the source fileand a lock test appended to the test file paired with it, and `apply_pattern` puts both in one21 unmodified linesPATTERNS: CONFIRMED (10 rows over 5 cards, 15 module level functions in the fixture)```Each row is a work case in the schema `lingologos_codex/casecorpus.py` defines, so the kernel can checkthe 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.## Working the fixture from the command line1 unmodified linecame back. The first one answers before anything is asked to change:```$ python -B -m lingologos_python symbols --workspace fixtures/pattern_lab --limit 5files=10 symbols=29 edges=290.0942 src/registry.py::render0.0838 src/tokens.py::count_words7 unmodified lineswhich tests a change is answerable to:```$ python -B -m lingologos_python select-tests --workspace fixtures/pattern_lab --files src/registry.pytests/test_registry.py```1 unmodified lineon, and the two long lines are wrapped here for width:```$ python -B -m lingologos_python patterns show --pattern open-to-context-manageropen-to-context-managerfamily resourcesshape a module level function that opens a file into a name and closes that name itself10 unmodified linesTo find out whether a workspace really holds the shape, rather than guessing:```$ python -B -m lingologos_python patterns scan --workspace fixtures/pattern_lab \--pattern chain-to-registry```This prints one hit, `src/registry.py::render`, with the two edits it would apply: the chain of `if`4 unmodified linesThe pair, verified and not committed:```$ python -B -m lingologos_python patterns apply --workspace fixtures/pattern_lab \--pattern chain-to-registry --target src/registry.py::render --dry-runVERIFIED (assurance 3, committed=False) OK_DUAL_CONFIRMATION: confirmed by adversary, gate_checker```3 unmodified linesnot move by a byte:```$ python -B -m lingologos_python patterns apply --workspace fixtures/pattern_lab \--pattern chain-to-registry --target src/registry.py::render_pair --dry-runREFUSED (assurance 0, committed=False) BRANCH_SHAPE_MISMATCH: the chain in 'render_pair' tests morethan one name against text literals, its branches do not take the same arguments, or its last branch4 unmodified linesA change of your own goes through the same six nodes, as a search and replace you wrote:```bashpython -B -m lingologos_python edit --workspace repo --file src/x.py \--search "def load(path):" --replace "def load(path: Path) -> dict:" --dry-run```9 unmodified lines## RunningFrom the folder of this dataset, with `LINGOLOGOS_CODEX_ROOT` pointing at the folder of the kerneldataset:```bashpython -B -m pytest -p no:cacheprovider tests -qpython -B tools/run_gates.pypython -B -m lingologos_python check-adapter --workspace fixtures/sample_pkgpython -B -m lingologos_python verify --workspace fixtures/sample_pkg --file src/mathops.pypython -B -m lingologos_python patterns listpython -B -m lingologos_python patterns show --pattern chain-to-registrypython -B -m lingologos_python patterns scan --workspace fixtures/pattern_lab \--pattern chain-to-registrypython -B -m lingologos_python patterns apply --workspace fixtures/pattern_lab \--pattern chain-to-registry --target src/registry.py::render --dry-run```3 unmodified linesthe commands above either read it or verify against a copy, and the tests copy it to a temporary folderbefore writing, so the folder as published keeps the exact shape the coverage numbers were counted on.## What this revision renamedThe two letter prefix is gone. The package is `lingologos_python`, where an earlier published revisionhad `lgpython`; the kernel it resolves is `lingologos_codex`, where that revision had `lgcodex`; theenvironment handle the bridge reads is `LINGOLOGOS_CODEX_ROOT`, where it was `LGCODEX_ROOT`; and thecommand line is `python -B -m lingologos_python`, the same name the console script of `pyproject.toml`carries. What did not move: the five adapter methods, the envelope kind string, the entry point group`lingologos.codex.adapters`, the work case schema version, and the ten rows of`patterns/pattern_cases.jsonl`, which are byte for byte what that revision published. The six seedenvelopes under `nodes/` do carry the adapter under its new dotted path, because naming a module that nolonger exists would make those files disagree with the code beside them. The dataset keeps its name,`tailot/codex-python`.## What this bundle needs from the codex kernel`lingologos_python` imports `lingologos_codex`, and `lingologos_python/_codex_bridge.py` resolves thatimport in one step: an already importable `lingologos_codex`, then the folder named by`LINGOLOGOS_CODEX_ROOT`, then a sibling `codex/` or a `datasets/codex/` among the ancestors of thepackage. Downloaded from here the two orders are the same folder, and the resolution is:pip install -r requirements.txtgit clone https://huggingface.co/datasets/tailot/lingologos-codexLINGOLOGOS_CODEX_ROOT=/path/to/lingologos-codex python -B -m pytest -p no:cacheprovider tests -qNothing in this bundle downloads anything at run time: the kernel is a second download you make once,and the tests fail with a named reason when it is missing rather than passing without it. The kernel6 unmodified linesof 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`lingologos_codex/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
2 unmodified lines34567897 unmodified lines171819202122232425262711 unmodified lines3940414243444546472 unmodified linesReads one JSON envelope on stdin, injects the external PythonLanguageAdapterwhen no explicit adapter or spec is already set on the dossier, delegates thestep to lgcodex.agents.run_step, and writes one JSON envelope to stdout."""from __future__ import annotations7 unmodified linesif str(PYTHON_ROOT) not in sys.path:sys.path.insert(0, str(PYTHON_ROOT))from lgpython._codex_bridge import ensure_codex_on_path # noqa: E402ensure_codex_on_path(PYTHON_ROOT)from lgcodex import agents, envelope as _envelope # noqa: E402def main() -> int:11 unmodified linesdossier = dict(_envelope.read_dossier(incoming))if not dossier.get("adapter") and not dossier.get("spec"):dossier["adapter"] = ("lgpython.adapter:StrictPythonLanguageAdapter"if args.strict_tools or dossier.get("strictTools")else "lgpython.adapter:PythonLanguageAdapter")incoming = dict(incoming)payload = dict(incoming.get("payload", {}))2 unmodified lines34567897 unmodified lines171819202122232425262711 unmodified lines3940414243444546472 unmodified linesReads one JSON envelope on stdin, injects the external PythonLanguageAdapterwhen no explicit adapter or spec is already set on the dossier, delegates thestep to lingologos_codex.agents.run_step, and writes one JSON envelope to stdout."""from __future__ import annotations7 unmodified linesif str(PYTHON_ROOT) not in sys.path:sys.path.insert(0, str(PYTHON_ROOT))from lingologos_python._codex_bridge import ensure_codex_on_path # noqa: E402ensure_codex_on_path(PYTHON_ROOT)from lingologos_codex import agents, envelope as _envelope # noqa: E402def main() -> int:11 unmodified linesdossier = dict(_envelope.read_dossier(incoming))if not dossier.get("adapter") and not dossier.get("spec"):dossier["adapter"] = ("lingologos_python.adapter:StrictPythonLanguageAdapter"if args.strict_tools or dossier.get("strictTools")else "lingologos_python.adapter:PythonLanguageAdapter")incoming = dict(incoming)payload = dict(incoming.get("payload", {}))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""External Python programming package built on top of the LingoLOGOS codex kernel."""
from lingologos_python._codex_bridge import ensure_codex_on_path, find_codex_root
ensure_codex_on_path()
from lingologos_python.adapter import ( # noqa: E402 ADAPTER_NAME, ADAPTER_VERSION, PythonLanguageAdapter, StrictPythonLanguageAdapter,)from lingologos_python.ast_graph import ( # noqa: E402 discover_python_files, extract_python_graph, module_names_for_file,)from lingologos_python.patterns import ( # noqa: E402 FAMILIES, PATTERNS, PATTERN_IDS, PatternPlan, PatternSpec, pattern_card, plan_pattern, render_card, scan_pattern,)from lingologos_python.rules import ( # noqa: E402 RULES, RULE_IDS, Edit, RuleHit, RuleMiss, Target, open_target,)from lingologos_python.session import ( # noqa: E402 PythonWorkspaceSession, SessionResult, run_topology_subprocesses,)from lingologos_python.test_selector import ( # noqa: E402 discover_test_files, is_test_file, select_python_tests,)
__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", "extract_python_graph", "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",]123456"""Module entry point for python -m lingologos_python."""
from lingologos_python.cli import main
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Locate and expose the sibling or configured LingoLOGOS codex kernel.
This module allows datasets/codex-python to remain an external package withoutcopying or modifying datasets/codex. When lingologos_codex is already importable, nothingis changed; otherwise the bridge searches LINGOLOGOS_CODEX_ROOT and ancestor datasets/codexdirectories and inserts the matching root on sys.path."""
from __future__ import annotations
import importlibimport osimport sysfrom pathlib import Pathfrom typing import Optional
def find_codex_root(start: Optional[Path] = None) -> Optional[Path]: """Return the path to the codex package root if found on disk.""" env_root = os.environ.get("LINGOLOGOS_CODEX_ROOT", "").strip() if env_root: candidate = Path(env_root).expanduser().resolve() if (candidate / "lingologos_codex").is_dir(): return candidate
anchor = (start or Path(__file__)).resolve() for parent in [anchor, *anchor.parents]: direct = parent / "lingologos_codex" if direct.is_dir(): return parent sibling_codex = parent / "codex" if (sibling_codex / "lingologos_codex").is_dir(): return sibling_codex datasets_codex = parent / "datasets" / "codex" if (datasets_codex / "lingologos_codex").is_dir(): return datasets_codex return None
def ensure_codex_on_path(start: Optional[Path] = None) -> Path: """Ensure lingologos_codex is importable and return the resolved codex root.""" try: mod = importlib.import_module("lingologos_codex") mod_file = getattr(mod, "__file__", None) if mod_file: return Path(mod_file).resolve().parent.parent except ImportError: pass
codex_root = find_codex_root(start=start) if codex_root is None: raise ImportError( "Unable to locate lingologos_codex. Install lingologos-codex or set LINGOLOGOS_CODEX_ROOT." ) codex_str = str(codex_root) if codex_str not in sys.path: sys.path.insert(0, codex_str) importlib.import_module("lingologos_codex") return codex_root123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""External Python LanguageAdapter conforming to the LingoLOGOS codex contract."""
from __future__ import annotations
import osfrom pathlib import Pathfrom typing import Dict, List, Sequence, Tuple
from lingologos_python._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lingologos_codex.adapter_contract import AdapterMetadata, BaseLanguageAdapter # noqa: E402from lingologos_codex.types import GateResult # noqa: E402
from lingologos_python.ast_graph import extract_python_graph # noqa: E402from lingologos_python.gates import ( # noqa: E402 SIGNATURE_RULES, parse_failed_targets, resolve_tool_gate_prefix, run_python_tests, run_syntax_gate, run_tool_gate,)from lingologos_python.test_selector import select_python_tests # noqa: E402
ADAPTER_NAME = "lingologos-python"ADAPTER_VERSION = "0.1.0"
DEFAULT_TOOL_ARGS: Dict[str, Tuple[str, ...]] = { "mypy": ("--ignore-missing-imports", "--no-incremental"), "pyright": (), "ruff": ("check", "--no-cache"), "flake8": (),}
class PythonLanguageAdapter(BaseLanguageAdapter): """Full-featured external Python adapter built on lingologos_codex.BaseLanguageAdapter.
By default it runs the in-process syntax and compile gate plus any static checkers explicitly requested or discovered when enabled. Calling with ``require_tools=("mypy", "ruff")`` enforces those tools strictly: when a required tool is missing on the host, the gate returns ABSTAIN so the codex arbiter refuses to guess. """
def __init__( self, workspace_root: str | Path, *, require_tools: Sequence[str] = (), use_installed_tools: bool = False, timeout_sec: float = 120.0, ) -> None: super().__init__(workspace_root, timeout_sec=timeout_sec) self.require_tools: Tuple[str, ...] = tuple(require_tools) self.use_installed_tools: bool = bool(use_installed_tools)
def meta(self) -> AdapterMetadata: return AdapterMetadata( name=ADAPTER_NAME, languages=("python",), extensions=(".py", ".pyi"), version=ADAPTER_VERSION, )
def command_env(self) -> Dict[str, str]: root_str = str(self.workspace_root) existing = os.environ.get("PYTHONPATH", "") pythonpath = f"{root_str}{os.pathsep}{existing}" if existing else root_str return {"PYTHONDONTWRITEBYTECODE": "1", "PYTHONPATH": pythonpath}
def extract_symbols_and_edges( self, workspace: str, files: Sequence[str] ) -> Tuple[List[str], List[Tuple[str, str]]]: cwd = self._checked_cwd(workspace) return extract_python_graph(cwd, files)
def select_tests(self, workspace: str, changed_files: Sequence[str]) -> List[str]: cwd = self._checked_cwd(workspace) return select_python_tests(cwd, changed_files)
def run_typecheck_and_lint( self, workspace: str, target_files: Sequence[str] ) -> List[GateResult]: cwd = self._checked_cwd(workspace) gates: List[GateResult] = [run_syntax_gate(cwd, target_files)] if not target_files: return gates
tools_to_run: List[str] = list(self.require_tools) if self.use_installed_tools: for candidate in ("mypy", "ruff"): if candidate not in tools_to_run and resolve_tool_gate_prefix(candidate) is not None: tools_to_run.append(candidate)
for tool in tools_to_run: args = DEFAULT_TOOL_ARGS.get(tool, ()) gates.append(run_tool_gate(self, cwd, tool, args, target_files)) return gates
def run_tests( self, workspace: str, targets: Sequence[str], full_suite: bool = False ) -> GateResult: cwd = self._checked_cwd(workspace) return run_python_tests(self, cwd, targets, full_suite=full_suite)
def failed_targets_from_output(self, output: str) -> Tuple[str, ...]: return parse_failed_targets(output)
def signature_rules(self) -> Tuple[Tuple[str, str], ...]: return SIGNATURE_RULES
class StrictPythonLanguageAdapter(PythonLanguageAdapter): """Variant that always demands mypy and ruff, abstaining when either is absent."""
def __init__(self, workspace_root: str | Path, timeout_sec: float = 120.0) -> None: super().__init__( workspace_root, require_tools=("mypy", "ruff"), use_installed_tools=False, timeout_sec=timeout_sec, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298"""Python AST symbol, import, inheritance, and call graph extractor.
Nothing here executes user code or writes bytecode to disk. Files that failto parse are skipped so the syntax gate owns syntax diagnostics."""
from __future__ import annotations
import astimport osfrom pathlib import Pathfrom typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple
IGNORED_DIRS: frozenset[str] = frozenset( { ".git", ".hg", ".svn", "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox", ".nox", ".venv", "venv", "env", "node_modules", "build", "dist", })
def _is_ignored(rel_parts: Sequence[str]) -> bool: for part in rel_parts[:-1]: if part in IGNORED_DIRS or part.endswith(".egg-info"): return True return False
def discover_python_files(workspace: Path) -> List[str]: """Return sorted POSIX relative paths for all Python source files in workspace.""" root = workspace.resolve() found: List[str] = [] for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = sorted( d for d in dirnames if d not in IGNORED_DIRS and not d.endswith(".egg-info") ) rel_dir = Path(dirpath).resolve().relative_to(root) for filename in sorted(filenames): if not filename.endswith(".py"): continue rel_path = (rel_dir / filename).as_posix() if rel_dir.parts else filename if not _is_ignored(rel_path.split("/")): found.append(rel_path) return sorted(found)
def module_names_for_file(rel_posix: str) -> List[str]: """Return candidate dotted module names for a relative Python path.""" parts = [p for p in rel_posix.replace("\\", "/").split("/") if p] if not parts: return [] if parts[-1] == "__init__.py": base_parts = parts[:-1] elif parts[-1].endswith(".py"): base_parts = [*parts[:-1], parts[-1][:-3]] else: base_parts = parts
candidates: List[str] = [] for start in range(len(base_parts)): dotted = ".".join(base_parts[start:]) if dotted and dotted not in candidates: candidates.append(dotted) if len(base_parts) > 1 and base_parts[0] in ("src", "lib", "python"): stripped = ".".join(base_parts[1:]) if stripped and stripped not in candidates: candidates.append(stripped) return candidates
def _read_source(workspace: Path, rel_posix: str) -> Optional[str]: target = workspace / Path(*rel_posix.replace("\\", "/").split("/")) if not target.is_file() or target.is_symlink(): return None try: return target.read_text(encoding="utf-8", errors="replace") except OSError: return None
def _collect_definitions( tree: ast.Module,) -> Tuple[List[str], Dict[str, List[str]], Dict[str, Set[str]]]: """Return symbol names, class-to-base-names map, and call map.""" symbols: List[str] = [] bases_by_class: Dict[str, List[str]] = {} calls_by_symbol: Dict[str, Set[str]] = {}
for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): symbols.append(node.name) calls_by_symbol[node.name] = _called_names(node) elif isinstance(node, ast.ClassDef): symbols.append(node.name) bases_by_class[node.name] = [_expr_name(base) for base in node.bases if _expr_name(base)] for item in node.body: if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): qualified = f"{node.name}.{item.name}" symbols.append(qualified) calls_by_symbol[qualified] = _called_names(item) return symbols, bases_by_class, calls_by_symbol
def _expr_name(node: ast.AST) -> str: if isinstance(node, ast.Name): return node.id if isinstance(node, ast.Attribute): prefix = _expr_name(node.value) return f"{prefix}.{node.attr}" if prefix else node.attr return ""
def _called_names(func_node: ast.AST) -> Set[str]: called: Set[str] = set() for inner in ast.walk(func_node): if isinstance(inner, ast.Call): if isinstance(inner.func, ast.Name): called.add(inner.func.id) elif isinstance(inner.func, ast.Attribute): called.add(inner.func.attr) full = _expr_name(inner.func) if full: called.add(full) return called
def _resolve_relative_module(rel_posix: str, level: int, module: Optional[str]) -> str: parts = rel_posix.replace("\\", "/").split("/") package_parts = parts[:-1] if level > len(package_parts): base_parts: List[str] = [] else: base_parts = package_parts[: len(package_parts) - (level - 1)] if module: return ".".join([*base_parts, *module.split(".")]) return ".".join(base_parts)
def _extract_imports( rel_posix: str, tree: ast.Module) -> Tuple[List[str], Dict[str, Tuple[str, str]]]: """Return imported module names and local-alias -> (module, imported_name) map.""" modules: List[str] = [] alias_map: Dict[str, Tuple[str, str]] = {}
for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: if alias.name not in modules: modules.append(alias.name) local = alias.asname or alias.name.split(".")[0] alias_map[local] = (alias.name, "") elif isinstance(node, ast.ImportFrom): if node.level > 0: mod_name = _resolve_relative_module(rel_posix, node.level, node.module) else: mod_name = node.module or "" if mod_name and mod_name not in modules: modules.append(mod_name) for alias in node.names: if alias.name == "*": continue local = alias.asname or alias.name if mod_name: alias_map[local] = (mod_name, alias.name) if not alias.asname: sub_mod = f"{mod_name}.{alias.name}" if sub_mod not in modules: modules.append(sub_mod) return modules, alias_map
def _match_module_file( module_name: str, files_by_module: Dict[str, str], all_files: Sequence[str], current_file: str,) -> Optional[str]: if module_name in files_by_module and files_by_module[module_name] != current_file: return files_by_module[module_name] leaf = module_name.split(".")[-1] for other in all_files: if other == current_file: continue if Path(other).stem == leaf: return other return None
def extract_python_graph( workspace: Path, files: Sequence[str]) -> Tuple[List[str], List[Tuple[str, str]]]: """Extract qualified Python symbols and dependency edges over workspace files.""" normalized_files = [f.replace("\\", "/") for f in files if f] files_by_module: Dict[str, str] = {} for rel in normalized_files: for mod in module_names_for_file(rel): files_by_module.setdefault(mod, rel)
parsed: Dict[str, ast.Module] = {} defs_by_file: Dict[str, List[str]] = {} bases_by_file: Dict[str, Dict[str, List[str]]] = {} calls_by_file: Dict[str, Dict[str, Set[str]]] = {} imports_by_file: Dict[str, Tuple[List[str], Dict[str, Tuple[str, str]]]] = {}
symbols: Set[str] = set() edges: Set[Tuple[str, str]] = set()
for rel in normalized_files: source = _read_source(workspace, rel) if source is None: symbols.add(rel) continue try: tree = ast.parse(source, filename=rel) except SyntaxError: symbols.add(rel) continue parsed[rel] = tree names, bases, calls = _collect_definitions(tree) defs_by_file[rel] = names bases_by_file[rel] = bases calls_by_file[rel] = calls imports_by_file[rel] = _extract_imports(rel, tree) if names: for name in names: symbols.add(f"{rel}::{name}") else: symbols.add(rel)
for rel in parsed: local_names = set(defs_by_file.get(rel, ())) modules, alias_map = imports_by_file.get(rel, ([], {}))
# File-level import edges for mod in modules: target_file = _match_module_file(mod, files_by_module, normalized_files, rel) if target_file: edges.add((rel, target_file))
# Inheritance edges for cls_name, base_list in bases_by_file.get(rel, {}).items(): src_sym = f"{rel}::{cls_name}" for base_name in base_list: short = base_name.split(".")[-1] if base_name in local_names and base_name != cls_name: edges.add((src_sym, f"{rel}::{base_name}")) elif short in alias_map: mod_name, imported_sym = alias_map[short] target_file = _match_module_file(mod_name, files_by_module, normalized_files, rel) if target_file: sym_name = imported_sym or short if sym_name in defs_by_file.get(target_file, ()): edges.add((src_sym, f"{target_file}::{sym_name}")) else: edges.add((src_sym, target_file))
# Intra-file and cross-file call edges for caller, called_set in calls_by_file.get(rel, {}).items(): src_sym = f"{rel}::{caller}" owner_class = caller.split(".")[0] if "." in caller else "" for called in called_set: if called in local_names and called != caller: edges.add((src_sym, f"{rel}::{called}")) elif owner_class and f"{owner_class}.{called}" in local_names: target_method = f"{owner_class}.{called}" if target_method != caller: edges.add((src_sym, f"{rel}::{target_method}")) else: head = called.split(".")[0] if head in alias_map: mod_name, imported_sym = alias_map[head] target_file = _match_module_file( mod_name, files_by_module, normalized_files, rel ) if target_file: candidate = imported_sym or ( called.split(".", 1)[1] if "." in called else "" ) if candidate and candidate in defs_by_file.get(target_file, ()): edges.add((src_sym, f"{target_file}::{candidate}")) else: edges.add((src_sym, target_file))
return sorted(symbols), sorted(edges)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276"""Command-line interface for the external LingoLOGOS Python programming package."""
from __future__ import annotations
import argparseimport jsonimport sysfrom dataclasses import asdictfrom pathlib import Pathfrom typing import List, Optional, Sequence
from lingologos_python._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lingologos_codex.adapter_contract import check_adapter_contract # noqa: E402from lingologos_codex.graph import compute_symbol_pagerank, top_symbols # noqa: E402
from lingologos_python.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter # noqa: E402from lingologos_python.ast_graph import discover_python_files, extract_python_graph # noqa: E402from lingologos_python.patterns import PATTERNS, pattern_card, render_card, scan_pattern # noqa: E402from lingologos_python.session import PythonWorkspaceSession # noqa: E402from lingologos_python.test_selector import select_python_tests # noqa: E402
def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="lingologos_python", description="Python programming workbench and language adapter powered by LingoLOGOS codex.", ) sub = parser.add_subparsers(dest="command", required=True)
# verify p_verify = sub.add_parser("verify", help="Verify a Python workspace through the six-node codex pipeline.") p_verify.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_verify.add_argument("--file", default=None, help="Optional relative Python file to focus on.") p_verify.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") p_verify.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.") p_verify.add_argument("--json", action="store_true", help="Print JSON output.")
# edit p_edit = sub.add_parser("edit", help="Propose, verify, and atomically commit a Python search-replace edit.") p_edit.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_edit.add_argument("--file", required=True, help="Relative Python file to edit.") p_edit.add_argument("--search", required=True, help="Search text block.") p_edit.add_argument("--replace", required=True, help="Replacement text block.") p_edit.add_argument("--dry-run", action="store_true", help="Verify without committing to disk.") p_edit.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") p_edit.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.") p_edit.add_argument("--allow-single-prover", action="store_true", help="Allow commit at assurance 2.") p_edit.add_argument("--json", action="store_true", help="Print JSON output.")
# create p_create = sub.add_parser("create", help="Create a new Python file after full codex verification.") p_create.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_create.add_argument("--file", required=True, help="Relative Python file path to create.") p_create.add_argument("--content-file", required=True, help="Path to file holding Python source content.") p_create.add_argument("--dry-run", action="store_true", help="Verify without committing to disk.") p_create.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") p_create.add_argument("--json", action="store_true", help="Print JSON output.")
# symbols p_sym = sub.add_parser("symbols", help="Extract Python AST symbols, edges, and PageRank.") p_sym.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_sym.add_argument("--files", nargs="*", default=None, help="Optional relative Python files.") p_sym.add_argument("--limit", type=int, default=10, help="Maximum top symbols to display.") p_sym.add_argument("--json", action="store_true", help="Print JSON output.")
# select-tests p_tests = sub.add_parser("select-tests", help="Select Python test files impacted by changed files.") p_tests.add_argument("--workspace", required=True, help="Target Python workspace directory.") 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.") p_check.add_argument("--strict-tools", action="store_true", help="Check StrictPythonLanguageAdapter.") p_check.add_argument("--json", action="store_true", help="Print JSON output.")
return parser
def main(argv: Optional[Sequence[str]] = None) -> int: parser = _build_parser() args = parser.parse_args(argv)
if args.command == "verify": session = PythonWorkspaceSession( args.workspace, strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, ) res = session.verify(target_file=args.file) if args.json: print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) else: print(f"{res.verdict} (assurance {res.assurance}) {res.reason}: {res.detail}") return 0 if res.accepted else 1
if args.command == "edit": min_assurance = 2 if args.allow_single_prover else 3 session = PythonWorkspaceSession( args.workspace, strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, min_assurance=min_assurance, ) res = session.edit_file( args.file, args.search, args.replace, commit=not args.dry_run, ) if args.json: print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) else: print( f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) " f"{res.reason}: {res.detail}" ) return 0 if res.assurance >= min_assurance else 1
if args.command == "create": content = Path(args.content_file).read_text(encoding="utf-8", newline="") session = PythonWorkspaceSession(args.workspace, strict_tools=args.strict_tools) res = session.create_file(args.file, content, commit=not args.dry_run) if args.json: print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) else: print( f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) " f"{res.reason}: {res.detail}" ) return 0 if res.accepted else 1
if args.command == "symbols": root = Path(args.workspace).resolve() files: List[str] = args.files if args.files else discover_python_files(root) symbols, edges = extract_python_graph(root, files) ranks = compute_symbol_pagerank(symbols, edges) top = top_symbols(ranks, limit=args.limit) if args.json: print( json.dumps( { "files": files, "symbols": symbols, "edges": [list(e) for e in edges], "top": [[name, score] for name, score in top], }, indent=2, ) ) else: print(f"files={len(files)} symbols={len(symbols)} edges={len(edges)}") for name, score in top: print(f" {score:.4f} {name}") return 0
if args.command == "select-tests": root = Path(args.workspace).resolve() selected = select_python_tests(root, args.files) if args.json: print(json.dumps({"selected_tests": selected}, indent=2)) else: for item in selected: 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": specs = [PATTERNS[name] for name in sorted(PATTERNS)] 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 specs ] if args.json: print(json.dumps({"patterns": rows}, indent=2, sort_keys=True)) else: for spec in specs: 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 = ( StrictPythonLanguageAdapter(root) if args.strict_tools else PythonLanguageAdapter(root) ) sample_files = discover_python_files(root)[:3] violations = check_adapter_contract(adapter, str(root), sample_files) if args.json: print( json.dumps( {"adapter": adapter.meta().name, "violations": violations}, indent=2, ) ) else: if violations: for v in violations: print(f"VIOLATION: {v}") else: print(f"ADAPTER OK: {adapter.meta().name}") return 1 if violations else 0
return 2
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"""Python quality and test gates with strict three-valued outcomes.
Every gate returns GateResult(CONFIRMED | REJECTED | ABSTAIN). A missingtoolchain never produces CONFIRMED or REJECTED; it returns ABSTAIN with aclear diagnostic note so the codex decision rule can block honestly."""
from __future__ import annotations
import astimport importlib.utilimport reimport shutilimport sysfrom pathlib import Pathfrom typing import TYPE_CHECKING, List, Sequence, Tuple
from lingologos_python._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lingologos_codex.types import ABSTAIN, CONFIRMED, REJECTED, GateResult # noqa: E402
if TYPE_CHECKING: from lingologos_codex.adapter_contract import BaseLanguageAdapter
FAILED_TARGET_PATTERNS: Tuple[str, ...] = ( r"FAILED (?P<target>[\w./\\-]+(?:::\S+)?)", r"^(?P<target>[\w./\\-]+\.py):\d+:", r'E\s+File "(?P<target>[^"]+)"', r'File "(?P<target>[^"]+\.py)", line \d+', r"ERROR: .* \((?P<target>[\w./\\-]+\.py)\)",)
SIGNATURE_RULES: Tuple[Tuple[str, str], ...] = ( (r"in [\d.]+s", "in <t>"), (r"Ran \d+ tests? in [\d.]+s", "Ran <n> tests in <t>"), (r"rootdir: \S+", "rootdir: <path>"), (r"plugins?: \S.*", "plugins: <set>"), (r"Found \d+ errors? in \d+ files?", "Found <n> errors in <m> files"),)
def _read_text_safe(cwd: Path, rel: str) -> str | None: target = cwd / Path(*rel.replace("\\", "/").split("/")) if not target.is_file() or target.is_symlink(): return None try: return target.read_text(encoding="utf-8", errors="replace") except OSError: return None
def has_python_module(module_name: str) -> bool: """Return True when module_name is importable in the active Python interpreter.""" return importlib.util.find_spec(module_name) is not None
def resolve_tool_argv(tool: str) -> List[str] | None: """Resolve a CLI tool binary on PATH or via python -m <tool>.""" binary = shutil.which(tool) if binary: return [binary] if has_python_module(tool): return [sys.executable, "-m", tool] return None
def run_syntax_gate(cwd: Path, target_files: Sequence[str]) -> GateResult: """Validate Python syntax and code-object compilation in memory without writing .pyc.""" files = [f.replace("\\", "/") for f in target_files if f] if not files: return GateResult(CONFIRMED, "ast.parse + compile (no target files)")
broken: List[str] = [] failed: List[str] = [] for rel in files: source = _read_text_safe(cwd, rel) if source is None: broken.append(f"{rel}: unreadable or missing") failed.append(rel) continue try: tree = ast.parse(source, filename=rel) compile(tree, filename=rel, mode="exec", dont_inherit=True) except SyntaxError as exc: broken.append(f"{rel}: line {exc.lineno}: {exc.msg}") failed.append(rel) except ValueError as exc: broken.append(f"{rel}: {exc}") failed.append(rel)
command = "ast.parse " + " ".join(files) if broken: return GateResult( REJECTED, command, output="\n".join(broken), failed_targets=tuple(failed), note=f"{len(broken)} file(s) failed syntax verification", ) return GateResult(CONFIRMED, command)
def run_tool_gate( adapter: BaseLanguageAdapter, cwd: Path, tool: str, args: Sequence[str], target_files: Sequence[str],) -> GateResult: """Run an external Python static checker or return ABSTAIN when unavailable.""" argv_prefix = resolve_tool_gate_prefix(tool) if argv_prefix is None: return GateResult( ABSTAIN, f"{tool} {' '.join(args)}".strip(), note=f"{tool} is not installed on this host, the gate has no judgement", ) if not target_files: return GateResult(CONFIRMED, f"{tool} (no target files)") return adapter.run_command( cwd.as_posix(), [*argv_prefix, *args, *[f.replace("\\", "/") for f in target_files]], gate_name=tool, )
def resolve_tool_gate_prefix(tool: str) -> List[str] | None: """Resolve supported Python static analysis tools.""" return resolve_tool_argv(tool)
def run_python_tests( adapter: BaseLanguageAdapter, cwd: Path, targets: Sequence[str], full_suite: bool = False,) -> GateResult: """Run pytest (no cacheprovider) or fall back to unittest discovery.""" if resolve_tool_argv("pytest") is not None: argv = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"] if full_suite or not targets: return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") return adapter.run_command( cwd.as_posix(), argv + [t.replace("\\", "/") for t in targets], gate_name="selected_tests", )
if has_python_module("unittest"): if full_suite or not targets: argv = [sys.executable, "-m", "unittest", "discover", "-q"] return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") argv = [sys.executable, "-m", "unittest", "-q", *[t.replace("\\", "/") for t in targets]] return adapter.run_command(cwd.as_posix(), argv, gate_name="selected_tests")
return GateResult( ABSTAIN, "python -m pytest", note="neither pytest nor unittest is available in this interpreter", )
def parse_failed_targets(output: str) -> Tuple[str, ...]: """Extract normalized failed target paths or node ids from Python tool output.""" found: List[str] = [] for pattern in FAILED_TARGET_PATTERNS: for match in re.finditer(pattern, output, re.MULTILINE): value = match.group("target").replace("\\", "/") if value and value not in found: found.append(value) return tuple(found[:50])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 ``lingologos_python.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 lingologos_python import rulesfrom lingologos_python.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))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755"""Transactional Python programming session built on the LingoLOGOS codex kernel.
A change is staged in an isolated copy of the workspace, evaluated by thesix-node codex pipeline (either in-process or as six isolated subprocesseswalking datasets/codex-python/topology.json), and committed atomically to the realworkspace via lingologos_codex.fsadapter only when the arbiter reaches the requiredassurance threshold."""
from __future__ import annotations
import jsonimport osimport shutilimport subprocessimport sysimport tempfilefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
from lingologos_python._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lingologos_codex import envelope as _envelope # noqa: E402from lingologos_codex.agents import ROLES, run_pipeline # noqa: E402from lingologos_codex.failures import detect_stall_from_hashes # noqa: E402from lingologos_codex.fsadapter import create_os_filesystem_adapter # noqa: E402from lingologos_codex.fspolicy import ( # noqa: E402 EOL_PRESERVE, FSPolicy, OP_DELETE, OP_WRITE, PathGuard, PathSecurityError, PlannedOp,)from lingologos_codex.patcher import ( # noqa: E402 FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch,)
from lingologos_python.ast_graph import IGNORED_DIRS, discover_python_files # noqa: E402from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E402
PYTHON_ROOT = Path(__file__).resolve().parent.parentDEFAULT_AGENT_SCRIPT = PYTHON_ROOT / "agents" / "python_agent.py"DEFAULT_TOPOLOGY_PATH = PYTHON_ROOT / "topology.json"
DEFAULT_ALLOWED_PATTERNS: Tuple[str, ...] = ("*.py", "*.pyi")DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ( "*.env", ".env*", "*.pem", "*.key", ".git/*", "__pycache__/*",)
ADAPTER_REF_DEFAULT = "lingologos_python.adapter:PythonLanguageAdapter"ADAPTER_REF_STRICT = "lingologos_python.adapter:StrictPythonLanguageAdapter"DEFAULT_GATES: Tuple[str, ...] = ("typecheck", "tests")
@dataclass(frozen=True)class SessionResult: """Outcome of running the six-node codex pipeline over a Python workspace."""
case_id: str verdict: str assurance: int reason: str detail: str committed: bool touched_files: Tuple[str, ...] = () trace: Tuple[Dict[str, Any], ...] = field(default_factory=tuple) dossier: Dict[str, Any] = field(default_factory=dict)
@property def accepted(self) -> bool: return self.verdict in ("VERIFIED", "SINGLE_PROVER")
def to_dict(self) -> Dict[str, Any]: return { "case_id": self.case_id, "verdict": self.verdict, "assurance": self.assurance, "reason": self.reason, "detail": self.detail, "committed": self.committed, "touched_files": list(self.touched_files), "decision": dict(self.dossier.get("decision", {})), "gates": list(self.dossier.get("gates", [])), "checkers": list(self.dossier.get("checkers", [])), }
def _copy_workspace_for_staging(src_root: Path, dst_root: Path) -> None: """Copy a workspace cleanly without caches or virtual environments.""" for dirpath, dirnames, filenames in os.walk(src_root): dirnames[:] = [ d for d in dirnames if d not in IGNORED_DIRS and not d.endswith(".egg-info") ] rel_dir = Path(dirpath).resolve().relative_to(src_root.resolve()) target_dir = dst_root / rel_dir target_dir.mkdir(parents=True, exist_ok=True) for name in filenames: src_file = Path(dirpath) / name if src_file.is_symlink(): continue shutil.copy2(src_file, target_dir / name)
def _subprocess_env() -> Dict[str, str]: env = dict(os.environ) env["PYTHONDONTWRITEBYTECODE"] = "1" python_pkg_root = str(PYTHON_ROOT) codex_root = str(ensure_codex_on_path()) existing = env.get("PYTHONPATH", "") parts = [python_pkg_root, codex_root] if existing: parts.append(existing) env["PYTHONPATH"] = os.pathsep.join(parts) return env
def run_topology_subprocesses( case: Dict[str, Any], *, agent_script: Path = DEFAULT_AGENT_SCRIPT, timeout_sec: float = 120.0,) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: """Execute the six roles via isolated node subprocesses communicating over JSON stdio.""" seed = _envelope.make_envelope("arbiter", 0, 0, "task received", dict(case)) trace: List[Dict[str, Any]] = [seed] current = seed env = _subprocess_env()
for role in ROLES: cmd = [sys.executable, "-B", str(agent_script), "--role", role, "--node-id", role] completed = subprocess.run( cmd, input=json.dumps(current), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout_sec, cwd=str(PYTHON_ROOT), env=env, ) if completed.returncode != 0: raise RuntimeError( f"node '{role}' exited with {completed.returncode}: {completed.stderr.strip()}" ) current = json.loads(completed.stdout) trace.append(current) return trace, _envelope.read_dossier(current)
class PythonWorkspaceSession: """High-level interface to inspect, edit, verify, and commit Python code via codex."""
def __init__( self, workspace_root: str | Path, *, allowed_patterns: Sequence[str] = DEFAULT_ALLOWED_PATTERNS, protected_patterns: Sequence[str] = DEFAULT_PROTECTED_PATTERNS, required_gates: Sequence[str] = DEFAULT_GATES, strict_tools: bool = False, spec_path: Optional[str | Path] = None, use_subprocesses: bool = False, min_assurance: int = 3, ) -> None: self.workspace_root = Path(workspace_root).resolve() if not self.workspace_root.is_dir(): raise FileNotFoundError(f"workspace does not exist: '{self.workspace_root}'") self.allowed_patterns = tuple(allowed_patterns) self.protected_patterns = tuple(protected_patterns) self.required_gates = tuple(required_gates) self.strict_tools = bool(strict_tools) self.spec_path = str(Path(spec_path).resolve()) if spec_path else None self.use_subprocesses = bool(use_subprocesses) self.min_assurance = int(min_assurance)
def policy_dict(self, root: Optional[Path] = None) -> Dict[str, Any]: return { "repo_root": str((root or self.workspace_root).resolve()), "allowed_patterns": list(self.allowed_patterns), "protected_patterns": list(self.protected_patterns), "default_eol": EOL_PRESERVE, }
def policy(self, root: Optional[Path] = None) -> FSPolicy: return FSPolicy( repo_root=str((root or self.workspace_root).resolve()), allowed_patterns=self.allowed_patterns, protected_patterns=self.protected_patterns, case_insensitive=(os.name == "nt"), default_eol=EOL_PRESERVE, )
def _os_fs(self, root: Path, *, check_allowed: bool = True): policy = FSPolicy( repo_root=str(root.resolve()), allowed_patterns=self.allowed_patterns if check_allowed else (), protected_patterns=self.protected_patterns, case_insensitive=(os.name == "nt"), default_eol=EOL_PRESERVE, ) fs = create_os_filesystem_adapter( root, protected_patterns=self.protected_patterns, allowed_patterns=self.allowed_patterns if check_allowed else (), ) fs.policy = policy fs.guard = PathGuard(policy) return fs
def _adapter_fields(self) -> Dict[str, Any]: if self.spec_path: return {"spec": self.spec_path} return {"adapter": ADAPTER_REF_STRICT if self.strict_tools else ADAPTER_REF_DEFAULT}
def _run_six_nodes(self, case: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: if self.use_subprocesses: return run_topology_subprocesses(case) return run_pipeline(case)
def list_files(self) -> List[str]: """Return all Python source files in the workspace.""" return discover_python_files(self.workspace_root)
def verify( self, target_file: Optional[str] = None, *, case_id: str = "python-verify", note: str = "verify Python workspace against codex gates", ) -> SessionResult: """Verify an existing file or the whole Python workspace without modifying disk.""" py_files = self.list_files() chosen = (target_file or (py_files[0] if py_files else "src/__init__.py")).replace("\\", "/") target_path = self.workspace_root / Path(*chosen.split("/")) if target_path.is_file(): text = target_path.read_text(encoding="utf-8", newline="") else: text = ""
# Verify without changing file content by probing a non-mutating exact check # over a temporary staging copy so real workspace files remain untouched. lines = text.splitlines(keepends=True) if lines: first_line = lines[0] probe_search = first_line probe_replace = first_line.rstrip("\r\n") + " # codex-verify-probe\n" original_for_patch = text else: probe_search = "# empty" probe_replace = "# empty verified" original_for_patch = "# empty\n"
case: Dict[str, Any] = { "case_id": case_id, "workspace": str(self.workspace_root), "file": chosen, "text": original_for_patch, "search": probe_search, "replace": probe_replace, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) return SessionResult( case_id=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=(chosen,), trace=tuple(trace), dossier=dossier, )
def edit_file( self, rel_path: str, search: str, replace: str, *, case_id: str = "python-edit", note: str = "apply controlled search-and-replace edit", commit: bool = True, attempt_signatures: Sequence[str] = (), patch_config: FuzzyPatchConfig = FuzzyPatchConfig(), ) -> SessionResult: """Stage a search-and-replace edit, verify via codex, and commit atomically on pass.""" rel_posix = rel_path.replace("\\", "/") guard = PathGuard(self.policy())
# Check path policy before touching or staging anything try: plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content="")]) except PathSecurityError: case = { "case_id": case_id, "workspace": str(self.workspace_root), "file": rel_posix, "text": "", "search": search, "replace": replace, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(), "attemptSignatures": list(attempt_signatures), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) return SessionResult( case_id=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=(rel_posix,), trace=tuple(trace), dossier=dossier, )
target = self.workspace_root / Path(*rel_posix.split("/")) original_text = target.read_text(encoding="utf-8", newline="") if target.is_file() else "" patch_res = apply_controlled_fuzzy_patch( original_text, SearchReplaceBlock(search, replace), patch_config )
with tempfile.TemporaryDirectory(prefix="lingologos_python_stage_") as tmp_dir: staged_root = Path(tmp_dir).resolve() _copy_workspace_for_staging(self.workspace_root, staged_root) if patch_res.applied and not plan.rejected: staged_fs = self._os_fs(staged_root) tx = staged_fs.begin_transaction() staged_fs.stage_write_text(tx, rel_posix, patch_res.updated_text) staged_fs.commit_transaction(tx)
case = { "case_id": case_id, "workspace": str(staged_root), "file": rel_posix, "text": original_text, "search": search, "replace": replace, "note": note, "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": list(attempt_signatures), **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 patch_res.applied and not plan.rejected and assurance >= self.min_assurance: real_fs = self._os_fs(self.workspace_root) tx = real_fs.begin_transaction() real_fs.stage_write_text(tx, rel_posix, patch_res.updated_text) real_fs.commit_transaction(tx) committed = True
return SessionResult( case_id=case_id, verdict=verdict, assurance=assurance, reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=committed, touched_files=(rel_posix,), trace=tuple(trace), 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="lingologos_python_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, content: str, *, case_id: str = "python-create", note: str = "create verified Python module", commit: bool = True, ) -> SessionResult: """Create a new Python file, verifying it in isolation before committing.""" rel_posix = rel_path.replace("\\", "/") target = self.workspace_root / Path(*rel_posix.split("/")) if target.exists(): raise FileExistsError(f"target already exists: '{rel_posix}'")
guard = PathGuard(self.policy()) try: plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content=content)]) except PathSecurityError: return self.edit_file(rel_posix, "# NEW_FILE", content, case_id=case_id, note=note, commit=False)
marker = "# __LGPYTHON_NEW_FILE__\n" with tempfile.TemporaryDirectory(prefix="lingologos_python_create_") as tmp_dir: staged_root = Path(tmp_dir).resolve() _copy_workspace_for_staging(self.workspace_root, staged_root) if not plan.rejected: staged_fs = self._os_fs(staged_root) tx = staged_fs.begin_transaction() staged_fs.stage_write_text(tx, rel_posix, content) staged_fs.commit_transaction(tx)
case = { "case_id": case_id, "workspace": str(staged_root), "file": rel_posix, "text": marker, "search": marker, "replace": content, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), **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 not plan.rejected and assurance >= self.min_assurance: real_fs = self._os_fs(self.workspace_root) tx = real_fs.begin_transaction() real_fs.stage_write_text(tx, rel_posix, content) real_fs.commit_transaction(tx) committed = True
return SessionResult( case_id=case_id, verdict=verdict, assurance=assurance, reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=committed, touched_files=(rel_posix,), trace=tuple(trace), dossier=dossier, )
def delete_file( self, rel_path: str, *, case_id: str = "python-delete", note: str = "delete Python module with full regression check", commit: bool = True, ) -> SessionResult: """Delete a Python file only if the full regression passes after removal.""" rel_posix = rel_path.replace("\\", "/") guard = PathGuard(self.policy()) try: plan = guard.plan_transaction([PlannedOp(op=OP_DELETE, rel_posix=rel_posix)]) except PathSecurityError: return self.edit_file(rel_posix, "# DELETE", "", case_id=case_id, note=note, commit=False)
target = self.workspace_root / Path(*rel_posix.split("/")) if not target.is_file(): raise FileNotFoundError(f"target file does not exist: '{rel_posix}'") original_text = target.read_text(encoding="utf-8", newline="")
with tempfile.TemporaryDirectory(prefix="lingologos_python_delete_") as tmp_dir: staged_root = Path(tmp_dir).resolve() _copy_workspace_for_staging(self.workspace_root, staged_root) if not plan.rejected: # Unlink only the target file; lingologos_codex.fsadapter.stage_delete walks parent dirs. staged_target = staged_root / Path(*rel_posix.split("/")) if staged_target.is_file() and not staged_target.is_symlink(): staged_target.unlink()
# Evaluate syntax over remaining files by targeting a surviving file if available remaining = [p for p in discover_python_files(staged_root) if p != rel_posix] gate_target = remaining[0] if remaining else rel_posix case = { "case_id": case_id, "workspace": str(staged_root), "file": gate_target, "text": original_text, "search": original_text if original_text.strip() else "# empty", "replace": "# deleted\n", "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), **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 not plan.rejected and assurance >= self.min_assurance: guard.resolve_safe(rel_posix, for_write=True) current = self.workspace_root for part in Path(*rel_posix.split("/")).parts: current = current / part if current.is_symlink(): raise PathSecurityError(f"refusing to delete across symlink: '{rel_posix}'") if target.is_file(): target.unlink() committed = True
return SessionResult( case_id=case_id, verdict=verdict, assurance=assurance, reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=committed, touched_files=(rel_posix,), trace=tuple(trace), dossier=dossier, )
def run_retry_loop( self, rel_path: str, proposer: Callable[[int, Optional[SessionResult]], Tuple[str, str]], *, max_attempts: int = 4, commit: bool = True, ) -> Tuple[SessionResult, List[SessionResult]]: """Run bounded edit attempts using codex stall detection to stop identical or cyclic failures.""" history: List[str] = [] attempts: List[SessionResult] = [] last: Optional[SessionResult] = None
for idx in range(1, max_attempts + 1): search, replace = proposer(idx, last) result = self.edit_file( rel_path, search, replace, case_id=f"retry-{idx}", commit=commit, attempt_signatures=history, ) attempts.append(result) last = result sig = str(result.dossier.get("patchSignature", "")) if sig: history.append(sig) if result.assurance >= self.min_assurance: return result, attempts if detect_stall_from_hashes(history) is not None: return result, attempts assert last is not None return last, attempts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Import-aware Python test discovery and selection."""
from __future__ import annotations
import astfrom pathlib import Pathfrom typing import Dict, List, Sequence, Set
from lingologos_python.ast_graph import ( discover_python_files, extract_python_graph, module_names_for_file,)
def is_test_file(rel_posix: str) -> bool: """Return True when a relative path follows Python test file naming conventions.""" name = Path(rel_posix).name return name.startswith("test_") and name.endswith(".py") or name.endswith("_test.py")
def discover_test_files(workspace: Path) -> List[str]: """Return sorted POSIX relative paths of all test files in workspace.""" all_py = discover_python_files(workspace) tests_first = [p for p in all_py if is_test_file(p) and (p.startswith("tests/") or "/tests/" in p)] others = [p for p in all_py if is_test_file(p) and p not in tests_first] return tests_first + others
def _naming_candidates(rel_posix: str) -> List[str]: parts = [p for p in rel_posix.replace("\\", "/").split("/") if p] if not parts: return [] stem = Path(parts[-1]).stem test_names = (f"test_{stem}.py", f"{stem}_test.py") candidates: List[str] = [] for tname in test_names: if len(parts) > 1: candidates.append("/".join([*parts[:-1], tname])) else: candidates.append(tname) candidates.append(f"tests/{tname}") candidates.append(f"tests/{stem}/{tname}") if len(parts) > 2 and parts[0] in ("src", "lib", "python"): sub_dir = "/".join(parts[1:-1]) candidates.append(f"tests/{sub_dir}/{tname}") return candidates
def _imported_names_in_file(path: Path) -> Set[str]: try: source = path.read_text(encoding="utf-8", errors="replace") tree = ast.parse(source, filename=str(path)) except (OSError, SyntaxError): return set()
imported: Set[str] = set() for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: imported.add(alias.name) imported.add(alias.name.split(".")[-1]) elif isinstance(node, ast.ImportFrom): if node.module: imported.add(node.module) imported.add(node.module.split(".")[-1]) for alias in node.names: if alias.name != "*": imported.add(alias.name) if node.module: imported.add(f"{node.module}.{alias.name}") return imported
def select_python_tests(workspace: Path, changed_files: Sequence[str]) -> List[str]: """Select test file paths relevant to changed_files using naming and AST imports.""" root = workspace.resolve() all_tests = discover_test_files(root) if not all_tests: return []
chosen: List[str] = [] test_set = set(all_tests)
# 1. Direct test file edits and naming conventions for raw in changed_files: rel = raw.replace("\\", "/") if rel in test_set and rel not in chosen: chosen.append(rel) continue for candidate in _naming_candidates(rel): if candidate in test_set and candidate not in chosen: chosen.append(candidate)
# 2. Transitive reverse-dependency closure across discovered Python files all_py = discover_python_files(root) _, graph_edges = extract_python_graph(root, all_py) dependents_of: Dict[str, Set[str]] = {} for src, dst in graph_edges: src_file = src.split("::", 1)[0] dst_file = dst.split("::", 1)[0] if src_file != dst_file: dependents_of.setdefault(dst_file, set()).add(src_file)
impacted: Set[str] = {raw.replace("\\", "/") for raw in changed_files if raw} queue: List[str] = list(impacted) while queue: current = queue.pop(0) for dep in sorted(dependents_of.get(current, ())): if dep not in impacted: impacted.add(dep) queue.append(dep)
for test_rel in all_tests: if test_rel in impacted and test_rel not in chosen: chosen.append(test_rel)
# 3. Fallback direct AST token scan for any remaining test files target_tokens: Dict[str, Set[str]] = {} for rel in impacted: tokens = set(module_names_for_file(rel)) stem = Path(rel).stem if stem and stem != "__init__": tokens.add(stem) target_tokens[rel] = tokens
combined_tokens: Set[str] = set() for tok_set in target_tokens.values(): combined_tokens.update(tok_set)
if combined_tokens: for test_rel in all_tests: if test_rel in chosen: continue test_path = root / Path(*test_rel.split("/")) imported = _imported_names_in_file(test_path) if imported & combined_tokens: chosen.append(test_rel)
return chosen6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python adversary awaiting independent suite verification.","abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_adversary\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python adversary awaiting independent suite verification.","abstractSyntaxTree": "{\"adapter\": \"lingologos_python.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_adversary\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [
1234-- Node arbiter (to planner): applies lgcodex.decision.decide without adding evidence.-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.abstract PythonArbiter = {cat1234-- Node arbiter (to planner): applies lingologos_codex.decision.decide without adding evidence.-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.abstract PythonArbiter = {cat
6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python arbiter awaiting gate_checker and adversary reports.","abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_arbiter\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python arbiter awaiting gate_checker and adversary reports.","abstractSyntaxTree": "{\"adapter\": \"lingologos_python.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_arbiter\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [
6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python executor awaiting patch proposal.","abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_executor\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python executor awaiting patch proposal.","abstractSyntaxTree": "{\"adapter\": \"lingologos_python.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_executor\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [
6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python gate checker awaiting commands to run.","abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_gate_checker\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python gate checker awaiting commands to run.","abstractSyntaxTree": "{\"adapter\": \"lingologos_python.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_gate_checker\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [
6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python planner awaiting workspace task.","abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_planner\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"plan\": {\"order\": [], \"parallelGroups\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python planner awaiting workspace task.","abstractSyntaxTree": "{\"adapter\": \"lingologos_python.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_planner\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"plan\": {\"order\": [], \"parallelGroups\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [
6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python retriever awaiting symbol graph request.","abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_retriever\", \"checkers\": [], \"context\": {\"edges\": [], \"symbols\": []}, \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [6 unmodified lines789101112136 unmodified lines},"payload": {"naturalLanguage": "Idle Python retriever awaiting symbol graph request.","abstractSyntaxTree": "{\"adapter\": \"lingologos_python.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_retriever\", \"checkers\": [], \"context\": {\"edges\": [], \"symbols\": []}, \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}","smtConstraints": {"declarations": [],"assertions": [
19 unmodified lines2021222324252627282930313219 unmodified lines][project.entry-points."lingologos.codex.adapters"]python = "lgpython.adapter:PythonLanguageAdapter"[project.scripts]lgpython = "lgpython.cli:main"[tool.setuptools.packages.find]include = ["lgpython*"][tool.pytest.ini_options]testpaths = ["tests"]19 unmodified lines2021222324252627282930313219 unmodified lines][project.entry-points."lingologos.codex.adapters"]python = "lingologos_python.adapter:PythonLanguageAdapter"[project.scripts]lingologos_python = "lingologos_python.cli:main"[tool.setuptools.packages.find]include = ["lingologos_python*"][tool.pytest.ini_options]testpaths = ["tests"]
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374{"schema": "lingologos-python-gates-1","verdict": "CONFIRMED","counts": {"CONFIRMED": 9,"REJECTED": 0,"ABSTAIN": 0},"gates": [{"name": "adapter_contract","verdict": "CONFIRMED","check": "check_adapter_contract on PythonLanguageAdapter","note": "no violations for lingologos-python","failed_targets": []},{"name": "ast_symbol_graph","verdict": "CONFIRMED","check": "Python AST symbol, method, inheritance, and import graph","note": "13 symbols, 10 edges extracted","failed_targets": []},{"name": "test_selection","verdict": "CONFIRMED","check": "import-aware Python test selection","note": "selected 2 dependent test file(s)","failed_targets": []},{"name": "strict_abstain_control","verdict": "CONFIRMED","check": "missing optional tools produce ABSTAIN and block verdict","note": "missing static tools abstained and ended in UNKNOWN/GATE_ABSTAIN","failed_targets": []},{"name": "session_transactions","verdict": "CONFIRMED","check": "staged edit commit on VERIFIED and disk isolation on refusal","note": "clean edit committed VERIFIED (3); syntax error and protected path refused","failed_targets": []},{"name": "external_topology","verdict": "CONFIRMED","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": []}]}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374{"schema": "lingologos-python-gates-1","verdict": "CONFIRMED","counts": {"CONFIRMED": 9,"REJECTED": 0,"ABSTAIN": 0},"gates": [{"name": "adapter_contract","verdict": "CONFIRMED","check": "check_adapter_contract on PythonLanguageAdapter","note": "no violations for lingologos-python","failed_targets": []},{"name": "ast_symbol_graph","verdict": "CONFIRMED","check": "Python AST symbol, method, inheritance, and import graph","note": "13 symbols, 10 edges extracted","failed_targets": []},{"name": "test_selection","verdict": "CONFIRMED","check": "import-aware Python test selection","note": "selected 2 dependent test file(s)","failed_targets": []},{"name": "strict_abstain_control","verdict": "CONFIRMED","check": "missing optional tools produce ABSTAIN and block verdict","note": "missing static tools abstained and ended in UNKNOWN/GATE_ABSTAIN","failed_targets": []},{"name": "session_transactions","verdict": "CONFIRMED","check": "staged edit commit on VERIFIED and disk isolation on refusal","note": "clean edit committed VERIFIED (3); syntax error and protected path refused","failed_targets": []},{"name": "external_topology","verdict": "CONFIRMED","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": []}]}
13 unmodified lines1415161718192013 unmodified linesif str(PYTHON_ROOT) not in sys.path:sys.path.insert(0, str(PYTHON_ROOT))from lgpython._codex_bridge import ensure_codex_on_path # noqa: E402ensure_codex_on_path(PYTHON_ROOT)13 unmodified lines1415161718192013 unmodified linesif str(PYTHON_ROOT) not in sys.path:sys.path.insert(0, str(PYTHON_ROOT))from lingologos_python._codex_bridge import ensure_codex_on_path # noqa: E402ensure_codex_on_path(PYTHON_ROOT)
5 unmodified lines67891011121 unmodified line141516171819202122232453 unmodified lines787980818283848586875 unmodified linesimport pytestfrom lgcodex.adapter_contract import (ADAPTER_SPEC_VERSION,CommandLanguageAdapter,WorkspaceBoundaryError,1 unmodified lineload_adapter_from_file,load_adapter_from_ref,)from lgcodex.types import ABSTAIN, CONFIRMED, REJECTEDfrom lgpython.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapterfrom lgpython.ast_graph import discover_python_filesfrom lgpython.gates import resolve_tool_gate_prefixdef test_python_adapter_passes_full_codex_contract(sample_pkg: Path) -> None:53 unmodified linesdef test_load_adapter_via_codex_ref_and_declarative_spec(sample_pkg: Path) -> None:python_root = Path(__file__).resolve().parent.parentby_module = load_adapter_from_ref("lgpython.adapter:PythonLanguageAdapter", sample_pkg)assert isinstance(by_module, PythonLanguageAdapter)adapter_file = python_root / "lgpython" / "adapter.py"by_file = load_adapter_from_ref(f"{adapter_file}:PythonLanguageAdapter", sample_pkg)assert by_file.meta().name == "lingologos-python"5 unmodified lines67891011121 unmodified line141516171819202122232453 unmodified lines787980818283848586875 unmodified linesimport pytestfrom lingologos_codex.adapter_contract import (ADAPTER_SPEC_VERSION,CommandLanguageAdapter,WorkspaceBoundaryError,1 unmodified lineload_adapter_from_file,load_adapter_from_ref,)from lingologos_codex.types import ABSTAIN, CONFIRMED, REJECTEDfrom lingologos_python.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapterfrom lingologos_python.ast_graph import discover_python_filesfrom lingologos_python.gates import resolve_tool_gate_prefixdef test_python_adapter_passes_full_codex_contract(sample_pkg: Path) -> None:53 unmodified linesdef test_load_adapter_via_codex_ref_and_declarative_spec(sample_pkg: Path) -> None:python_root = Path(__file__).resolve().parent.parentby_module = load_adapter_from_ref("lingologos_python.adapter:PythonLanguageAdapter", sample_pkg)assert isinstance(by_module, PythonLanguageAdapter)adapter_file = python_root / "lingologos_python" / "adapter.py"by_file = load_adapter_from_ref(f"{adapter_file}:PythonLanguageAdapter", sample_pkg)assert by_file.meta().name == "lingologos-python"
3 unmodified lines456789103 unmodified linesfrom pathlib import Pathfrom lgpython.ast_graph import discover_python_files, extract_python_graph, module_names_for_filedef test_discover_python_files_ignores_caches_and_venvs(sample_pkg: Path) -> None:3 unmodified lines456789103 unmodified linesfrom pathlib import Pathfrom lingologos_python.ast_graph import discover_python_files, extract_python_graph, module_names_for_filedef test_discover_python_files_ignores_caches_and_venvs(sample_pkg: Path) -> None:
14 unmodified lines1516171819202122232 unmodified lines2627282930313214 unmodified linesfrom pathlib import Pathfrom typing import Any, Dictfrom lgpython.patterns import PATTERNSfrom lgpython.rules import RULE_IDSROOT = Path(__file__).resolve().parents[1]LAB = ROOT / "fixtures" / "pattern_lab"2 unmodified linesdef run_cli(*args: str) -> subprocess.CompletedProcess:return subprocess.run([sys.executable, "-B", "-m", "lgpython", *args],cwd=str(ROOT),capture_output=True,text=True,14 unmodified lines1516171819202122232 unmodified lines2627282930313214 unmodified linesfrom pathlib import Pathfrom typing import Any, Dictfrom lingologos_python.patterns import PATTERNSfrom lingologos_python.rules import RULE_IDSROOT = Path(__file__).resolve().parents[1]LAB = ROOT / "fixtures" / "pattern_lab"2 unmodified linesdef run_cli(*args: str) -> subprocess.CompletedProcess:return subprocess.run([sys.executable, "-B", "-m", "lingologos_python", *args],cwd=str(ROOT),capture_output=True,text=True,
7 unmodified lines891011121314157 unmodified linesfrom pathlib import Pathfrom typing import Dictfrom lgpython.patterns import PATTERNS, plan_patternfrom lgpython.session import DEFAULT_PROTECTED_PATTERNS, PythonWorkspaceSessionPOSITIVE = {"annotate-literal-defaults": "src/tokens.py::count_words",7 unmodified lines891011121314157 unmodified linesfrom pathlib import Pathfrom typing import Dictfrom lingologos_python.patterns import PATTERNS, plan_patternfrom lingologos_python.session import DEFAULT_PROTECTED_PATTERNS, PythonWorkspaceSessionPOSITIVE = {"annotate-literal-defaults": "src/tokens.py::count_words",
7 unmodified lines89101112131415165 unmodified lines2223242526272821 unmodified lines505152535455567 unmodified linesfrom pathlib import Pathfrom typing import Dict, Listfrom lgcodex.casecorpus import read_rows, validate_case_rowsfrom lgpython.patterns import (FAMILIES,PATTERNS,PATTERN_IDS,5 unmodified linessplit_target,TARGET_SEPARATOR,)from lgpython.rules import RULE_IDSROOT = Path(__file__).resolve().parents[1]LAB = ROOT / "fixtures" / "pattern_lab"21 unmodified linesdef _reason_codes() -> List[str]:from lgpython import rulesreturn [name for name in dir(rules) if name.isupper() and "_" in name]7 unmodified lines89101112131415165 unmodified lines2223242526272821 unmodified lines505152535455567 unmodified linesfrom pathlib import Pathfrom typing import Dict, Listfrom lingologos_codex.casecorpus import read_rows, validate_case_rowsfrom lingologos_python.patterns import (FAMILIES,PATTERNS,PATTERN_IDS,5 unmodified linessplit_target,TARGET_SEPARATOR,)from lingologos_python.rules import RULE_IDSROOT = Path(__file__).resolve().parents[1]LAB = ROOT / "fixtures" / "pattern_lab"21 unmodified linesdef _reason_codes() -> List[str]:from lingologos_python import rulesreturn [name for name in dir(rules) if name.isupper() and "_" in name]
4 unmodified lines5678910111213144 unmodified linesfrom pathlib import Pathfrom typing import Callable, Dict, Optionalfrom lgcodex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patchfrom lgpython import rulesfrom lgpython.patterns import PATTERNSROOT = Path(__file__).resolve().parents[1]LAB = ROOT / "fixtures" / "pattern_lab"4 unmodified lines5678910111213144 unmodified linesfrom pathlib import Pathfrom typing import Callable, Dict, Optionalfrom lingologos_codex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patchfrom lingologos_python import rulesfrom lingologos_python.patterns import PATTERNSROOT = Path(__file__).resolve().parents[1]LAB = ROOT / "fixtures" / "pattern_lab"
3 unmodified lines456789103 unmodified linesfrom pathlib import Pathfrom lgpython.session import PythonWorkspaceSessiondef test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None:3 unmodified lines456789103 unmodified linesfrom pathlib import Pathfrom lingologos_python.session import PythonWorkspaceSessiondef test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None:
3 unmodified lines456789103 unmodified linesfrom pathlib import Pathfrom lgpython.test_selector import discover_test_files, is_test_file, select_python_testsdef test_is_test_file_conventions() -> None:3 unmodified lines456789103 unmodified linesfrom pathlib import Pathfrom lingologos_python.test_selector import discover_test_files, is_test_file, select_python_testsdef test_is_test_file_conventions() -> None:
6 unmodified lines7891011121314151617186 unmodified linesimport sysfrom pathlib import Pathfrom lgcodex.agents import ROLESfrom lgcodex.decision import dossier_from_dictfrom lgcodex.envelope import ENVELOPE_KINDfrom lgpython import clifrom lgpython.session import PythonWorkspaceSessionPYTHON_ROOT = Path(__file__).resolve().parent.parent6 unmodified lines7891011121314151617186 unmodified linesimport sysfrom pathlib import Pathfrom lingologos_codex.agents import ROLESfrom lingologos_codex.decision import dossier_from_dictfrom lingologos_codex.envelope import ENVELOPE_KINDfrom lingologos_python import clifrom lingologos_python.session import PythonWorkspaceSessionPYTHON_ROOT = Path(__file__).resolve().parent.parent
6 unmodified lines7891011121318 unmodified lines32333435363738394041424344456 unmodified linesBoth 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.18 unmodified linessys.path.insert(0, str(ROOT))sys.dont_write_bytecode = Truefrom lgpython._codex_bridge import ensure_codex_on_path # noqa: E402ensure_codex_on_path(ROOT)from lgcodex.casecorpus import read_rows, validate_case_rows, write_rows # noqa: E402from lgpython.ast_graph import discover_python_files # noqa: E402from lgpython.patterns import ( # noqa: E402PATTERNS,module_level_functions,plan_pattern,6 unmodified lines7891011121318 unmodified lines32333435363738394041424344456 unmodified linesBoth 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 `lingologos_codex.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.18 unmodified linessys.path.insert(0, str(ROOT))sys.dont_write_bytecode = Truefrom lingologos_python._codex_bridge import ensure_codex_on_path # noqa: E402ensure_codex_on_path(ROOT)from lingologos_codex.casecorpus import read_rows, validate_case_rows, write_rows # noqa: E402from lingologos_python.ast_graph import discover_python_files # noqa: E402from lingologos_python.patterns import ( # noqa: E402PATTERNS,module_level_functions,plan_pattern,
79 unmodified lines8081828384858611 unmodified lines98991001011021031049 unmodified lines1141151161171181191201211221231241251261276 unmodified lines13413513613713813914026 unmodified lines16716816917017117217317488 unmodified lines26326426526626726826927079 unmodified lines"`datasets/`, so its six instances point at `codex-python/agents/python_agent.py`.","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 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"11 unmodified lines),("From `datasets/codex-python`:","From the folder of this dataset, with `LGCODEX_ROOT` pointing at the folder of the kernel dataset:",),("- `topology.json`, `agents/python_agent.py`, `nodes/<role>/`: external six-node topology using\n"9 unmodified lines## What this bundle needs from the codex kernel`lgpython` imports `lgcodex`, and `lgpython/_codex_bridge.py` resolves that import in one step: analready importable `lgcodex`, then the folder named by `LGCODEX_ROOT`, then a sibling `codex/` or a`datasets/codex/` among the ancestors of the package. Downloaded from here the two orders are the samefolder, and the resolution is:pip install -r requirements.txtgit clone https://huggingface.co/datasets/tailot/lingologos-codexLGCODEX_ROOT=/path/to/lingologos-codex python -B -m pytest -p no:cacheprovider tests -qNothing in this bundle downloads anything at run time: the kernel is a second download you make once,and the tests fail with a named reason when it is missing rather than passing without it. The kernel6 unmodified linesof 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 writes26 unmodified lines"""The files of this folder, caches out.The underscore rule the other bundles use cannot be copied here. This package holds`lgpython/_codex_bridge.py`, a private module that resolves the kernel, and `lgpython/__main__.py`,the entry point of `python -m lgpython`: a rule that drops names starting with an underscore wouldupload a package that cannot import itself. Only caches and bytecode stay out."""88 unmodified lines):raise SystemExit(f"nodes/{role}/seed_payload.json requires no gates")if (ROOT / "lgcodex").exists():raise SystemExit("the kernel must not be vendored here: lgcodex/ is present in this folder")offenders = []for path in local_files():79 unmodified lines8081828384858611 unmodified lines98991001011021031041059 unmodified lines1151161171181191201211221231241251261271286 unmodified lines13513613713813914014126 unmodified lines16816917017117217317417588 unmodified lines26426526626726826927027179 unmodified lines"`datasets/`, so its six instances point at `codex-python/agents/python_agent.py`.","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 `lingologos_python/`, the six node folders with their grammar,\n""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"11 unmodified lines),("From `datasets/codex-python`:","From the folder of this dataset, with `LINGOLOGOS_CODEX_ROOT` pointing at the folder of the kernel\n""dataset:",),("- `topology.json`, `agents/python_agent.py`, `nodes/<role>/`: external six-node topology using\n"9 unmodified lines## What this bundle needs from the codex kernel`lingologos_python` imports `lingologos_codex`, and `lingologos_python/_codex_bridge.py` resolves thatimport in one step: an already importable `lingologos_codex`, then the folder named by`LINGOLOGOS_CODEX_ROOT`, then a sibling `codex/` or a `datasets/codex/` among the ancestors of thepackage. Downloaded from here the two orders are the same folder, and the resolution is:pip install -r requirements.txtgit clone https://huggingface.co/datasets/tailot/lingologos-codexLINGOLOGOS_CODEX_ROOT=/path/to/lingologos-codex python -B -m pytest -p no:cacheprovider tests -qNothing in this bundle downloads anything at run time: the kernel is a second download you make once,and the tests fail with a named reason when it is missing rather than passing without it. The kernel6 unmodified linesof 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`lingologos_codex/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 writes26 unmodified lines"""The files of this folder, caches out.The underscore rule the other bundles use cannot be copied here. This package holds`lingologos_python/_codex_bridge.py`, a private module that resolves the kernel, and `lingologos_python/__main__.py`,the entry point of `python -m lingologos_python`: a rule that drops names starting with an underscore wouldupload a package that cannot import itself. Only caches and bytecode stay out."""88 unmodified lines):raise SystemExit(f"nodes/{role}/seed_payload.json requires no gates")if (ROOT / "lingologos_codex").exists():raise SystemExit("the kernel must not be vendored here: lingologos_codex/ is present in this folder")offenders = []for path in local_files():
14 unmodified lines151617181920212223242526272829303132333435363766 unmodified lines10410510610710810911046 unmodified lines157158159160161162163165 unmodified lines32933033133233333433514 unmodified linessys.path.insert(0, str(ROOT))sys.dont_write_bytecode = Truefrom lgpython._codex_bridge import ensure_codex_on_path # noqa: E402ensure_codex_on_path(ROOT)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: E402from 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: E402FIXTURE_PKG = ROOT / "fixtures" / "sample_pkg"PATTERN_LAB = ROOT / "fixtures" / "pattern_lab"66 unmodified linesdef gate_session_transactions() -> GateResult:check = "staged edit commit on VERIFIED and disk isolation on refusal"with tempfile.TemporaryDirectory(prefix="lgpython_gate_") as tmp_dir:ws = Path(tmp_dir) / "pkg"shutil.copytree(FIXTURE_PKG, ws)session = PythonWorkspaceSession(ws)46 unmodified linesreturn _rejected(check, f"invalid seed in {folder}")dossier_from_dict(json.loads(seed["payload"]["abstractSyntaxTree"]))with tempfile.TemporaryDirectory(prefix="lgpython_subproc_") as tmp_dir:ws = Path(tmp_dir) / "pkg"shutil.copytree(FIXTURE_PKG, ws)session = PythonWorkspaceSession(ws, use_subprocesses=True)165 unmodified linesfor name, _ in GATES],}out_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")return 1 if overall == REJECTED else 014 unmodified lines151617181920212223242526272829303132333435363766 unmodified lines10410510610710810911046 unmodified lines157158159160161162163165 unmodified lines32933033133233333433514 unmodified linessys.path.insert(0, str(ROOT))sys.dont_write_bytecode = Truefrom lingologos_python._codex_bridge import ensure_codex_on_path # noqa: E402ensure_codex_on_path(ROOT)from lingologos_codex.adapter_contract import check_adapter_contract # noqa: E402from lingologos_codex.agents import ROLES # noqa: E402from lingologos_codex.casecorpus import read_rows, validate_case_rows # noqa: E402from lingologos_codex.decision import dossier_from_dict # noqa: E402from lingologos_codex.envelope import ENVELOPE_KIND # noqa: E402from lingologos_codex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch # noqa: E402from lingologos_codex.types import ABSTAIN, CONFIRMED, REJECTED, VERDICTS, GateResult # noqa: E402from lingologos_python.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter # noqa: E402from lingologos_python.ast_graph import discover_python_files, extract_python_graph # noqa: E402from lingologos_python.patterns import PATTERNS, module_level_functions, plan_pattern # noqa: E402from lingologos_python.session import PythonWorkspaceSession # noqa: E402from lingologos_python.test_selector import select_python_tests # noqa: E402FIXTURE_PKG = ROOT / "fixtures" / "sample_pkg"PATTERN_LAB = ROOT / "fixtures" / "pattern_lab"66 unmodified linesdef gate_session_transactions() -> GateResult:check = "staged edit commit on VERIFIED and disk isolation on refusal"with tempfile.TemporaryDirectory(prefix="lingologos_python_gate_") as tmp_dir:ws = Path(tmp_dir) / "pkg"shutil.copytree(FIXTURE_PKG, ws)session = PythonWorkspaceSession(ws)46 unmodified linesreturn _rejected(check, f"invalid seed in {folder}")dossier_from_dict(json.loads(seed["payload"]["abstractSyntaxTree"]))with tempfile.TemporaryDirectory(prefix="lingologos_python_subproc_") as tmp_dir:ws = Path(tmp_dir) / "pkg"shutil.copytree(FIXTURE_PKG, ws)session = PythonWorkspaceSession(ws, use_subprocesses=True)165 unmodified linesfor name, _ in GATES],}out_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8", newline="\n")return 1 if overall == REJECTED else 0
README.md+63-46
agents/python_agent.py+5-5
lingologos_python/__init__.pyAdded+81
lingologos_python/__main__.pyAdded+6
lingologos_python/_codex_bridge.pyAdded+59
lingologos_python/adapter.pyAdded+125
lingologos_python/ast_graph.pyAdded+298
lingologos_python/cli.pyAdded+276
lingologos_python/gates.pyAdded+174
lingologos_python/patterns.pyAdded+410
lingologos_python/rules.pyAdded+1030
lingologos_python/session.pyAdded+755
lingologos_python/test_selector.pyAdded+140
nodes/adversary/seed_payload.json+1-1
nodes/arbiter/grammar.gf+1-1
nodes/arbiter/seed_payload.json+1-1
nodes/executor/seed_payload.json+1-1
nodes/gate_checker/seed_payload.json+1-1
nodes/planner/seed_payload.json+1-1
nodes/retriever/seed_payload.json+1-1
pyproject.toml+3-3
results/gates.json+74-74
tests/conftest.py+1-1
tests/test_adapter.py+7-7
tests/test_ast_graph.py+1-1
tests/test_cli.py+3-3
tests/test_pattern_session.py+2-2
tests/test_patterns.py+4-4
tests/test_rules.py+3-3
tests/test_session.py+1-1
tests/test_test_selector.py+1-1
tests/test_topology_and_cli.py+5-5
tools/build_patterns.py+5-5
tools/publish_dataset.py+13-12
tools/run_gates.py+16-16