Upload folder using huggingface_hub
Browse filesFiles changed (14)
- README.md+36-7
- lingologos_python/ast_graph.py+7-4
- lingologos_python/cli.py+35-4
- lingologos_python/reasons.py+19-1
- lingologos_python/session.py+41-2
- results/gates.json+10-2
- tests/test_ast_imports.pyAdded+87
- tests/test_cli_card.pyAdded+59
- tests/test_reasons.py+32-1
- tests/test_self_lint.py+19
- tests/test_session.py+23
- tests/test_session_fuzz.pyAdded+183
- tools/publish_dataset.py+25
- tools/run_gates.py+112
31 unmodified lines32333435353637383839404142434445464748494 unmodified lines54555657585960616217 unmodified lines808182768384858687889 unmodified lines98991009210110210310410510657 unmodified lines164165166167168169170171172173174175176177178121 unmodified lines3003013022833033043053063072863083093103113123133143153163173188 unmodified lines32732832930133033133233331 unmodified lines
```
python -B tools/run_gates.py
GATES: CONFIRMED (11 gates: 11 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
GATES: CONFIRMED (12 gates: 12 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
```
The gate runner is where this bundle states its numbers out loud: 11 gates, 145 tests across 12 files,
The gate runner is where this bundle states its numbers out loud: 12 gates, 159 tests across 15 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.
The report names the tree it describes. `results/gates.json` embeds a digest of every byte of the bundle
except 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.
## Contents
- `lingologos_python/_codex_bridge.py`: finds the kernel without copying it: an already importable4 unmodified lines- `lingologos_python/ast_graph.py`: AST symbol, method, inheritance, relative/absolute import, and call
graph extraction (`discover_python_files`, `extract_python_graph`, `importers_of`). 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 the
source.
`discover_python_files` prunes a symlinked or junctioned directory instead of walking into it, and
`is_linked_path` answers for both kinds of link on every platform.
- `lingologos_python/test_selector.py`: import-aware Python test selection (`select_python_tests`).17 unmodified lines below disagree.
- `lingologos_python/session.py`: `PythonWorkspaceSession` for safe staged verification and atomic disk
commits via `lingologos_codex.fsadapter` (`verify`, `edit_file`, `create_file`, `delete_file`,
`apply_pattern`, `run_retry_loop`, and `run_topology_subprocesses`). A commit re-reads what is on disk
`apply_pattern`, `run_retry_loop`, and `run_topology_subprocesses`). A proposer that accepts a third argument is handed a `RetryContext`
with the attempts so far, their traces and their reasons; a two-argument proposer keeps its
signature. A commit re-reads what is on disk
and refuses with `PATCH_NOT_APPLIED` when the workspace moved while the six nodes were running. A
write the disk refuses part way is undone from the in-memory originals, so a run never reports a
change it did not land. A delete names the surviving files that import the module being removed,9 unmodified lines run at a time: every verb takes an exclusive lock at the workspace root before it reads
anything and releases it in a finally even when the run was refused; a lock left behind
by a process that no longer runs is taken over, one whose owner cannot be read is never
stolen, and a live holder is answered REFUSED with the reason `SESSION_LOCKED`.
stolen, and a live holder is answered REFUSED with the reason `SESSION_LOCKED`. The lock names its holder by process
number, and a number recycled by a young process can keep a tree locked past the death of the run
that planted it; deleting the lock file is the operator's remedy, not an unlock verb the bundle offers.
- `lingologos_python/cli.py`: `lingologos_python` CLI (`verify`, `edit`, `create`, `delete`, `symbols`,
`select-tests`, `patterns list|show|scan|apply`, `check-adapter`).
- `fixtures/pattern_lab/`: a small package with one function planted in the shape of each card and57 unmodified linesa hit whose anchors are ASCII LF text, apply, and leave the file parsing, or a refusal naming one of the
codes below. A crash, or a name the registry does not hold, fails the sweep.
The same sweep shape guards the session itself. `tests/test_session_fuzz.py` runs a fixed-seed plan of
planned operations: real edits and creates that commit, traversal paths, protected paths, missing files,
ghost cards, empty patches, and a planted live lock in the middle. The invariant is that nothing on disk
moves unless the answer committed, and that every REFUSED and every UNKNOWN names a code the registry
holds. That sweep found a real gap on its first run: the six-node pipeline answers with the kernel's own
vocabulary, and six of its words were not yet in the registry. `tests/test_reasons.py` now checks the
registry against the kernel's decision module itself, so the alphabet cannot fall behind the kernel
again.
The pair then goes through the six nodes of the kernel as any other change does: the proposing roles
claim it, `gate_checker` runs the syntax gate and the selected tests, `adversary` reproduces the
result by another path, and the arbiter returns `VERIFIED` with assurance 3 only when both trusted121 unmodified linesrun, in whichever mode, also budgets each runner command it launches, the test gate and any static
checker, through `--gate-timeout SEC`, one hundred and twenty seconds by default: a runner that outruns
it is killed and answered with the named abstain `GATE_ABSTAIN`, because a hung test run is not a
passing test run.
passing test run. The gate budget reaches the kernel through one environment variable per process: a
process 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.
`check-adapter` says whether the Python adapter holds the contract of the kernel, and exits non-zero
when it does not.
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`,
because the kernel reads it as an identical-failure loop rather than as learning; a retry that wants to
be read as a move has to change the fate of the patch, not only its text. `--allow-single-prover`
commits at assurance 2 on all five verbs that write, and a
card that states its own bar keeps it. `edit` takes each side of its pair from a file as readily as
from the command line, through `--search-file` and `--replace-file`, so a multi-line pair survives a
shell. `--version` prints the envelope this bundle speaks.
`tests/test_cli.py` runs the documented commands as separate processes and asserts their exit codes and
their answers, because a documented command that crashes breaks a promise even when every library call8 unmodified lines
- Refusals the session raises itself: `PATH_POLICY`, `PATCH_NOT_APPLIED`, `NODE_TIMEOUT`,
`LINKED_PATH_IN_WORKSPACE`, `SESSION_LOCKED`.
- Verdicts the codex kernel brings back: `GATE_REJECTED`, `GATE_ABSTAIN`.
- Verdicts the codex kernel brings back: `GATE_REJECTED`, `GATE_ABSTAIN`, `GATE_MISSING`, `CHECKER_REJECTED`, `CHECKER_ABSTAIN`, `NOT_APPLIED`, `PROTECTED_PATH`, `NO_INDEPENDENT_CONFIRMATION`.
- The refusal the catalog layer adds above the rules: `AMBIGUOUS_TARGET`.
- Preflight and shape refusals of the rules: `MISSING_TARGET_FILE`, `NO_SUCH_FUNCTION`,
`NOT_A_MODULE_FUNCTION`, `NOT_PARSEABLE`, `NOT_ASCII_TARGET`, `TAB_INDENTED_TARGET`, `CRLF_TARGET`,237 unmodified lines238239240241242243241242243244244245246247248249250237 unmodified lines local = alias.asname or alias.name if mod_name: alias_map[local] = (mod_name, alias.name) # A from-import can pull in a submodule rather than a name, # and it does so whether or not the importer renames it: # `from app.core import engine` and `from app.core import if not alias.asname: sub_mod = f"{mod_name}.{alias.name}" if sub_mod not in modules: modules.append(sub_mod) # engine as eng` bind the same file, so both record the edge. sub_mod = f"{mod_name}.{alias.name}" if sub_mod not in modules: modules.append(sub_mod) return modules, alias_map
13 unmodified lines141516171819208 unmodified lines29303132333435363738394015 unmodified lines5657585253596061626364654 unmodified lines707172737475765 unmodified lines8283848586878820 unmodified lines1091101111121131141155 unmodified lines12112212312412512612712812913013113213313413513613725 unmodified lines16316416516616716816917017117214514617317417517617713 unmodified lines19119219319419519619719 unmodified lines217218219220221222223127 unmodified lines35135235335435535635713 unmodified linesensure_codex_on_path()
from lingologos_codex.adapter_contract import check_adapter_contract # noqa: E402from lingologos_codex.envelope import ENVELOPE_KIND # noqa: E402from lingologos_codex.graph import compute_symbol_pagerank, top_symbols # noqa: E402
from lingologos_python.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter # noqa: E4028 unmodified lines prog="lingologos_python", description="Python programming workbench and language adapter powered by LingoLOGOS codex.", ) parser.add_argument( "--version", action="version", version="lingologos_python, codex envelope %s" % ENVELOPE_KIND, help="Print the envelope this bundle speaks and exit.", ) sub = parser.add_subparsers(dest="command", required=True)
# Flags shared by every verb that opens a session: the same tools, the same15 unmodified lines p_edit = sub.add_parser("edit", parents=[session_flags], help="Propose, verify, and atomically commit a Python search-replace edit.") p_edit.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_edit.add_argument("--file", required=True, help="Relative Python file to edit.") p_edit.add_argument("--search", required=True, help="Search text block.") p_edit.add_argument("--replace", required=True, help="Replacement text block.") p_edit.add_argument("--search", default=None, help="Search text block.") p_edit.add_argument("--search-file", default=None, help="Path to a file holding the search text block.") 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("--json", action="store_true", help="Print JSON output.")4 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("--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("--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("--json", action="store_true", help="Print JSON output.")
# check-adapter5 unmodified lines return parser
def _side_text(value: Optional[str], path: Optional[str], side: str) -> Optional[str]: """One side of the edit pair, from the command line or from a file, never from both."""
if value is not None and path is not None: print("give --%s or --%s-file, not both" % (side, side), file=sys.stderr) return None if path is not None: return Path(path).read_text(encoding="utf-8", newline="") return value
def main(argv: Optional[Sequence[str]] = None) -> int: parser = _build_parser() args = parser.parse_args(argv)25 unmodified lines total_budget_sec=args.total_timeout, gate_timeout_sec=args.gate_timeout, ) 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 res = session.edit_file( args.file, args.search, args.replace, search_text, replace_text, commit=not args.dry_run, ) if args.json:13 unmodified lines 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,19 unmodified lines 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,127 unmodified lines 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,27 unmodified lines282930313233343536373839404142344344454647484950515253545527 unmodified lines)
# Verdicts the codex kernel brings back when the gates fail or decline to answer.# The six-node run answers with the kernel's own vocabulary; the registry holds# every word of it that can arrive on a REFUSED or UNKNOWN line, so the promise# that every refusal names a registered code survives the pipeline too.GATE_REJECTED = "GATE_REJECTED"GATE_ABSTAIN = "GATE_ABSTAIN"GATE_MISSING = "GATE_MISSING"CHECKER_REJECTED = "CHECKER_REJECTED"CHECKER_ABSTAIN = "CHECKER_ABSTAIN"NOT_APPLIED = "NOT_APPLIED"PROTECTED_PATH = "PROTECTED_PATH"NO_INDEPENDENT_CONFIRMATION = "NO_INDEPENDENT_CONFIRMATION"
KERNEL_REASONS: Tuple[str, ...] = (GATE_REJECTED, GATE_ABSTAIN)KERNEL_REASONS: Tuple[str, ...] = ( GATE_REJECTED, GATE_ABSTAIN, GATE_MISSING, CHECKER_REJECTED, CHECKER_ABSTAIN, NOT_APPLIED, PROTECTED_PATH, NO_INDEPENDENT_CONFIRMATION,)
# The refusal the catalog layer adds above the rules: a scan found the card fits# more than one target and the caller named none.11 unmodified lines12131415161718144 unmodified lines1631641651661671681691701711721731741751761771781791801811821831841851239 unmodified lines14251426142714101428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541416145514561457145811 unmodified linesimport astimport ctypesimport hashlibimport inspectimport jsonimport osimport shutil144 unmodified lines }
@dataclass(frozen=True)class RetryContext: """What the attempts before this one leave to the proposer: results with trace and dossier.
A loop that hands the proposer only the index and the last result teaches it nothing about why the nodes refused. A proposer that accepts a third argument receives all of it: every prior result with its verdict, reason, trace lines and the dossier the kernel returned. A two-argument proposer keeps working unchanged. """
attempt: int rel_path: str attempts: Tuple[SessionResult, ...] = () failure_reasons: Tuple[str, ...] = ()
def _disk_text(root: Path, rel_posix: str) -> str: """The current text of one workspace file, or an empty string when it is not there."""
1239 unmodified lines max_attempts: int = 4, commit: bool = True, ) -> Tuple[SessionResult, List[SessionResult]]: """Run bounded edit attempts using codex stall detection to stop identical or cyclic failures.""" """Run bounded edit attempts using codex stall detection to stop identical or cyclic failures.
The proposer takes the attempt index and the last result. A proposer that accepts a third argument also receives a RetryContext with every prior attempt, its trace and its dossier. """ history: List[str] = [] attempts: List[SessionResult] = [] last: Optional[SessionResult] = None try: accepts_context = len(inspect.signature(proposer).parameters) >= 3 except (TypeError, ValueError): accepts_context = False
for idx in range(1, max_attempts + 1): if accepts_context: search, replace = proposer( idx, last, RetryContext( attempt=idx, rel_path=rel_path, attempts=tuple(attempts), failure_reasons=tuple(r.reason for r in attempts), ), ) else: search, replace = proposer(idx, last) search, replace = proposer(idx, last) result = self.edit_file( rel_path, search,123455678968 unmodified lines78798081828384858687888990918492939495{ "schema": "lingologos-python-gates-1", "verdict": "CONFIRMED", "sources_sha256": "b65bae4a72d222f72e68b45b176d7dfa814de9314cf604e7cc497e063dac5125", "counts": { "CONFIRMED": 11, "CONFIRMED": 12, "REJECTED": 0, "ABSTAIN": 0 },68 unmodified lines "note": "8 cards over 8 source files and 21 module level functions, denominator stated as the fixture", "failed_targets": [] }, { "name": "cli_card_agreement", "verdict": "CONFIRMED", "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", "failed_targets": [] }, { "name": "self_lint", "verdict": "CONFIRMED", "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 166 symbols and 348 edges; 39 reason codes, every one named in the card; 34 names promised in the Contents, all defined", "note": "12 modules parse, compile, and carry docstrings; own graph has 168 symbols and 350 edges; 45 reason codes, every one named in the card; 34 names promised in the Contents, all defined", "failed_targets": [] } ]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687"""Import resolution over a package that uses the awkward import forms."""
from __future__ import annotations
from pathlib import Pathfrom typing import List, Tuple
from lingologos_python.ast_graph import discover_python_files, extract_python_graphfrom lingologos_python.test_selector import select_python_tests
def _write(root: Path, rel_posix: str, text: str) -> None: path = root / Path(*rel_posix.split("/")) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8", newline="\n")
def _hard_package(root: Path) -> None: """One package with the forms that broke selection before: dots, stars, aliases, no __init__.""" _write(root, "app/__init__.py", "") _write(root, "app/core/__init__.py", "") _write(root, "app/core/engine.py", "def run() -> int:\n return 1\n") _write(root, "app/core/legacy.py", "def old() -> int:\n return 0\n") _write(root, "app/core/sub/__init__.py", "") _write( root, "app/core/sub/calc.py", "from ..engine import run\n\n\ndef twice() -> int:\n return run() + run()\n", ) # app/plugins carries no __init__.py: a namespace package, named by its folder. _write(root, "app/plugins/extra.py", "def assist() -> str:\n return 'assist'\n") _write( root, "tests/test_plain.py", "from app.core.engine import run\n\n\ndef test_run():\n assert run() == 1\n", ) _write( root, "tests/test_alias.py", "from app.core import engine as eng\n\n\ndef test_eng():\n assert eng.run() == 1\n", ) _write( root, "tests/test_star.py", "from app.core.legacy import *\n\n\ndef test_old():\n assert old() == 0\n", ) _write( root, "tests/test_ns.py", "from app.plugins.extra import assist\n\n\ndef test_assist():\n assert assist() == 'assist'\n", )
def _file_edges(root: Path) -> List[Tuple[str, str]]: _, edges = extract_python_graph(root, discover_python_files(root)) return [(s.split("::", 1)[0], d.split("::", 1)[0]) for s, d in edges]
def test_relative_dots_namespace_and_star_imports_become_file_edges(tmp_path: Path) -> None: _hard_package(tmp_path) edges = set(_file_edges(tmp_path)) assert ("app/core/sub/calc.py", "app/core/engine.py") in edges assert ("tests/test_alias.py", "app/core/engine.py") in edges assert ("tests/test_star.py", "app/core/legacy.py") in edges assert ("tests/test_ns.py", "app/plugins/extra.py") in edges
def test_an_aliased_module_import_selects_the_module_it_names(tmp_path: Path) -> None: _hard_package(tmp_path) selected = select_python_tests(tmp_path, ["app/core/engine.py"]) assert "tests/test_alias.py" in selected assert "tests/test_plain.py" in selected assert "tests/test_star.py" not in selected assert "tests/test_ns.py" not in selected
def test_a_star_import_selects_the_test_that_stars_the_changed_module(tmp_path: Path) -> None: _hard_package(tmp_path) selected = select_python_tests(tmp_path, ["app/core/legacy.py"]) assert "tests/test_star.py" in selected assert "tests/test_plain.py" not in selected
def test_a_namespace_package_change_selects_its_only_importer(tmp_path: Path) -> None: _hard_package(tmp_path) selected = select_python_tests(tmp_path, ["app/plugins/extra.py"]) assert selected == ["tests/test_ns.py"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Tests for the gate that keeps the printed commands of the card runnable."""
from __future__ import annotations
import importlib.utilfrom pathlib import Path
_ROOT = Path(__file__).resolve().parent.parent# The kernel bundle carries a tools/run_gates.py of its own, so this file loads# the bundle runner by path instead of by package name._spec = importlib.util.spec_from_file_location( "codex_python_gates_runner_card", _ROOT / "tools" / "run_gates.py")assert _spec is not None and _spec.loader is not None_run_gates = importlib.util.module_from_spec(_spec)_spec.loader.exec_module(_run_gates)
_card_commands = _run_gates._card_commands_card_command_problems = _run_gates._card_command_problems_parser_surface = _run_gates._parser_surfacegate_cli_card_agreement = _run_gates.gate_cli_card_agreement
from lingologos_python.cli import _build_parser
def test_the_card_agreement_gate_confirms_the_real_pair() -> None: res = gate_cli_card_agreement() assert res.verdict == "CONFIRMED" assert "agree with" in res.note
def test_a_wrapped_example_is_still_one_command() -> None: card = ( "text\n\n" "```bash\n" "$ python -B -m lingologos_python edit --workspace w \\\n" " --file f.py --search a --replace b --json\n" "```\n" ) commands = _card_commands(card) assert commands == [("edit", ["--workspace", "--file", "--search", "--replace", "--json"])]
def test_the_parser_surface_carries_the_flags_a_reader_copies_today() -> None: top, verbs = _parser_surface(_build_parser()) assert "--version" in top assert "--search-file" in verbs["edit"] and "--replace-file" in verbs["edit"] for verb in ("create", "delete", "patterns"): assert "--allow-single-prover" in verbs[verb]
def test_a_flag_invented_in_the_card_is_reported_as_not_carried() -> None: card = ( "python -B -m lingologos_python edit --workspace w --file f.py --invented-flag x\n" "python -B -m lingologos_python frobnicate --workspace w\n" ) problems = _card_command_problems(card, _build_parser()) assert "edit --invented-flag" in problems assert "verb frobnicate" in problems7 unmodified lines8910111213141516171819202122232425262712 unmodified lines404142374344454647484950515253545517 unmodified lines737475767778798081828384858687888990919293947 unmodified linesfrom lingologos_python import session as session_modulefrom lingologos_python.reasons import ( AMBIGUOUS_TARGET, CHECKER_ABSTAIN, CHECKER_REJECTED, GATE_ABSTAIN, GATE_MISSING, GATE_REJECTED, KERNEL_REASONS, LINKED_PATH_IN_WORKSPACE, NODE_TIMEOUT, NOT_APPLIED, NO_INDEPENDENT_CONFIRMATION, PATCH_NOT_APPLIED, PATH_POLICY, PATTERN_REASONS, PROTECTED_PATH, REASON_CODES, RULE_REASONS, SESSION_LOCKED,12 unmodified lines LINKED_PATH_IN_WORKSPACE, SESSION_LOCKED, } assert set(KERNEL_REASONS) == {GATE_REJECTED, GATE_ABSTAIN} assert set(KERNEL_REASONS) == { GATE_REJECTED, GATE_ABSTAIN, GATE_MISSING, CHECKER_REJECTED, CHECKER_ABSTAIN, NOT_APPLIED, PROTECTED_PATH, NO_INDEPENDENT_CONFIRMATION, } assert set(PATTERN_REASONS) == {AMBIGUOUS_TARGET} assert set(SESSION_REASONS) | set(KERNEL_REASONS) | set(PATTERN_REASONS) <= REASON_CODES
17 unmodified lines assert getattr(session_module, name) == name
def test_the_registry_covers_every_refusal_the_kernel_can_answer_with() -> None: """A sweep found kernel reasons the registry did not hold; the drift may not return.""" from lingologos_codex import decision as kernel_decision
verdict_words = {"VERIFIED", "SINGLE_PROVER", "UNKNOWN", "CONFIRMED", "REJECTED", "ABSTAIN"} kernel_refusals = { value for name, value in vars(kernel_decision).items() if isinstance(value, str) and value.upper() == value and value not in verdict_words and not value.startswith("OK_") } assert kernel_refusals <= set(REASON_CODES)
def test_every_registered_code_is_named_in_the_card() -> None: """A code the bundle can answer with must be listed in the card a reader holds.""" readme = (ROOT / "README.md").read_text(encoding="utf-8", newline="")2 unmodified lines345678955 unmodified lines6566676869707172737475767778798081828384852 unmodified linesfrom __future__ import annotations
import importlib.utilimport jsonfrom pathlib import Path
_ROOT = Path(__file__).resolve().parent.parent55 unmodified lines "## Next\n\nNothing.\n" ) assert _card_promises(fake_card) == []
def test_the_digest_anchors_the_report_to_the_tree_it_was_run_on(tmp_path: Path) -> None: first = tmp_path / "a.py" second = tmp_path / "b.txt" first.write_text("x = 1\n", encoding="utf-8", newline="\n") second.write_text("note\n", encoding="utf-8", newline="\n") before = _run_gates.bundle_digest([second, first], tmp_path) assert _run_gates.bundle_digest([first, second], tmp_path) == before first.write_text("x = 2\n", encoding="utf-8", newline="\n") assert _run_gates.bundle_digest([first, second], tmp_path) != before
def test_the_report_in_the_tree_describes_the_tree_it_sits_in() -> None: report = json.loads((_ROOT / "results" / "gates.json").read_text(encoding="utf-8")) assert report["sources_sha256"] == _run_gates.bundle_digest( _run_gates.digest_input_files(_ROOT) )111 unmodified lines112113114115116117118119120121122123124125126127128129130131132133134135136137138139140111 unmodified lines assert any(c.get("role") == "adversary_loop" for c in final.dossier.get("checkers", []))
def test_a_three_argument_proposer_is_handed_the_failure_it_should_learn_from(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg) seen: Dict[str, object] = {}
def learning_proposer(attempt: int, last_result: object, context: object) -> tuple[str, str]: if attempt == 1: # An anchor that is not in the file: the patch is not applied, so the # second attempt is a move and not the loop the stall detector blocks. return ("return left * right", "return left / right") seen["reasons"] = tuple(context.failure_reasons) seen["trace"] = context.attempts[0].trace seen["attempt"] = context.attempt seen["path"] = context.rel_path return ("return left + right", "return left + right # proposed again")
final, _attempts = session.run_retry_loop("src/mathops.py", learning_proposer, max_attempts=3) assert final.committed is True assert seen["reasons"] assert len(seen["trace"]) >= 6 assert seen["attempt"] == 2 assert seen["path"] == "src/mathops.py"
def test_verify_probe_annotates_a_line_that_keeps_the_file_parsable() -> None: text = '"""Module doc.\n\nSpread over several lines.\n"""\n\n\ndef go() -> int:\n return 1\n' search, replace, original = _verify_probe(text)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183"""A fixed-seed sweep of random session operations over one sample package.
The property under test is the one the session card makes: no change lands ondisk unless a verified verdict committed it, and no refusal leaves a trace.Every operation answers with a verdict: accepted runs carry the kernel'sconfirmation phrase, and every REFUSED or UNKNOWN names a registered reason.The disk state is checked after every single operation."""
from __future__ import annotations
import osimport randomfrom pathlib import Pathfrom typing import Dict, List, Tuple
from lingologos_python.reasons import REASON_CODESfrom lingologos_python.session import SESSION_LOCK_NAME, PythonWorkspaceSession
SEED = 20261203
# Pipeline runs are not free, so the expensive kinds are capped and the rest of# the sweep is made of operations that must refuse before any node runs.PLAN: List[str] = ( ["valid_edit_commit"] * 4 + ["valid_edit_dry"] * 4 + ["valid_create_commit"] * 3 + ["verify"] * 3 + ["traversal_edit"] * 6 + ["protected_create"] * 5 + ["non_python_create"] * 5 + ["missing_edit"] * 5 + ["missing_delete"] * 5 + ["bad_pattern"] * 4 + ["create_existing"] * 4 + ["empty_edit"] * 5)
def _build_ops(rng: random.Random) -> List[Tuple[str, str]]: kinds = list(PLAN) rng.shuffle(kinds) files = [ "src/mathops.py", "src/textops.py", "tests/test_mathops.py", "tests/test_textops.py", ] return [(kind, rng.choice(files)) for kind in kinds]
def _tree_state(root: Path) -> Dict[str, bytes]: state: Dict[str, bytes] = {} for path in root.rglob("*"): if not path.is_file(): continue rel = path.relative_to(root).as_posix() parts = rel.split("/") if any(part in ("__pycache__", ".pytest_cache") for part in parts[:-1]): continue if path.suffix in (".pyc", ".pyo"): continue state[rel] = path.read_bytes() return state
def _anchor_pair(path: Path) -> Tuple[str, str]: text = path.read_text(encoding="utf-8", newline="") lines = [line for line in text.split("\n") if line.strip()] anchor = lines[-1] return anchor, anchor + "\n# swept"
def _check_committed(result, before: Dict[str, bytes], after: Dict[str, bytes]) -> List[str]: problems: List[str] = [] changed = {rel for rel in set(before) | set(after) if before.get(rel) != after.get(rel)} named = set(result.touched_files) if not named: problems.append("a commit named no touched files") if changed != changed & named: problems.append( "files changed that the result did not name: " + ", ".join(sorted(changed - named)) ) return problems
def test_the_same_seed_always_sweeps_the_same_operations() -> None: assert _build_ops(random.Random(SEED)) == _build_ops(random.Random(SEED))
def test_a_seeded_sweep_never_lands_a_change_it_did_not_verify(sample_pkg: Path) -> None: rng = random.Random(SEED) ops = _build_ops(rng) failures: List[str] = [] committed = 0 refused = 0 raised = 0
for index, (kind, rel) in enumerate(ops): session = PythonWorkspaceSession(str(sample_pkg)) lock_held = False if index == 10: # Plant a live holder: our own process is alive, so the lock is real. (sample_pkg / SESSION_LOCK_NAME).write_text(str(os.getpid()), encoding="ascii") lock_held = True before = _tree_state(sample_pkg) try: if kind == "valid_edit_commit" or kind == "valid_edit_dry": path = sample_pkg / Path(*rel.split("/")) search, replace = _anchor_pair(path) res = session.edit_file(rel, search, replace, commit=(kind.endswith("commit"))) elif kind == "valid_create_commit": res = session.create_file( "src/extra_%d.py" % index, "def extra_%d() -> int:\n return %d\n" % (index, index), commit=True, ) elif kind == "verify": res = session.verify(target_file=rel if index % 2 else None) elif kind == "traversal_edit": res = session.edit_file("../outside_the_tree.py", "a", "b", commit=True) elif kind == "protected_create": res = session.create_file(".env", "SECRET=1\n", commit=True) elif kind == "non_python_create": res = session.create_file("notes_%d.txt" % index, "prose\n", commit=True) elif kind == "missing_edit": res = session.edit_file("src/absent_%d.py" % index, "a", "b", commit=True) elif kind == "missing_delete": try: res = session.delete_file("src/gone_%d.py" % index, commit=True) except FileNotFoundError: raised += 1 res = None elif kind == "bad_pattern": try: res = session.apply_pattern("ghost-card-%d" % index, commit=True) except KeyError: raised += 1 res = None elif kind == "create_existing": try: res = session.create_file(rel, "x = 1\n", commit=True) except FileExistsError: raised += 1 res = None elif kind == "empty_edit": res = session.edit_file(rel, "", "", commit=True) else: raise AssertionError("unknown op kind %s" % kind)
after = _tree_state(sample_pkg) if res is None: if after != before: failures.append("%d %s: an expected exception still wrote to disk" % (index, kind)) continue if res.verdict in ("REFUSED", "UNKNOWN") and res.reason not in REASON_CODES: failures.append("%d %s: unregistered reason %s" % (index, kind, res.reason)) if res.committed: committed += 1 if not (res.verdict in ("VERIFIED", "SINGLE_PROVER") and res.accepted): failures.append( "%d %s: committed with verdict %s" % (index, kind, res.verdict) ) failures.extend(_check_committed(res, before, after)) else: refused += 1 if after != before: failures.append( "%d %s (%s): disk moved without a commit" % (index, kind, res.reason) ) if lock_held and res.verdict != "REFUSED": failures.append("%d %s: a planted lock did not refuse the run" % (index, kind)) except Exception as exc: # a crash of the sweep itself is a finding, not a pass failures.append("%d %s: %s: %s" % (index, kind, type(exc).__name__, exc)) finally: if lock_held: (sample_pkg / SESSION_LOCK_NAME).unlink(missing_ok=True)
assert failures == [] assert committed >= 7 # Most of the sweep must be made of refusals: half the plan plus the # three pipeline kinds that can refuse honestly when the workspace moved. assert refused + raised >= len(PLAN) - 8240 unmodified lines24124224324424524624724824925025125225325425525625725825926026126226323 unmodified lines287288289290291292293294295296297298299300240 unmodified lines return hashlib.sha256(data).hexdigest()
def tree_digest(files: List[Path]) -> str: """The digest the gate runner writes into its report, over the same bytes.
Two implementations on purpose: the runner attests the tree it judged, the publisher attests the tree it uploads, and they must agree on one number. """
digest = hashlib.sha256() for path in sorted( (p for p in files if p.relative_to(ROOT).parts[0] != "results"), key=lambda p: p.relative_to(ROOT).as_posix(), ): digest.update(path.relative_to(ROOT).as_posix().encode("ascii") + b"\0") digest.update(path.read_bytes() + b"\0") return digest.hexdigest()
def gate_verdict_line(payload: dict) -> str: """The verdict line the gate runner prints, rebuilt from the report it wrote."""
23 unmodified lines line = gate_verdict_line(payload) if line not in readme: raise SystemExit(f"the README no longer prints the verdict line the report gives: {line}") stated = payload.get("sources_sha256") current = tree_digest(local_files()) if stated != current: raise SystemExit( "results/gates.json describes a different revision of this tree (report %s, tree %s): " "rerun python -B tools/run_gates.py --report results/gates.json" % (str(stated)[:12], current[:12]) ) return len(gates)
3 unmodified lines4567891037 unmodified lines4849505152535455565758596061626364656667686970717273747576777879808182374 unmodified lines45745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154265 unmodified lines60860961061161261361429 unmodified lines6446456466476486496503 unmodified lines
import argparseimport astimport hashlibimport jsonimport reimport shutil37 unmodified lines return GateResult(CONFIRMED, check, note=note)
# The report states what the gates judged; the digest anchors that claim to the# tree the gates were run on. Everything published is hashed except the reports# folder itself, so a publisher can refuse a report describing another# revision, and a test can refuse a stale report in the tree.DIGEST_IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git", ".venv", ".venv-train", "results"}
def digest_input_files(root: Path = ROOT) -> List[Path]: files: List[Path] = [] for path in root.rglob("*"): if not path.is_file(): continue rel = path.relative_to(root) if any(part in DIGEST_IGNORED_DIRS for part in rel.parts[:-1]): continue if path.suffix in (".pyc", ".pyo"): continue files.append(path) return files
def bundle_digest(files: Sequence[Path], root: Path = ROOT) -> str: digest = hashlib.sha256() for path in sorted(files, key=lambda p: p.relative_to(root).as_posix()): digest.update(path.relative_to(root).as_posix().encode("ascii") + b"\0") digest.update(path.read_bytes() + b"\0") return digest.hexdigest()
def _rejected(check: str, note: str, failed: Sequence[str] = ()) -> GateResult: return GateResult(REJECTED, check, failed_targets=tuple(failed), note=note)
374 unmodified lines return promises
def _card_commands(readme: str) -> List[Tuple[str, List[str]]]: """Verbs and long flags the card prints as runnable command lines.
Continuation backslashes are joined, so a wrapped example is still one command. Lines that launch another tool (pytest, the gate runner itself) carry no verb of this CLI and stay out. """ commands: List[Tuple[str, List[str]]] = [] pending: List[str] = [] for raw in readme.splitlines(): line = raw.strip() if line.startswith("$ "): line = line[2:].strip() if pending: line = " ".join(pending + [line]).strip() pending = [] if line.endswith("\\"): pending.append(line[:-1].strip()) continue for prefix in ("python -B -m lingologos_python", "python -m lingologos_python"): if line.startswith(prefix): rest = line[len(prefix):].split() if rest: verb = rest[0] commands.append((verb, [t for t in rest[1:] if t.startswith("--")])) break return commands
def _parser_surface(parser: argparse.ArgumentParser) -> Tuple[Set[str], Dict[str, Set[str]]]: """Top-level long flags, and the long flags of every verb of the parser.""" top = {opt for action in parser._actions for opt in action.option_strings if opt.startswith("--")} verbs: Dict[str, Set[str]] = {} for action in parser._actions: if isinstance(action, argparse._SubParsersAction): for name, sub in action.choices.items(): verbs[name] = { opt for a in sub._actions for opt in a.option_strings if opt.startswith("--") } return top, verbs
def _card_command_problems(readme: str, parser: argparse.ArgumentParser) -> List[str]: top, verbs = _parser_surface(parser) problems: List[str] = [] for verb, flags in _card_commands(readme): if verb.startswith("--"): if verb not in top: problems.append(verb) continue if verb not in verbs: problems.append("verb %s" % verb) continue for flag in flags: name = flag.split("=", 1)[0] if name not in top and name not in verbs[verb]: problems.append("%s %s" % (verb, name)) return problems
def gate_cli_card_agreement() -> GateResult: check = "every verb and flag the card prints exists in the real parser" from lingologos_python.cli import _build_parser
readme = (ROOT / "README.md").read_text(encoding="utf-8") printed = _card_commands(readme) problems = _card_command_problems(readme, _build_parser()) if problems: return _rejected( check, "the card prints commands the parser does not carry: " + ", ".join(problems), problems, ) _, verbs = _parser_surface(_build_parser()) return _confirmed( check, "%d printed command lines agree with the %d verbs of the parser" % (len(printed), len(verbs)), )
def gate_self_lint() -> GateResult: check = "the package reads itself: modules compile, the graph spans them, the reason registry matches the card, the promised names exist" pkg = ROOT / "lingologos_python"65 unmodified lines ("pattern_round_trip", gate_pattern_round_trip), ("pattern_pair_honesty", gate_pattern_pair_honesty), ("pattern_coverage", gate_pattern_coverage), ("cli_card_agreement", gate_cli_card_agreement), ("self_lint", gate_self_lint),)
29 unmodified lines payload = { "schema": "lingologos-python-gates-1", "verdict": overall, "sources_sha256": bundle_digest(digest_input_files(ROOT)), "counts": counts, "gates": [ {README.md+36-7
lingologos_python/ast_graph.py+7-4
lingologos_python/cli.py+35-4
lingologos_python/reasons.py+19-1
lingologos_python/session.py+41-2
results/gates.json+10-2
tests/test_ast_imports.pyAdded+87
tests/test_cli_card.pyAdded+59
tests/test_reasons.py+32-1
tests/test_self_lint.py+19
tests/test_session.py+23
tests/test_session_fuzz.pyAdded+183
tools/publish_dataset.py+25
tools/run_gates.py+112