Upload folder using huggingface_hub
Browse filesFiles changed (27)
- README.md+184-31
- fixtures/pattern_lab/src/asyncops.pyAdded+56
- fixtures/pattern_lab/src/legacy.pyAdded+17
- fixtures/pattern_lab/src/widgets.pyAdded+26
- fixtures/pattern_lab/tests/test_asyncops.pyAdded+64
- fixtures/pattern_lab/tests/test_legacy.pyAdded+15
- fixtures/pattern_lab/tests/test_widgets.pyAdded+19
- lingologos_python/ast_graph.py+129-2
- lingologos_python/cli.py+246-57
- lingologos_python/patterns.py+80-5
- lingologos_python/rules.py+348-12
- lingologos_python/session.py+128-39
- patterns/coverage.json+62-17
- patterns/pattern_cases.jsonl+14
- pyproject.toml+3
- results/gates.json+30-21
- tests/test_ast_imports.py+101
- tests/test_cli.py+272
- tests/test_coverage.pyAdded+43
- tests/test_patterns.py+89-8
- tests/test_rules.py+10-5
- tests/test_self_lint.py+48
- tests/test_session.py+108
- tools/build_patterns.py+75-70
- tools/measure_coverage.pyAdded+160
- tools/publish_dataset.py+45-14
- tools/run_gates.py+204-24
31 unmodified lines3233343535363738383940412 unmodified lines44454647474849505152535455565758596061624 unmodified lines6768695870717273747549 unmodified lines1251261271141281291301311161321331341351361371381391401411421431441451461 unmodified line1481491501281511521531545 unmodified lines1601611621631641651661671 unmodified line1691701711471481721731741751761771781791801811511521821831841851861871881891901911921931941957 unmodified lines20320420516716816920620720820921017121121221321418 unmodified lines2332342351961972362372382392402412422432442452462032472482492508 unmodified lines2592602612182192202212222232622632642652662672682692702272712722732741 unmodified line2762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103116 unmodified lines31831932032132232332424932532632732815 unmodified lines3443453462713473483493503513523533543553563573583593603613623633643653663673683 unmodified lines37237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340431 unmodified lines43643743843944044144244344444544644744844945045145245327 unmodified lines48148248335148448548648748848911 unmodified lines5015025035045055065075084 unmodified lines5135145155165175185195205215225235245255265275285295305315325331 unmodified line53553653738638738853853954054154254354431 unmodified lines
```
python -B tools/run_gates.py
GATES: CONFIRMED (13 gates: 13 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
GATES: CONFIRMED (14 gates: 14 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
```
The gate runner is where this bundle states its numbers out loud: 13 gates, 167 tests across 15 files,
The gate runner is where this bundle states its numbers out loud: 14 gates, 196 tests across 16 files,
18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives every
one of those numbers from the tree it is standing in and stops the upload when the card and the code
beside it disagrees.2 unmodified linesexcept the reports folder itself, and the publisher refuses to upload a tree that the report does not
describe byte for byte; `tests/test_self_lint.py` holds the report sitting in this folder to that bar.
The runner takes that digest before the first gate and asks it again before writing: a tree that moved
while the gates ran gets no report, and the report says how many seconds each gate took.
while the gates ran gets no report, and the report says how many seconds each gate took. The report
also names the kernel it resolved, as one digest of every kernel byte: the behaviour promised here is
tied to one revision of the codex kernel, and that kernel still does not sit in this folder.
What the card asks to be trusted is checkable from the tree: the numbers in the sentence above are
re-derived by the gate runner, by `tests/test_self_lint.py`, and by the publisher, which stops the
upload when the card and the code beside it disagree; the transcripts below are what the printed
commands printed against this tree; every refusal names one code from a registry the gates check
against the code that raises it; and the exit codes are collected in a table under Running that a
test probes against the real commands. What the card does not claim: the kernel, which this folder
neither carries nor modifies; a benchmark, the corpus being generated from the rules against one
fixture that is stated as its denominator; and facts the host will not answer, which the lock record
writes as a dash rather than a guess.
## Contents
4 unmodified lines implementing the five-method `lingologos_codex.adapter_contract.LanguageAdapter` contract.
- `lingologos_python/ast_graph.py`: AST symbol, method, inheritance, relative/absolute import, and call
graph extraction (`discover_python_files`, `extract_python_graph`, `importers_of`, `reexported_names`,
`hardlinked_file`). A file whose bytes
`hardlinked_file`, `build_reverse_index`, `importers_from_index`). The reverse index answers, for a
whole tree at once, which files import each module: `delete` asks it before removing a file, and
the `graph` command prints it. A file whose bytes
are not UTF-8 text is named as a file and given no symbols, rather than decoded into inventions.
An aliased `from x import y as z` keeps its edge to the submodule `x.y` even though the name is
renamed, and a dotted relative import crosses the same number of packages in the graph as in the49 unmodified lines death of its run; a leftover lock is claimed by renaming it first, so two runs racing over one
corpse leave exactly one holder; and release deletes the lock only while the token in it is the one
this run wrote, so a run never unlinks a lock another run took over. A live holder is answered
REFUSED with the reason `SESSION_LOCKED`, and one whose owner cannot be read is never stolen.
REFUSED with the reason `SESSION_LOCKED`, and one whose owner cannot be read is never stolen. A run
that meets a live holder can wait instead: `--lock-wait SEC` budgets that wait, and a wait that
runs out answers the same refusal it would have answered at once.
- `lingologos_python/cli.py`: `lingologos_python` CLI (`verify`, `edit`, `create`, `delete`, `symbols`,
`select-tests`, `patterns list|show|scan|apply`, `check-adapter`).
`select-tests`, `patterns list|show|scan|apply`, `graph`, `lock-status`, `check-adapter`). The
session verbs take `--config` for a JSON file holding the same knobs, `--protect` for policy
paths, `--print-diff` to show the pair beside the verdict, and `--audit` to append one JSON line
per run to a ledger.
- `fixtures/pattern_lab/`: a small package with one function planted in the shape of each card and
one planted to be refused, used by the tests and by the coverage counts.
- `patterns/pattern_cases.jsonl`, `patterns/coverage.json`: the generated case corpus (one accepted
and one refused case per card) and the coverage statement, whose denominator is that fixture.
- `tools/`: `build_patterns.py` generates the corpus and `--check` re-derives it; `run_gates.py` is
the gate runner of the numbers above; `measure_coverage.py` traces how much of the package the
suite enters; `publish_dataset.py` turns this README into the dataset card and refuses to upload
a tree that contradicts it.
- `topology.json`, `agents/python_agent.py`, `nodes/<role>/`: external six-node topology using the
`codex` kernel as its base. The six executables it names are written relative to `datasets/`, so in
a standalone copy that leading name is simply the folder you are standing in.1 unmodified line
## The pattern catalog
Eight cards, one per shape this bundle can actually carry out:
Ten cards, one per shape this bundle can actually carry out:
| Card | Shape it claims | Family |
|---|---|---|5 unmodified lines| `bare-except-to-narrow-exception` | an `except:` that names no class, so it also catches the exits of the interpreter | contracts |
| `none-comparison-to-identity` | a test against `None` written with `==` or `!=`, which asks agreement and not identity | shape |
| `empty-len-to-truthiness` | an emptiness test that counts the collection with `len` and compares to zero | shape |
| `drop-unused-imports` | a module level import whose bound name the module never reads again | shape |
| `init-missing-super` | an `__init__` of a subclass that never reaches its base through `super()` | contracts |
A card is not a prompt: it names a syntax-tree shape, and `lingologos_python/rules.py` refuses anything
that is not that shape. `chain-to-registry` refuses a chain whose branches take different kinds of1 unmodified lineit opened (`HANDLE_ESCAPE`), `mutable-default-to-none` refuses a default that already carries an
annotation (`ANNOTATED_MUTABLE_DEFAULT`), `bare-except-to-narrow-exception` refuses a bare handler that
re-raises what it caught (`BARE_EXCEPT_RE_RAISES`), `none-comparison-to-identity` refuses a test against
`None` inside a chained comparison (`NONE_COMPARISON_IS_CHAINED`), and `empty-len-to-truthiness` refuses
a count of something that is not a plain name (`LEN_TARGET_IS_NOT_A_NAME`). A refusal is an answer, not
`None` inside a chained comparison (`NONE_COMPARISON_IS_CHAINED`), `empty-len-to-truthiness` refuses
a count of something that is not a plain name (`LEN_TARGET_IS_NOT_A_NAME`), `drop-unused-imports`
refuses a star import in the file and a name the module exports (`STAR_IMPORT_IN_FILE`,
`NAME_LISTED_IN_ALL`) and answers `NO_UNUSED_IMPORT` when the import it was asked to drop is read
again in the module, and `init-missing-super` refuses a class whose bases it cannot read and a
constructor that already calls its base (`SUPER_BASES_UNREADABLE`, `SUPER_CALL_ALREADY_FIRST`),
answering `NO_INIT_METHOD` and `INIT_TAKES_MORE_THAN_SELF` when the named method is not the
constructor the card claims. A refusal is an answer, not
a failure: it names the reason code and writes nothing. Each card also lists the refusals the plan around
a rule shares: a target that is not
there (`MISSING_TARGET_FILE`), a test file that cannot carry the lock (`NO_TEST_FILE`, `CRLF_TARGET`,
`INVALID_COMPANION_PATH`), a coroutine the lock tests could not call directly (`ASYNC_TARGET`), an assert
there (`MISSING_TARGET_FILE`), a class or method target that is not what it claims (`NO_SUCH_CLASS`,
`NOT_A_MODULE_CLASS`, `NOT_A_METHOD`), an import removal that cannot cut cleanly through the file
(`PACKAGE_FILE_TARGET`, `IMPORTS_NOT_CONTIGUOUS`), a test file that cannot carry the lock (`NO_TEST_FILE`,
`CRLF_TARGET`, `INVALID_COMPANION_PATH`), an assert
whose message is built at call time (`NON_LITERAL_ASSERT_MESSAGE`), and anchors that collide (`ANCHOR_OVERLAP`).
Five of the ten cards read a coroutine as readily as a plain function: their rules read the syntax
tree, and their lock tests either read the function's signature and source or drive it through an
explicit `asyncio.run`, so each of the five carries an async pair in the published corpus. The three
cards whose published lock calls the rewritten function straight out, with no loop anywhere, stay
honest the other way and refuse a coroutine with `ASYNC_TARGET`, saying on the card that they carry
no pair that would prove a lock waits for one.
Every change this bundle makes is a pair. The rule returns two edits, the change in the source file
and a lock test appended to the test file paired with it, and `apply_pattern` puts both in one7 unmodified linesThe `pattern_pair_honesty` gate runs exactly that experiment for every card: it writes only the test
side of the pair into a copy of the laboratory and reruns its suite, and it fails the gates if any
such copy still passes.
The three newest cards write their lock as a reading rather than a call: the test opens the function
with `inspect` and asserts on the text the rewrite leaves behind and the text it removes, so the lock
still fails while the old shape stands, but it answers about the source and not about a behavior.
Five of the ten cards, the two newest among them, write their lock as a reading rather than a call:
the test opens the function with `inspect` and asserts on the text the rewrite leaves behind and the
text it removes, so the lock still fails while the old shape stands, but it answers about the source
and not about a behavior.
The sixteen pairs are what the bundle ships, not the only check the rules face: `tests/test_rules_fuzz.py`
The thirty pairs are what the bundle ships, not the only check the rules face: `tests/test_rules_fuzz.py`
sweeps, with a fixed seed, shapes the corpus never visits: randomly assembled modules carrying mutations
(tabs, CRLF, non-ASCII, a class wrapper, a tail no parser accepts), companion tests missing or silent,
names that are not in the file. For every candidate and every rule the answer must be one of two things:18 unmodified lines
This is a catalog of patterns this bundle has carried out and can re-derive, not a claim that it can
change Python in general. `patterns/coverage.json` says what has been shown and names its denominator:
the eight cards over the eight source files and twenty-one module level functions of
`fixtures/pattern_lab/`, not over Python and not over any corpus of real repositories.
the ten cards over the eleven source files and thirty-three module level functions of
`fixtures/pattern_lab/`, not over Python and not over any corpus of real repositories. The bundle
also measures itself from the inside: `tools/measure_coverage.py` runs the suite under a trace
profile and counts how many of the package's own functions the tests enter, 169 of 179 at the time
of this card, and `tests/test_coverage.py` holds that count above a floor of ninety percent and
refuses to state it at all while the traced suite is failing.
The corpus is generated, like the kernel's own:
```
python -B tools/build_patterns.py --check
PATTERNS: CONFIRMED (16 rows over 8 cards, 21 module level functions in the fixture)
PATTERNS: CONFIRMED (30 rows over 10 cards, 33 module level functions in the fixture)
```
Each row is a work case in the schema `lingologos_codex/casecorpus.py` defines, so the kernel can check8 unmodified lines
```
$ python -B -m lingologos_python symbols --workspace fixtures/pattern_lab --limit 5
files=16 symbols=43 edges=40
0.0669 src/registry.py::render
0.0594 src/tokens.py::count_words
0.0475 src/guards.py::open_ticket
0.0406 src/registry.py::format_short
0.0341 src/registry.py::format_json
files=22 symbols=78 edges=59
0.0385 src/registry.py::render
0.0342 src/tokens.py::count_words
0.0273 src/guards.py::open_ticket
0.0236 src/widgets.py::Box
0.0234 src/registry.py::format_short
```
The ranking is PageRank over the call and import graph, and the three highest ranked functions here are
three of the eight the catalog claims: the dispatcher, the annotatable default, the bare guard. To know
three of the shapes the ten cards claim: the dispatcher, the annotatable default, the bare guard. To know
which tests a change is answerable to:
```1 unmodified linetests/test_registry.py
```
The import edges alone, printed as the reverse index the delete verb consults: for every module,
which files would stop importing it if it went.
```
$ python -B -m lingologos_python graph --workspace fixtures/pattern_lab
files=22 import_edges=11
src/asyncops.py <- tests/test_asyncops.py
src/baskets.py <- tests/test_baskets.py
src/guards.py <- tests/test_guards.py
src/labels.py <- tests/test_labels.py
src/legacy.py <- tests/test_legacy.py
src/notes.py <- tests/test_notes.py
src/registry.py <- tests/test_registry.py
src/retries.py <- tests/test_retries.py
src/slugify.py <- tests/test_slugify.py
src/tokens.py <- tests/test_tokens.py
src/widgets.py <- tests/test_widgets.py
```
Before a run that would take the workspace lock, the same tree can be asked who holds it, and the
answer costs no session:
```
$ python -B -m lingologos_python lock-status --workspace fixtures/pattern_lab
free: no lock file named .lingologos-session.lock in this workspace
```
Exit is zero when the lock is free or absent and one when a live holder, or a lock whose owner
cannot be read, sits there.
A card states its terms before you use it. This transcript is abridged to the lines a decision turns
on, and the two long lines are wrapped here for width:
6 unmodified lines out, and the reader has to trace every exit to believe the handle is closed.
needs
- the name is used only inside that function and never stored or returned
- a coroutine target is refused with ASYNC_TARGET: this card carries no coroutine pair that
would prove its lock test waits for one
lock 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
refuses ALREADY_SCOPED, NO_BARE_OPEN, HANDLE_ESCAPE, NOT_A_MODULE_FUNCTION
refuses ALREADY_SCOPED, NO_BARE_OPEN, HANDLE_ESCAPE, NOT_A_MODULE_FUNCTION, ASYNC_TARGET
needs assurance >= 3 to commit
```
15 unmodified linesthat becomes a mapping of handlers, and the lock test appended to `tests/test_registry.py`. `--json`
prints the same answer as data, with the `search` and `replace` text of every edit beside it.
`render_pair`, in the same file, is not listed: its chain is not in the shape the card claims, and a
card that does not claim a shape does not touch it.
card that does not claim a shape does not touch it. Ask the same question of a card that reads
coroutines, and the same laboratory answers twice:
```
$ python -B -m lingologos_python patterns scan --workspace fixtures/pattern_lab \
--pattern mutable-default-to-none
mutable-default-to-none: 2 hit(s) in this workspace
src/asyncops.py::gather
src/asyncops.py shared default of 'gather'
tests/test_asyncops.py lock test 'test_gather_has_no_shared_default' appended after 'test_item_count_counts_items'
why: the default of 'tags' is a value every call would share
src/slugify.py::add_tag
src/slugify.py shared default of 'add_tag'
tests/test_slugify.py lock test 'test_add_tag_has_no_shared_default' appended after 'test_join_parts_uses_its_tuple_default'
why: the default of 'tags' is a value every call would share
```
The first hit is an `async def`: five of the ten cards read a coroutine as well as a plain function,
and the laboratory carries a coroutine in the shape of each of them so the published counts show it.
The pair, verified and not committed:
3 unmodified linesVERIFIED (assurance 3, committed=False) OK_DUAL_CONFIRMATION: confirmed by adversary, gate_checker
```
The same apply, asked to show the pair before any node runs, abridged here to the source hunk of
its two diffs:
```
$ python -B -m lingologos_python patterns apply --workspace fixtures/pattern_lab \
--pattern chain-to-registry --target src/registry.py::render --dry-run --print-diff
--- a/src/registry.py
+++ b/src/registry.py
@@ -1,9 +1,6 @@
def render(kind, item):
- if kind == "short":
- return format_short(item)
- elif kind == "long":
- return format_long(item)
- elif kind == "json":
- return format_json(item)
- else:
+ handlers = {"short": format_short, "long": format_long, "json": format_json}
+ handled = handlers.get(kind)
+ if handled is None:
raise ValueError("unsupported kind")
+ return handled(item)
```
The hunk below it adds the twenty-three lines of the lock test to `tests/test_registry.py`.
`--print-diff` prints beside the verdicts of every verb that writes, and what it prints is the pair
the run plans, not a report of what it wrote.
The same command without `--dry-run` writes both files in one transaction. Ask for the function whose
shape is wrong and the answer is a refusal with a reason, an exit code of 1, and a workspace that did
not move by a byte:31 unmodified linesprocess therefore carries one session's gate budget at a time, and two sessions open in the same process
would overwrite each other's last written value.
The knobs a session runs with are the flags, and the same knobs can sit in one JSON file: `--config
FILE` carries `strict_tools`, `subprocesses`, `allow_single_prover`, `node_timeout`, `total_timeout`,
`gate_timeout`, `lock_wait`, and `protect`; a flag on the command line outranks the file, and a key
the list does not hold, or a value of the wrong kind, stops the run before a node is asked anything.
`--protect src/x.py` adds to the protected paths the policy carries, and a write naming one is
answered `PROTECTED_PATH` with no node consulted. `--lock-wait SEC` says how many seconds a run may
wait for a live holder before it answers `SESSION_LOCKED`; the default of zero answers at once,
because a caller that did not ask to wait gets the refusal it asked for. `--print-diff` prints the
unified diff of the pair a write is about to attempt. `--audit FILE` appends one JSON line per run,
whatever the answer was: command, workspace, verdict, reason, and whether anything was committed,
so what the tools refused on a tree leaves a record that does not live in a terminal scrollback.
`check-adapter` says whether the Python adapter holds the contract of the kernel, and exits non-zero
when it does not. `run_retry_loop` runs the kernel's stall detection between attempts: a second attempt
that applies a patch on the same target with the same patch status is answered `CHECKER_ABSTAIN`,27 unmodified lines `NOT_THE_FIRST_STATEMENT`, `ASYNC_TARGET`, `NON_LITERAL_ASSERT_MESSAGE`, `INVALID_COMPANION_PATH`,
`ANCHOR_OVERLAP`, `NO_BARE_EXCEPT`, `BARE_EXCEPT_RE_RAISES`, `EXCEPT_HANDLER_UNREADABLE`,
`NO_NONE_COMPARISON`, `NONE_COMPARISON_IS_CHAINED`, `NO_EMPTY_LEN_CHECK`,
`LEN_TARGET_IS_NOT_A_NAME`.
`LEN_TARGET_IS_NOT_A_NAME`, `NO_SUCH_CLASS`, `NOT_A_MODULE_CLASS`, `NOT_A_METHOD`, `NO_INIT_METHOD`,
`INIT_TAKES_MORE_THAN_SELF`, `SUPER_CALL_ALREADY_FIRST`, `SUPER_BASES_UNREADABLE`, `NO_UNUSED_IMPORT`,
`STAR_IMPORT_IN_FILE`, `NAME_LISTED_IN_ALL`, `PACKAGE_FILE_TARGET`, `IMPORTS_NOT_CONTIGUOUS`.
## Running
11 unmodified lines --pattern chain-to-registry
python -B -m lingologos_python patterns apply --workspace fixtures/pattern_lab \
--pattern chain-to-registry --target src/registry.py::render --dry-run
python -B -m lingologos_python graph --workspace fixtures/pattern_lab
python -B -m lingologos_python lock-status --workspace fixtures/pattern_lab
```
`patterns apply` without `--dry-run` commits, and only on a verdict the kernel accepts: it commits4 unmodified linesthe commands above either read it or verify against a copy, and the tests copy it to a temporary folder
before writing, so the folder as published keeps the exact shape the coverage numbers were counted on.
### Exit codes
| command | 0 | 1 | 2 |
|---|---|---|---|
| `verify` | a verdict the session accepts, nothing written | `REFUSED` or `UNKNOWN` | bad flag, unreadable or unknown-key config |
| `edit`, `create`, `delete`, `patterns apply` | the change landed, or a `--dry-run` was accepted | refused, unverified, or a lock held past the wait budget | bad flag, unreadable or unknown-key config |
| `patterns list`, `patterns show`, `patterns scan` | the answer printed | -- | unknown card, missing flag |
| `symbols`, `select-tests` | the answer printed | -- | bad flag |
| `graph`, `lock-status` | the answer printed; a free lock is an answer | workspace missing; a live or unreadable lock | bad flag |
| `check-adapter` | the adapter holds the kernel contract | the contract is violated | bad flag |
`tests/test_cli.py` parses this table off the card and probes the printed commands against it: a
cell that promises an exit code the real command does not answer, or a command line the table
forgot, fails the suite.
## What this revision renamed
The two letter prefix is gone. The package is `lingologos_python`, where an earlier published revision1 unmodified lineenvironment handle the bridge reads is `LINGOLOGOS_CODEX_ROOT`, where it was `LGCODEX_ROOT`; and the
command 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` that the earlier revision published, which this revision kept byte for
byte while adding one pair for each of its three new cards. The six seed
`lingologos.codex.adapters`, the work case schema version, and the sixteen rows of
`patterns/pattern_cases.jsonl` that the previous revision published, which this revision carried over byte
for byte, in one group per card, adding one pair for each of its two new cards and an async pair for each of the five cards
whose rule reads a coroutine as well as a plain function. The six seed
envelopes under `nodes/` do carry the adapter under its new dotted path, because naming a module that no
longer exists would make those files disagree with the code beside them. The dataset keeps its name,
`tailot/codex-python`.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""A module of coroutines for the coroutine pairs of this catalog.
Every function here is a coroutine on purpose. The cards that vouch for coroutinescarry a pair over these names, so the claim is proven over an async def and not juststated; the cards that do not vouch for coroutines have to say what they answer whenone of these functions is named as their target."""
async def render_page(url, width=80): return str(url).ljust(width)
async def sized(n: int = 4) -> int: return n
async def gather(seed, tags=[]): return tags + [seed]
async def plain(value): return value
async def check_name(name): assert name return name
async def check_after(name): shown = name or "unnamed" assert shown return shown
async def describe(value): if value == None: return "nothing" return str(value)
async def present(value): if value is not None: return str(value) return "nothing"
async def word_total(items): if len(items) == 0: return 0 return sum(len(item.split()) for item in items)
async def item_count(items): return len(items)1234567891011121314151617"""A module that outgrew one of its import lines.
One of the two import lines below binds a name no other line of this file reads:that is the shape the unused import card of this bundle removes, and the two linessit on consecutive lines, so one anchor can take the unread one out."""
import jsonimport os
def read_size(path): return os.path.getsize(path)
def note_path(name): return os.path.join("notes", name + ".txt")1234567891011121314151617181920212223242526"""Boxes, shutters and a grille: three constructors, three different shapes.
Box is the constructor the constructor-chain card of this bundle claims: it takesself alone, names no base, and builds without opening the chain. Shutter alreadyopens the chain first, and Grille takes an argument the rule cannot forward."""
class Box: def __init__(self): self.sides = 4 self.closed = False
def area(self): return self.sides * self.sides
class Shutter: def __init__(self): super().__init__() self.open = False
class Grille: def __init__(self, bars): self.bars = bars12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Tests for the coroutine shapes in src.asyncops."""
import asyncio
from src.asyncops import ( check_after, check_name, describe, gather, item_count, plain, present, render_page, sized, word_total,)
def test_render_page_pads_the_text_to_the_width() -> None: assert asyncio.run(render_page("ab", 5)) == "ab "
def test_sized_answers_its_own_default() -> None: assert asyncio.run(sized()) == 4
def test_gather_puts_the_seed_last() -> None: assert asyncio.run(gather("x", ["a"])) == ["a", "x"]
def test_plain_gives_the_value_back() -> None: assert asyncio.run(plain(3)) == 3
def test_check_name_refuses_the_empty_name() -> None: try: asyncio.run(check_name("")) except AssertionError: pass else: raise AssertionError("check_name accepted an empty name")
def test_check_after_names_the_fallback() -> None: assert asyncio.run(check_after("")) == "unnamed"
def test_describe_calls_none_nothing() -> None: assert asyncio.run(describe(None)) == "nothing" assert asyncio.run(describe(2)) == "2"
def test_present_answers_for_both_sides() -> None: assert asyncio.run(present(None)) == "nothing" assert asyncio.run(present(2)) == "2"
def test_word_total_counts_words() -> None: assert asyncio.run(word_total(["a b", "c"])) == 3 assert asyncio.run(word_total([])) == 0
def test_item_count_counts_items() -> None: assert asyncio.run(item_count([1, 2])) == 2123456789101112131415"""Tests for the two readers in src.legacy."""
from pathlib import Path
from src.legacy import note_path, read_size
def test_read_size_reports_the_file(tmp_path) -> None: path = tmp_path / "note.txt" path.write_text("abcd", encoding="utf-8") assert read_size(str(path)) == 4
def test_note_path_names_the_file() -> None: assert Path(note_path("one")).name == "one.txt"12345678910111213141516171819"""Tests for the three constructors in src.widgets."""
from src.widgets import Box, Grille, Shutter
def test_box_reports_a_square_area() -> None: assert Box().area() == 16
def test_box_starts_open() -> None: assert Box().closed is False
def test_shutter_starts_closed() -> None: assert Shutter().open is False
def test_grille_keeps_its_bars() -> None: assert Grille(3).bars == 3161 unmodified lines16216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620766 unmodified lines27427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232323 unmodified lines34734834935035135235335435535635735835914 unmodified lines3743753763773783793803813823833843853862 unmodified lines389390391392393394395396397398399400401402403404297405406407408409410411412413414415416417418419302420421422423424425426427428429430431432161 unmodified lines return found
def build_reverse_index(workspace: Path, files: Sequence[str]) -> Dict[str, Set[str]]: """Map every dotted module name to the files whose imports could bind it.
importers_of asks this question one target at a time and parses the whole tree for each question. A caller that reads the same workspace once and asks about many files parses every file once here instead, and answers each later question from the buckets. """ index: Dict[str, Set[str]] = {} for rel in files: source = _read_source(workspace, rel) if source is None: continue try: tree = ast.parse(source, filename=rel) except (SyntaxError, ValueError): continue modules, _ = _extract_imports(rel, tree) buckets = list(modules) buckets.extend(name.rsplit(".", 1)[0] for name in modules if "." in name) buckets.extend(_reexport_dotted_names(workspace, tree)) for name in buckets: if name: index.setdefault(name, set()).add(rel) return index
def importers_from_index(index: Dict[str, Set[str]], target_rel: str) -> List[str]: """Answer importers_of from an index built once for the workspace."""
wanted = set(module_names_for_file(target_rel)) if not wanted: return [] found: Set[str] = set() for name in wanted: found.update(index.get(name, set())) found.discard(target_rel) return sorted(found)
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():66 unmodified lines return ".".join(base_parts)
def _module_public_names(workspace: Path, dotted_module: str) -> List[str]: """Names a `from module import *` would hand to the importer.
Star imports are an explicit contract when the module writes __all__: those strings, and only those. Without __all__ the honest expansion is the module's own top-level public names, since star skips underscored names and never re-imports a name the module never defined. """ rel = dotted_module.replace(".", "/") + ".py" source = _read_source(workspace, rel) if source is None: return [] try: tree = ast.parse(source, filename=rel) except (SyntaxError, ValueError): return [] for node in tree.body: if isinstance(node, ast.Assign) and any( isinstance(t, ast.Name) and t.id == "__all__" for t in node.targets ): if isinstance(node.value, (ast.List, ast.Tuple)): return [ elt.value for elt in node.value.elts if isinstance(elt, ast.Constant) and isinstance(elt.value, str) ] return [] names: List[str] = [] for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): name = node.name elif ( isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) ): name = node.targets[0].id else: continue if not name.startswith("_"): names.append(name) return names
def reexported_names(workspace: Path, init_rel: str) -> Dict[str, List[str]]: """External name -> dotted candidates, for a package __init__ that re-exports names.
23 unmodified lines continue for alias in node.names: if alias.name == "*": if not node.module: continue for public in _module_public_names(workspace, base): options = table.setdefault(public, []) dotted = f"{base}.{public}" if dotted not in options: options.append(dotted) continue key = alias.asname or alias.name options = table.setdefault(key, [])14 unmodified lines table = reexported_names(workspace, node.module.replace(".", "/") + "/__init__.py") for alias in node.names: if alias.name == "*": for options in table.values(): for dotted in options: # The module holding the name is the candidate the naming # check can match; the name inside it cannot be a file. for candidate in (dotted.rsplit(".", 1)[0], dotted): if candidate and candidate not in reached: reached.append(candidate) continue key = alias.asname or alias.name for dotted in table.get(key, ()):2 unmodified lines return reached
def _literal_module_name(node: Optional[ast.expr]) -> Optional[str]: if isinstance(node, ast.Constant) and isinstance(node.value, str) and node.value: if node.value.startswith("."): # A relative name handed to import_module needs the package argument # to be resolved, and that argument is code we do not evaluate. return None return node.value return None
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.""" """Return imported module names and local-alias -> (module, imported_name) map.
A literal name passed to import_module or __import__ is an import written as a call: the string is as fixed as the one after the import keyword, so the graph treats it as an edge too. Anything that is not a plain string literal stays invisible, which is why the graph is a naming check and not a trace. """ modules: List[str] = [] alias_map: Dict[str, Tuple[str, str]] = {}
def add_module(name: str) -> None: if name and name not in modules: modules.append(name)
for node in ast.walk(tree): if isinstance(node, ast.Import): if isinstance(node, ast.Call): called = node.func dynamic = None if isinstance(called, ast.Attribute) and called.attr == "import_module": dynamic = _literal_module_name(node.args[0] if node.args else None) elif isinstance(called, ast.Name) and called.id == "__import__": dynamic = _literal_module_name(node.args[0] if node.args else None) if dynamic: add_module(dynamic) elif isinstance(node, ast.Import): for alias in node.names: if alias.name not in modules: modules.append(alias.name)2 unmodified lines34567891010111213144 unmodified lines1920212122232223242526272829303132333435363738394041424313 unmodified lines5758594344456061626364656667686970717210 unmodified lines83848564868788892 unmodified lines92939473959697985 unmodified lines1041051068510710810911020 unmodified lines1311321331121341351361372 unmodified lines1401411421431441451461471481491501511521531541551561571581591601618 unmodified lines1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852861401411421431441451461472872882892902912922932942952961561571581591601611621631641652972982993003013023033043053063079 unmodified lines3173183193201863213223233241901911921931941951961971983253263273283293308 unmodified lines3393403413423433443452162172182192202212222232243463473483493503513523538 unmodified lines362363364365366367368105 unmodified lines4744754763503513523533543553563573584774784794804814824834844854864874884894906 unmodified lines49749849950050150250320 unmodified lines5245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875882 unmodified linesfrom __future__ import annotations
import argparseimport difflibimport jsonimport sysfrom dataclasses import asdictfrom pathlib import Pathfrom typing import List, Optional, Sequencefrom typing import Any, Dict, List, Optional, Sequence, Tuple
from lingologos_python._codex_bridge import ensure_codex_on_path
4 unmodified linesfrom 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.ast_graph import ( # noqa: E402 build_reverse_index, discover_python_files, extract_python_graph, importers_from_index,)from lingologos_python.patterns import ( # noqa: E402 PATTERNS, pattern_card, plan_pattern, render_card, scan_pattern,)from lingologos_python.session import ( # noqa: E402 DEFAULT_PROTECTED_PATTERNS, SESSION_LOCK_NAME, PythonWorkspaceSession, workspace_lock_status,)from lingologos_python.test_selector import select_python_tests # noqa: E402
13 unmodified lines # Flags shared by every verb that opens a session: the same tools, the same # topology, and the same budgets answer from verify to delete. session_flags = argparse.ArgumentParser(add_help=False) session_flags.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") session_flags.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.") session_flags.add_argument("--node-timeout", type=float, default=120.0, metavar="SEC", help="Per-node budget when nodes run as subprocesses; an exhausted budget answers UNKNOWN.") session_flags.add_argument("--strict-tools", action="store_const", const=True, default=None, help="Demand mypy and ruff; abstain when absent.") session_flags.add_argument("--subprocesses", action="store_const", const=True, default=None, help="Run the six topology nodes as separate subprocesses.") session_flags.add_argument("--node-timeout", type=float, default=None, metavar="SEC", help="Per-node budget when nodes run as subprocesses; an exhausted budget answers UNKNOWN.") session_flags.add_argument("--total-timeout", type=float, default=None, metavar="SEC", help="Cap the sum of the six node waits; each node gets the smaller of its budget and the remaining time.") session_flags.add_argument("--gate-timeout", type=float, default=None, metavar="SEC", help="Wall-clock budget for each gate command (test runner, static checker); a runner that exhausts it abstains.") session_flags.add_argument("--lock-wait", type=float, default=None, metavar="SEC", help="Wait up to SEC seconds for a workspace lock another session holds; 0 answers the refusal at once.") session_flags.add_argument("--protect", action="append", default=None, metavar="PATTERN", help="Add one protected pattern on top of the defaults; repeatable.") session_flags.add_argument("--config", default=None, metavar="FILE", help="JSON file holding these session defaults; a flag on the command line wins over the file.") session_flags.add_argument("--print-diff", action="store_const", const=True, default=None, help="Print a unified diff of the pair before the verdict line.") session_flags.add_argument("--audit", default=None, metavar="FILE", help="Append one JSON line describing this run to FILE.")
# verify p_verify = sub.add_parser("verify", parents=[session_flags], help="Verify a Python workspace through the six-node codex pipeline.")10 unmodified lines p_edit.add_argument("--replace", default=None, help="Replacement text block.") p_edit.add_argument("--replace-file", default=None, help="Path to a file holding the replacement text block.") p_edit.add_argument("--dry-run", action="store_true", help="Verify without committing to disk.") p_edit.add_argument("--allow-single-prover", action="store_true", help="Allow commit at assurance 2.") p_edit.add_argument("--allow-single-prover", action="store_const", const=True, default=None, help="Allow commit at assurance 2.") p_edit.add_argument("--json", action="store_true", help="Print JSON output.")
# create2 unmodified lines 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("--allow-single-prover", action="store_true", help="Commit at assurance 2 when the two trusted roles do not both agree.") p_create.add_argument("--allow-single-prover", action="store_const", const=True, default=None, help="Commit at assurance 2 when the two trusted roles do not both agree.") p_create.add_argument("--json", action="store_true", help="Print JSON output.")
# delete5 unmodified lines p_delete.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_delete.add_argument("--file", required=True, help="Relative Python file to delete.") p_delete.add_argument("--dry-run", action="store_true", help="Verify the removal without deleting from disk.") p_delete.add_argument("--allow-single-prover", action="store_true", help="Commit at assurance 2 when the two trusted roles do not both agree.") p_delete.add_argument("--allow-single-prover", action="store_const", const=True, default=None, help="Commit at assurance 2 when the two trusted roles do not both agree.") p_delete.add_argument("--json", action="store_true", help="Print JSON output.")
# symbols20 unmodified lines 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("--allow-single-prover", action="store_true", help="Commit at assurance 2 when the two trusted roles do not both agree; a card that states its own bar keeps it.") p_pat.add_argument("--allow-single-prover", action="store_const", const=True, default=None, help="Commit at assurance 2 when the two trusted roles do not both agree; a card that states its own bar keeps it.") p_pat.add_argument("--json", action="store_true", help="Print JSON output.")
# check-adapter2 unmodified lines p_check.add_argument("--strict-tools", action="store_true", help="Check StrictPythonLanguageAdapter.") p_check.add_argument("--json", action="store_true", help="Print JSON output.")
# graph p_graph = sub.add_parser( "graph", help="Print which files import which, forward and backward, and prove the two answers mirror.", ) p_graph.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_graph.add_argument("--json", action="store_true", help="Print JSON output.")
# lock-status p_lock = sub.add_parser( "lock-status", help="Read who holds the workspace session lock, touching nothing.", ) p_lock.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_lock.add_argument("--json", action="store_true", help="Print JSON output.")
return parser
8 unmodified lines return value
CONFIG_KEYS = ( "strict_tools", "subprocesses", "allow_single_prover", "node_timeout", "total_timeout", "gate_timeout", "lock_wait", "protect",)
def _load_config(path: str) -> Dict[str, Any]: """The JSON defaults of one config file, checked key by key before anything runs.""" try: data = json.loads(Path(path).read_text(encoding="utf-8")) except OSError as exc: raise ValueError("cannot read config file '%s': %s" % (path, exc.strerror or exc)) except json.JSONDecodeError as exc: raise ValueError("config file '%s' is not JSON: %s" % (path, exc)) if not isinstance(data, dict): raise ValueError("config file '%s' must hold one JSON object" % path) for key, value in sorted(data.items()): if key not in CONFIG_KEYS: raise ValueError("config file names unknown key '%s'" % key) if key == "protect": if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value): raise ValueError("config key 'protect' must hold a list of pattern strings") elif key in ("strict_tools", "subprocesses", "allow_single_prover"): if not isinstance(value, bool): raise ValueError("config key '%s' must hold true or false" % key) elif isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError("config key '%s' must hold a number of seconds" % key) return data
def _session_options(args: argparse.Namespace) -> argparse.Namespace: """Merge three sources in one honest order: the flag, then the config file, then the built-in default.""" config: Dict[str, Any] = {} if getattr(args, "config", None) is not None: config = _load_config(args.config)
def pick(flag_value: Any, key: str, default: Any) -> Any: if flag_value is not None: return flag_value if key in config: return config[key] return default
opts = argparse.Namespace() opts.strict_tools = bool(pick(getattr(args, "strict_tools", None), "strict_tools", False)) opts.use_subprocesses = bool(pick(getattr(args, "subprocesses", None), "subprocesses", False)) opts.min_assurance = 2 if pick(getattr(args, "allow_single_prover", None), "allow_single_prover", False) else 3 opts.node_timeout_sec = pick(getattr(args, "node_timeout", None), "node_timeout", 120.0) opts.total_budget_sec = pick(getattr(args, "total_timeout", None), "total_timeout", None) opts.gate_timeout_sec = pick(getattr(args, "gate_timeout", None), "gate_timeout", None) opts.lock_wait_sec = pick(getattr(args, "lock_wait", None), "lock_wait", 0.0) protect = pick(getattr(args, "protect", None), "protect", None) opts.protected_patterns = DEFAULT_PROTECTED_PATTERNS + tuple(protect or ()) return opts
def _open_session(args: argparse.Namespace) -> Tuple[PythonWorkspaceSession, argparse.Namespace]: opts = _session_options(args) session = PythonWorkspaceSession( args.workspace, protected_patterns=opts.protected_patterns, strict_tools=opts.strict_tools, use_subprocesses=opts.use_subprocesses, min_assurance=opts.min_assurance, node_timeout_sec=opts.node_timeout_sec, total_budget_sec=opts.total_budget_sec, gate_timeout_sec=opts.gate_timeout_sec, lock_wait_sec=opts.lock_wait_sec, ) return session, opts
def _print_diff(old_label: str, new_label: str, before: str, after: str) -> None: """The pair as a unified diff, the same shape any git reader already knows.""" for line in difflib.unified_diff( before.splitlines(), after.splitlines(), fromfile=old_label, tofile=new_label, lineterm="", ): print(line)
def _append_audit(args: argparse.Namespace, res: Any) -> None: """One JSONL line per session run, wherever the reader asked the ledger to sit.""" if getattr(args, "audit", None) is None: return row = {"command": args.command, "workspace": str(Path(args.workspace).resolve())} row.update(res.to_dict()) with open(args.audit, "a", encoding="utf-8", newline="\n") as handle: handle.write(json.dumps(row, sort_keys=True) + "\n")
def main(argv: Optional[Sequence[str]] = None) -> int: parser = _build_parser() args = parser.parse_args(argv) try: return _run(args) except ValueError as exc: # A bad config file, an unknown key, or a budget the session refuses: # the command shape is fine, the values are not, and exit 2 says so. print("REFUSED: %s" % exc, file=sys.stderr) return 2
def _run(args: argparse.Namespace) -> int: if args.command == "verify": session = PythonWorkspaceSession( args.workspace, strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, node_timeout_sec=args.node_timeout, total_budget_sec=args.total_timeout, gate_timeout_sec=args.gate_timeout, ) session, _opts = _open_session(args) 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}") _append_audit(args, res) 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, node_timeout_sec=args.node_timeout, total_budget_sec=args.total_timeout, gate_timeout_sec=args.gate_timeout, ) session, opts = _open_session(args) search_text = _side_text(args.search, args.search_file, "search") replace_text = _side_text(args.replace, args.replace_file, "replace") if search_text is None or replace_text is None: print("edit needs exactly one source of text on each side of the pair", file=sys.stderr) return 2 if args.print_diff and not args.json: _print_diff("a/" + args.file, "b/" + args.file, search_text, replace_text) res = session.edit_file( args.file, search_text,9 unmodified lines ) # Exit 0 only when the edit landed on disk, or a dry run cleared the bar. # An accepted verdict whose commit never landed is a failure to report. _append_audit(args, res) return 0 if res.committed or (args.dry_run and res.assurance >= min_assurance) else 1 return 0 if res.committed or (args.dry_run and res.assurance >= opts.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, use_subprocesses=args.subprocesses, min_assurance=2 if args.allow_single_prover else 3, node_timeout_sec=args.node_timeout, total_budget_sec=args.total_timeout, gate_timeout_sec=args.gate_timeout, ) session, _opts = _open_session(args) if args.print_diff and not args.json: _print_diff("/dev/null", "b/" + args.file, "", content) try: res = session.create_file(args.file, content, commit=not args.dry_run) except FileExistsError as exc:8 unmodified lines ) # Exit 0 only when the file landed, or a dry run was accepted; a verdict # that never wrote anything is a failure, whatever its assurance says. _append_audit(args, res) return 0 if res.committed or (args.dry_run and res.accepted) else 1
if args.command == "delete": session = PythonWorkspaceSession( args.workspace, strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, min_assurance=2 if args.allow_single_prover else 3, node_timeout_sec=args.node_timeout, total_budget_sec=args.total_timeout, gate_timeout_sec=args.gate_timeout, ) session, _opts = _open_session(args) source = Path(args.workspace) / Path(*args.file.split("/")) if args.print_diff and not args.json: original = source.read_text(encoding="utf-8", newline="") if source.is_file() else "" _print_diff("a/" + args.file, "/dev/null", original, "") try: res = session.delete_file(args.file, commit=not args.dry_run) except FileNotFoundError as exc:8 unmodified lines ) # A removal lands or it does not: exit 0 only when the file is gone, # or when a dry run verified the removal without touching the disk. _append_audit(args, res) return 0 if res.committed or (args.dry_run and res.accepted) else 1
if args.command == "symbols":105 unmodified lines for line in hit.evidence: print(" why: %s" % line) return 0 session = PythonWorkspaceSession( args.workspace, strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, min_assurance=2 if args.allow_single_prover else 3, node_timeout_sec=args.node_timeout, total_budget_sec=args.total_timeout, gate_timeout_sec=args.gate_timeout, ) session, _opts = _open_session(args) if args.print_diff and not args.json: plan = plan_pattern(root, args.pattern, args.target) if plan.refused: print( "the card refuses %s with %s, so there is no diff to show" % (args.target or "every function in this workspace", plan.reason_code) ) else: for edit in plan.edits: _print_diff("a/" + edit.file, "b/" + edit.file, edit.search, edit.replace) 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))6 unmodified lines print("nothing was written; the card named this reason before any node ran") # Exit 0 only when the pair landed, or a dry run was accepted: a card can # be verified in staging and still lose the commit to the disk. _append_audit(args, res) return 0 if res.committed or (args.dry_run and res.accepted) else 1
if args.command == "check-adapter":20 unmodified lines print(f"ADAPTER OK: {adapter.meta().name}") return 1 if violations else 0
if args.command == "graph": root = Path(args.workspace).resolve() if not root.is_dir(): print("REFUSED: workspace does not exist: %s" % root, file=sys.stderr) return 1 files = discover_python_files(root) _symbols, edges = extract_python_graph(root, files) file_edges = sorted( { (edge[0], edge[1]) for edge in edges if "::" not in edge[0] and "::" not in edge[1] } ) index = build_reverse_index(root, files) importers = {rel: importers_from_index(index, rel) for rel in files} if any(source not in importers.get(target, []) for source, target in file_edges): print( "REFUSED: the forward walk and the reverse index disagree about an import edge", file=sys.stderr, ) return 1 if args.json: print( json.dumps( { "files": files, "import_edges": [list(edge) for edge in file_edges], "importers": importers, }, indent=2, sort_keys=True, ) ) else: print("files=%d import_edges=%d" % (len(files), len(file_edges))) for rel in files: if importers[rel]: print(" %s <- %s" % (rel, ", ".join(importers[rel]))) return 0
if args.command == "lock-status": root = Path(args.workspace) if not root.is_dir(): print("REFUSED: workspace does not exist: %s" % root, file=sys.stderr) return 1 status = workspace_lock_status(root) if args.json: print(json.dumps(status, indent=2, sort_keys=True)) elif not status["present"]: print("free: no lock file named %s in this workspace" % SESSION_LOCK_NAME) elif status["unreadable"]: print("held: a lock file sits there and its owner cannot be read") elif status["held"]: print("held: process %d holds the workspace" % status["holder_pid"]) else: print("free: the leftover lock names process %d, which no longer runs" % status["holder_pid"]) return 1 if status["held"] else 0
return 2
42 unmodified lines4344454646474897 unmodified lines14614714814915015115212 unmodified lines16516616716816917017116 unmodified lines1881891901911921931941951961941971981992007 unmodified lines2082092102112122132142152162122172182192206 unmodified lines22722822923023123223312 unmodified lines2462472482492502512522533 unmodified lines2572582592602612622638 unmodified lines27227327427527627727812 unmodified lines29129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036179 unmodified lines44144244337544444544644712 unmodified lines46046146239446346446546646746846947047147242 unmodified lines rules.NOT_ASCII_TARGET, rules.TAB_INDENTED_TARGET, rules.CRLF_TARGET, rules.ASYNC_TARGET, rules.NO_TEST_FILE, rules.NO_TEST_ANCHOR, rules.AMBIGUOUS_TEST_ANCHOR,97 unmodified lines "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", "a coroutine target is claimed too: the lock reads the signature, which needs no call and waits for nothing", ), (LOCK_COMPANION,), "the signature of the function carries the annotation the pattern added and the default it started with",12 unmodified lines "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", "a coroutine target is claimed too, and the lock waits for its two calls with asyncio.run", ), (LOCK_COMPANION,), "the default is None, the guard is in the source, and two calls that omit the argument answer differently",16 unmodified lines "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", "a coroutine target is refused with ASYNC_TARGET: the rewrite moves the calls of the chain, " "and this card carries no coroutine pair that would say whether they await", ), (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), (rules.NO_DISPATCH_CHAIN, rules.BRANCH_SHAPE_MISMATCH, rules.NOT_A_MODULE_FUNCTION, rules.ASYNC_TARGET), ), _card( "open-to-context-manager",7 unmodified lines "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", "a coroutine target is refused with ASYNC_TARGET: this card carries no coroutine pair " "that would prove its lock test waits for one", ), (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), (rules.ALREADY_SCOPED, rules.NO_BARE_OPEN, rules.HANDLE_ESCAPE, rules.NOT_A_MODULE_FUNCTION, rules.ASYNC_TARGET), ), _card( "bare-assert-to-explicit-raise",6 unmodified lines "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", "a coroutine target is claimed too, and the lock waits for its one call with asyncio.run", ), (LOCK_COMPANION,), "the source carries the raise and no assert line, and the call still refuses the argument the check "12 unmodified lines "the handler carries the bare header text the rule anchors on, 'except:'", "the handler body does not end by re-raising what it caught, which is a second change", "the function text holds no other 'except:' the lock could confuse with a header", "a coroutine target is refused with ASYNC_TARGET: the lock reads the text, but the corpus " "carries no coroutine pair for this card to vouch for the read", ), (LOCK_COMPANION,), "the source names Exception in every handler that was bare and carries no bare header left; "3 unmodified lines rules.BARE_EXCEPT_RE_RAISES, rules.EXCEPT_HANDLER_UNREADABLE, rules.NOT_A_MODULE_FUNCTION, rules.ASYNC_TARGET, ), ), _card(8 unmodified lines "the comparison is a single equality test against None, not a chained comparison", "None is written as the plain literal on one side of the test", "the file is ASCII text with LF endings and spaces for indentation", "a coroutine target is claimed too: the lock reads the text and waits for nothing", ), (LOCK_COMPANION,), "every test the pattern touched reads with is or is not, and the source carries no == None or "12 unmodified lines "the value counted is a plain name, so the rewrite evaluates it no more than before", "the comparison is a single test against the number 0, not against False or a chain", "the file is ASCII text with LF endings and spaces for indentation", "a coroutine target is claimed too: the lock reads the text and waits for nothing", ), (LOCK_COMPANION,), "each check the pattern touched became a truthiness test, and its counted comparison is gone " "from the source; the lock reads the function back with inspect, so it answers about the text", (rules.NO_EMPTY_LEN_CHECK, rules.LEN_TARGET_IS_NOT_A_NAME, rules.NOT_A_MODULE_FUNCTION), ), _card( "init-missing-super", "contracts", ("construction", "inheritance", "super"), "a module level class whose '__init__' takes only self, names no base of its own, and " "does not open the constructor chain first", "a constructor that builds without calling super leaves the parts a base would have " "initialized missing, and the class only looks finished until one of those parts is " "asked for. Opening the chain first puts the base back in the path it was written to be in.", ( "the class is defined at module level and names no base or keyword argument, so super is the object itself", "the '__init__' takes self alone, so the rule has nothing to forward and changes no arguments", "the call goes after the docstring and before the first statement that builds", "a file named '__init__.py' is refused: there a line means the package, not a class", ), (LOCK_COMPANION,), "the first executable line of the constructor is 'super().__init__()', and the class " "still builds the object its tests ask for", ( rules.NO_SUCH_CLASS, rules.NOT_A_MODULE_CLASS, rules.NOT_A_METHOD, rules.NO_INIT_METHOD, rules.INIT_TAKES_MORE_THAN_SELF, rules.SUPER_CALL_ALREADY_FIRST, rules.SUPER_BASES_UNREADABLE, rules.PACKAGE_FILE_TARGET, rules.ASYNC_TARGET, ), ), _card( "drop-unused-imports", "shape", ("imports", "cleanup", "dead code"), "a module level function in a file whose top level import lines bind names that no other " "line of the file reads", "an import that binds nothing is a promise to a module nobody calls: it costs the reader a " "line to learn nothing, and it keeps a dependency alive that the file does not use. The " "rewrite removes exactly the lines the text itself shows unread.", ( "the claim reaches only top level import statements, whose effect on the file is readable from the file", "a name counts as read when another line of the file spells it, outside the import lines themselves", "the unread lines sit on consecutive lines, so one anchor removes them together", "a file with an __all__ or a star import is refused, because there a name can be carried without being spelled", "a file named '__init__.py' is refused, because there an import line can be the interface of a package", ), (LOCK_COMPANION,), "the removed import lines are gone from the module and the function that never read them " "is still callable; the lock reads the module back with inspect, so it answers about the text", ( rules.NO_UNUSED_IMPORT, rules.STAR_IMPORT_IN_FILE, rules.NAME_LISTED_IN_ALL, rules.PACKAGE_FILE_TARGET, rules.IMPORTS_NOT_CONTIGUOUS, rules.NOT_A_MODULE_FUNCTION, ), ), )}
79 unmodified lines tree = ast.parse(text) except SyntaxError: return () return tuple(node.name for node in tree.body if isinstance(node, ast.FunctionDef)) return tuple(node.name for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)))
def scan_pattern(root: str | Path, pattern_id: str, *, files: Optional[Sequence[str]] = None) -> List[Tuple[str, rules.RuleHit]]:12 unmodified lines tree = ast.parse(text) except SyntaxError: continue for symbol in tuple(node.name for node in tree.body if isinstance(node, ast.FunctionDef)): symbols = [node.name for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))] for node in tree.body: if isinstance(node, ast.ClassDef): for item in node.body: if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): symbols.append("%s.%s" % (node.name, item.name)) for symbol in symbols: target, miss = rules.open_target_with_tree(rel, symbol, text, tree, reader) if target is None: continue28 unmodified lines2930313233343530 unmodified lines666768697071727374757677787980818283193 unmodified lines277278279267268280281282283284285286287288289272290291292293294277295296297298193 unmodified lines49249349447749549649749874 unmodified lines57357457555857657757857968 unmodified lines64864965063363465165265365465565665765824 unmodified lines683684685686687688689690691692693694695696697698699700701702703704705373 unmodified lines1079108010811046108210831084108530 unmodified lines111611171118108311191120112111225 unmodified lines1128112911301131113211331134127 unmodified lines1262126312641228126512661267126882 unmodified lines1351135213531317135413551356135764 unmodified lines1422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317243 unmodified lines1728172917301731173217331734173528 unmodified lines
import astimport keywordimport refrom dataclasses import dataclassfrom typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
30 unmodified linesNONE_COMPARISON_IS_CHAINED = "NONE_COMPARISON_IS_CHAINED"NO_EMPTY_LEN_CHECK = "NO_EMPTY_LEN_CHECK"LEN_TARGET_IS_NOT_A_NAME = "LEN_TARGET_IS_NOT_A_NAME"NO_SUCH_CLASS = "NO_SUCH_CLASS"NOT_A_MODULE_CLASS = "NOT_A_MODULE_CLASS"NOT_A_METHOD = "NOT_A_METHOD"NO_INIT_METHOD = "NO_INIT_METHOD"INIT_TAKES_MORE_THAN_SELF = "INIT_TAKES_MORE_THAN_SELF"SUPER_CALL_ALREADY_FIRST = "SUPER_CALL_ALREADY_FIRST"SUPER_BASES_UNREADABLE = "SUPER_BASES_UNREADABLE"NO_UNUSED_IMPORT = "NO_UNUSED_IMPORT"STAR_IMPORT_IN_FILE = "STAR_IMPORT_IN_FILE"NAME_LISTED_IN_ALL = "NAME_LISTED_IN_ALL"PACKAGE_FILE_TARGET = "PACKAGE_FILE_TARGET"IMPORTS_NOT_CONTIGUOUS = "IMPORTS_NOT_CONTIGUOUS"
INDENT = " "_MUTABLE_LITERALS = (ast.List, ast.Dict, ast.Set)193 unmodified lines 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."""def module_function(target: Target, allow_async: bool = False) -> Tuple[Optional[ast.FunctionDef], Optional[RuleMiss]]: """The module level function the target names, or the refusal that says why not.
A coroutine is a refusal unless the card opted in. A lock test written for a coroutine has to wait for it, and only the cards that do that name coroutines among their targets; the rest answer ASYNC_TARGET and say so on the card. """
for node in target.tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol: if isinstance(node, ast.AsyncFunctionDef): if isinstance(node, ast.AsyncFunctionDef) and not allow_async: return None, _miss( target.rel_posix, target.symbol, ASYNC_TARGET, "'%s' is a coroutine, and the lock tests of this catalog call their target directly" % target.symbol, "'%s' is a coroutine, and this card writes its lock test for a plain def" % target.symbol, ) return node, None for node in ast.walk(target.tree):193 unmodified lines for it is an Optional, and that needs an import this transform will not add. """
function, miss = module_function(target) function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None74 unmodified lines the default, so the value each call starts from is the one the author wrote. """
function, miss = module_function(target) function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None68 unmodified lines "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")), "first = %s" % _run_call(function, alias, target.symbol, _probe_arguments(function, mutable, "alpha")), "second = %s" % _run_call(function, alias, target.symbol, _probe_arguments(function, mutable, "beta")), "assert first != second", ], headers=_lock_headers(function), ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None:24 unmodified lines return ", ".join(repr(word) for _ in needed)
def _run_call(function: ast.FunctionDef, alias: str, symbol: str, arguments: str) -> str: """One lock-test call of the target: straight for a def, through asyncio for a coroutine."""
call = "%s.%s(%s)" % (alias, symbol, arguments) if isinstance(function, ast.AsyncFunctionDef): return "asyncio.run(%s)" % call return call
def _lock_headers(function: ast.FunctionDef) -> Tuple[str, ...]: """The extra imports a lock test needs when its target is a coroutine."""
if isinstance(function, ast.AsyncFunctionDef): return ("import asyncio",) return ()
# ---------------------------------------------------------------------------# Rule 3: an equality chain that returns calls becomes a registry.# ---------------------------------------------------------------------------373 unmodified lines does before it refuses. """
function, miss = module_function(target) function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None30 unmodified lines "assert 'raise AssertionError(' in source", "assert not [line for line in source.splitlines() if line.strip().startswith('assert ')]", "try:", ' %s.%s("")' % (alias, target.symbol), ' %s' % _run_call(function, alias, target.symbol, '""'), "except AssertionError as caught:", " pass" if check.msg is None else " assert %s in str(caught)" % arguments, "else:",5 unmodified lines test_name, "Lock the raise that replaced the assert, and the refusal the function still carries.", statements, headers=_lock_headers(function), ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None:127 unmodified lines whatever that equality happens to say. Identity asks the question that was meant. """
function, miss = module_function(target) function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None82 unmodified linesdef rule_empty_len_to_truthiness(target: Target) -> Outcome: """Ask whether a collection is empty by truthiness instead of counting it."""
function, miss = module_function(target) function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None64 unmodified lines return _hit("empty-len-to-truthiness", target, edit, companion, evidence)
# ---------------------------------------------------------------------------# Rule 9: a constructor that replaced the chain should open it first.# ---------------------------------------------------------------------------
def module_method(target: Target) -> Tuple[Optional[ast.FunctionDef], Optional[RuleMiss]]: """The module level class method a ``Class.method`` target names, or the refusal."""
class_name, separator, method_name = target.symbol.partition(".") if not separator or not method_name: return None, _miss( target.rel_posix, target.symbol, NOT_A_METHOD, "'%s' names no class and method split by a dot" % target.symbol, ) for node in target.tree.body: if isinstance(node, ast.ClassDef) and node.name == class_name: for item in node.body: if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and item.name == method_name: if isinstance(item, ast.AsyncFunctionDef): return None, _miss( target.rel_posix, target.symbol, ASYNC_TARGET, "'%s.%s' is a coroutine, and no lock test of this catalog waits for one" % (class_name, method_name), ) return item, None if method_name == "__init__": return None, _miss( target.rel_posix, target.symbol, NO_INIT_METHOD, "class '%s' defines no '__init__' of its own" % class_name, ) return None, _miss( target.rel_posix, target.symbol, NOT_A_METHOD, "class '%s' defines no method named '%s'" % (class_name, method_name), ) for node in ast.walk(target.tree): if isinstance(node, ast.ClassDef) and node.name == class_name: return None, _miss( target.rel_posix, target.symbol, NOT_A_MODULE_CLASS, "class '%s' is not defined at module level in '%s'" % (class_name, target.rel_posix), ) return None, _miss( target.rel_posix, target.symbol, NO_SUCH_CLASS, "no class named '%s' in '%s'" % (class_name, target.rel_posix), )
def _opens_super(statement: ast.stmt) -> bool: """True for a bare ``super().__init__(...)`` statement."""
return ( isinstance(statement, ast.Expr) and isinstance(statement.value, ast.Call) and isinstance(statement.value.func, ast.Attribute) and statement.value.func.attr == "__init__" and isinstance(statement.value.func.value, ast.Call) and isinstance(statement.value.func.value.func, ast.Name) and statement.value.func.value.func.id == "super" )
def rule_init_missing_super(target: Target) -> Outcome: """Open the constructor chain of a module level class that replaced it.
The rule claims the narrowest shape it can state honestly: a class naming no base of its own, whose ``__init__`` takes only ``self``. A named base is a constructor with arguments this rule cannot forward, and calling super without them would change what the class builds, which a cleanup pattern may not do. """
method, miss = module_method(target) if method is None: return miss assert method is not None if method.name != "__init__": return _miss( target.rel_posix, target.symbol, NOT_A_METHOD, "this card writes a constructor, and '%s' names no '__init__'" % target.symbol, ) starts = line_starts(target.text) class_name = target.symbol.partition(".")[0] class_node: Optional[ast.ClassDef] = None for node in target.tree.body: if isinstance(node, ast.ClassDef) and node.name == class_name: class_node = node break assert class_node is not None if class_node.bases or class_node.keywords: return _miss( target.rel_posix, target.symbol, SUPER_BASES_UNREADABLE, "class '%s' names base classes, and this rule cannot say which constructor super reaches " "or what arguments it takes" % class_name, ) if ( [argument.arg for argument in method.args.posonlyargs + method.args.args] != ["self"] or method.args.kwonlyargs or method.args.vararg or method.args.kwarg ): return _miss( target.rel_posix, target.symbol, INIT_TAKES_MORE_THAN_SELF, "'%s' takes arguments this rule cannot forward, and calling super without them " "would change what the class builds" % target.symbol, ) real = [statement for statement in method.body if not _is_string_statement(statement)] if real and _opens_super(real[0]): return _miss( target.rel_posix, target.symbol, SUPER_CALL_ALREADY_FIRST, "class '%s' already opens its constructor chain first" % class_name, ) has_docstring = bool(method.body and _is_string_statement(method.body[0])) if real: body_start = starts[real[0].lineno - 1] + real[0].col_offset indent = " " * real[0].col_offset else: docstring = method.body[0] body_start = starts[docstring.end_lineno - 1] + docstring.end_col_offset + 1 indent = " " * docstring.col_offset splices = [_Splice(start=body_start, end=body_start, text="super().__init__()\n%s" % indent)] edit = _rewrite_function(target, starts, method, splices, "constructor chain of '%s' opened" % target.symbol)
alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s.%s)" % (alias, target.symbol), "assert 'super().__init__()' in source", "lines = [line.strip() for line in source.splitlines() if line.strip()]", "assert lines[0].startswith('def __init__')", "assert lines[%d] == 'super().__init__()'" % (2 if has_docstring else 1), "created = %s.%s()" % (alias, class_name), "assert isinstance(created, %s.%s)" % (alias, class_name), ] test_name = "%s_init_calls_super_first" % class_name lock = lock_source( target.rel_posix, test_name, "Lock the super call this rule put first in the constructor, and the class that still builds.", 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 = ("'%s.__init__' builds its object without opening the constructor chain first" % class_name,) return _hit("init-missing-super", target, edit, companion, evidence)
# ---------------------------------------------------------------------------# Rule 10: an import that binds nothing is a promise to a module nobody calls.# ---------------------------------------------------------------------------
def rule_drop_unused_imports(target: Target) -> Outcome: """Remove top level imports that bind a name no other line of the file reads.
A name that appears nowhere else in the text is decidable from the file alone, and that is exactly the limit of the rule: ``__all__``, a star import, and a package ``__init__.py`` all let one line of a file mean more than the names it spells, and the rule refuses them rather than guess what a reader of the package expects. """
function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None starts = line_starts(target.text) if target.rel_posix == "__init__.py" or target.rel_posix.endswith("/__init__.py"): return _miss( target.rel_posix, target.symbol, PACKAGE_FILE_TARGET, "'%s' is a package interface, where an import line can be the name the package publishes" % target.rel_posix, ) import_nodes = [node for node in target.tree.body if isinstance(node, (ast.Import, ast.ImportFrom))] if not import_nodes: return _miss( target.rel_posix, target.symbol, NO_UNUSED_IMPORT, "'%s' imports nothing at top level, so nothing there can go unread" % target.rel_posix, ) if any( isinstance(node, ast.ImportFrom) and any(alias.name == "*" for alias in node.names) for node in import_nodes ): return _miss( target.rel_posix, target.symbol, STAR_IMPORT_IN_FILE, "'%s' takes names through a star import, so the file can read names its text never writes" % target.rel_posix, ) for node in target.tree.body: if isinstance(node, (ast.Assign, ast.AnnAssign)): for assignment in getattr(node, "targets", [node.target]): if isinstance(assignment, ast.Name) and assignment.id == "__all__": return _miss( target.rel_posix, target.symbol, NAME_LISTED_IN_ALL, "'%s' publishes an __all__, and a name the text never reads can still carry that promise" % target.rel_posix, ) covered = set() for node in import_nodes: covered.update(range(node.lineno, node.end_lineno + 1)) other_text = "\n".join( line for index, line in enumerate(target.text.split("\n"), start=1) if index not in covered ) unused_nodes: List[ast.stmt] = [] unused_names: List[str] = [] for node in import_nodes: names = [ alias.asname or (alias.name.split(".")[0] if isinstance(node, ast.Import) else alias.name) for alias in node.names ] if all(re.search(r"\b%s\b" % re.escape(name), other_text) is None for name in names): unused_nodes.append(node) unused_names.extend(names) if not unused_nodes: return _miss( target.rel_posix, target.symbol, NO_UNUSED_IMPORT, "every top level import of '%s' binds a name another line of the file reads" % target.rel_posix, ) unused_nodes.sort(key=lambda node: node.lineno) for previous, following in zip(unused_nodes, unused_nodes[1:]): if following.lineno != previous.end_lineno + 1: return _miss( target.rel_posix, target.symbol, IMPORTS_NOT_CONTIGUOUS, "the unread imports of '%s' are not on consecutive lines, so one anchor cannot remove them together" % target.rel_posix, ) block_start = starts[unused_nodes[0].lineno - 1] last_node = unused_nodes[-1] block_end = starts[last_node.end_lineno - 1] + last_node.end_col_offset + 1 block = target.text[block_start:block_end] if target.text.count(block) != 1: return _miss( target.rel_posix, target.symbol, ANCHOR_OVERLAP, "the import block this rule would remove appears more than once in '%s'" % target.rel_posix, ) edit = Edit( file=target.rel_posix, search=block, replace="", label="unread imports of '%s' removed" % target.rel_posix, )
alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s)" % alias, "import_lines = [line.strip() for line in source.splitlines() if line.strip().startswith(('import ', 'from '))]", ] for name in sorted(set(unused_names)): statements.append("assert not [line for line in import_lines if %r in line.split()]" % name) statements.append("assert callable(%s.%s)" % (alias, function.name)) test_name = "%s_keeps_no_unread_imports" % function.name lock = lock_source( target.rel_posix, test_name, "Lock the import lines this rule removed from the module and the function they never reached.", 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 import of '%s' binds a name no other line of '%s' reads" % (name, target.rel_posix) for name in sorted(set(unused_names)) ) return _hit("drop-unused-imports", 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,3 unmodified lines "bare-except-to-narrow-exception": rule_bare_except_to_narrow_exception, "none-comparison-to-identity": rule_none_comparison_to_identity, "empty-len-to-truthiness": rule_empty_len_to_truthiness, "init-missing-super": rule_init_missing_super, "drop-unused-imports": rule_drop_unused_imports,}
RULE_IDS: Tuple[str, ...] = tuple(sorted(RULES))19 unmodified lines2021222324252629 unmodified lines565758596061606263646544 unmodified lines11011111211311411511611711811912012112296 unmodified lines219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265370 unmodified lines6366376386396406416429 unmodified lines65265365465565660565765865966066166266366455 unmodified lines72072172272372472572667067167267367467567667767867968068168268368468568668772772872973073173273373473573673773873974074174274374474574668969069174774874975075157 unmodified lines8098108118128138148158168178188198208218228238248258268278288298308318328338348354 unmodified lines84084184284376584484584684716 unmodified lines864865866788867868869870871872873793874875876877878879880881882883884885886795796797798799800887888889890248 unmodified lines11391140114110551142114311441145225 unmodified lines13711372137312871374137513761377119 unmodified lines1497149814991413150015011502150384 unmodified lines1588158915901504159115921593159418 unmodified lines1613161416151529161616171618161984 unmodified lines17041705170616201621170717081709171017111712171319 unmodified linesimport subprocessimport sysimport tempfileimport threadingimport timeimport uuidfrom dataclasses import dataclass, field29 unmodified linesfrom lingologos_python.adapter import GATE_TIMEOUT_ENV # noqa: E402from lingologos_python.ast_graph import ( # noqa: E402 IGNORED_DIRS, build_reverse_index, discover_python_files, hardlinked_file, importers_of, importers_from_index, is_linked_path,)from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E40244 unmodified linesSESSION_LOCK_NAME = ".lingologos-session.lock"SESSION_LOCK_CLAIM_SUFFIX = ".stale"
# The gate budget reaches the kernel through the environment, and a process# carries one such window at a time: every six-node call, together with the# environment set and restore around it, is serialized by this lock. Documented# limit: two CodeLinguistSessions in one process take their six-node turns in# order rather than interleaving._KERNEL_CALL_LOCK = threading.Lock()
def _process_alive(pid: int) -> bool: """Best effort: is a process with this pid still running on this machine?"""96 unmodified lines return True
def workspace_lock_status(workspace_root: str | Path) -> Dict[str, Any]: """What a reader may know about the workspace lock, reading and touching nothing.
Three answers, no fourth: no lock at all; a lock whose holder lives; and a leftover whose holder no longer runs, which the next session takes over through the rename and which therefore reads as free. A lock file whose owner cannot even be read counts as held, because no run may grant itself the workspace without the takeover dance. """ root = Path(workspace_root).resolve() lock = root / SESSION_LOCK_NAME status: Dict[str, Any] = { "workspace": str(root), "lock_file": SESSION_LOCK_NAME, "present": lock.is_file(), "held": False, "stale": False, "unreadable": False, "holder_pid": None, "holder_birth": None, "holder_alive": None, } if not status["present"]: return status record = _read_lock_record(lock) if record is None: status["held"] = True status["unreadable"] = True return status pid, birth, _token = record alive = _lock_holder_is_alive(record) status.update( holder_pid=pid, holder_birth=birth, holder_alive=alive, held=alive, stale=not alive, ) return status
DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ( "*.env", ".env*",370 unmodified lines node_timeout_sec: float = 120.0, total_budget_sec: Optional[float] = None, gate_timeout_sec: Optional[float] = None, lock_wait_sec: float = 0.0, ) -> None: self.workspace_root = Path(workspace_root).resolve() if not self.workspace_root.is_dir():9 unmodified lines node_timeout_sec <= 0 or (total_budget_sec is not None and total_budget_sec <= 0) or (gate_timeout_sec is not None and gate_timeout_sec <= 0) or lock_wait_sec < 0 ): raise ValueError("budgets must be positive numbers of seconds") raise ValueError("budgets must be positive numbers of seconds, and the lock wait may not go negative") self.node_timeout_sec = float(node_timeout_sec) self.total_budget_sec = float(total_budget_sec) if total_budget_sec else None self.gate_timeout_sec = float(gate_timeout_sec) if gate_timeout_sec else None self.lock_wait_sec = float(lock_wait_sec)
def policy_dict(self, root: Optional[Path] = None) -> Dict[str, Any]: return {55 unmodified lines os.environ[GATE_TIMEOUT_ENV] = previous
def _run_six_nodes(self, case: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: with _KERNEL_CALL_LOCK: # The budget travels through the environment, which one process # shares; holding the module lock across the whole call is what # keeps one session's window from bleeding into another's. previous_env = self._enter_gate_timeout_env() try: if self.use_subprocesses: return run_topology_subprocesses( case, timeout_sec=self.node_timeout_sec, total_budget_sec=self.total_budget_sec, ) return run_pipeline(case) except NodeTimeoutError as exc: # A node that exhausts its budget abstains: the session answers # UNKNOWN with the named reason instead of a traceback or a verdict. return [], { "decision": { "verdict": "UNKNOWN", "assurance": 0, "reason": NODE_TIMEOUT, "detail": str(exc), previous_env = self._enter_gate_timeout_env() try: if self.use_subprocesses: return run_topology_subprocesses( case, timeout_sec=self.node_timeout_sec, total_budget_sec=self.total_budget_sec, ) return run_pipeline(case) except NodeTimeoutError as exc: # A node that exhausts its budget abstains: the session answers # UNKNOWN with the named reason instead of a traceback or a verdict. return [], { "decision": { "verdict": "UNKNOWN", "assurance": 0, "reason": NODE_TIMEOUT, "detail": str(exc), } } } finally: self._exit_gate_timeout_env(previous_env) finally: self._exit_gate_timeout_env(previous_env)
def _link_refusal(self, case_id: str, rel_posix: str, exc: WorkspaceLinkError) -> SessionResult: """A workspace held together by links cannot be copied to staging faithfully."""57 unmodified lines "a linked %s appeared in the workspace before the commit: '%s'" % (kind, rel), )
def _lock_lost_at_commit(self) -> Optional[Tuple[str, int, str, str]]: """The lock question, asked again at the moment of writing.
The workspace lock is taken at the start of a run, and another run can take over a leftover claim while this run is busy. A commit whose lock no longer names this run is a named refusal: the bytes are still the tree the six nodes verified, but they would be written without a holder. """ token = getattr(self, "_lock_token", None) if token is None: return None record = _read_lock_record(self._lock_path()) if record is not None and record[2] == token: return None return ( "REFUSED", 0, SESSION_LOCKED, "the workspace lock no longer names this run before the commit: '%s'" % self._lock_path(), )
def _lock_path(self) -> Path: return Path(self.workspace_root) / SESSION_LOCK_NAME
4 unmodified lines def _lock_detail(lock: Path, record: Optional[Tuple[int, Optional[int], Optional[str]]]) -> str: if record is None: return "a lock file sits at '%s' and its owner cannot be read" % lock note = "" if record[1] is not None else ", whose birth time this system cannot read" return "another session run holds the workspace: '%s' names process %d" % (lock, record[0]) return "another session run holds the workspace: '%s' names process %d%s" % (lock, record[0], note)
def _acquire_session_lock(self) -> None: """Take the workspace lock with an exclusive create, never a polite ask.16 unmodified lines except OSError: pass token = uuid.uuid4().hex for attempt in (0, 1): deadline = time.monotonic() + max(0.0, self.lock_wait_sec) takeovers = 0 while True: try: handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) except FileExistsError: record = self._lock_owner() if attempt or record is None or _lock_holder_is_alive(record): if record is not None and not _lock_holder_is_alive(record) and takeovers < 2: takeovers += 1 try: os.rename(str(lock), str(claim)) except OSError: raise SessionLockError( "the leftover lock at '%s' is being taken over by another run" % lock ) continue # A live holder keeps the workspace until it releases or the # caller's patience runs out; waiting was asked, waiting is what happens. if time.monotonic() >= deadline: raise SessionLockError(self._lock_detail(lock, record)) try: os.rename(str(lock), str(claim)) except OSError: raise SessionLockError( "the leftover lock at '%s' is being taken over by another run" % lock ) time.sleep(min(0.05, max(0.0, deadline - time.monotonic()))) continue birth = _process_creation_time(os.getpid()) try:248 unmodified lines committed = False
if commit and patch_res.applied and not plan.rejected and assurance >= self.min_assurance: late_link = self._late_link_at_commit() late_link = self._late_link_at_commit() or self._lock_lost_at_commit() if late_link is not None: verdict, assurance, reason, detail = late_link elif _disk_text(self.workspace_root, rel_posix) != original_text:225 unmodified lines committed = False
if commit and assurance >= needed: late_link = self._late_link_at_commit() late_link = self._late_link_at_commit() or self._lock_lost_at_commit() drifted = [] if late_link is not None else [ edit.file for edit in plan.edits if _disk_text(self.workspace_root, edit.file) != originals[edit.file]119 unmodified lines detail = str(decision.get("detail", "")) committed = False if commit and not plan.rejected and assurance >= self.min_assurance: late_link = self._late_link_at_commit() late_link = self._late_link_at_commit() or self._lock_lost_at_commit() if late_link is not None: verdict, assurance, reason, detail = late_link elif target.is_file():84 unmodified lines # import the module being removed are the gate target and its companions, # not the alphabetically first file of the copy. remaining = [p for p in discover_python_files(staged_root) if p != rel_posix] importers = importers_of(staged_root, remaining, rel_posix) importers = importers_from_index(build_reverse_index(staged_root, remaining), rel_posix) gate_target = importers[0] if importers else (remaining[0] if remaining else rel_posix) companion_files = [p for p in importers if p != gate_target] case = {18 unmodified lines detail = str(decision.get("detail", "")) committed = False if commit and not plan.rejected and assurance >= self.min_assurance: late_link = self._late_link_at_commit() late_link = self._late_link_at_commit() or self._lock_lost_at_commit() if late_link is not None: verdict, assurance, reason, detail = late_link elif _disk_text(self.workspace_root, rel_posix) != original_text:84 unmodified lines if not sig: # Two attempts that propose the same anchor and the same text have to # share one hash even when the kernel recorded no patch signature, or # the stall detector never sees the repetition. sig = hashlib.sha1((search + "\x00" + replace).encode("utf-8")).hexdigest() # the stall detector never sees the repetition. The hash keeps the # shape of a kernel signature, "sha256:" and sixteen hex digits, so a # history of attempts never mixes two notations for one fact. sig = "sha256:" + hashlib.sha256((search + "\x00" + replace).encode("utf-8")).hexdigest()[:16] history.append(sig) if result.assurance >= self.min_assurance: return result, attempts12344567891011121314131516171819202119222321242526272829303132333430353637383935404137424344454647484950445152535427 unmodified lines82838478858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128911291309313113213313413513613713813910014014114214314410514514610714714814915015115215315415511415615715815910 unmodified lines170171172131173174175176177178179180181182183184141185186187188{ "denominator": "the counts below are over one fixture of this bundle, not over Python. They say how many of the functions this bundle planted are in a shape the catalog claims, so a reader can see that the catalog is a set of verified cards and not a claim about arbitrary code.", "fixture": "fixtures/pattern_lab", "module_level_functions": 21, "module_level_functions": 33, "module_level_functions_by_file": { "src/asyncops.py": 10, "src/baskets.py": 2, "src/guards.py": 2, "src/labels.py": 2, "src/legacy.py": 2, "src/notes.py": 2, "src/registry.py": 6, "src/retries.py": 2, "src/slugify.py": 2, "src/tokens.py": 3 "src/tokens.py": 3, "src/widgets.py": 0 }, "patterns": [ { "family": "typing", "min_assurance": 3, "negative_rows": 1, "negative_rows": 2, "pattern_id": "annotate-literal-defaults", "positive_rows": 1, "positive_rows": 2, "refusals_recorded": [ "ALREADY_ANNOTATED", "ALREADY_ANNOTATED" ], "targets_in_shape": [ "src/asyncops.py::render_page", "src/slugify.py::join_parts", "src/tokens.py::count_words", "src/tokens.py::summarize" ], "targets_planted_in_shape": 3 "targets_planted_in_shape": 4 }, { "family": "contracts", "min_assurance": 3, "negative_rows": 1, "negative_rows": 2, "pattern_id": "bare-assert-to-explicit-raise", "positive_rows": 1, "positive_rows": 2, "refusals_recorded": [ "NOT_THE_FIRST_STATEMENT", "NOT_THE_FIRST_STATEMENT" ], "targets_in_shape": [ "src/asyncops.py::check_name", "src/guards.py::open_ticket" ], "targets_planted_in_shape": 1 "targets_planted_in_shape": 2 }, { "family": "contracts",27 unmodified lines "family": "shape", "min_assurance": 3, "negative_rows": 1, "pattern_id": "empty-len-to-truthiness", "pattern_id": "drop-unused-imports", "positive_rows": 1, "refusals_recorded": [ "NO_UNUSED_IMPORT" ], "targets_in_shape": [ "src/legacy.py::read_size", "src/legacy.py::note_path" ], "targets_planted_in_shape": 2 }, { "family": "shape", "min_assurance": 3, "negative_rows": 2, "pattern_id": "empty-len-to-truthiness", "positive_rows": 2, "refusals_recorded": [ "NO_EMPTY_LEN_CHECK", "NO_EMPTY_LEN_CHECK" ], "targets_in_shape": [ "src/asyncops.py::word_total", "src/baskets.py::describe" ], "targets_planted_in_shape": 2 }, { "family": "contracts", "min_assurance": 3, "negative_rows": 1, "pattern_id": "init-missing-super", "positive_rows": 1, "refusals_recorded": [ "SUPER_CALL_ALREADY_FIRST" ], "targets_in_shape": [ "src/widgets.py::Box.__init__" ], "targets_planted_in_shape": 1 }, { "family": "mutation", "min_assurance": 3, "negative_rows": 1, "negative_rows": 2, "pattern_id": "mutable-default-to-none", "positive_rows": 1, "positive_rows": 2, "refusals_recorded": [ "NOT_A_MUTABLE_DEFAULT", "NOT_A_MUTABLE_DEFAULT" ], "targets_in_shape": [ "src/asyncops.py::gather", "src/slugify.py::add_tag" ], "targets_planted_in_shape": 1 "targets_planted_in_shape": 2 }, { "family": "shape", "min_assurance": 3, "negative_rows": 1, "negative_rows": 2, "pattern_id": "none-comparison-to-identity", "positive_rows": 1, "positive_rows": 2, "refusals_recorded": [ "NO_NONE_COMPARISON", "NO_NONE_COMPARISON" ], "targets_in_shape": [ "src/asyncops.py::describe", "src/labels.py::label_for" ], "targets_planted_in_shape": 1 "targets_planted_in_shape": 2 }, { "family": "resources",10 unmodified lines "targets_planted_in_shape": 1 } ], "rows": 16, "rows": 30, "schema": "lingologos-python-pattern-coverage-1", "source_files": [ "src/asyncops.py", "src/baskets.py", "src/guards.py", "src/labels.py", "src/legacy.py", "src/notes.py", "src/registry.py", "src/retries.py", "src/slugify.py", "src/tokens.py" "src/tokens.py", "src/widgets.py" ]}123456789101112131415161718192021222324252627282930{"case_id": "pat-annotate-literal-defaults-positive", "edits": [{"file": "src/tokens.py", "label": "signature of 'count_words'", "replace": "def count_words(text: str = \"\", unit: str = \"word\"):\n parts = text.split()\n if unit == \"word\":\n return len(parts)\n if unit == \"line\":\n return len(text.splitlines())\n return 0", "search": "def count_words(text=\"\", unit=\"word\"):\n parts = text.split()\n if unit == \"word\":\n return len(parts)\n if unit == \"line\":\n return len(text.splitlines())\n return 0"}, {"file": "tests/test_tokens.py", "label": "lock test 'test_count_words_parameters_keep_their_defaults' appended after 'test_summarize_follows_the_unit'", "replace": "def test_summarize_follows_the_unit() -> None:\n assert summarize(\"a b\", unit=\"word\") == 2\n assert count_lines(\"a\\nb\") == 2\n\n\ndef test_count_words_parameters_keep_their_defaults() -> None:\n \"\"\"Lock the annotations this pattern added and the defaults it had to leave alone.\"\"\"\n import inspect\n\n from src import tokens\n parameters = inspect.signature(tokens.count_words).parameters\n assert parameters['text'].annotation is str\n assert parameters['text'].default == ''\n assert parameters['unit'].annotation is str\n assert parameters['unit'].default == 'word'\n", "search": "def test_summarize_follows_the_unit() -> None:\n assert summarize(\"a b\", unit=\"word\") == 2\n assert count_lines(\"a\\nb\") == 2"}], "expect": "VERIFIED", "family": "typing", "intent_tags": ["annotate", "defaults", "types"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter has a literal default and no annotation", "pattern_id": "annotate-literal-defaults", "rule": "annotate-literal-defaults", "targets": ["src/tokens.py::count_words"]}{"case_id": "pat-annotate-literal-defaults-negative", "edits": [], "expect": "REFUSED", "family": "typing", "intent_tags": ["annotate", "defaults", "types"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter has a literal default and no annotation", "pattern_id": "annotate-literal-defaults", "reason_code": "ALREADY_ANNOTATED", "rule": "annotate-literal-defaults", "targets": ["src/tokens.py::count_lines"]}{"case_id": "pat-annotate-literal-defaults-coroutine-positive", "edits": [{"file": "src/asyncops.py", "label": "signature of 'render_page'", "replace": "async def render_page(url, width: int = 80):\n return str(url).ljust(width)", "search": "async def render_page(url, width=80):\n return str(url).ljust(width)"}, {"file": "tests/test_asyncops.py", "label": "lock test 'test_render_page_parameters_keep_their_defaults' appended after 'test_item_count_counts_items'", "replace": "def test_item_count_counts_items() -> None:\n assert asyncio.run(item_count([1, 2])) == 2\n\n\ndef test_render_page_parameters_keep_their_defaults() -> None:\n \"\"\"Lock the annotations this pattern added and the defaults it had to leave alone.\"\"\"\n import inspect\n\n from src import asyncops\n parameters = inspect.signature(asyncops.render_page).parameters\n assert parameters['width'].annotation is int\n assert parameters['width'].default == 80\n", "search": "def test_item_count_counts_items() -> None:\n assert asyncio.run(item_count([1, 2])) == 2"}], "expect": "VERIFIED", "family": "typing", "intent_tags": ["annotate", "defaults", "types"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter has a literal default and no annotation", "pattern_id": "annotate-literal-defaults", "rule": "annotate-literal-defaults", "targets": ["src/asyncops.py::render_page"]}{"case_id": "pat-annotate-literal-defaults-coroutine-negative", "edits": [], "expect": "REFUSED", "family": "typing", "intent_tags": ["annotate", "defaults", "types"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter has a literal default and no annotation", "pattern_id": "annotate-literal-defaults", "reason_code": "ALREADY_ANNOTATED", "rule": "annotate-literal-defaults", "targets": ["src/asyncops.py::sized"]}{"case_id": "pat-bare-assert-to-explicit-raise-positive", "edits": [{"file": "src/guards.py", "label": "explicit raise of 'open_ticket'", "replace": "def open_ticket(queue_name):\n if not queue_name:\n raise AssertionError(\"queue name is required\")\n return {\"queue\": queue_name, \"opened\": True}", "search": "def open_ticket(queue_name):\n assert queue_name, \"queue name is required\"\n return {\"queue\": queue_name, \"opened\": True}"}, {"file": "tests/test_guards.py", "label": "lock test 'test_open_ticket_raises_in_stead_of_asserting' appended after 'test_close_ticket_clears_the_flag'", "replace": "def test_close_ticket_clears_the_flag() -> None:\n closed = close_ticket(open_ticket(\"builds\"))\n assert closed[\"opened\"] is False\n with pytest.raises(AssertionError):\n close_ticket({\"queue\": \"\"})\n\n\ndef test_open_ticket_raises_in_stead_of_asserting() -> None:\n \"\"\"Lock the raise that replaced the assert, and the refusal the function still carries.\"\"\"\n import inspect\n\n from src import guards\n source = inspect.getsource(guards.open_ticket)\n assert 'raise AssertionError(' in source\n assert not [line for line in source.splitlines() if line.strip().startswith('assert ')]\n try:\n guards.open_ticket(\"\")\n except AssertionError as caught:\n assert \"queue name is required\" in str(caught)\n else:\n raise AssertionError('open_ticket accepted an argument its check rejects')\n", "search": "def test_close_ticket_clears_the_flag() -> None:\n closed = close_ticket(open_ticket(\"builds\"))\n assert closed[\"opened\"] is False\n with pytest.raises(AssertionError):\n close_ticket({\"queue\": \"\"})"}], "expect": "VERIFIED", "family": "contracts", "intent_tags": ["preconditions", "errors", "contracts"], "language": "python", "min_assurance": 3, "note": "a module level function whose first statement is an assert guarding its arguments", "pattern_id": "bare-assert-to-explicit-raise", "rule": "bare-assert-to-explicit-raise", "targets": ["src/guards.py::open_ticket"]}{"case_id": "pat-bare-assert-to-explicit-raise-negative", "edits": [], "expect": "REFUSED", "family": "contracts", "intent_tags": ["preconditions", "errors", "contracts"], "language": "python", "min_assurance": 3, "note": "a module level function whose first statement is an assert guarding its arguments", "pattern_id": "bare-assert-to-explicit-raise", "reason_code": "NOT_THE_FIRST_STATEMENT", "rule": "bare-assert-to-explicit-raise", "targets": ["src/guards.py::close_ticket"]}{"case_id": "pat-bare-assert-to-explicit-raise-coroutine-positive", "edits": [{"file": "src/asyncops.py", "label": "explicit raise of 'check_name'", "replace": "async def check_name(name):\n if not name:\n raise AssertionError()\n return name", "search": "async def check_name(name):\n assert name\n return name"}, {"file": "tests/test_asyncops.py", "label": "lock test 'test_check_name_raises_in_stead_of_asserting' appended after 'test_item_count_counts_items'", "replace": "def test_item_count_counts_items() -> None:\n assert asyncio.run(item_count([1, 2])) == 2\n\n\ndef test_check_name_raises_in_stead_of_asserting() -> None:\n \"\"\"Lock the raise that replaced the assert, and the refusal the function still carries.\"\"\"\n import inspect\n import asyncio\n\n from src import asyncops\n source = inspect.getsource(asyncops.check_name)\n assert 'raise AssertionError(' in source\n assert not [line for line in source.splitlines() if line.strip().startswith('assert ')]\n try:\n asyncio.run(asyncops.check_name(\"\"))\n except AssertionError as caught:\n pass\n else:\n raise AssertionError('check_name accepted an argument its check rejects')\n", "search": "def test_item_count_counts_items() -> None:\n assert asyncio.run(item_count([1, 2])) == 2"}], "expect": "VERIFIED", "family": "contracts", "intent_tags": ["preconditions", "errors", "contracts"], "language": "python", "min_assurance": 3, "note": "a module level function whose first statement is an assert guarding its arguments", "pattern_id": "bare-assert-to-explicit-raise", "rule": "bare-assert-to-explicit-raise", "targets": ["src/asyncops.py::check_name"]}{"case_id": "pat-bare-assert-to-explicit-raise-coroutine-negative", "edits": [], "expect": "REFUSED", "family": "contracts", "intent_tags": ["preconditions", "errors", "contracts"], "language": "python", "min_assurance": 3, "note": "a module level function whose first statement is an assert guarding its arguments", "pattern_id": "bare-assert-to-explicit-raise", "reason_code": "NOT_THE_FIRST_STATEMENT", "rule": "bare-assert-to-explicit-raise", "targets": ["src/asyncops.py::check_after"]}{"case_id": "pat-bare-except-to-narrow-exception-positive", "edits": [{"file": "src/retries.py", "label": "named handler of 'call_or_none'", "replace": "def call_or_none(source):\n try:\n return source.read()\n except Exception:\n return \"\"", "search": "def call_or_none(source):\n try:\n return source.read()\n except:\n return \"\""}, {"file": "tests/test_retries.py", "label": "lock test 'test_call_or_none_answers_named_exceptions' appended after 'test_call_or_none_falls_back_when_reading_fails'", "replace": "def test_call_or_none_falls_back_when_reading_fails() -> None:\n assert call_or_none(_BrokenSource()) == \"\"\n\n\ndef test_call_or_none_answers_named_exceptions() -> None:\n \"\"\"Lock the class every handler of this function now names.\"\"\"\n import inspect\n\n from src import retries\n source = inspect.getsource(retries.call_or_none)\n assert 'except Exception:' in source\n assert 'except:' not in source\n", "search": "def test_call_or_none_falls_back_when_reading_fails() -> None:\n assert call_or_none(_BrokenSource()) == \"\""}], "expect": "VERIFIED", "family": "contracts", "intent_tags": ["errors", "exceptions", "contracts"], "language": "python", "min_assurance": 3, "note": "a module level function with an except handler that names no exception class", "pattern_id": "bare-except-to-narrow-exception", "rule": "bare-except-to-narrow-exception", "targets": ["src/retries.py::call_or_none"]}{"case_id": "pat-bare-except-to-narrow-exception-negative", "edits": [], "expect": "REFUSED", "family": "contracts", "intent_tags": ["errors", "exceptions", "contracts"], "language": "python", "min_assurance": 3, "note": "a module level function with an except handler that names no exception class", "pattern_id": "bare-except-to-narrow-exception", "reason_code": "NO_BARE_EXCEPT", "rule": "bare-except-to-narrow-exception", "targets": ["src/retries.py::call_or_note"]}{"case_id": "pat-chain-to-registry-positive", "edits": [{"file": "src/registry.py", "label": "dispatch registry of 'render'", "replace": "def render(kind, item):\n handlers = {\"short\": format_short, \"long\": format_long, \"json\": format_json}\n handled = handlers.get(kind)\n if handled is None:\n raise ValueError(\"unsupported kind\")\n return handled(item)", "search": "def render(kind, item):\n if kind == \"short\":\n return format_short(item)\n elif kind == \"long\":\n return format_long(item)\n elif kind == \"json\":\n return format_json(item)\n else:\n raise ValueError(\"unsupported kind\")"}, {"file": "tests/test_registry.py", "label": "lock test 'test_render_dispatches_through_a_registry' appended after 'test_render_rejects_an_unknown_kind'", "replace": "def test_render_rejects_an_unknown_kind() -> None:\n with pytest.raises(ValueError):\n render(\"yaml\", 5)\n\n\ndef test_render_dispatches_through_a_registry() -> None:\n \"\"\"Lock the registry the chain became, and the answers the chain used to give.\"\"\"\n import inspect\n\n from src import registry\n source = inspect.getsource(registry.render)\n assert 'handlers = {' in source\n assert '\"short\": format_short' in source\n assert '\"long\": format_long' in source\n assert '\"json\": format_json' in source\n assert 'handlers.get(kind)' in source\n assert 'elif' not in source\n assert registry.render('short', \"\") == registry.format_short(\"\")\n assert registry.render('long', \"\") == registry.format_long(\"\")\n assert registry.render('json', \"\") == registry.format_json(\"\")\n try:\n registry.render('~no such kind~', \"\")\n except ValueError:\n pass\n else:\n raise AssertionError('render accepted a kind no branch carries')\n", "search": "def test_render_rejects_an_unknown_kind() -> None:\n with pytest.raises(ValueError):\n render(\"yaml\", 5)"}], "expect": "VERIFIED", "family": "shape", "intent_tags": ["dispatch", "registry", "extension"], "language": "python", "min_assurance": 3, "note": "a module level function that dispatches an if/elif chain of one name compared to text literals", "pattern_id": "chain-to-registry", "rule": "chain-to-registry", "targets": ["src/registry.py::render"]}{"case_id": "pat-chain-to-registry-negative", "edits": [], "expect": "REFUSED", "family": "shape", "intent_tags": ["dispatch", "registry", "extension"], "language": "python", "min_assurance": 3, "note": "a module level function that dispatches an if/elif chain of one name compared to text literals", "pattern_id": "chain-to-registry", "reason_code": "BRANCH_SHAPE_MISMATCH", "rule": "chain-to-registry", "targets": ["src/registry.py::render_pair"]}{"case_id": "pat-drop-unused-imports-positive", "edits": [{"file": "src/legacy.py", "label": "unread imports of 'src/legacy.py' removed", "replace": "", "search": "import json\n"}, {"file": "tests/test_legacy.py", "label": "lock test 'test_read_size_keeps_no_unread_imports' appended after 'test_note_path_names_the_file'", "replace": "def test_note_path_names_the_file() -> None:\n assert Path(note_path(\"one\")).name == \"one.txt\"\n\n\ndef test_read_size_keeps_no_unread_imports() -> None:\n \"\"\"Lock the import lines this rule removed from the module and the function they never reached.\"\"\"\n import inspect\n\n from src import legacy\n source = inspect.getsource(legacy)\n import_lines = [line.strip() for line in source.splitlines() if line.strip().startswith(('import ', 'from '))]\n assert not [line for line in import_lines if 'json' in line.split()]\n assert callable(legacy.read_size)\n", "search": "def test_note_path_names_the_file() -> None:\n assert Path(note_path(\"one\")).name == \"one.txt\""}], "expect": "VERIFIED", "family": "shape", "intent_tags": ["imports", "cleanup", "dead code"], "language": "python", "min_assurance": 3, "note": "a module level function in a file whose top level import lines bind names that no other line of the file reads", "pattern_id": "drop-unused-imports", "rule": "drop-unused-imports", "targets": ["src/legacy.py::read_size"]}{"case_id": "pat-drop-unused-imports-negative", "edits": [], "expect": "REFUSED", "family": "shape", "intent_tags": ["imports", "cleanup", "dead code"], "language": "python", "min_assurance": 3, "note": "a module level function in a file whose top level import lines bind names that no other line of the file reads", "pattern_id": "drop-unused-imports", "reason_code": "NO_UNUSED_IMPORT", "rule": "drop-unused-imports", "targets": ["src/tokens.py::count_words"]}{"case_id": "pat-empty-len-to-truthiness-positive", "edits": [{"file": "src/baskets.py", "label": "truthiness emptiness test of 'describe'", "replace": "def describe(items):\n if not items:\n return \"empty\"\n return \"full\"", "search": "def describe(items):\n if len(items) == 0:\n return \"empty\"\n return \"full\""}, {"file": "tests/test_baskets.py", "label": "lock test 'test_describe_asks_for_truthiness' appended after 'test_first_or_none_gives_the_head_or_nothing'", "replace": "def test_first_or_none_gives_the_head_or_nothing() -> None:\n assert first_or_none([7]) == 7\n assert first_or_none([]) is None\n\n\ndef test_describe_asks_for_truthiness() -> None:\n \"\"\"Lock the truthiness test that replaced the counted emptiness.\"\"\"\n import inspect\n\n from src import baskets\n source = inspect.getsource(baskets.describe)\n assert 'not items' in source\n assert 'len(items) == 0' not in source\n", "search": "def test_first_or_none_gives_the_head_or_nothing() -> None:\n assert first_or_none([7]) == 7\n assert first_or_none([]) is None"}], "expect": "VERIFIED", "family": "shape", "intent_tags": ["collections", "truthiness", "emptiness"], "language": "python", "min_assurance": 3, "note": "a module level function that counts a value with len and compares the count to zero", "pattern_id": "empty-len-to-truthiness", "rule": "empty-len-to-truthiness", "targets": ["src/baskets.py::describe"]}{"case_id": "pat-empty-len-to-truthiness-negative", "edits": [], "expect": "REFUSED", "family": "shape", "intent_tags": ["collections", "truthiness", "emptiness"], "language": "python", "min_assurance": 3, "note": "a module level function that counts a value with len and compares the count to zero", "pattern_id": "empty-len-to-truthiness", "reason_code": "NO_EMPTY_LEN_CHECK", "rule": "empty-len-to-truthiness", "targets": ["src/baskets.py::first_or_none"]}{"case_id": "pat-empty-len-to-truthiness-coroutine-positive", "edits": [{"file": "src/asyncops.py", "label": "truthiness emptiness test of 'word_total'", "replace": "async def word_total(items):\n if not items:\n return 0\n return sum(len(item.split()) for item in items)", "search": "async def word_total(items):\n if len(items) == 0:\n return 0\n return sum(len(item.split()) for item in items)"}, {"file": "tests/test_asyncops.py", "label": "lock test 'test_word_total_asks_for_truthiness' appended after 'test_item_count_counts_items'", "replace": "def test_item_count_counts_items() -> None:\n assert asyncio.run(item_count([1, 2])) == 2\n\n\ndef test_word_total_asks_for_truthiness() -> None:\n \"\"\"Lock the truthiness test that replaced the counted emptiness.\"\"\"\n import inspect\n\n from src import asyncops\n source = inspect.getsource(asyncops.word_total)\n assert 'not items' in source\n assert 'len(items) == 0' not in source\n", "search": "def test_item_count_counts_items() -> None:\n assert asyncio.run(item_count([1, 2])) == 2"}], "expect": "VERIFIED", "family": "shape", "intent_tags": ["collections", "truthiness", "emptiness"], "language": "python", "min_assurance": 3, "note": "a module level function that counts a value with len and compares the count to zero", "pattern_id": "empty-len-to-truthiness", "rule": "empty-len-to-truthiness", "targets": ["src/asyncops.py::word_total"]}{"case_id": "pat-empty-len-to-truthiness-coroutine-negative", "edits": [], "expect": "REFUSED", "family": "shape", "intent_tags": ["collections", "truthiness", "emptiness"], "language": "python", "min_assurance": 3, "note": "a module level function that counts a value with len and compares the count to zero", "pattern_id": "empty-len-to-truthiness", "reason_code": "NO_EMPTY_LEN_CHECK", "rule": "empty-len-to-truthiness", "targets": ["src/asyncops.py::item_count"]}{"case_id": "pat-init-missing-super-positive", "edits": [{"file": "src/widgets.py", "label": "constructor chain of 'Box.__init__' opened", "replace": "def __init__(self):\n super().__init__()\n self.sides = 4\n self.closed = False", "search": "def __init__(self):\n self.sides = 4\n self.closed = False"}, {"file": "tests/test_widgets.py", "label": "lock test 'test_Box_init_calls_super_first' appended after 'test_grille_keeps_its_bars'", "replace": "def test_grille_keeps_its_bars() -> None:\n assert Grille(3).bars == 3\n\n\ndef test_Box_init_calls_super_first() -> None:\n \"\"\"Lock the super call this rule put first in the constructor, and the class that still builds.\"\"\"\n import inspect\n\n from src import widgets\n source = inspect.getsource(widgets.Box.__init__)\n assert 'super().__init__()' in source\n lines = [line.strip() for line in source.splitlines() if line.strip()]\n assert lines[0].startswith('def __init__')\n assert lines[1] == 'super().__init__()'\n created = widgets.Box()\n assert isinstance(created, widgets.Box)\n", "search": "def test_grille_keeps_its_bars() -> None:\n assert Grille(3).bars == 3"}], "expect": "VERIFIED", "family": "contracts", "intent_tags": ["construction", "inheritance", "super"], "language": "python", "min_assurance": 3, "note": "a module level class whose '__init__' takes only self, names no base of its own, and does not open the constructor chain first", "pattern_id": "init-missing-super", "rule": "init-missing-super", "targets": ["src/widgets.py::Box.__init__"]}{"case_id": "pat-init-missing-super-negative", "edits": [], "expect": "REFUSED", "family": "contracts", "intent_tags": ["construction", "inheritance", "super"], "language": "python", "min_assurance": 3, "note": "a module level class whose '__init__' takes only self, names no base of its own, and does not open the constructor chain first", "pattern_id": "init-missing-super", "reason_code": "SUPER_CALL_ALREADY_FIRST", "rule": "init-missing-super", "targets": ["src/widgets.py::Shutter.__init__"]}{"case_id": "pat-mutable-default-to-none-positive", "edits": [{"file": "src/slugify.py", "label": "shared default of 'add_tag'", "replace": "def add_tag(name, tags=None):\n if tags is None:\n tags = []\n tags.append(name)\n return tags", "search": "def add_tag(name, tags=[]):\n tags.append(name)\n return tags"}, {"file": "tests/test_slugify.py", "label": "lock test 'test_add_tag_has_no_shared_default' appended after 'test_join_parts_uses_its_tuple_default'", "replace": "def test_join_parts_uses_its_tuple_default() -> None:\n assert join_parts() == \"root\"\n assert join_parts((\"a\", \"b\"), sep=\"/\") == \"a/b\"\n\n\ndef test_add_tag_has_no_shared_default() -> None:\n \"\"\"Lock the default this pattern unshared, the guard that replaced it, and the call that no longer shares state.\"\"\"\n import inspect\n\n from src import slugify\n signature = inspect.signature(slugify.add_tag)\n source = inspect.getsource(slugify.add_tag)\n assert signature.parameters['tags'].default is None\n assert 'if tags is None:' in source\n first = slugify.add_tag('alpha')\n second = slugify.add_tag('beta')\n assert first != second\n", "search": "def test_join_parts_uses_its_tuple_default() -> None:\n assert join_parts() == \"root\"\n assert join_parts((\"a\", \"b\"), sep=\"/\") == \"a/b\""}], "expect": "VERIFIED", "family": "mutation", "intent_tags": ["defaults", "aliasing", "mutation"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter defaults to a list, dict or set built at definition time", "pattern_id": "mutable-default-to-none", "rule": "mutable-default-to-none", "targets": ["src/slugify.py::add_tag"]}{"case_id": "pat-mutable-default-to-none-negative", "edits": [], "expect": "REFUSED", "family": "mutation", "intent_tags": ["defaults", "aliasing", "mutation"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter defaults to a list, dict or set built at definition time", "pattern_id": "mutable-default-to-none", "reason_code": "NOT_A_MUTABLE_DEFAULT", "rule": "mutable-default-to-none", "targets": ["src/slugify.py::join_parts"]}{"case_id": "pat-mutable-default-to-none-coroutine-positive", "edits": [{"file": "src/asyncops.py", "label": "shared default of 'gather'", "replace": "async def gather(seed, tags=None):\n if tags is None:\n tags = []\n return tags + [seed]", "search": "async def gather(seed, tags=[]):\n return tags + [seed]"}, {"file": "tests/test_asyncops.py", "label": "lock test 'test_gather_has_no_shared_default' appended after 'test_item_count_counts_items'", "replace": "def test_item_count_counts_items() -> None:\n assert asyncio.run(item_count([1, 2])) == 2\n\n\ndef test_gather_has_no_shared_default() -> None:\n \"\"\"Lock the default this pattern unshared, the guard that replaced it, and the call that no longer shares state.\"\"\"\n import inspect\n import asyncio\n\n from src import asyncops\n signature = inspect.signature(asyncops.gather)\n source = inspect.getsource(asyncops.gather)\n assert signature.parameters['tags'].default is None\n assert 'if tags is None:' in source\n first = asyncio.run(asyncops.gather('alpha'))\n second = asyncio.run(asyncops.gather('beta'))\n assert first != second\n", "search": "def test_item_count_counts_items() -> None:\n assert asyncio.run(item_count([1, 2])) == 2"}], "expect": "VERIFIED", "family": "mutation", "intent_tags": ["defaults", "aliasing", "mutation"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter defaults to a list, dict or set built at definition time", "pattern_id": "mutable-default-to-none", "rule": "mutable-default-to-none", "targets": ["src/asyncops.py::gather"]}{"case_id": "pat-mutable-default-to-none-coroutine-negative", "edits": [], "expect": "REFUSED", "family": "mutation", "intent_tags": ["defaults", "aliasing", "mutation"], "language": "python", "min_assurance": 3, "note": "a module level function whose parameter defaults to a list, dict or set built at definition time", "pattern_id": "mutable-default-to-none", "reason_code": "NOT_A_MUTABLE_DEFAULT", "rule": "mutable-default-to-none", "targets": ["src/asyncops.py::plain"]}{"case_id": "pat-none-comparison-to-identity-positive", "edits": [{"file": "src/labels.py", "label": "identity comparisons of 'label_for'", "replace": "def label_for(value):\n if value is None:\n return \"none\"\n if value is not None and value == \"\":\n return \"blank\"\n return \"given\"", "search": "def label_for(value):\n if value == None:\n return \"none\"\n if value != None and value == \"\":\n return \"blank\"\n return \"given\""}, {"file": "tests/test_labels.py", "label": "lock test 'test_label_for_compares_none_by_identity' appended after 'test_is_missing_answers_for_none'", "replace": "def test_is_missing_answers_for_none() -> None:\n assert is_missing(None)\n assert not is_missing(\"\")\n\n\ndef test_label_for_compares_none_by_identity() -> None:\n \"\"\"Lock the identity tests that replaced the equality against None.\"\"\"\n import inspect\n\n from src import labels\n source = inspect.getsource(labels.label_for)\n assert '== None' not in source\n assert '!= None' not in source\n assert 'value is None' in source\n assert 'value is not None' in source\n", "search": "def test_is_missing_answers_for_none() -> None:\n assert is_missing(None)\n assert not is_missing(\"\")"}], "expect": "VERIFIED", "family": "shape", "intent_tags": ["equality", "identity", "none"], "language": "python", "min_assurance": 3, "note": "a module level function that asks whether a value is None with == or !=", "pattern_id": "none-comparison-to-identity", "rule": "none-comparison-to-identity", "targets": ["src/labels.py::label_for"]}{"case_id": "pat-none-comparison-to-identity-negative", "edits": [], "expect": "REFUSED", "family": "shape", "intent_tags": ["equality", "identity", "none"], "language": "python", "min_assurance": 3, "note": "a module level function that asks whether a value is None with == or !=", "pattern_id": "none-comparison-to-identity", "reason_code": "NO_NONE_COMPARISON", "rule": "none-comparison-to-identity", "targets": ["src/labels.py::is_missing"]}{"case_id": "pat-none-comparison-to-identity-coroutine-positive", "edits": [{"file": "src/asyncops.py", "label": "identity comparisons of 'describe'", "replace": "async def describe(value):\n if value is None:\n return \"nothing\"\n return str(value)", "search": "async def describe(value):\n if value == None:\n return \"nothing\"\n return str(value)"}, {"file": "tests/test_asyncops.py", "label": "lock test 'test_describe_compares_none_by_identity' appended after 'test_item_count_counts_items'", "replace": "def test_item_count_counts_items() -> None:\n assert asyncio.run(item_count([1, 2])) == 2\n\n\ndef test_describe_compares_none_by_identity() -> None:\n \"\"\"Lock the identity tests that replaced the equality against None.\"\"\"\n import inspect\n\n from src import asyncops\n source = inspect.getsource(asyncops.describe)\n assert '== None' not in source\n assert '!= None' not in source\n assert 'value is None' in source\n", "search": "def test_item_count_counts_items() -> None:\n assert asyncio.run(item_count([1, 2])) == 2"}], "expect": "VERIFIED", "family": "shape", "intent_tags": ["equality", "identity", "none"], "language": "python", "min_assurance": 3, "note": "a module level function that asks whether a value is None with == or !=", "pattern_id": "none-comparison-to-identity", "rule": "none-comparison-to-identity", "targets": ["src/asyncops.py::describe"]}{"case_id": "pat-none-comparison-to-identity-coroutine-negative", "edits": [], "expect": "REFUSED", "family": "shape", "intent_tags": ["equality", "identity", "none"], "language": "python", "min_assurance": 3, "note": "a module level function that asks whether a value is None with == or !=", "pattern_id": "none-comparison-to-identity", "reason_code": "NO_NONE_COMPARISON", "rule": "none-comparison-to-identity", "targets": ["src/asyncops.py::present"]}{"case_id": "pat-open-to-context-manager-positive", "edits": [{"file": "src/notes.py", "label": "scoped handle of 'read_note'", "replace": "def read_note(path):\n with open(path, \"r\", encoding=\"utf-8\") as handle:\n body = handle.read()\n return body", "search": "def read_note(path):\n handle = open(path, \"r\", encoding=\"utf-8\")\n body = handle.read()\n handle.close()\n return body"}, {"file": "tests/test_notes.py", "label": "lock test 'test_read_note_scopes_its_handle' appended after 'test_read_note_of_an_empty_file'", "replace": "def test_read_note_of_an_empty_file(tmp_path) -> None:\n path = tmp_path / \"empty.txt\"\n write_note(path, \"\")\n assert read_note(path) == \"\"\n\n\ndef test_read_note_scopes_its_handle() -> None:\n \"\"\"Lock the scope the pattern gave the handle, the close it made redundant, and the read still working.\"\"\"\n import inspect\n import os\n import shutil\n import tempfile\n\n from src import notes\n source = inspect.getsource(notes.read_note)\n assert 'with open(' in source\n assert '.close()' not in source\n assert 'handle = open(' not in source\n directory = tempfile.mkdtemp()\n try:\n path = os.path.join(directory, \"lock note.txt\")\n with open(path, \"w\", encoding=\"utf-8\") as writer:\n writer.write(\"alpha\")\n assert notes.read_note(path) == 'alpha'\n finally:\n shutil.rmtree(directory, ignore_errors=True)\n", "search": "def test_read_note_of_an_empty_file(tmp_path) -> None:\n path = tmp_path / \"empty.txt\"\n write_note(path, \"\")\n assert read_note(path) == \"\""}], "expect": "VERIFIED", "family": "resources", "intent_tags": ["files", "lifetime", "resources"], "language": "python", "min_assurance": 3, "note": "a module level function that opens a file into a name and closes that name itself", "pattern_id": "open-to-context-manager", "rule": "open-to-context-manager", "targets": ["src/notes.py::read_note"]}{"case_id": "pat-open-to-context-manager-negative", "edits": [], "expect": "REFUSED", "family": "resources", "intent_tags": ["files", "lifetime", "resources"], "language": "python", "min_assurance": 3, "note": "a module level function that opens a file into a name and closes that name itself", "pattern_id": "open-to-context-manager", "reason_code": "ALREADY_SCOPED", "rule": "open-to-context-manager", "targets": ["src/notes.py::write_note"]}17 unmodified lines18192021222324252617 unmodified lines "mypy>=1.0.0", "ruff>=0.4.0",]publish = [ "huggingface_hub>=0.23.0",]
[project.entry-points."lingologos.codex.adapters"]python = "lingologos_python.adapter:PythonLanguageAdapter"12344566789101 unmodified line12131414151617181 unmodified line20212222232425266 unmodified lines333435363738394041424344454638474849501 unmodified line52535446555657581 unmodified line6061625463645665666768697062717273741 unmodified line7677787071727980818283848586788788808990919293948695968897989910010110294103104961051061071081 unmodified line110111112104113114115116117118110119120112121122123124{ "schema": "lingologos-python-gates-1", "verdict": "CONFIRMED", "sources_sha256": "c67f159b042510540c5ceaeed6cb105d706b1af6c84c4956460676ed22d85bcf", "sources_sha256": "61140dfd7ae4bb0e5af8c33a702a8c6b39ea44d3edf7b60db052028bdcc14fe8", "kernel_sha256": "8d5ec321cc5b76c8cf2a21f86f1d26473bdd5349aadc268211d253d577810c7c", "counts": { "CONFIRMED": 13, "CONFIRMED": 14, "REJECTED": 0, "ABSTAIN": 0 },1 unmodified line { "name": "adapter_contract", "verdict": "CONFIRMED", "seconds": 0.829, "seconds": 0.782, "check": "check_adapter_contract on PythonLanguageAdapter", "note": "no violations for lingologos-python", "failed_targets": []1 unmodified line { "name": "ast_symbol_graph", "verdict": "CONFIRMED", "seconds": 0.002, "seconds": 0.003, "check": "Python AST symbol, method, inheritance, and import graph", "note": "13 symbols, 10 edges extracted", "failed_targets": []6 unmodified lines "note": "selected 2 dependent test file(s)", "failed_targets": [] }, { "name": "graph_scaling", "verdict": "CONFIRMED", "seconds": 13.322, "check": "the symbol graph stays exact at 1500 generated files", "note": "1500 files, 1449 import edges exact, reverse index agrees on 12 probes, 13.3s total with 8.0s extract", "failed_targets": [] }, { "name": "strict_abstain_control", "verdict": "CONFIRMED", "seconds": 0.848, "seconds": 0.863, "check": "missing optional tools produce ABSTAIN and block verdict", "note": "missing static tools abstained and ended in UNKNOWN/GATE_ABSTAIN", "failed_targets": []1 unmodified line { "name": "session_transactions", "verdict": "CONFIRMED", "seconds": 3.11, "seconds": 2.775, "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": []1 unmodified line { "name": "session_sweep", "verdict": "CONFIRMED", "seconds": 6.659, "seconds": 7.624, "check": "fixed-seed sweep of session verbs over a copied package", "note": "12 seeded operations: 3 committed, 9 refused or raised, tree state compared after each one", "note": "13 seeded operations: 3 committed, 6 refused, 3 raised, 1 verified without a write, tree state compared after each one", "failed_targets": [] }, { "name": "external_topology", "verdict": "CONFIRMED", "seconds": 1.887, "seconds": 1.8, "check": "external topology.json, node folders, and six subprocess turns", "note": "6 node folders valid, 7 subprocess envelopes reached VERIFIED (3)", "failed_targets": []1 unmodified line { "name": "pattern_corpus_schema", "verdict": "CONFIRMED", "seconds": 0.0, "check": "patterns/pattern_cases.jsonl is a valid case-1 corpus with one pair per card", "note": "16 rows over 8 cards, each with its lock test and its refusal", "seconds": 0.002, "check": "patterns/pattern_cases.jsonl is a valid case-1 corpus with a pair at least for every card", "note": "30 rows over 10 cards, each with its lock test and its refusal", "failed_targets": [] }, { "name": "pattern_round_trip", "verdict": "CONFIRMED", "seconds": 0.01, "seconds": 0.054, "check": "every row of the pattern corpus re-plans on the fixture as written", "note": "16 rows re-planned: 8 pairs land and compile, 8 refusals repeat with the same code", "note": "30 rows re-planned: 15 pairs land and compile, 15 refusals repeat with the same code", "failed_targets": [] }, { "name": "pattern_pair_honesty", "verdict": "CONFIRMED", "seconds": 5.182, "seconds": 8.396, "check": "each card's lock test fails until the source edit of its pair lands", "note": "8 cards: every lock test fails while its source edit is missing, so the pair is not decoration", "note": "15 pairs: every lock test fails while its source edit is missing, so the pairs are not decoration", "failed_targets": [] }, { "name": "pattern_coverage", "verdict": "CONFIRMED", "seconds": 0.003, "seconds": 0.007, "check": "patterns/coverage.json states a denominator this fixture still supports", "note": "8 cards over 8 source files and 21 module level functions, denominator stated as the fixture", "note": "10 cards over 11 source files and 33 module level functions, denominator stated as the fixture", "failed_targets": [] }, {1 unmodified line "verdict": "CONFIRMED", "seconds": 0.005, "check": "every verb and flag the card prints exists in the real parser", "note": "13 printed command lines agree with the 8 verbs of the parser", "note": "19 printed command lines agree with the 10 verbs of the parser", "failed_targets": [] }, { "name": "self_lint", "verdict": "CONFIRMED", "seconds": 0.145, "seconds": 0.338, "check": "the package reads itself: modules compile, the graph spans them, the reason registry matches the card, the promised names exist", "note": "12 modules parse, compile, and carry docstrings; own graph has 175 symbols and 361 edges; 46 reason codes, every one named in the card; 36 names promised in the Contents, all defined", "note": "12 modules parse, compile, and carry docstrings; own graph has 193 symbols and 415 edges; 58 reason codes, every one named in the card; 40 names promised in the Contents, all defined", "failed_targets": [] } ]5 unmodified lines6789101112131415112 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282295 unmodified linesfrom typing import List, Tuple
from lingologos_python.ast_graph import ( build_reverse_index, discover_python_files, extract_python_graph, importers_from_index, importers_of, reexported_names,)112 unmodified lines assert ("tests/test_app.py", "app/impl.py") in edges selected = select_python_tests(tmp_path, ["app/impl.py"]) assert "tests/test_app.py" in selected
def _star_reexport_package(root: Path) -> None: """A package whose __init__ stars two modules: one lists __all__, one does not.""" _write(root, "app/__init__.py", "from .impl import *\nfrom .tools import *\n") _write( root, "app/impl.py", "__all__ = ['shown']\n\nhidden = 3\n\n\ndef shown() -> int:\n return 5\n", ) _write( root, "app/tools.py", "visible = 1\n_hidden = 2\n\n\ndef usable() -> int:\n return visible\n", ) _write( root, "tests/test_star_app.py", "from app import *\n\n\ndef test_shown():\n assert shown() == 5\n", )
def test_a_star_reexport_table_expands_to_the_names_the_star_hands_over( tmp_path: Path,) -> None: _star_reexport_package(tmp_path) table = reexported_names(tmp_path, "app/__init__.py") assert table.get("shown") == ["app.impl.shown"] assert "hidden" not in table # __all__ said shown, and __all__ is the contract assert table.get("visible") == ["app.tools.visible"] assert table.get("usable") == ["app.tools.usable"] assert "_hidden" not in table # a star never carries an underscored name
def test_a_change_behind_a_star_reexport_selects_the_test_that_stars_the_package( tmp_path: Path,) -> None: _star_reexport_package(tmp_path) edges = set(_file_edges(tmp_path)) assert ("tests/test_star_app.py", "app/impl.py") in edges selected = select_python_tests(tmp_path, ["app/impl.py"]) assert "tests/test_star_app.py" in selected
def test_a_literal_dynamic_import_counts_as_an_import(tmp_path: Path) -> None: """import_module and __import__ with a plain string name bind a file like any import.""" root = tmp_path _write(root, "app/__init__.py", "") _write(root, "app/impl.py", "def helper() -> int:\n return 2\n") _write( root, "tests/test_module_lib.py", "import importlib\n\n\ndef test_dyn():\n" " mod = importlib.import_module('app.impl')\n" " assert mod.helper() == 2\n", ) _write( root, "tests/test_dunder_import.py", "impl = __import__('app.impl')\n\n\ndef test_dyn():\n" " assert impl.helper() == 2\n", ) _write( root, "tests/test_opaque.py", "import importlib\n\n\ndef test_opaque():\n" " mod = importlib.import_module(NAME_FROM_CONFIG)\n" " assert mod is not None\n", ) files = discover_python_files(tmp_path) importers = importers_of(tmp_path, files, "app/impl.py") assert "tests/test_module_lib.py" in importers assert "tests/test_dunder_import.py" in importers assert "tests/test_opaque.py" not in importers edges = set(_file_edges(tmp_path)) assert ("tests/test_module_lib.py", "app/impl.py") in edges assert ("tests/test_dunder_import.py", "app/impl.py") in edges selected = select_python_tests(tmp_path, ["app/impl.py"]) assert "tests/test_module_lib.py" in selected assert "tests/test_dunder_import.py" in selected assert "tests/test_opaque.py" not in selected
def test_an_index_built_once_answers_every_target_as_a_per_query_walk_does( tmp_path: Path,) -> None: """A workspace parsed once gives the same importers as parsing it once per question.""" hard = tmp_path / "hard" _hard_package(hard) reexported = tmp_path / "reexported" _reexport_package(reexported) for workspace in (hard, reexported): files = discover_python_files(workspace) index = build_reverse_index(workspace, files) for target in files: remaining = [p for p in files if p != target] assert importers_from_index(index, target) == sorted( importers_of(workspace, remaining, target) ), "the index and the walk disagree about %s" % target9 unmodified lines101112131415161718192021250 unmodified lines2722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425439 unmodified lines
import hashlibimport jsonimport osimport reimport shutilimport subprocessimport sysimport timefrom pathlib import Pathfrom typing import Any, Dict
250 unmodified lines proc = run_cli("delete", "--workspace", str(ws), "--file", "src/absent.py") assert proc.returncode == 1 assert "REFUSED" in proc.stderr
def _hold_the_lock(ws: Path) -> None: """A lock record naming this live test process, the shape a running session writes.""" (ws / ".lingologos-session.lock").write_text( "%d - %s" % (os.getpid(), "0" * 32), encoding="utf-8", newline="" )
def test_graph_shows_both_directions_and_the_reverse_index_agrees() -> None: proc = run_cli("graph", "--workspace", str(LAB)) assert proc.returncode == 0, proc.stdout + proc.stderr assert "import_edges=" in proc.stdout back = [line for line in proc.stdout.splitlines() if line.startswith(" src/registry.py <- ")] assert back and "tests/test_registry.py" in back[0]
def test_graph_json_lists_the_importers_of_every_file() -> None: proc = run_cli("graph", "--workspace", str(LAB), "--json") assert proc.returncode == 0, proc.stdout + proc.stderr payload = json.loads(proc.stdout) assert set(payload) == {"files", "import_edges", "importers"} assert "tests/test_registry.py" in payload["importers"]["src/registry.py"] assert any(edge[1] == "src/registry.py" for edge in payload["import_edges"]) for source, target in payload["import_edges"]: assert source in payload["importers"][target]
def test_graph_refuses_a_workspace_that_is_not_a_directory(tmp_path: Path) -> None: proc = run_cli("graph", "--workspace", str(tmp_path / "nowhere")) assert proc.returncode == 1 assert "does not exist" in proc.stderr
def test_lock_status_reads_a_quiet_workspace_as_free(tmp_path: Path) -> None: proc = run_cli("lock-status", "--workspace", str(tmp_path), "--json") assert proc.returncode == 0, proc.stdout + proc.stderr payload = json.loads(proc.stdout) assert payload["present"] is False assert payload["held"] is False text = run_cli("lock-status", "--workspace", str(tmp_path)) assert text.returncode == 0 assert "free: no lock file" in text.stdout
def test_lock_status_names_a_live_holder_and_says_held(tmp_path: Path) -> None: _hold_the_lock(tmp_path) proc = run_cli("lock-status", "--workspace", str(tmp_path)) assert proc.returncode == 1 assert "held: process %d" % os.getpid() in proc.stdout
def test_lock_status_reads_a_leftover_lock_as_free(tmp_path: Path) -> None: (tmp_path / ".lingologos-session.lock").write_text( "999999 - %s" % ("0" * 32), encoding="utf-8", newline="" ) proc = run_cli("lock-status", "--workspace", str(tmp_path)) assert proc.returncode == 0 assert "no longer runs" in proc.stdout
def test_a_held_workspace_refuses_at_once_and_a_wait_budget_is_honoured(tmp_path: Path) -> None: ws = _delete_workspace(tmp_path) _hold_the_lock(ws) started = time.monotonic() proc = run_cli( "delete", "--workspace", str(ws), "--file", "src/helper.py", "--dry-run", "--lock-wait", "0", ) at_once = time.monotonic() - started assert proc.returncode == 1 assert "SESSION_LOCKED" in proc.stdout started = time.monotonic() proc = run_cli( "delete", "--workspace", str(ws), "--file", "src/helper.py", "--dry-run", "--lock-wait", "0.6", ) waited = time.monotonic() - started assert proc.returncode == 1 assert "SESSION_LOCKED" in proc.stdout assert waited >= at_once + 0.3
def test_a_config_file_sets_the_same_knobs_and_a_flag_still_wins(tmp_path: Path) -> None: ws = _delete_workspace(tmp_path) _hold_the_lock(ws) config = tmp_path / "codex.python.json" config.write_text(json.dumps({"lock_wait": -5}), encoding="utf-8") refused = run_cli( "delete", "--workspace", str(ws), "--file", "src/helper.py", "--config", str(config) ) assert refused.returncode == 2 assert "REFUSED" in refused.stderr config.write_text(json.dumps({"lock_wait": 1.5}), encoding="utf-8") started = time.monotonic() overridden = run_cli( "delete", "--workspace", str(ws), "--file", "src/helper.py", "--config", str(config), "--lock-wait", "0", ) at_once = time.monotonic() - started assert overridden.returncode == 1 assert "SESSION_LOCKED" in overridden.stdout started = time.monotonic() followed = run_cli( "delete", "--workspace", str(ws), "--file", "src/helper.py", "--config", str(config) ) waited = time.monotonic() - started assert followed.returncode == 1 assert "SESSION_LOCKED" in followed.stdout assert waited >= at_once + 1.2
def test_a_config_file_that_makes_no_sense_refuses_with_exit_two(tmp_path: Path) -> None: ws = tmp_path / "quiet" ws.mkdir() config = tmp_path / "bad.json" config.write_text(json.dumps({"invented": 1}), encoding="utf-8") unknown = run_cli("verify", "--workspace", str(ws), "--config", str(config)) assert unknown.returncode == 2 assert "unknown key" in unknown.stderr config.write_text("{ this is not json", encoding="utf-8") broken = run_cli("verify", "--workspace", str(ws), "--config", str(config)) assert broken.returncode == 2 assert "not JSON" in broken.stderr config.write_text(json.dumps({"strict_tools": "yes"}), encoding="utf-8") mistyped = run_cli("verify", "--workspace", str(ws), "--config", str(config)) assert mistyped.returncode == 2 assert "true or false" in mistyped.stderr
def test_an_audit_file_collects_one_json_line_per_session_run(tmp_path: Path) -> None: ws = _delete_workspace(tmp_path) _hold_the_lock(ws) audit = tmp_path / "ledger.jsonl" for _ in range(2): proc = run_cli( "delete", "--workspace", str(ws), "--file", "src/helper.py", "--dry-run", "--lock-wait", "0", "--audit", str(audit), ) assert proc.returncode == 1 assert "SESSION_LOCKED" in proc.stdout lines = audit.read_text(encoding="utf-8").splitlines() assert len(lines) == 2 for line in lines: row = json.loads(line) assert row["command"] == "delete" assert row["verdict"] == "REFUSED" assert row["reason"] == "SESSION_LOCKED" assert row["committed"] is False
def test_the_exit_code_table_in_the_card_holds_for_the_real_commands() -> None: readme = (ROOT / "README.md").read_text(encoding="utf-8", newline="") table: Dict[str, Dict[int, str]] = {} for line in readme.splitlines(): if not line.startswith("| `"): continue cells = [cell.strip() for cell in line.strip().strip("|").split("|")] if len(cells) != 4: continue codes = {0: cells[1], 1: cells[2], 2: cells[3]} for verb in cells[0].strip("`").split("`, `"): table[verb] = codes assert table, "the card lost its exit code table"
surface = re.search(r"\{([a-z][a-z, |-]+)\}", run_cli("--help").stdout) assert surface is not None, "the parser surface no longer prints in the usage line" for verb in (part.strip() for part in surface.group(1).split(",")): covered = any(name == verb or name.startswith(verb + " ") for name in table) assert covered, "the table forgot the verb " + verb
probes = [ (("patterns", "show", "--pattern", "no-such-card"), "patterns show", 2), (("graph", "--workspace", str(ROOT / "no-such-workspace")), "graph", 1), (("lock-status", "--workspace", str(LAB)), "lock-status", 0), (("symbols", "--workspace", str(SAMPLE)), "symbols", 0), (("verify", "--workspace", str(SAMPLE), "--file", "src/mathops.py"), "verify", 0), ] for argv, verb, expected in probes: proc = run_cli(*argv) assert proc.returncode == expected, "%s answered %d, not %d" % ( " ".join(argv), proc.returncode, expected, ) cell = table[verb][expected] assert cell and cell != "--", "%s answers %d but the table leaves that cell empty" % ( verb, expected, )
def test_protect_adds_one_more_path_the_session_will_not_write(tmp_path: Path) -> None: ws = tmp_path / "guarded" shutil.copytree(SAMPLE, ws) before = (ws / "src" / "mathops.py").read_text(encoding="utf-8") proc = run_cli( "edit", "--workspace", str(ws), "--file", "src/mathops.py", "--search", "return left + right", "--replace", "return left - right", "--protect", "src/mathops.py", ) assert proc.returncode == 1, proc.stdout + proc.stderr assert "PROTECTED_PATH" in proc.stdout assert (ws / "src" / "mathops.py").read_text(encoding="utf-8") == before
def test_print_diff_shows_the_pair_before_the_verdict(tmp_path: Path) -> None: ws = _delete_workspace(tmp_path) proc = run_cli( "edit", "--workspace", str(ws), "--file", "src/mathops.py", "--search", "return left + right", "--replace", "return left + right # the sum keeps its name", "--dry-run", "--print-diff", ) assert proc.returncode == 0, proc.stdout + proc.stderr assert "--- a/src/mathops.py" in proc.stdout assert "+++ b/src/mathops.py" in proc.stdout assert "-return left + right" in proc.stdout assert "+return left + right # the sum keeps its name" in proc.stdout
def test_delete_prints_what_the_removal_takes_away(tmp_path: Path) -> None: ws = _delete_workspace(tmp_path) proc = run_cli( "delete", "--workspace", str(ws), "--file", "src/helper.py", "--dry-run", "--print-diff", ) assert proc.returncode == 0, proc.stdout + proc.stderr assert "--- a/src/helper.py" in proc.stdout assert "+++ /dev/null" in proc.stdout assert "-VALUE = 1" in proc.stdout
def test_a_card_shows_its_pair_before_the_verdict(pattern_lab: Path) -> None: proc = run_cli( "patterns", "apply", "--workspace", str(pattern_lab), "--pattern", "chain-to-registry", "--target", "src/registry.py::render", "--dry-run", "--print-diff", ) assert proc.returncode == 0, proc.stdout + proc.stderr assert "--- a/src/registry.py" in proc.stdout assert "--- a/tests/test_registry.py" in proc.stdout12345678910111213141516171819202122232425262728293031323334353637383940414243"""The suite enters the package it ships: a floor keeps dark corners from piling up."""
from __future__ import annotations
import jsonimport osimport subprocessimport sysfrom pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
# Measured at 95.9 percent when this floor was first written; ten points of# margin let one refactor breathe without letting a whole module go dark.FLOOR = 90.0
@pytest.mark.skipif( os.environ.get("LINGOLOGOS_COVERAGE_CHILD") == "1", reason="this test is the measurement: inside the traced child it would nest forever",)def test_the_suite_enters_most_of_the_package_it_ships(tmp_path: Path) -> None: report = tmp_path / "coverage.json" status = subprocess.run( [ sys.executable, "-B", "tools/measure_coverage.py", "--floor", str(FLOOR), "--report", str(report), ], cwd=str(ROOT), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ).returncode assert status == 0, "the traced suite failed or the coverage floor was missed" payload = json.loads(report.read_text(encoding="utf-8")) assert payload["percent"] >= FLOOR assert payload["total"] > 100, "a denominator that small measures nothing"34 unmodified lines3536373839404142433 unmodified lines474849505152535455565758596061626364656667686970717273747576777890 unmodified lines16917017117217317417517617739 unmodified lines2172182191952202212221982232242252262022032272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792803 unmodified lines28428528621321421521628728828929029129229329429529629729829930034 unmodified lines "bare-assert-to-explicit-raise": "src/guards.py::open_ticket", "bare-except-to-narrow-exception": "src/retries.py::call_or_none", "chain-to-registry": "src/registry.py::render", "drop-unused-imports": "src/legacy.py::read_size", "empty-len-to-truthiness": "src/baskets.py::describe", "init-missing-super": "src/widgets.py::Box.__init__", "mutable-default-to-none": "src/slugify.py::add_tag", "none-comparison-to-identity": "src/labels.py::label_for", "open-to-context-manager": "src/notes.py::read_note",3 unmodified lines "bare-assert-to-explicit-raise": "src/guards.py::close_ticket", "bare-except-to-narrow-exception": "src/retries.py::call_or_note", "chain-to-registry": "src/registry.py::render_pair", "drop-unused-imports": "src/tokens.py::count_words", "empty-len-to-truthiness": "src/baskets.py::first_or_none", "init-missing-super": "src/widgets.py::Shutter.__init__", "mutable-default-to-none": "src/slugify.py::join_parts", "none-comparison-to-identity": "src/labels.py::is_missing", "open-to-context-manager": "src/notes.py::write_note",}
# The five cards that vouch for coroutines carry a second pair over an async def; the# other five answer ASYNC_TARGET for one and say so on the card.COROUTINE_POSITIVE = { "annotate-literal-defaults": "src/asyncops.py::render_page", "bare-assert-to-explicit-raise": "src/asyncops.py::check_name", "empty-len-to-truthiness": "src/asyncops.py::word_total", "mutable-default-to-none": "src/asyncops.py::gather", "none-comparison-to-identity": "src/asyncops.py::describe",}COROUTINE_NEGATIVE = { "annotate-literal-defaults": "src/asyncops.py::sized", "bare-assert-to-explicit-raise": "src/asyncops.py::check_after", "empty-len-to-truthiness": "src/asyncops.py::item_count", "mutable-default-to-none": "src/asyncops.py::plain", "none-comparison-to-identity": "src/asyncops.py::present",}COROUTINE_LOCKED = {"mutable-default-to-none", "bare-assert-to-explicit-raise"}
def _card(pattern_id: str) -> PatternSpec: return pattern_card(pattern_id)90 unmodified lines found = [label for label, _hit in scan_pattern(LAB, pattern_id)] assert POSITIVE[pattern_id] in found, "%s does not find the function planted for it" % pattern_id assert NEGATIVE[pattern_id] not in found, "%s finds the function planted to be refused" % pattern_id if pattern_id in COROUTINE_POSITIVE: assert COROUTINE_POSITIVE[pattern_id] in found, "%s misses the coroutine planted for it" % pattern_id assert COROUTINE_NEGATIVE[pattern_id] not in found only_one = scan_pattern(LAB, "open-to-context-manager") assert [label for label, _hit in only_one] == ["src/notes.py::read_note"]
39 unmodified lines assert "PATTERNS: CONFIRMED" in proc.stdout
def test_the_corpus_holds_one_pair_for_every_card_and_validates() -> None:def test_the_corpus_holds_a_pair_for_every_card_and_validates() -> None: rows = read_rows(CASES) assert validate_case_rows(rows) == [] assert len(rows) == 2 * len(PATTERNS) assert len(rows) == 2 * len(PATTERNS) + 2 * len(COROUTINE_POSITIVE) for pattern_id in PATTERN_IDS: positive = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "VERIFIED"] negative = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED"] assert [str(row["targets"][0]) for row in positive] == [POSITIVE[pattern_id]] assert [str(row["targets"][0]) for row in negative] == [NEGATIVE[pattern_id]] expected = [POSITIVE[pattern_id]] expected_negative = [NEGATIVE[pattern_id]] if pattern_id in COROUTINE_POSITIVE: expected.append(COROUTINE_POSITIVE[pattern_id]) expected_negative.append(COROUTINE_NEGATIVE[pattern_id]) assert [str(row["targets"][0]) for row in positive] == expected assert [str(row["targets"][0]) for row in negative] == expected_negative for row in positive: assert len(row["edits"]) == 2
def test_the_coroutine_pairs_plan_over_coroutines_and_the_lock_waits_where_it_calls() -> None: for pattern_id in COROUTINE_POSITIVE: plan = plan_pattern(LAB, pattern_id, COROUTINE_POSITIVE[pattern_id]) assert not plan.refused, plan.detail assert len(plan.edits) == 2 companion = plan.edits[1] if pattern_id in COROUTINE_LOCKED: assert "asyncio.run(" in companion.replace assert "import asyncio" in companion.replace for pattern_id, target in COROUTINE_NEGATIVE.items(): plan = plan_pattern(LAB, pattern_id, target) assert plan.refused
def test_the_cards_without_a_coroutine_pair_answer_async_target() -> None: for pattern_id in ("chain-to-registry", "open-to-context-manager", "bare-except-to-narrow-exception"): plan = plan_pattern(LAB, pattern_id, "src/asyncops.py::describe") assert plan.refused assert plan.reason_code == "ASYNC_TARGET" assert "ASYNC_TARGET" in _card(pattern_id).refuses_as
def test_the_constructor_card_claims_only_a_self_only_constructor_without_the_chain() -> None: for target, code in ( ("src/widgets.py::Grille.__init__", "INIT_TAKES_MORE_THAN_SELF"), ("src/widgets.py::NoSuch.__init__", "NO_SUCH_CLASS"), ("src/widgets.py::Box.area", "NOT_A_METHOD"), ): plan = plan_pattern(LAB, "init-missing-super", target) assert plan.refused, "%s was applied" % target assert plan.reason_code == code, "%s refused with %s" % (target, plan.reason_code)
def test_the_unused_import_card_removes_only_the_line_no_other_line_reads() -> None: plan = plan_pattern(LAB, "drop-unused-imports", "src/legacy.py::read_size") assert not plan.refused, plan.detail assert plan.primary().replace == "" assert "json" in plan.primary().search assert "os" not in plan.primary().search assert plan.edits[1].replace.count("def test_read_size_keeps_no_unread_imports") == 1
def test_coverage_states_the_fixture_as_its_denominator() -> None:3 unmodified lines assert payload["rows"] == len(read_rows(CASES)) assert sorted(str(entry["pattern_id"]) for entry in payload["patterns"]) == list(PATTERN_IDS) for entry in payload["patterns"]: assert entry["positive_rows"] == 1 and entry["negative_rows"] == 1 assert POSITIVE[str(entry["pattern_id"])] in entry["targets_in_shape"] assert len(entry["refusals_recorded"]) == 1 assert entry["refusals_recorded"][0] in _card(str(entry["pattern_id"])).refuses_as pattern_id = str(entry["pattern_id"]) pair_count = 2 if pattern_id in COROUTINE_POSITIVE else 1 assert entry["positive_rows"] == pair_count and entry["negative_rows"] == pair_count assert POSITIVE[pattern_id] in entry["targets_in_shape"] rows_for_card = [ row for row in read_rows(CASES) if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED" ] assert entry["refusals_recorded"] == sorted(str(row.get("reason_code", "")) for row in rows_for_card) for code in entry["refusals_recorded"]: assert code in _card(pattern_id).refuses_as
def test_every_card_lists_the_refusals_a_plan_can_answer_with() -> None:334 unmodified lines335336337338338339340340341342343344345346347345346347348349350351352353354355334 unmodified lines assert outcome.reason_code == rules.NON_LITERAL_ASSERT_MESSAGE
def test_a_coroutine_target_is_refused_by_name_before_any_rewrite(tmp_path: Path) -> None:def test_a_card_refuses_a_coroutine_only_when_its_lock_does_not_wait_for_one(tmp_path: Path) -> None: root = tmp_path / "ws" _write(root / "src" / "coro.py", "async def gather(items=[]):\n items.append(1)\n return items\n") _write(root / "src" / "coro.py", "async def gather(items=[]):\n return items\n") _write( root / "tests" / "test_coro.py", "from src.coro import gather\n\n\ndef test_gather_exists() -> None:\n assert callable(gather)\n", ) outcome = _outcome("src/coro.py", "gather", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.ASYNC_TARGET claimed = _outcome("src/coro.py", "gather", "mutable-default-to-none", root) assert isinstance(claimed, rules.RuleHit) assert "asyncio.run(" in claimed.edits[1].replace assert "import asyncio" in claimed.edits[1].replace for rule_id in ("chain-to-registry", "open-to-context-manager", "bare-except-to-narrow-exception"): refusal = _outcome("src/coro.py", "gather", rule_id, root) assert isinstance(refusal, rules.RuleMiss) assert refusal.reason_code == rules.ASYNC_TARGET
def test_a_test_file_the_lock_cannot_append_to_is_refused_as_a_target(tmp_path: Path) -> None:1 unmodified line23456789101173 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331 unmodified line
from __future__ import annotations
import astimport importlib.utilimport jsonimport refrom pathlib import Path
_ROOT = Path(__file__).resolve().parent.parent73 unmodified lines assert report["sources_sha256"] == _run_gates.bundle_digest( _run_gates.digest_input_files(_ROOT) )
def test_the_gates_line_in_the_card_matches_the_saved_report() -> None: """The card's gate tally is not a sentence to trust; it is a checked equality.""" readme = (_ROOT / "README.md").read_text(encoding="utf-8", newline="") report = json.loads((_ROOT / "results" / "gates.json").read_text(encoding="utf-8")) line = re.search( r"GATES: (\w+) \((\d+) gates: (\d+) CONFIRMED, (\d+) REJECTED, (\d+) ABSTAIN\)", readme, ) assert line is not None verdict, total, confirmed, rejected, abstain = line.groups() gate_names = [gate["name"] for gate in report["gates"]] assert int(total) == len(report["gates"]) == len(_run_gates.GATES) assert gate_names == [name for name, _ in _run_gates.GATES] counts = report["counts"] assert int(confirmed) == counts.get("CONFIRMED", 0) assert int(rejected) == counts.get("REJECTED", 0) assert int(abstain) == counts.get("ABSTAIN", 0) assert verdict == report["verdict"]
def test_the_numbers_sentence_in_the_card_is_countable_from_the_tree() -> None: """Gates, tests, test files, and node files in the card come from the tree, not from memory.""" readme = (_ROOT / "README.md").read_text(encoding="utf-8", newline="") sentence = re.search( r"The gate runner is where this bundle states its numbers out loud: (\d+) gates, " r"(\d+) tests across (\d+) files,\n(\d+) files under `nodes/`, and a kernel it does not carry\.", readme, ) assert sentence is not None gates, tests, files, node_files = (int(value) for value in sentence.groups()) assert gates == len(_run_gates.GATES) test_files = sorted((_ROOT / "tests").glob("test_*.py")) assert files == len(test_files) collected = 0 for path in test_files: tree = ast.parse(path.read_text(encoding="utf-8")) collected += sum( 1 for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name.startswith("test_") ) assert tests == collected assert node_files == sum(1 for path in (_ROOT / "nodes").rglob("*") if path.is_file())2 unmodified lines345678910694 unmodified lines70570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875920 unmodified lines7807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388392 unmodified linesfrom __future__ import annotations
import osimport subprocessimport sysimport threadingimport timefrom pathlib import Path694 unmodified lines lock.unlink()
def test_a_commit_refuses_when_the_lock_stops_naming_the_run( sample_pkg: Path, monkeypatch) -> None: """The commit re-asks the lock question: a stolen lock stops the write.""" lock = sample_pkg / session_module.SESSION_LOCK_NAME real_pipeline = session_module.run_pipeline
def hijack_pipeline(case): lock.write_text("99999999 - someone-elses-token\n", encoding="ascii", newline="") return real_pipeline(case)
monkeypatch.setattr(session_module, "run_pipeline", hijack_pipeline) session = PythonWorkspaceSession(sample_pkg) target = sample_pkg / "src" / "mathops.py" before = target.read_bytes() res = session.edit_file( "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=True ) assert res.verdict == "REFUSED" assert res.reason == session_module.SESSION_LOCKED assert res.committed is False assert target.read_bytes() == before assert "someone-elses-token" in lock.read_text(encoding="ascii") lock.unlink()
def test_a_commit_refuses_when_the_lock_disappears_mid_run( sample_pkg: Path, monkeypatch) -> None: """A lock unlinked while the run works leaves the commit without a holder.""" lock = sample_pkg / session_module.SESSION_LOCK_NAME real_pipeline = session_module.run_pipeline
def vanish_pipeline(case): lock.unlink() return real_pipeline(case)
monkeypatch.setattr(session_module, "run_pipeline", vanish_pipeline) session = PythonWorkspaceSession(sample_pkg) target = sample_pkg / "src" / "mathops.py" before = target.read_bytes() res = session.edit_file( "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=True ) assert res.verdict == "REFUSED" assert res.reason == session_module.SESSION_LOCKED assert target.read_bytes() == before
def test_a_hardlinked_pair_in_the_workspace_is_refused_by_name(sample_pkg: Path) -> None: """Two names, one file: the copy would split what the disk holds as one.""" twin = sample_pkg / "src" / "mathops_twin.py"20 unmodified lines text = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="") assert "return left + right" in text twin.unlink()
def test_a_killed_session_freezes_no_tree_and_blocks_no_next_run( sample_pkg: Path, tmp_path: Path) -> None: """The crash drill: kill a live session mid run and check what the disk keeps.
A helper process takes the workspace lock and starts an edit; the test kills it as soon as the lock appears, while the six nodes are still talking and no commit has been attempted. The tree must hold exactly the bytes it held before, the lock must stay behind naming a process that no longer runs, and the next session must take that leftover over and finish the very edit the killed run left undone. """ helper_path = sample_pkg / "src" / "crashme.py" helper_path.write_text('"""Crash subject."""\n\nVALUE = 1\n', encoding="utf-8", newline="") script = tmp_path / "crash_helper.py" script.write_text( "import sys\n" "from lingologos_python.session import PythonWorkspaceSession\n" "session = PythonWorkspaceSession(sys.argv[1])\n" "res = session.edit_file('src/crashme.py', 'VALUE = 1', 'VALUE = 2')\n" "print(res.verdict)\n", encoding="utf-8", newline="", ) root = Path(__file__).resolve().parents[1] proc = subprocess.Popen( [sys.executable, "-B", str(script), str(sample_pkg)], cwd=str(root), env=dict(os.environ, PYTHONPATH=str(root)), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) lock = sample_pkg / session_module.SESSION_LOCK_NAME deadline = time.monotonic() + 20.0 while not lock.is_file() and time.monotonic() < deadline: if proc.poll() is not None: pytest.fail("the helper session ended before it took the workspace lock") time.sleep(0.05) assert lock.is_file(), "the helper session never took the workspace lock" proc.kill() proc.wait(timeout=10)
assert helper_path.read_text(encoding="utf-8") == '"""Crash subject."""\n\nVALUE = 1\n' status = session_module.workspace_lock_status(sample_pkg) assert status["present"] is True assert status["held"] is False assert status["stale"] is True
session = PythonWorkspaceSession(sample_pkg) res = session.edit_file("src/crashme.py", "VALUE = 1", "VALUE = 2", commit=True) assert res.verdict == "VERIFIED" assert res.assurance == 3 assert res.committed is True assert "VALUE = 2" in helper_path.read_text(encoding="utf-8") assert session_module.workspace_lock_status(sample_pkg)["present"] is False50 unmodified lines51525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596975455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911010610710810911011111211311411511611711811912012112212312412512612712812913013111111211311411511611711811912012112212312412512612712812913013113213313413513613713813950 unmodified linesCOVERAGE_PATH = ROOT / "patterns" / "coverage.json"COVERAGE_SCHEMA = "lingologos-python-pattern-coverage-1"
# One pair per card: a function of the fixture in the shape, and a function beside it that is not.# The right column states the reason code the rule is expected to give, so a rule that stops# refusing for the reason the card claims is caught here rather than in a reader's session.PAIRS: Dict[str, Tuple[str, str, str]] = { "annotate-literal-defaults": ( "src/tokens.py::count_words", "src/tokens.py::count_lines", "ALREADY_ANNOTATED", ), "bare-assert-to-explicit-raise": ( "src/guards.py::open_ticket", "src/guards.py::close_ticket", "NOT_THE_FIRST_STATEMENT", ), "bare-except-to-narrow-exception": ( "src/retries.py::call_or_none", "src/retries.py::call_or_note", "NO_BARE_EXCEPT", ), "chain-to-registry": ( "src/registry.py::render", "src/registry.py::render_pair", "BRANCH_SHAPE_MISMATCH", ), "empty-len-to-truthiness": ( "src/baskets.py::describe", "src/baskets.py::first_or_none", "NO_EMPTY_LEN_CHECK", ), "mutable-default-to-none": ( "src/slugify.py::add_tag", "src/slugify.py::join_parts", "NOT_A_MUTABLE_DEFAULT", ), "none-comparison-to-identity": ( "src/labels.py::label_for", "src/labels.py::is_missing", "NO_NONE_COMPARISON", ), "open-to-context-manager": ( "src/notes.py::read_note", "src/notes.py::write_note", "ALREADY_SCOPED", ),# One or more pairs per card: a function of the fixture in the shape, and a function beside it that# is not. The right column states the reason code the rule is expected to give, so a rule that stops# refusing for the reason the card claims is caught here rather than in a reader's session. A pair# with the tag "coroutine" states the same claim again over an async def: the card that vouches for# coroutines carries its own pair, and the card that does not is recorded refusing one.Pair = Tuple[str, str, str, str]
PAIRS: Dict[str, List[Pair]] = { "annotate-literal-defaults": [ ("src/tokens.py::count_words", "src/tokens.py::count_lines", "ALREADY_ANNOTATED", ""), ("src/asyncops.py::render_page", "src/asyncops.py::sized", "ALREADY_ANNOTATED", "coroutine"), ], "bare-assert-to-explicit-raise": [ ("src/guards.py::open_ticket", "src/guards.py::close_ticket", "NOT_THE_FIRST_STATEMENT", ""), ("src/asyncops.py::check_name", "src/asyncops.py::check_after", "NOT_THE_FIRST_STATEMENT", "coroutine"), ], "bare-except-to-narrow-exception": [ ("src/retries.py::call_or_none", "src/retries.py::call_or_note", "NO_BARE_EXCEPT", ""), ], "chain-to-registry": [ ("src/registry.py::render", "src/registry.py::render_pair", "BRANCH_SHAPE_MISMATCH", ""), ], "drop-unused-imports": [ ("src/legacy.py::read_size", "src/tokens.py::count_words", "NO_UNUSED_IMPORT", ""), ], "empty-len-to-truthiness": [ ("src/baskets.py::describe", "src/baskets.py::first_or_none", "NO_EMPTY_LEN_CHECK", ""), ("src/asyncops.py::word_total", "src/asyncops.py::item_count", "NO_EMPTY_LEN_CHECK", "coroutine"), ], "init-missing-super": [ ("src/widgets.py::Box.__init__", "src/widgets.py::Shutter.__init__", "SUPER_CALL_ALREADY_FIRST", ""), ], "mutable-default-to-none": [ ("src/slugify.py::add_tag", "src/slugify.py::join_parts", "NOT_A_MUTABLE_DEFAULT", ""), ("src/asyncops.py::gather", "src/asyncops.py::plain", "NOT_A_MUTABLE_DEFAULT", "coroutine"), ], "none-comparison-to-identity": [ ("src/labels.py::label_for", "src/labels.py::is_missing", "NO_NONE_COMPARISON", ""), ("src/asyncops.py::describe", "src/asyncops.py::present", "NO_NONE_COMPARISON", "coroutine"), ], "open-to-context-manager": [ ("src/notes.py::read_note", "src/notes.py::write_note", "ALREADY_SCOPED", ""), ],}
def _case_id(pattern_id: str, tag: str, half: str) -> str: if tag: return "pat-%s-%s-%s" % (pattern_id, tag, half) return "pat-%s-%s" % (pattern_id, half)
def build_rows() -> List[Dict[str, object]]: """Every row of the corpus, in the order it belongs in the file."""
rows: List[Dict[str, object]] = [] for pattern_id in sorted(PATTERNS): positive_target, negative_target, expected_code = PAIRS[pattern_id] applied = plan_pattern(LAB, pattern_id, positive_target) if applied.refused: raise SystemExit( "the card '%s' refuses the target built for it: %s (%s)" % (pattern_id, applied.detail, applied.reason_code) ) if len(applied.edits) < 2: raise SystemExit( "the card '%s' planned %d edits, and a card without its lock test does not belong " "in this corpus" % (pattern_id, len(applied.edits)) ) rows.append(applied.to_row("pat-%s-positive" % pattern_id))
refusal = plan_pattern(LAB, pattern_id, negative_target) if not refusal.refused: raise SystemExit( "the card '%s' applied to the target built to be refused: %s" % (pattern_id, negative_target) ) if refusal.reason_code != expected_code: raise SystemExit( "the card '%s' refused '%s' with '%s', this tool expects '%s'" % (pattern_id, negative_target, refusal.reason_code, expected_code) ) rows.append(refusal.to_row("pat-%s-negative" % pattern_id)) for positive_target, negative_target, expected_code, tag in PAIRS[pattern_id]: applied = plan_pattern(LAB, pattern_id, positive_target) if applied.refused: raise SystemExit( "the card '%s' refuses the target built for it: %s (%s)" % (pattern_id, applied.detail, applied.reason_code) ) if len(applied.edits) < 2: raise SystemExit( "the card '%s' planned %d edits, and a card without its lock test does not belong " "in this corpus" % (pattern_id, len(applied.edits)) ) rows.append(applied.to_row(_case_id(pattern_id, tag, "positive")))
refusal = plan_pattern(LAB, pattern_id, negative_target) if not refusal.refused: raise SystemExit( "the card '%s' applied to the target built to be refused: %s" % (pattern_id, negative_target) ) if refusal.reason_code != expected_code: raise SystemExit( "the card '%s' refused '%s' with '%s', this tool expects '%s'" % (pattern_id, negative_target, refusal.reason_code, expected_code) ) rows.append(refusal.to_row(_case_id(pattern_id, tag, "negative")))
problems = validate_case_rows(rows) if problems:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""Count which functions of the package the test suite actually enters.
The tool starts the suite once in a traced child process and records everyfunction of lingologos_python that any test called. Functions no test entersstay dark, so a test can promise a floor for the lit share instead of afeeling. Only the standard library is used: the profile hook is the counter,and the syntax tree of the package is the denominator."""
from __future__ import annotations
import argparseimport astimport jsonimport osimport subprocessimport sysimport tempfilefrom pathlib import Pathfrom typing import List, Set, Tuple
ROOT = Path(__file__).resolve().parents[1]if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))sys.dont_write_bytecode = True
PACKAGE_DIR = ROOT / "lingologos_python"DEFAULT_FLOOR = 90.0
def module_name(rel: Path) -> str: """Dotted module name a file inside the package answers to.""" parts = list(rel.with_suffix("").parts) if parts and parts[-1] == "__init__": parts = parts[:-1] return ".".join(["lingologos_python", *parts])
def definitions(path: Path) -> List[str]: """Qualnames of every function the file defines, in the form co_qualname uses.""" tree = ast.parse(path.read_text(encoding="utf-8", newline="")) found: List[str] = []
def walk(node: ast.AST, prefix: str) -> None: for child in ast.iter_child_nodes(node): if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): qual = child.name if not prefix else prefix + "." + child.name found.append(qual) walk(child, qual) elif isinstance(child, ast.ClassDef): walk(child, child.name)
walk(tree, "") return found
def package_files() -> List[Path]: return sorted(PACKAGE_DIR.rglob("*.py"))
def run_child(report: Path) -> int: """Run the suite in this process while a profile hook records entered functions.""" # The suite carries a test that starts this tool; that test stands down # when it runs inside the traced child, so the measurement never nests. os.environ["LINGOLOGOS_COVERAGE_CHILD"] = "1" seen: Set[Tuple[str, str]] = set() package = str(PACKAGE_DIR) + os.sep
def probe(frame, event, _argument): if event == "call": code = frame.f_code if code.co_filename.startswith(package): rel = Path(code.co_filename).relative_to(PACKAGE_DIR) seen.add((module_name(rel), code.co_qualname))
sys.setprofile(probe) import pytest
status = int(pytest.main(["-q", "-p", "no:cacheprovider", "tests"])) sys.setprofile(None) report.write_text( json.dumps({"executed": sorted(seen)}, sort_keys=True) + "\n", encoding="utf-8", newline="\n", ) return status
def summarize(child_report: Path) -> Tuple[float, int, int, List[str]]: """Percent of package functions the child entered, plus the dark list.""" payload = json.loads(child_report.read_text(encoding="utf-8")) executed = {(str(module), str(qual)) for module, qual in payload["executed"]} total = 0 lit = 0 dark: List[str] = [] for path in package_files(): module = module_name(path.relative_to(PACKAGE_DIR)) for qual in definitions(path): total += 1 if (module, qual) in executed: lit += 1 else: dark.append("%s::%s" % (module, qual)) percent = (100.0 * lit / total) if total else 0.0 return percent, lit, total, dark
def main(argv: List[str] | None = None) -> int: parser = argparse.ArgumentParser( description="Measure how much of lingologos_python the test suite enters." ) parser.add_argument("--floor", type=float, default=DEFAULT_FLOOR, help="minimum percent to pass") parser.add_argument("--report", default=None, help="write the JSON summary here") parser.add_argument("--child", action="store_true", help=argparse.SUPPRESS) parser.add_argument("--child-report", default=None, help=argparse.SUPPRESS) args = parser.parse_args(argv)
if args.child: child_report = Path(args.child_report or (Path(tempfile.mkdtemp()) / "child.json")) return run_child(child_report)
env = dict(os.environ, LINGOLOGOS_COVERAGE_CHILD="1") with tempfile.TemporaryDirectory(prefix="lingologos_coverage_") as tmp_dir: child_report = Path(tmp_dir) / "child.json" status = subprocess.run( [sys.executable, "-B", str(Path(__file__).resolve()), "--child", "--child-report", str(child_report)], cwd=str(ROOT), env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ).returncode if not child_report.is_file(): print("coverage: the traced suite wrote no record (exit %d)" % status) return 1 percent, lit, total, dark = summarize(child_report)
report = { "percent": round(percent, 2), "lit": lit, "total": total, "floor": args.floor, "dark": sorted(dark), } if args.report: target = Path(args.report) target.parent.mkdir(parents=True, exist_ok=True) target.write_text(json.dumps(report, sort_keys=True, indent=2) + "\n", encoding="utf-8", newline="\n") print("coverage: %d of %d functions entered (%.1f%%), floor %.1f%%" % (lit, total, percent, args.floor)) if status != 0: print("coverage: the traced suite exited %d, so the number describes a failing run" % status) return 1 if percent < args.floor: print("coverage: below the floor; %d functions never entered" % len(dark)) return 1 return 0
if __name__ == "__main__": raise SystemExit(main())10 unmodified lines111213141415161617181916 unmodified lines36373839404041424344197 unmodified lines242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273147 unmodified lines4214224233974244254264274284024034044294304314324334342 unmodified lines4374384394134404414424434442 unmodified lines44744844945045142242342442542645245345445545645745842845946046146210 unmodified linessiblings) and deliberately avoids `publish_to_hub.py`: that name belongs to the release builder ofthe multilingual track.
This bundle carries no kernel. It carries one corpus of its own, the sixteen pattern cases underThis bundle carries no kernel. It carries one corpus of its own, the thirty pattern cases under`patterns/`, generated from the rules and the fixture beside them, and the card states theirdenominator rather than letting sixteen rows look like a benchmark. Every number the card statesdenominator rather than letting thirty rows look like a benchmark. Every number the card states(gates, tests and the files holding them, node files) is re-derived from this tree, the cardsentence that states them is parsed back and compared, and no constant in this file duplicatesany of them: a number can only change here by changing the code that produces it. A card that16 unmodified linesimport shutilimport sysimport tempfileimport timefrom pathlib import Pathfrom typing import List, Tuplefrom typing import Callable, List, Tuple, TypeVar
ROOT = Path(__file__).resolve().parents[1]
197 unmodified lines return hashlib.sha256(data).hexdigest()
T = TypeVar("T")
def with_retry(label: str, action: Callable[[], T], attempts: int = 3, pause_sec: float = 2.0) -> T: """One hub call, given three honest chances with a fixed wait between them.
A flaky network is not a reason to re-run a publisher that has already proven its card against its tree. Every remote call goes through here: the same call is retried up to `attempts` times with a fixed `pause_sec` wait, and the failure of the last attempt is the failure the run reports. """
for attempt in range(1, attempts + 1): try: return action() except Exception as exc: if attempt == attempts: raise print( "%s failed (%s); retrying in %.1f seconds (attempt %d of %d)" % (label, exc, pause_sec, attempt + 1, attempts) ) time.sleep(pause_sec) raise AssertionError("unreachable")
def tree_digest(files: List[Path]) -> str: """The digest the gate runner writes into its report, over the same bytes.
147 unmodified lines from huggingface_hub import HfApi, hf_hub_download # noqa: E402 (only needed to publish)
api = HfApi(token=token) who = api.whoami() who = with_retry("token check", api.whoami) auth = who.get("auth") or {} if isinstance(auth, dict) and str(auth.get("role", "")) == "read": print("note: this token is read only, it cannot write a dataset") print(f"token belongs to {who.get('name')}") api.create_repo(args.repo, repo_type="dataset", exist_ok=True) api.upload_folder(folder_path=str(staging), repo_id=args.repo, repo_type="dataset") remote = api.list_repo_files(args.repo, repo_type="dataset") with_retry("create repo", lambda: api.create_repo(args.repo, repo_type="dataset", exist_ok=True)) with_retry("upload folder", lambda: api.upload_folder(folder_path=str(staging), repo_id=args.repo, repo_type="dataset")) remote = with_retry("file listing", lambda: api.list_repo_files(args.repo, repo_type="dataset"))
expected = {str(p.relative_to(ROOT)).replace("\\", "/") for p in files} missing = sorted(expected - set(remote))2 unmodified lines for name in sorted(expected & set(remote)): local = sha256((staging / name).read_bytes()) # hf_hub_download hands back a path, not the bytes, and the cached copy is read from there. hub = sha256(Path(hf_hub_download(args.repo, name, repo_type="dataset")).read_bytes()) fetched = with_retry("download " + name, lambda: hf_hub_download(args.repo, name, repo_type="dataset")) hub = sha256(Path(fetched).read_bytes()) if local != hub: differ.append(name)
2 unmodified lines
if args.prune and extra: print("pruning files the folder no longer holds") with_retry( "file removal", api.delete_files( repo_id=args.repo, repo_type="dataset", delete_patterns=extra, commit_message="drop removed files", lambda: api.delete_files( repo_id=args.repo, repo_type="dataset", delete_patterns=extra, commit_message="drop removed files", ), ) remote = api.list_repo_files(args.repo, repo_type="dataset") remote = with_retry("file listing", lambda: api.list_repo_files(args.repo, repo_type="dataset")) missing = sorted(expected - set(remote)) extra = sorted(set(remote) - expected - {".gitattributes"}) print(34 unmodified lines35363738383940414243444540464748495036 unmodified lines8788899091929394959697989910010110210310410510610710810911011140 unmodified lines15215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323462 unmodified lines29729829930030130230330430530630730830931031131231331431531631731831932032126 unmodified lines34834935035135235335440 unmodified lines39539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244322 unmodified lines46646746830546947047147247347447530830947647747847931331448048148248348448548648748848949049128 unmodified lines5205215223495235245255267 unmodified lines53453553636353753836536653954054154254354454554664 unmodified lines6116126134374384394404416146156166176186196206216223 unmodified lines6266276284514526296306314546326334566346356366374606386396406413 unmodified lines6456466474706486496506511 unmodified line653654655478656657658659660661484662663664665254 unmodified lines92092192292392492592655 unmodified lines98298398498598698798834 unmodified linesfrom lingologos_codex.types import ABSTAIN, CONFIRMED, REJECTED, VERDICTS, GateResult # 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.ast_graph import ( build_reverse_index, discover_python_files, extract_python_graph, importers_from_index, importers_of,) # noqa: E402from lingologos_python.patterns import PATTERNS, module_level_functions, plan_pattern # noqa: E402from lingologos_python.reasons import REASON_CODES # noqa: E402from lingologos_python.reasons import REASON_CODES, SESSION_LOCKED # noqa: E402import lingologos_python.session as session_module # noqa: E402from lingologos_python.session import SESSION_LOCK_NAME, PythonWorkspaceSession # noqa: E402from lingologos_python.test_selector import select_python_tests # noqa: E402
36 unmodified lines return digest.hexdigest()
CODEX_KERNEL_ROOT = ROOT.parent / "codex"
def kernel_digest() -> str: """The bytes of the kernel this bundle tests against, as one hash.
The kernel lives in its own bundle, is never carried here, and is never modified here. Naming its digest pins which kernel answered the gates in this report, so a card can promise behaviour without anyone remembering which kernel revision produced it. """ files = [ path for path in CODEX_KERNEL_ROOT.rglob("*.py") if "__pycache__" not in path.relative_to(CODEX_KERNEL_ROOT).parts ] return bundle_digest(files, CODEX_KERNEL_ROOT)
def _rejected(check: str, note: str, failed: Sequence[str] = ()) -> GateResult: return GateResult(REJECTED, check, failed_targets=tuple(failed), note=note)
40 unmodified lines return _confirmed(check, f"selected {len(selected)} dependent test file(s)")
GRAPH_SCALING_PACKAGES = 50GRAPH_SCALING_FILES = 1500GRAPH_SCALING_SEED = 20261127
def _seed_scaling_workspace(root: Path) -> Set[Tuple[str, str]]: """Write a deterministic import web and return the file edges those imports state.
Every generated module but the first imports one function from a module written before it, so the expected edges are known the moment the text is written: the gate can then demand that the extractor answer with exactly that set. """ rng = random.Random(GRAPH_SCALING_SEED) earlier: List[Tuple[str, str, str]] = [] edges: Set[Tuple[str, str]] = set() written = 0 for package in range(GRAPH_SCALING_PACKAGES): package_dir = root / "app" / ("pkg%d" % package) package_dir.mkdir(parents=True) (package_dir / "__init__.py").write_text("", encoding="utf-8", newline="\n") written += 1 for module in range((GRAPH_SCALING_FILES - GRAPH_SCALING_PACKAGES) // GRAPH_SCALING_PACKAGES): rel = "app/pkg%d/mod%d.py" % (package, module) dotted = "app.pkg%d.mod%d" % (package, module) name = "value_%d_%d" % (package, module) if not earlier: text = "def %s() -> int:\n return 0\n" % name else: source_dotted, source_rel, source_name = rng.choice(earlier) text = ( "from %s import %s as handed\n\n\ndef %s() -> int:\n return handed() + 1\n" % (source_dotted, source_name, name) ) edges.add((rel, source_rel)) (root / Path(*rel.split("/"))).write_text(text, encoding="utf-8", newline="\n") earlier.append((dotted, rel, name)) written += 1 return edges
def gate_graph_scaling() -> GateResult: check = "the symbol graph stays exact at %d generated files" % GRAPH_SCALING_FILES started = time.perf_counter() with tempfile.TemporaryDirectory(prefix="lingologos_scaling_") as tmp_dir: root = Path(tmp_dir) expected = _seed_scaling_workspace(root) files = discover_python_files(root) if len(files) != GRAPH_SCALING_FILES: return _rejected( check, "generated %d python files, discovery found %d" % (GRAPH_SCALING_FILES, len(files)), ) read = time.perf_counter() _symbols, edges = extract_python_graph(root, files) extract_seconds = time.perf_counter() - read file_edges = {edge for edge in edges if "::" not in edge[0] and "::" not in edge[1]} missing = sorted(str(edge) for edge in (expected - file_edges)) extra = sorted(str(edge) for edge in (file_edges - expected)) if missing or extra: return _rejected( check, "file edges drifted: missing %s, extra %s" % (missing[:3], extra[:3]), missing[:3] + extra[:3], ) index = build_reverse_index(root, files) probe = random.Random(GRAPH_SCALING_SEED + 1) for target in probe.sample(files, 12): remaining = [p for p in files if p != target] if importers_from_index(index, target) != sorted(importers_of(root, remaining, target)): return _rejected(check, "the index and the walk disagree about %s" % target, [target]) return _confirmed( check, "%d files, %d import edges exact, reverse index agrees on 12 probes, %.1fs total with %.1fs extract" % (GRAPH_SCALING_FILES, len(expected), time.perf_counter() - started, extract_seconds), )
def gate_strict_abstain_control() -> GateResult: check = "missing optional tools produce ABSTAIN and block verdict" adapter = StrictPythonLanguageAdapter(FIXTURE_PKG)62 unmodified lines + ["create_existing"] + ["empty_edit"] + ["bad_pattern"] + ["tampered_lock_edit"])# The sweep states, per operation, how it must end. "verified_no_write" is a# verify that judged the file without touching the tree. Operation 5 of the# shuffle always runs under a planted live lock, so its only honest outcome is# a refusal whatever the verb.SESSION_SWEEP_EXPECTED: Dict[str, str] = { "valid_edit_commit": "committed", "valid_create_commit": "committed", "verify": "verified_no_write", "traversal_edit": "refused", "protected_create": "refused", "missing_edit": "refused", "missing_delete": "raised", "create_existing": "raised", "empty_edit": "refused", "bad_pattern": "raised", "tampered_lock_edit": "refused",}
def _sweep_tree_state(root: Path) -> Dict[str, bytes]:26 unmodified lines committed = 0 refused = 0 raised = 0 outcomes: List[str] = [] for index, (kind, rel) in enumerate(ops): session = PythonWorkspaceSession(ws) lock_held = False40 unmodified lines res = session.apply_pattern("ghost-card-%d" % index, commit=True) except KeyError: raised += 1 elif kind == "tampered_lock_edit": # An outsider overwrites our lock mid-run: the commit must # notice that the lock no longer names this run and refuse, # leaving both the tree and the stolen lock in place. path = ws / Path(*rel.split("/")) text = path.read_text(encoding="utf-8", newline="") anchor = [line for line in text.split("\n") if line.strip()][-1] real_run = session_module.run_pipeline
def tamper(case, _real=real_run): (ws / SESSION_LOCK_NAME).write_text( "%d - not-our-token" % os.getpid(), encoding="ascii" ) return _real(case)
session_module.run_pipeline = tamper try: res = session.edit_file(rel, anchor, anchor + "\n# swept", commit=True) finally: session_module.run_pipeline = real_run (ws / SESSION_LOCK_NAME).unlink(missing_ok=True) after = _sweep_tree_state(ws) if res is None: outcome = "raised" elif res.committed: outcome = "committed" elif res.verdict in ("REFUSED", "UNKNOWN"): outcome = "refused" else: outcome = "verified_no_write" outcomes.append(outcome) if res is not None: expected = "refused" if index == 5 else SESSION_SWEEP_EXPECTED[kind] if outcome != expected: failures.append( "%d %s: ended %s where the plan promised %s" % (index, kind, outcome, expected) ) if kind == "tampered_lock_edit" and res.reason != SESSION_LOCKED: failures.append( "%d %s: refused for %s instead of %s" % (index, kind, res.reason, SESSION_LOCKED) ) if res is None: if after != before: failures.append("%d %s: an expected exception still wrote to disk" % (index, kind))22 unmodified lines (ws / SESSION_LOCK_NAME).unlink(missing_ok=True) if failures: return _rejected(check, "; ".join(failures), failures) if committed < 2 or refused + raised < len(SESSION_SWEEP_PLAN) - 3: promised = [ "refused" if index == 5 else SESSION_SWEEP_EXPECTED[kind] for index, (kind, _rel) in enumerate(ops) ] if outcomes != promised: return _rejected( check, "sweep landed %d commits and %d refusals out of %d operations" % (committed, refused + raised, len(SESSION_SWEEP_PLAN)), "sweep outcomes %s do not match the promised %s" % (outcomes, promised), ) return _confirmed( check, "%d seeded operations: %d committed, %d refused or raised, tree state compared after each one" % (len(ops), committed, refused + raised), "%d seeded operations: %d committed, %d refused, %d raised, %d verified without a write, " "tree state compared after each one" % ( len(ops), outcomes.count("committed"), outcomes.count("refused"), outcomes.count("raised"), outcomes.count("verified_no_write"), ), )
28 unmodified lines
def gate_pattern_corpus_schema() -> GateResult: check = "patterns/pattern_cases.jsonl is a valid case-1 corpus with one pair per card" check = "patterns/pattern_cases.jsonl is a valid case-1 corpus with a pair at least for every card" if not PATTERN_CASES.is_file(): return _rejected(check, "patterns/pattern_cases.jsonl is missing") rows = read_rows(PATTERN_CASES)7 unmodified lines for pattern_id in sorted(PATTERNS): positive = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "VERIFIED"] negative = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED"] if len(positive) != 1 or len(negative) != 1: if len(positive) < 1 or len(negative) < 1: short.append("%s has %d positive and %d negative rows" % (pattern_id, len(positive), len(negative))) elif len(positive[0]["edits"]) < 2: short.append("%s claims a companion test but its row holds %d edits" % (pattern_id, len(positive[0]["edits"]))) for row in positive: if len(row["edits"]) < 2: short.append( "%s claims a companion test but its row holds %d edits" % (row["case_id"], len(row["edits"])) ) if short: return _rejected(check, "; ".join(short), short) return _confirmed(check, f"{len(rows)} rows over {len(PATTERNS)} cards, each with its lock test and its refusal")64 unmodified lines
def gate_pattern_pair_honesty() -> GateResult: check = "each card's lock test fails until the source edit of its pair lands" positives: Dict[str, str] = {} for row in read_rows(PATTERN_CASES): if row["expect"] == "VERIFIED" and str(row["pattern_id"]) not in positives: positives[str(row["pattern_id"])] = str(row["targets"][0]) missing = sorted(set(PATTERNS) - set(positives)) positives: List[Tuple[str, str, str]] = [ (str(row["case_id"]), str(row["pattern_id"]), str(row["targets"][0])) for row in read_rows(PATTERN_CASES) if row["expect"] == "VERIFIED" ] missing = sorted(set(PATTERNS) - {pattern_id for _case, pattern_id, _target in positives}) if missing: return _rejected(check, "no positive corpus row names a target for: " + ", ".join(missing), missing)
3 unmodified lines shutil.copytree(PATTERN_LAB, base) if _pytest_return_code(base) != 0: return _rejected(check, "the pattern_lab fixture does not pass its own suite as published") for pattern_id in sorted(positives): lab = Path(tmp) / ("lab_" + pattern_id) for case_id, pattern_id, target in positives: lab = Path(tmp) / ("lab_" + case_id) shutil.copytree(PATTERN_LAB, lab) plan = plan_pattern(lab, pattern_id, positives[pattern_id]) plan = plan_pattern(lab, pattern_id, target) if plan.refused: failures.append("%s: the positive row no longer plans: %s" % (pattern_id, plan.detail)) failures.append("%s: the positive row no longer plans: %s" % (case_id, plan.detail)) continue companions = plan.companions() if not companions: failures.append("%s: the card carries no lock test in its pair" % pattern_id) failures.append("%s: the card carries no lock test in its pair" % case_id) continue broke = False for edit in companions:3 unmodified lines original, SearchReplaceBlock(edit.search, edit.replace), FuzzyPatchConfig() ) if not outcome.applied: failures.append("%s: the lock test anchor for '%s' does not apply" % (pattern_id, edit.file)) failures.append("%s: the lock test anchor for '%s' does not apply" % (case_id, edit.file)) broke = True break path.write_text(outcome.updated_text, encoding="utf-8", newline="")1 unmodified line continue if _pytest_return_code(lab) == 0: failures.append( "%s: the suite still passes with only the test side of the pair written" % pattern_id "%s: the suite still passes with only the test side of the pair written" % case_id ) if failures: return _rejected(check, "; ".join(failures), failures) return _confirmed( check, "%d cards: every lock test fails while its source edit is missing, so the pair is not decoration" "%d pairs: every lock test fails while its source edit is missing, so the pairs are not decoration" % len(positives), )
254 unmodified lines ("adapter_contract", gate_adapter_contract), ("ast_symbol_graph", gate_ast_graph), ("test_selection", gate_test_selection), ("graph_scaling", gate_graph_scaling), ("strict_abstain_control", gate_strict_abstain_control), ("session_transactions", gate_session_transactions), ("session_sweep", gate_session_sweep),55 unmodified lines "schema": "lingologos-python-gates-1", "verdict": overall, "sources_sha256": opening_digest, "kernel_sha256": kernel_digest(), "counts": counts, "gates": [ {README.md+184-31
fixtures/pattern_lab/src/asyncops.pyAdded+56
fixtures/pattern_lab/src/legacy.pyAdded+17
fixtures/pattern_lab/src/widgets.pyAdded+26
fixtures/pattern_lab/tests/test_asyncops.pyAdded+64
fixtures/pattern_lab/tests/test_legacy.pyAdded+15
fixtures/pattern_lab/tests/test_widgets.pyAdded+19
lingologos_python/ast_graph.py+129-2
lingologos_python/cli.py+246-57
lingologos_python/patterns.py+80-5
lingologos_python/rules.py+348-12
lingologos_python/session.py+128-39
patterns/coverage.json+62-17
patterns/pattern_cases.jsonl+14
pyproject.toml+3
results/gates.json+30-21
tests/test_ast_imports.py+101
tests/test_cli.py+272
tests/test_coverage.pyAdded+43
tests/test_patterns.py+89-8
tests/test_rules.py+10-5
tests/test_self_lint.py+48
tests/test_session.py+108
tools/build_patterns.py+75-70
tools/measure_coverage.pyAdded+160
tools/publish_dataset.py+45-14
tools/run_gates.py+204-24