Upload folder using huggingface_hub
Browse filesFiles changed (47)
- .gitignoreAdded+7
- README.mdAdded+109
- agents/python_agent.pyAdded+57
- codex.python.jsonAdded+35
- fixtures/sample_pkg/src/mathops.pyAdded+37
- fixtures/sample_pkg/src/textops.pyAdded+11
- fixtures/sample_pkg/tests/test_mathops.pyAdded+17
- fixtures/sample_pkg/tests/test_textops.pyAdded+7
- lgpython/__init__.pyAdded+45
- lgpython/__main__.pyAdded+6
- lgpython/_codex_bridge.pyAdded+59
- lgpython/adapter.pyAdded+125
- lgpython/ast_graph.pyAdded+298
- lgpython/cli.pyAdded+197
- lgpython/gates.pyAdded+174
- lgpython/session.pyAdded+571
- lgpython/test_selector.pyAdded+140
- nodes/adversary/grammar.gfAdded+21
- nodes/adversary/ontology.smt2Added+5
- nodes/adversary/seed_payload.jsonAdded+19
- nodes/arbiter/grammar.gfAdded+23
- nodes/arbiter/ontology.smt2Added+7
- nodes/arbiter/seed_payload.jsonAdded+19
- nodes/executor/grammar.gfAdded+19
- nodes/executor/ontology.smt2Added+6
- nodes/executor/seed_payload.jsonAdded+19
- nodes/gate_checker/grammar.gfAdded+23
- nodes/gate_checker/ontology.smt2Added+6
- nodes/gate_checker/seed_payload.jsonAdded+19
- nodes/planner/grammar.gfAdded+25
- nodes/planner/ontology.smt2Added+6
- nodes/planner/seed_payload.jsonAdded+19
- nodes/retriever/grammar.gfAdded+19
- nodes/retriever/ontology.smt2Added+6
- nodes/retriever/seed_payload.jsonAdded+19
- pyproject.tomlAdded+33
- requirements.txtAdded+1
- results/gates.jsonAdded+53
- tests/conftest.pyAdded+28
- tests/test_adapter.pyAdded+90
- tests/test_ast_graph.pyAdded+62
- tests/test_session.pyAdded+95
- tests/test_test_selector.pyAdded+34
- tests/test_topology_and_cli.pyAdded+102
- tools/publish_dataset.pyAdded+370
- tools/run_gates.pyAdded+226
- topology.jsonAdded+77
1234567__pycache__/*.py[cod].pytest_cache/*.egg-info/build/dist/.venv*/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109---
language:
- en
tags:
- code
- program-synthesis
- multi-agent-systems
- software-engineering
- static-analysis
- testing
- formal-verification
- python
pretty_name: "LingoLOGOS codex-python: a Python programming layer over the codex kernel"
size_categories:
- n<1K
---
# LingoLOGOS codex-python topology
An external Python programming package and six-node topology built on top of the LingoLOGOS
`codex` kernel, a kernel this folder neither modifies nor carries. This dataset is that folder
published as it stands: the package under `lgpython/`, the six node folders with their grammar,
ontology and seed envelope, the one executable the six roles share, the fixture package under
`fixtures/`, the tests, the gate runner and the publisher, and this card in place of the folder
README. The kernel is a separate dataset, https://huggingface.co/datasets/tailot/lingologos-codex,
and the section "What this bundle needs from the codex kernel" below says how the two find each
other.
It provides everything needed to inspect, edit, test, and transactionally commit changes in a
Python repository through the `codex` assurance rules (`VERIFIED`, `SINGLE_PROVER`, `UNKNOWN`).
```
python -B tools/run_gates.py
GATES: CONFIRMED (6 gates: 6 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
```
The gate runner is where this bundle states its numbers out loud: 6 gates, 26 tests across 5 files,
18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives every
one of those numbers from the tree it is standing in and stops the upload when the card and the code
beside it disagree.
## Contents
- `lgpython/_codex_bridge.py`: finds the kernel without copying it: an already importable `lgcodex`,
then `LGCODEX_ROOT`, then a sibling `codex/` or `datasets/codex/` among the ancestors.
- `lgpython/adapter.py`: `PythonLanguageAdapter` and `StrictPythonLanguageAdapter` implementing the
five-method `lgcodex.adapter_contract.LanguageAdapter` contract.
- `lgpython/ast_graph.py`: AST symbol, method, inheritance, relative/absolute import, and call
graph extraction (`discover_python_files`, `extract_python_graph`).
- `lgpython/test_selector.py`: import-aware Python test selection (`select_python_tests`).
- `lgpython/gates.py`: bytecode-free `ast.parse` + in-memory `compile` gate, optional static
checkers (`mypy`, `ruff`, `pyright`, `flake8`) that return `ABSTAIN` when missing, and `pytest`
/ `unittest` test runner with failed-target parsing.
- `lgpython/session.py`: `PythonWorkspaceSession` for safe staged verification and atomic disk
commits via `lgcodex.fsadapter` (`verify`, `edit_file`, `create_file`, `delete_file`,
`run_retry_loop`, and `run_topology_subprocesses`).
- `lgpython/cli.py`: `lgpython` CLI (`verify`, `edit`, `create`, `symbols`, `select-tests`,
`check-adapter`).
- `topology.json`, `agents/python_agent.py`, `nodes/<role>/`: external six-node topology using the
`codex` kernel as its base. The six executables it names are written relative to `datasets/`, so in
a standalone copy that leading name is simply the folder you are standing in.
- `codex.python.json`: declarative `CommandLanguageAdapter` template for Python projects.
## Running
From the folder of this dataset, with `LGCODEX_ROOT` pointing at the folder of the kernel dataset:
```bash
python -B -m pytest -p no:cacheprovider tests -q
python -B tools/run_gates.py
python -B -m lgpython check-adapter --workspace fixtures/sample_pkg
python -B -m lgpython verify --workspace fixtures/sample_pkg --file src/mathops.py
```
## What this bundle needs from the codex kernel
`lgpython` imports `lgcodex`, and `lgpython/_codex_bridge.py` resolves that import in one step: an
already importable `lgcodex`, then the folder named by `LGCODEX_ROOT`, then a sibling `codex/` or a
`datasets/codex/` among the ancestors of the package. Downloaded from here the two orders are the same
folder, and the resolution is:
pip install -r requirements.txt
git clone https://huggingface.co/datasets/tailot/lingologos-codex
LGCODEX_ROOT=/path/to/lingologos-codex python -B -m pytest -p no:cacheprovider tests -q
Nothing in this bundle downloads anything at run time: the kernel is a second download you make once,
and the tests fail with a named reason when it is missing rather than passing without it. The kernel
never imports this folder, so the dependency has exactly one direction, and one copy of the kernel can
serve any number of workspaces.
## Rights
The dataset is published by the author of LingoLOGOS under the same account, `tailot`. The source tree
is the `codex-python/` folder of https://github.com/tailot/LingoLOGOS, where the project states its own
terms. Neither that repository root nor this folder carries a `LICENSE` file, so no license is claimed
here beyond what the publisher states on the repository and on this dataset page; ask there before
reusing the code. The fixture package under `fixtures/sample_pkg/` was written for this dataset and is
not taken from a third-party project.
## Citation
@misc{lingologos_codex_python,
title = {LingoLOGOS codex-python: a Python programming layer over the codex kernel},
author = {{LingoLOGOS}},
year = {2026},
howpublished = {\url{https://huggingface.co/datasets/tailot/codex-python}},
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657#!/usr/bin/env python3"""External Python topology node executable built on LingoLOGOS codex.
Reads one JSON envelope on stdin, injects the external PythonLanguageAdapterwhen no explicit adapter or spec is already set on the dossier, delegates thestep to lgcodex.agents.run_step, and writes one JSON envelope to stdout."""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
PYTHON_ROOT = Path(__file__).resolve().parent.parentif str(PYTHON_ROOT) not in sys.path: sys.path.insert(0, str(PYTHON_ROOT))
from lgpython._codex_bridge import ensure_codex_on_path # noqa: E402
ensure_codex_on_path(PYTHON_ROOT)
from lgcodex import agents, envelope as _envelope # noqa: E402
def main() -> int: parser = argparse.ArgumentParser(description="External Python topology node") parser.add_argument("--role", required=True, choices=sorted(agents.STEPS)) parser.add_argument("--node-id", default=None) parser.add_argument( "--strict-tools", action="store_true", help="Use StrictPythonLanguageAdapter requiring mypy and ruff.", ) args, _ignored = parser.parse_known_args()
incoming = json.loads(sys.stdin.read()) dossier = dict(_envelope.read_dossier(incoming)) if not dossier.get("adapter") and not dossier.get("spec"): dossier["adapter"] = ( "lgpython.adapter:StrictPythonLanguageAdapter" if args.strict_tools or dossier.get("strictTools") else "lgpython.adapter:PythonLanguageAdapter" ) incoming = dict(incoming) payload = dict(incoming.get("payload", {})) payload["abstractSyntaxTree"] = json.dumps(dossier, sort_keys=True) incoming["payload"] = payload
outgoing = agents.run_step(args.role, incoming, args.node_id or args.role) sys.stdout.write(json.dumps(outgoing)) return 0
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435{ "name": "python-workspace", "languages": [ "python" ], "extensions": [ ".py", ".pyi" ], "version": "0.1.0", "spec_version": "1", "typecheck": "python -m compileall -q src", "test": "python -m pytest -q -p no:cacheprovider {targets}", "full_test": "python -m pytest -q -p no:cacheprovider", "test_map": { "src/*.py": [ "tests" ] }, "failed_target_patterns": [ "FAILED (?P<target>[\\w./\\-]+(?:::\\S+)?)", "^(?P<target>[\\w./\\-]+\\.py):\\d+:" ], "signature_rules": [ { "pattern": "in [\\d.]+s", "replacement": "in <t>" }, { "pattern": "rootdir: \\S+", "replacement": "rootdir: <path>" } ], "timeout_sec": 120.0}12345678910111213141516171819202122232425262728293031323334353637"""Arithmetic helpers for the sample Python fixture package."""
from __future__ import annotations
class Accumulator: """Running sum helper used to verify class and method graph extraction."""
def __init__(self, initial: int = 0) -> None: self.total = initial
def add(self, value: int) -> int: self.total += value return self.total
class BoundedAccumulator(Accumulator): """Accumulator bounded by an upper limit."""
def __init__(self, limit: int, initial: int = 0) -> None: super().__init__(initial=initial) self.limit = limit
def add(self, value: int) -> int: next_value = min(self.limit, self.total + value) self.total = next_value return self.total
def add_numbers(left: int, right: int) -> int: """Return the sum of two integers.""" return left + right
def double_sum(left: int, right: int) -> int: """Double the sum returned by add_numbers.""" return add_numbers(left, right) * 21234567891011"""Formatting helpers depending on mathops."""
from __future__ import annotations
from src.mathops import add_numbers
def format_sum(left: int, right: int) -> str: """Format an addition summary.""" total = add_numbers(left, right) return f"{left} + {right} = {total}"1234567891011121314151617"""Tests for src.mathops."""
from src.mathops import BoundedAccumulator, add_numbers, double_sum
def test_add_numbers() -> None: assert add_numbers(2, 3) == 5
def test_double_sum() -> None: assert double_sum(2, 3) == 10
def test_bounded_accumulator() -> None: acc = BoundedAccumulator(limit=5, initial=1) assert acc.add(3) == 4 assert acc.add(10) == 51234567"""Tests for src.textops."""
from src.textops import format_sum
def test_format_sum() -> None: assert format_sum(4, 6) == "4 + 6 = 10"123456789101112131415161718192021222324252627282930313233343536373839404142434445"""External Python programming package built on top of the LingoLOGOS codex kernel."""
from lgpython._codex_bridge import ensure_codex_on_path, find_codex_root
ensure_codex_on_path()
from lgpython.adapter import ( # noqa: E402 ADAPTER_NAME, ADAPTER_VERSION, PythonLanguageAdapter, StrictPythonLanguageAdapter,)from lgpython.ast_graph import ( # noqa: E402 discover_python_files, extract_python_graph, module_names_for_file,)from lgpython.session import ( # noqa: E402 PythonWorkspaceSession, SessionResult, run_topology_subprocesses,)from lgpython.test_selector import ( # noqa: E402 discover_test_files, is_test_file, select_python_tests,)
__all__ = [ "ADAPTER_NAME", "ADAPTER_VERSION", "PythonLanguageAdapter", "PythonWorkspaceSession", "SessionResult", "StrictPythonLanguageAdapter", "discover_python_files", "discover_test_files", "ensure_codex_on_path", "extract_python_graph", "find_codex_root", "is_test_file", "module_names_for_file", "run_topology_subprocesses", "select_python_tests",]123456"""Module entry point for python -m lgpython."""
from lgpython.cli import main
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Locate and expose the sibling or configured LingoLOGOS codex kernel.
This module allows datasets/codex-python to remain an external package withoutcopying or modifying datasets/codex. When lgcodex is already importable, nothingis changed; otherwise the bridge searches LGCODEX_ROOT and ancestor datasets/codexdirectories and inserts the matching root on sys.path."""
from __future__ import annotations
import importlibimport osimport sysfrom pathlib import Pathfrom typing import Optional
def find_codex_root(start: Optional[Path] = None) -> Optional[Path]: """Return the path to the codex package root if found on disk.""" env_root = os.environ.get("LGCODEX_ROOT", "").strip() if env_root: candidate = Path(env_root).expanduser().resolve() if (candidate / "lgcodex").is_dir(): return candidate
anchor = (start or Path(__file__)).resolve() for parent in [anchor, *anchor.parents]: direct = parent / "lgcodex" if direct.is_dir(): return parent sibling_codex = parent / "codex" if (sibling_codex / "lgcodex").is_dir(): return sibling_codex datasets_codex = parent / "datasets" / "codex" if (datasets_codex / "lgcodex").is_dir(): return datasets_codex return None
def ensure_codex_on_path(start: Optional[Path] = None) -> Path: """Ensure lgcodex is importable and return the resolved codex root.""" try: mod = importlib.import_module("lgcodex") mod_file = getattr(mod, "__file__", None) if mod_file: return Path(mod_file).resolve().parent.parent except ImportError: pass
codex_root = find_codex_root(start=start) if codex_root is None: raise ImportError( "Unable to locate lgcodex. Install lingologos-codex or set LGCODEX_ROOT." ) codex_str = str(codex_root) if codex_str not in sys.path: sys.path.insert(0, codex_str) importlib.import_module("lgcodex") return codex_root123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""External Python LanguageAdapter conforming to the LingoLOGOS codex contract."""
from __future__ import annotations
import osfrom pathlib import Pathfrom typing import Dict, List, Sequence, Tuple
from lgpython._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lgcodex.adapter_contract import AdapterMetadata, BaseLanguageAdapter # noqa: E402from lgcodex.types import GateResult # noqa: E402
from lgpython.ast_graph import extract_python_graph # noqa: E402from lgpython.gates import ( # noqa: E402 SIGNATURE_RULES, parse_failed_targets, resolve_tool_gate_prefix, run_python_tests, run_syntax_gate, run_tool_gate,)from lgpython.test_selector import select_python_tests # noqa: E402
ADAPTER_NAME = "lingologos-python"ADAPTER_VERSION = "0.1.0"
DEFAULT_TOOL_ARGS: Dict[str, Tuple[str, ...]] = { "mypy": ("--ignore-missing-imports", "--no-incremental"), "pyright": (), "ruff": ("check", "--no-cache"), "flake8": (),}
class PythonLanguageAdapter(BaseLanguageAdapter): """Full-featured external Python adapter built on lgcodex.BaseLanguageAdapter.
By default it runs the in-process syntax and compile gate plus any static checkers explicitly requested or discovered when enabled. Calling with ``require_tools=("mypy", "ruff")`` enforces those tools strictly: when a required tool is missing on the host, the gate returns ABSTAIN so the codex arbiter refuses to guess. """
def __init__( self, workspace_root: str | Path, *, require_tools: Sequence[str] = (), use_installed_tools: bool = False, timeout_sec: float = 120.0, ) -> None: super().__init__(workspace_root, timeout_sec=timeout_sec) self.require_tools: Tuple[str, ...] = tuple(require_tools) self.use_installed_tools: bool = bool(use_installed_tools)
def meta(self) -> AdapterMetadata: return AdapterMetadata( name=ADAPTER_NAME, languages=("python",), extensions=(".py", ".pyi"), version=ADAPTER_VERSION, )
def command_env(self) -> Dict[str, str]: root_str = str(self.workspace_root) existing = os.environ.get("PYTHONPATH", "") pythonpath = f"{root_str}{os.pathsep}{existing}" if existing else root_str return {"PYTHONDONTWRITEBYTECODE": "1", "PYTHONPATH": pythonpath}
def extract_symbols_and_edges( self, workspace: str, files: Sequence[str] ) -> Tuple[List[str], List[Tuple[str, str]]]: cwd = self._checked_cwd(workspace) return extract_python_graph(cwd, files)
def select_tests(self, workspace: str, changed_files: Sequence[str]) -> List[str]: cwd = self._checked_cwd(workspace) return select_python_tests(cwd, changed_files)
def run_typecheck_and_lint( self, workspace: str, target_files: Sequence[str] ) -> List[GateResult]: cwd = self._checked_cwd(workspace) gates: List[GateResult] = [run_syntax_gate(cwd, target_files)] if not target_files: return gates
tools_to_run: List[str] = list(self.require_tools) if self.use_installed_tools: for candidate in ("mypy", "ruff"): if candidate not in tools_to_run and resolve_tool_gate_prefix(candidate) is not None: tools_to_run.append(candidate)
for tool in tools_to_run: args = DEFAULT_TOOL_ARGS.get(tool, ()) gates.append(run_tool_gate(self, cwd, tool, args, target_files)) return gates
def run_tests( self, workspace: str, targets: Sequence[str], full_suite: bool = False ) -> GateResult: cwd = self._checked_cwd(workspace) return run_python_tests(self, cwd, targets, full_suite=full_suite)
def failed_targets_from_output(self, output: str) -> Tuple[str, ...]: return parse_failed_targets(output)
def signature_rules(self) -> Tuple[Tuple[str, str], ...]: return SIGNATURE_RULES
class StrictPythonLanguageAdapter(PythonLanguageAdapter): """Variant that always demands mypy and ruff, abstaining when either is absent."""
def __init__(self, workspace_root: str | Path, timeout_sec: float = 120.0) -> None: super().__init__( workspace_root, require_tools=("mypy", "ruff"), use_installed_tools=False, timeout_sec=timeout_sec, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298"""Python AST symbol, import, inheritance, and call graph extractor.
Nothing here executes user code or writes bytecode to disk. Files that failto parse are skipped so the syntax gate owns syntax diagnostics."""
from __future__ import annotations
import astimport osfrom pathlib import Pathfrom typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple
IGNORED_DIRS: frozenset[str] = frozenset( { ".git", ".hg", ".svn", "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox", ".nox", ".venv", "venv", "env", "node_modules", "build", "dist", })
def _is_ignored(rel_parts: Sequence[str]) -> bool: for part in rel_parts[:-1]: if part in IGNORED_DIRS or part.endswith(".egg-info"): return True return False
def discover_python_files(workspace: Path) -> List[str]: """Return sorted POSIX relative paths for all Python source files in workspace.""" root = workspace.resolve() found: List[str] = [] for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = sorted( d for d in dirnames if d not in IGNORED_DIRS and not d.endswith(".egg-info") ) rel_dir = Path(dirpath).resolve().relative_to(root) for filename in sorted(filenames): if not filename.endswith(".py"): continue rel_path = (rel_dir / filename).as_posix() if rel_dir.parts else filename if not _is_ignored(rel_path.split("/")): found.append(rel_path) return sorted(found)
def module_names_for_file(rel_posix: str) -> List[str]: """Return candidate dotted module names for a relative Python path.""" parts = [p for p in rel_posix.replace("\\", "/").split("/") if p] if not parts: return [] if parts[-1] == "__init__.py": base_parts = parts[:-1] elif parts[-1].endswith(".py"): base_parts = [*parts[:-1], parts[-1][:-3]] else: base_parts = parts
candidates: List[str] = [] for start in range(len(base_parts)): dotted = ".".join(base_parts[start:]) if dotted and dotted not in candidates: candidates.append(dotted) if len(base_parts) > 1 and base_parts[0] in ("src", "lib", "python"): stripped = ".".join(base_parts[1:]) if stripped and stripped not in candidates: candidates.append(stripped) return candidates
def _read_source(workspace: Path, rel_posix: str) -> Optional[str]: target = workspace / Path(*rel_posix.replace("\\", "/").split("/")) if not target.is_file() or target.is_symlink(): return None try: return target.read_text(encoding="utf-8", errors="replace") except OSError: return None
def _collect_definitions( tree: ast.Module,) -> Tuple[List[str], Dict[str, List[str]], Dict[str, Set[str]]]: """Return symbol names, class-to-base-names map, and call map.""" symbols: List[str] = [] bases_by_class: Dict[str, List[str]] = {} calls_by_symbol: Dict[str, Set[str]] = {}
for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): symbols.append(node.name) calls_by_symbol[node.name] = _called_names(node) elif isinstance(node, ast.ClassDef): symbols.append(node.name) bases_by_class[node.name] = [_expr_name(base) for base in node.bases if _expr_name(base)] for item in node.body: if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): qualified = f"{node.name}.{item.name}" symbols.append(qualified) calls_by_symbol[qualified] = _called_names(item) return symbols, bases_by_class, calls_by_symbol
def _expr_name(node: ast.AST) -> str: if isinstance(node, ast.Name): return node.id if isinstance(node, ast.Attribute): prefix = _expr_name(node.value) return f"{prefix}.{node.attr}" if prefix else node.attr return ""
def _called_names(func_node: ast.AST) -> Set[str]: called: Set[str] = set() for inner in ast.walk(func_node): if isinstance(inner, ast.Call): if isinstance(inner.func, ast.Name): called.add(inner.func.id) elif isinstance(inner.func, ast.Attribute): called.add(inner.func.attr) full = _expr_name(inner.func) if full: called.add(full) return called
def _resolve_relative_module(rel_posix: str, level: int, module: Optional[str]) -> str: parts = rel_posix.replace("\\", "/").split("/") package_parts = parts[:-1] if level > len(package_parts): base_parts: List[str] = [] else: base_parts = package_parts[: len(package_parts) - (level - 1)] if module: return ".".join([*base_parts, *module.split(".")]) return ".".join(base_parts)
def _extract_imports( rel_posix: str, tree: ast.Module) -> Tuple[List[str], Dict[str, Tuple[str, str]]]: """Return imported module names and local-alias -> (module, imported_name) map.""" modules: List[str] = [] alias_map: Dict[str, Tuple[str, str]] = {}
for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: if alias.name not in modules: modules.append(alias.name) local = alias.asname or alias.name.split(".")[0] alias_map[local] = (alias.name, "") elif isinstance(node, ast.ImportFrom): if node.level > 0: mod_name = _resolve_relative_module(rel_posix, node.level, node.module) else: mod_name = node.module or "" if mod_name and mod_name not in modules: modules.append(mod_name) for alias in node.names: if alias.name == "*": continue local = alias.asname or alias.name if mod_name: alias_map[local] = (mod_name, alias.name) if not alias.asname: sub_mod = f"{mod_name}.{alias.name}" if sub_mod not in modules: modules.append(sub_mod) return modules, alias_map
def _match_module_file( module_name: str, files_by_module: Dict[str, str], all_files: Sequence[str], current_file: str,) -> Optional[str]: if module_name in files_by_module and files_by_module[module_name] != current_file: return files_by_module[module_name] leaf = module_name.split(".")[-1] for other in all_files: if other == current_file: continue if Path(other).stem == leaf: return other return None
def extract_python_graph( workspace: Path, files: Sequence[str]) -> Tuple[List[str], List[Tuple[str, str]]]: """Extract qualified Python symbols and dependency edges over workspace files.""" normalized_files = [f.replace("\\", "/") for f in files if f] files_by_module: Dict[str, str] = {} for rel in normalized_files: for mod in module_names_for_file(rel): files_by_module.setdefault(mod, rel)
parsed: Dict[str, ast.Module] = {} defs_by_file: Dict[str, List[str]] = {} bases_by_file: Dict[str, Dict[str, List[str]]] = {} calls_by_file: Dict[str, Dict[str, Set[str]]] = {} imports_by_file: Dict[str, Tuple[List[str], Dict[str, Tuple[str, str]]]] = {}
symbols: Set[str] = set() edges: Set[Tuple[str, str]] = set()
for rel in normalized_files: source = _read_source(workspace, rel) if source is None: symbols.add(rel) continue try: tree = ast.parse(source, filename=rel) except SyntaxError: symbols.add(rel) continue parsed[rel] = tree names, bases, calls = _collect_definitions(tree) defs_by_file[rel] = names bases_by_file[rel] = bases calls_by_file[rel] = calls imports_by_file[rel] = _extract_imports(rel, tree) if names: for name in names: symbols.add(f"{rel}::{name}") else: symbols.add(rel)
for rel in parsed: local_names = set(defs_by_file.get(rel, ())) modules, alias_map = imports_by_file.get(rel, ([], {}))
# File-level import edges for mod in modules: target_file = _match_module_file(mod, files_by_module, normalized_files, rel) if target_file: edges.add((rel, target_file))
# Inheritance edges for cls_name, base_list in bases_by_file.get(rel, {}).items(): src_sym = f"{rel}::{cls_name}" for base_name in base_list: short = base_name.split(".")[-1] if base_name in local_names and base_name != cls_name: edges.add((src_sym, f"{rel}::{base_name}")) elif short in alias_map: mod_name, imported_sym = alias_map[short] target_file = _match_module_file(mod_name, files_by_module, normalized_files, rel) if target_file: sym_name = imported_sym or short if sym_name in defs_by_file.get(target_file, ()): edges.add((src_sym, f"{target_file}::{sym_name}")) else: edges.add((src_sym, target_file))
# Intra-file and cross-file call edges for caller, called_set in calls_by_file.get(rel, {}).items(): src_sym = f"{rel}::{caller}" owner_class = caller.split(".")[0] if "." in caller else "" for called in called_set: if called in local_names and called != caller: edges.add((src_sym, f"{rel}::{called}")) elif owner_class and f"{owner_class}.{called}" in local_names: target_method = f"{owner_class}.{called}" if target_method != caller: edges.add((src_sym, f"{rel}::{target_method}")) else: head = called.split(".")[0] if head in alias_map: mod_name, imported_sym = alias_map[head] target_file = _match_module_file( mod_name, files_by_module, normalized_files, rel ) if target_file: candidate = imported_sym or ( called.split(".", 1)[1] if "." in called else "" ) if candidate and candidate in defs_by_file.get(target_file, ()): edges.add((src_sym, f"{target_file}::{candidate}")) else: edges.add((src_sym, target_file))
return sorted(symbols), sorted(edges)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197"""Command-line interface for the external LingoLOGOS Python programming package."""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Pathfrom typing import List, Optional, Sequence
from lgpython._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lgcodex.adapter_contract import check_adapter_contract # noqa: E402from lgcodex.graph import compute_symbol_pagerank, top_symbols # noqa: E402
from lgpython.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter # noqa: E402from lgpython.ast_graph import discover_python_files, extract_python_graph # noqa: E402from lgpython.session import PythonWorkspaceSession # noqa: E402from lgpython.test_selector import select_python_tests # noqa: E402
def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="lgpython", description="Python programming workbench and language adapter powered by LingoLOGOS codex.", ) sub = parser.add_subparsers(dest="command", required=True)
# verify p_verify = sub.add_parser("verify", help="Verify a Python workspace through the six-node codex pipeline.") p_verify.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_verify.add_argument("--file", default=None, help="Optional relative Python file to focus on.") p_verify.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") p_verify.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.") p_verify.add_argument("--json", action="store_true", help="Print JSON output.")
# edit p_edit = sub.add_parser("edit", help="Propose, verify, and atomically commit a Python search-replace edit.") p_edit.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_edit.add_argument("--file", required=True, help="Relative Python file to edit.") p_edit.add_argument("--search", required=True, help="Search text block.") p_edit.add_argument("--replace", required=True, help="Replacement text block.") p_edit.add_argument("--dry-run", action="store_true", help="Verify without committing to disk.") p_edit.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") p_edit.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.") p_edit.add_argument("--allow-single-prover", action="store_true", help="Allow commit at assurance 2.") p_edit.add_argument("--json", action="store_true", help="Print JSON output.")
# create p_create = sub.add_parser("create", help="Create a new Python file after full codex verification.") p_create.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_create.add_argument("--file", required=True, help="Relative Python file path to create.") p_create.add_argument("--content-file", required=True, help="Path to file holding Python source content.") p_create.add_argument("--dry-run", action="store_true", help="Verify without committing to disk.") p_create.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") p_create.add_argument("--json", action="store_true", help="Print JSON output.")
# symbols p_sym = sub.add_parser("symbols", help="Extract Python AST symbols, edges, and PageRank.") p_sym.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_sym.add_argument("--files", nargs="*", default=None, help="Optional relative Python files.") p_sym.add_argument("--limit", type=int, default=10, help="Maximum top symbols to display.") p_sym.add_argument("--json", action="store_true", help="Print JSON output.")
# select-tests p_tests = sub.add_parser("select-tests", help="Select Python test files impacted by changed files.") p_tests.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_tests.add_argument("--files", nargs="+", required=True, help="Changed relative Python files.") p_tests.add_argument("--json", action="store_true", help="Print JSON output.")
# check-adapter p_check = sub.add_parser("check-adapter", help="Validate PythonLanguageAdapter against the codex contract.") p_check.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_check.add_argument("--strict-tools", action="store_true", help="Check StrictPythonLanguageAdapter.") p_check.add_argument("--json", action="store_true", help="Print JSON output.")
return parser
def main(argv: Optional[Sequence[str]] = None) -> int: parser = _build_parser() args = parser.parse_args(argv)
if args.command == "verify": session = PythonWorkspaceSession( args.workspace, strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, ) res = session.verify(target_file=args.file) if args.json: print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) else: print(f"{res.verdict} (assurance {res.assurance}) {res.reason}: {res.detail}") return 0 if res.accepted else 1
if args.command == "edit": min_assurance = 2 if args.allow_single_prover else 3 session = PythonWorkspaceSession( args.workspace, strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, min_assurance=min_assurance, ) res = session.edit_file( args.file, args.search, args.replace, commit=not args.dry_run, ) if args.json: print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) else: print( f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) " f"{res.reason}: {res.detail}" ) return 0 if res.assurance >= min_assurance else 1
if args.command == "create": content = Path(args.content_file).read_text(encoding="utf-8", newline="") session = PythonWorkspaceSession(args.workspace, strict_tools=args.strict_tools) res = session.create_file(args.file, content, commit=not args.dry_run) if args.json: print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) else: print( f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) " f"{res.reason}: {res.detail}" ) return 0 if res.accepted else 1
if args.command == "symbols": root = Path(args.workspace).resolve() files: List[str] = args.files if args.files else discover_python_files(root) symbols, edges = extract_python_graph(root, files) ranks = compute_symbol_pagerank(symbols, edges) top = top_symbols(ranks, limit=args.limit) if args.json: print( json.dumps( { "files": files, "symbols": symbols, "edges": [list(e) for e in edges], "top": [[name, score] for name, score in top], }, indent=2, ) ) else: print(f"files={len(files)} symbols={len(symbols)} edges={len(edges)}") for name, score in top: print(f" {score:.4f} {name}") return 0
if args.command == "select-tests": root = Path(args.workspace).resolve() selected = select_python_tests(root, args.files) if args.json: print(json.dumps({"selected_tests": selected}, indent=2)) else: for item in selected: print(item) return 0
if args.command == "check-adapter": root = Path(args.workspace).resolve() adapter = ( StrictPythonLanguageAdapter(root) if args.strict_tools else PythonLanguageAdapter(root) ) sample_files = discover_python_files(root)[:3] violations = check_adapter_contract(adapter, str(root), sample_files) if args.json: print( json.dumps( {"adapter": adapter.meta().name, "violations": violations}, indent=2, ) ) else: if violations: for v in violations: print(f"VIOLATION: {v}") else: print(f"ADAPTER OK: {adapter.meta().name}") return 1 if violations else 0
return 2
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"""Python quality and test gates with strict three-valued outcomes.
Every gate returns GateResult(CONFIRMED | REJECTED | ABSTAIN). A missingtoolchain never produces CONFIRMED or REJECTED; it returns ABSTAIN with aclear diagnostic note so the codex decision rule can block honestly."""
from __future__ import annotations
import astimport importlib.utilimport reimport shutilimport sysfrom pathlib import Pathfrom typing import TYPE_CHECKING, List, Sequence, Tuple
from lgpython._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lgcodex.types import ABSTAIN, CONFIRMED, REJECTED, GateResult # noqa: E402
if TYPE_CHECKING: from lgcodex.adapter_contract import BaseLanguageAdapter
FAILED_TARGET_PATTERNS: Tuple[str, ...] = ( r"FAILED (?P<target>[\w./\\-]+(?:::\S+)?)", r"^(?P<target>[\w./\\-]+\.py):\d+:", r'E\s+File "(?P<target>[^"]+)"', r'File "(?P<target>[^"]+\.py)", line \d+', r"ERROR: .* \((?P<target>[\w./\\-]+\.py)\)",)
SIGNATURE_RULES: Tuple[Tuple[str, str], ...] = ( (r"in [\d.]+s", "in <t>"), (r"Ran \d+ tests? in [\d.]+s", "Ran <n> tests in <t>"), (r"rootdir: \S+", "rootdir: <path>"), (r"plugins?: \S.*", "plugins: <set>"), (r"Found \d+ errors? in \d+ files?", "Found <n> errors in <m> files"),)
def _read_text_safe(cwd: Path, rel: str) -> str | None: target = cwd / Path(*rel.replace("\\", "/").split("/")) if not target.is_file() or target.is_symlink(): return None try: return target.read_text(encoding="utf-8", errors="replace") except OSError: return None
def has_python_module(module_name: str) -> bool: """Return True when module_name is importable in the active Python interpreter.""" return importlib.util.find_spec(module_name) is not None
def resolve_tool_argv(tool: str) -> List[str] | None: """Resolve a CLI tool binary on PATH or via python -m <tool>.""" binary = shutil.which(tool) if binary: return [binary] if has_python_module(tool): return [sys.executable, "-m", tool] return None
def run_syntax_gate(cwd: Path, target_files: Sequence[str]) -> GateResult: """Validate Python syntax and code-object compilation in memory without writing .pyc.""" files = [f.replace("\\", "/") for f in target_files if f] if not files: return GateResult(CONFIRMED, "ast.parse + compile (no target files)")
broken: List[str] = [] failed: List[str] = [] for rel in files: source = _read_text_safe(cwd, rel) if source is None: broken.append(f"{rel}: unreadable or missing") failed.append(rel) continue try: tree = ast.parse(source, filename=rel) compile(tree, filename=rel, mode="exec", dont_inherit=True) except SyntaxError as exc: broken.append(f"{rel}: line {exc.lineno}: {exc.msg}") failed.append(rel) except ValueError as exc: broken.append(f"{rel}: {exc}") failed.append(rel)
command = "ast.parse " + " ".join(files) if broken: return GateResult( REJECTED, command, output="\n".join(broken), failed_targets=tuple(failed), note=f"{len(broken)} file(s) failed syntax verification", ) return GateResult(CONFIRMED, command)
def run_tool_gate( adapter: BaseLanguageAdapter, cwd: Path, tool: str, args: Sequence[str], target_files: Sequence[str],) -> GateResult: """Run an external Python static checker or return ABSTAIN when unavailable.""" argv_prefix = resolve_tool_gate_prefix(tool) if argv_prefix is None: return GateResult( ABSTAIN, f"{tool} {' '.join(args)}".strip(), note=f"{tool} is not installed on this host, the gate has no judgement", ) if not target_files: return GateResult(CONFIRMED, f"{tool} (no target files)") return adapter.run_command( cwd.as_posix(), [*argv_prefix, *args, *[f.replace("\\", "/") for f in target_files]], gate_name=tool, )
def resolve_tool_gate_prefix(tool: str) -> List[str] | None: """Resolve supported Python static analysis tools.""" return resolve_tool_argv(tool)
def run_python_tests( adapter: BaseLanguageAdapter, cwd: Path, targets: Sequence[str], full_suite: bool = False,) -> GateResult: """Run pytest (no cacheprovider) or fall back to unittest discovery.""" if resolve_tool_argv("pytest") is not None: argv = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"] if full_suite or not targets: return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") return adapter.run_command( cwd.as_posix(), argv + [t.replace("\\", "/") for t in targets], gate_name="selected_tests", )
if has_python_module("unittest"): if full_suite or not targets: argv = [sys.executable, "-m", "unittest", "discover", "-q"] return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") argv = [sys.executable, "-m", "unittest", "-q", *[t.replace("\\", "/") for t in targets]] return adapter.run_command(cwd.as_posix(), argv, gate_name="selected_tests")
return GateResult( ABSTAIN, "python -m pytest", note="neither pytest nor unittest is available in this interpreter", )
def parse_failed_targets(output: str) -> Tuple[str, ...]: """Extract normalized failed target paths or node ids from Python tool output.""" found: List[str] = [] for pattern in FAILED_TARGET_PATTERNS: for match in re.finditer(pattern, output, re.MULTILINE): value = match.group("target").replace("\\", "/") if value and value not in found: found.append(value) return tuple(found[:50])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571"""Transactional Python programming session built on the LingoLOGOS codex kernel.
A change is staged in an isolated copy of the workspace, evaluated by thesix-node codex pipeline (either in-process or as six isolated subprocesseswalking datasets/codex-python/topology.json), and committed atomically to the realworkspace via lgcodex.fsadapter only when the arbiter reaches the requiredassurance threshold."""
from __future__ import annotations
import jsonimport osimport shutilimport subprocessimport sysimport tempfilefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
from lgpython._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lgcodex import envelope as _envelope # noqa: E402from lgcodex.agents import ROLES, run_pipeline # noqa: E402from lgcodex.failures import detect_stall_from_hashes # noqa: E402from lgcodex.fsadapter import create_os_filesystem_adapter # noqa: E402from lgcodex.fspolicy import ( # noqa: E402 EOL_PRESERVE, FSPolicy, OP_DELETE, OP_WRITE, PathGuard, PathSecurityError, PlannedOp,)from lgcodex.patcher import ( # noqa: E402 FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch,)
from lgpython.ast_graph import IGNORED_DIRS, discover_python_files # noqa: E402
PYTHON_ROOT = Path(__file__).resolve().parent.parentDEFAULT_AGENT_SCRIPT = PYTHON_ROOT / "agents" / "python_agent.py"DEFAULT_TOPOLOGY_PATH = PYTHON_ROOT / "topology.json"
DEFAULT_ALLOWED_PATTERNS: Tuple[str, ...] = ("*.py", "*.pyi")DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ( "*.env", ".env*", "*.pem", "*.key", ".git/*", "__pycache__/*",)
ADAPTER_REF_DEFAULT = "lgpython.adapter:PythonLanguageAdapter"ADAPTER_REF_STRICT = "lgpython.adapter:StrictPythonLanguageAdapter"DEFAULT_GATES: Tuple[str, ...] = ("typecheck", "tests")
@dataclass(frozen=True)class SessionResult: """Outcome of running the six-node codex pipeline over a Python workspace."""
case_id: str verdict: str assurance: int reason: str detail: str committed: bool touched_files: Tuple[str, ...] = () trace: Tuple[Dict[str, Any], ...] = field(default_factory=tuple) dossier: Dict[str, Any] = field(default_factory=dict)
@property def accepted(self) -> bool: return self.verdict in ("VERIFIED", "SINGLE_PROVER")
def to_dict(self) -> Dict[str, Any]: return { "case_id": self.case_id, "verdict": self.verdict, "assurance": self.assurance, "reason": self.reason, "detail": self.detail, "committed": self.committed, "touched_files": list(self.touched_files), "decision": dict(self.dossier.get("decision", {})), "gates": list(self.dossier.get("gates", [])), "checkers": list(self.dossier.get("checkers", [])), }
def _copy_workspace_for_staging(src_root: Path, dst_root: Path) -> None: """Copy a workspace cleanly without caches or virtual environments.""" for dirpath, dirnames, filenames in os.walk(src_root): dirnames[:] = [ d for d in dirnames if d not in IGNORED_DIRS and not d.endswith(".egg-info") ] rel_dir = Path(dirpath).resolve().relative_to(src_root.resolve()) target_dir = dst_root / rel_dir target_dir.mkdir(parents=True, exist_ok=True) for name in filenames: src_file = Path(dirpath) / name if src_file.is_symlink(): continue shutil.copy2(src_file, target_dir / name)
def _subprocess_env() -> Dict[str, str]: env = dict(os.environ) env["PYTHONDONTWRITEBYTECODE"] = "1" python_pkg_root = str(PYTHON_ROOT) codex_root = str(ensure_codex_on_path()) existing = env.get("PYTHONPATH", "") parts = [python_pkg_root, codex_root] if existing: parts.append(existing) env["PYTHONPATH"] = os.pathsep.join(parts) return env
def run_topology_subprocesses( case: Dict[str, Any], *, agent_script: Path = DEFAULT_AGENT_SCRIPT, timeout_sec: float = 120.0,) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: """Execute the six roles via isolated node subprocesses communicating over JSON stdio.""" seed = _envelope.make_envelope("arbiter", 0, 0, "task received", dict(case)) trace: List[Dict[str, Any]] = [seed] current = seed env = _subprocess_env()
for role in ROLES: cmd = [sys.executable, "-B", str(agent_script), "--role", role, "--node-id", role] completed = subprocess.run( cmd, input=json.dumps(current), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout_sec, cwd=str(PYTHON_ROOT), env=env, ) if completed.returncode != 0: raise RuntimeError( f"node '{role}' exited with {completed.returncode}: {completed.stderr.strip()}" ) current = json.loads(completed.stdout) trace.append(current) return trace, _envelope.read_dossier(current)
class PythonWorkspaceSession: """High-level interface to inspect, edit, verify, and commit Python code via codex."""
def __init__( self, workspace_root: str | Path, *, allowed_patterns: Sequence[str] = DEFAULT_ALLOWED_PATTERNS, protected_patterns: Sequence[str] = DEFAULT_PROTECTED_PATTERNS, required_gates: Sequence[str] = DEFAULT_GATES, strict_tools: bool = False, spec_path: Optional[str | Path] = None, use_subprocesses: bool = False, min_assurance: int = 3, ) -> None: self.workspace_root = Path(workspace_root).resolve() if not self.workspace_root.is_dir(): raise FileNotFoundError(f"workspace does not exist: '{self.workspace_root}'") self.allowed_patterns = tuple(allowed_patterns) self.protected_patterns = tuple(protected_patterns) self.required_gates = tuple(required_gates) self.strict_tools = bool(strict_tools) self.spec_path = str(Path(spec_path).resolve()) if spec_path else None self.use_subprocesses = bool(use_subprocesses) self.min_assurance = int(min_assurance)
def policy_dict(self, root: Optional[Path] = None) -> Dict[str, Any]: return { "repo_root": str((root or self.workspace_root).resolve()), "allowed_patterns": list(self.allowed_patterns), "protected_patterns": list(self.protected_patterns), "default_eol": EOL_PRESERVE, }
def policy(self, root: Optional[Path] = None) -> FSPolicy: return FSPolicy( repo_root=str((root or self.workspace_root).resolve()), allowed_patterns=self.allowed_patterns, protected_patterns=self.protected_patterns, case_insensitive=(os.name == "nt"), default_eol=EOL_PRESERVE, )
def _os_fs(self, root: Path, *, check_allowed: bool = True): policy = FSPolicy( repo_root=str(root.resolve()), allowed_patterns=self.allowed_patterns if check_allowed else (), protected_patterns=self.protected_patterns, case_insensitive=(os.name == "nt"), default_eol=EOL_PRESERVE, ) fs = create_os_filesystem_adapter( root, protected_patterns=self.protected_patterns, allowed_patterns=self.allowed_patterns if check_allowed else (), ) fs.policy = policy fs.guard = PathGuard(policy) return fs
def _adapter_fields(self) -> Dict[str, Any]: if self.spec_path: return {"spec": self.spec_path} return {"adapter": ADAPTER_REF_STRICT if self.strict_tools else ADAPTER_REF_DEFAULT}
def _run_six_nodes(self, case: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: if self.use_subprocesses: return run_topology_subprocesses(case) return run_pipeline(case)
def list_files(self) -> List[str]: """Return all Python source files in the workspace.""" return discover_python_files(self.workspace_root)
def verify( self, target_file: Optional[str] = None, *, case_id: str = "python-verify", note: str = "verify Python workspace against codex gates", ) -> SessionResult: """Verify an existing file or the whole Python workspace without modifying disk.""" py_files = self.list_files() chosen = (target_file or (py_files[0] if py_files else "src/__init__.py")).replace("\\", "/") target_path = self.workspace_root / Path(*chosen.split("/")) if target_path.is_file(): text = target_path.read_text(encoding="utf-8", newline="") else: text = ""
# Verify without changing file content by probing a non-mutating exact check # over a temporary staging copy so real workspace files remain untouched. lines = text.splitlines(keepends=True) if lines: first_line = lines[0] probe_search = first_line probe_replace = first_line.rstrip("\r\n") + " # codex-verify-probe\n" original_for_patch = text else: probe_search = "# empty" probe_replace = "# empty verified" original_for_patch = "# empty\n"
case: Dict[str, Any] = { "case_id": case_id, "workspace": str(self.workspace_root), "file": chosen, "text": original_for_patch, "search": probe_search, "replace": probe_replace, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) return SessionResult( case_id=case_id, verdict=str(decision.get("verdict", "UNKNOWN")), assurance=int(decision.get("assurance", 0)), reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=False, touched_files=(chosen,), trace=tuple(trace), dossier=dossier, )
def edit_file( self, rel_path: str, search: str, replace: str, *, case_id: str = "python-edit", note: str = "apply controlled search-and-replace edit", commit: bool = True, attempt_signatures: Sequence[str] = (), patch_config: FuzzyPatchConfig = FuzzyPatchConfig(), ) -> SessionResult: """Stage a search-and-replace edit, verify via codex, and commit atomically on pass.""" rel_posix = rel_path.replace("\\", "/") guard = PathGuard(self.policy())
# Check path policy before touching or staging anything try: plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content="")]) except PathSecurityError: case = { "case_id": case_id, "workspace": str(self.workspace_root), "file": rel_posix, "text": "", "search": search, "replace": replace, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(), "attemptSignatures": list(attempt_signatures), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) return SessionResult( case_id=case_id, verdict=str(decision.get("verdict", "UNKNOWN")), assurance=int(decision.get("assurance", 0)), reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=False, touched_files=(rel_posix,), trace=tuple(trace), dossier=dossier, )
target = self.workspace_root / Path(*rel_posix.split("/")) original_text = target.read_text(encoding="utf-8", newline="") if target.is_file() else "" patch_res = apply_controlled_fuzzy_patch( original_text, SearchReplaceBlock(search, replace), patch_config )
with tempfile.TemporaryDirectory(prefix="lgpython_stage_") as tmp_dir: staged_root = Path(tmp_dir).resolve() _copy_workspace_for_staging(self.workspace_root, staged_root) if patch_res.applied and not plan.rejected: staged_fs = self._os_fs(staged_root) tx = staged_fs.begin_transaction() staged_fs.stage_write_text(tx, rel_posix, patch_res.updated_text) staged_fs.commit_transaction(tx)
case = { "case_id": case_id, "workspace": str(staged_root), "file": rel_posix, "text": original_text, "search": search, "replace": replace, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), "options": { "min_similarity": patch_config.min_similarity, "ambiguity_margin": patch_config.ambiguity_margin, }, "attemptSignatures": list(attempt_signatures), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case)
decision = dict(dossier.get("decision", {})) verdict = str(decision.get("verdict", "UNKNOWN")) assurance = int(decision.get("assurance", 0)) committed = False
if commit and patch_res.applied and not plan.rejected and assurance >= self.min_assurance: real_fs = self._os_fs(self.workspace_root) tx = real_fs.begin_transaction() real_fs.stage_write_text(tx, rel_posix, patch_res.updated_text) real_fs.commit_transaction(tx) committed = True
return SessionResult( case_id=case_id, verdict=verdict, assurance=assurance, reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=committed, touched_files=(rel_posix,), trace=tuple(trace), dossier=dossier, )
def create_file( self, rel_path: str, content: str, *, case_id: str = "python-create", note: str = "create verified Python module", commit: bool = True, ) -> SessionResult: """Create a new Python file, verifying it in isolation before committing.""" rel_posix = rel_path.replace("\\", "/") target = self.workspace_root / Path(*rel_posix.split("/")) if target.exists(): raise FileExistsError(f"target already exists: '{rel_posix}'")
guard = PathGuard(self.policy()) try: plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content=content)]) except PathSecurityError: return self.edit_file(rel_posix, "# NEW_FILE", content, case_id=case_id, note=note, commit=False)
marker = "# __LGPYTHON_NEW_FILE__\n" with tempfile.TemporaryDirectory(prefix="lgpython_create_") as tmp_dir: staged_root = Path(tmp_dir).resolve() _copy_workspace_for_staging(self.workspace_root, staged_root) if not plan.rejected: staged_fs = self._os_fs(staged_root) tx = staged_fs.begin_transaction() staged_fs.stage_write_text(tx, rel_posix, content) staged_fs.commit_transaction(tx)
case = { "case_id": case_id, "workspace": str(staged_root), "file": rel_posix, "text": marker, "search": marker, "replace": content, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case)
decision = dict(dossier.get("decision", {})) verdict = str(decision.get("verdict", "UNKNOWN")) assurance = int(decision.get("assurance", 0)) committed = False if commit and not plan.rejected and assurance >= self.min_assurance: real_fs = self._os_fs(self.workspace_root) tx = real_fs.begin_transaction() real_fs.stage_write_text(tx, rel_posix, content) real_fs.commit_transaction(tx) committed = True
return SessionResult( case_id=case_id, verdict=verdict, assurance=assurance, reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=committed, touched_files=(rel_posix,), trace=tuple(trace), dossier=dossier, )
def delete_file( self, rel_path: str, *, case_id: str = "python-delete", note: str = "delete Python module with full regression check", commit: bool = True, ) -> SessionResult: """Delete a Python file only if the full regression passes after removal.""" rel_posix = rel_path.replace("\\", "/") guard = PathGuard(self.policy()) try: plan = guard.plan_transaction([PlannedOp(op=OP_DELETE, rel_posix=rel_posix)]) except PathSecurityError: return self.edit_file(rel_posix, "# DELETE", "", case_id=case_id, note=note, commit=False)
target = self.workspace_root / Path(*rel_posix.split("/")) if not target.is_file(): raise FileNotFoundError(f"target file does not exist: '{rel_posix}'") original_text = target.read_text(encoding="utf-8", newline="")
with tempfile.TemporaryDirectory(prefix="lgpython_delete_") as tmp_dir: staged_root = Path(tmp_dir).resolve() _copy_workspace_for_staging(self.workspace_root, staged_root) if not plan.rejected: # Unlink only the target file; lgcodex.fsadapter.stage_delete walks parent dirs. staged_target = staged_root / Path(*rel_posix.split("/")) if staged_target.is_file() and not staged_target.is_symlink(): staged_target.unlink()
# Evaluate syntax over remaining files by targeting a surviving file if available remaining = [p for p in discover_python_files(staged_root) if p != rel_posix] gate_target = remaining[0] if remaining else rel_posix case = { "case_id": case_id, "workspace": str(staged_root), "file": gate_target, "text": original_text, "search": original_text if original_text.strip() else "# empty", "replace": "# deleted\n", "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case)
decision = dict(dossier.get("decision", {})) verdict = str(decision.get("verdict", "UNKNOWN")) assurance = int(decision.get("assurance", 0)) committed = False if commit and not plan.rejected and assurance >= self.min_assurance: guard.resolve_safe(rel_posix, for_write=True) current = self.workspace_root for part in Path(*rel_posix.split("/")).parts: current = current / part if current.is_symlink(): raise PathSecurityError(f"refusing to delete across symlink: '{rel_posix}'") if target.is_file(): target.unlink() committed = True
return SessionResult( case_id=case_id, verdict=verdict, assurance=assurance, reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=committed, touched_files=(rel_posix,), trace=tuple(trace), dossier=dossier, )
def run_retry_loop( self, rel_path: str, proposer: Callable[[int, Optional[SessionResult]], Tuple[str, str]], *, max_attempts: int = 4, commit: bool = True, ) -> Tuple[SessionResult, List[SessionResult]]: """Run bounded edit attempts using codex stall detection to stop identical or cyclic failures.""" history: List[str] = [] attempts: List[SessionResult] = [] last: Optional[SessionResult] = None
for idx in range(1, max_attempts + 1): search, replace = proposer(idx, last) result = self.edit_file( rel_path, search, replace, case_id=f"retry-{idx}", commit=commit, attempt_signatures=history, ) attempts.append(result) last = result sig = str(result.dossier.get("patchSignature", "")) if sig: history.append(sig) if result.assurance >= self.min_assurance: return result, attempts if detect_stall_from_hashes(history) is not None: return result, attempts assert last is not None return last, attempts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Import-aware Python test discovery and selection."""
from __future__ import annotations
import astfrom pathlib import Pathfrom typing import Dict, List, Sequence, Set
from lgpython.ast_graph import ( discover_python_files, extract_python_graph, module_names_for_file,)
def is_test_file(rel_posix: str) -> bool: """Return True when a relative path follows Python test file naming conventions.""" name = Path(rel_posix).name return name.startswith("test_") and name.endswith(".py") or name.endswith("_test.py")
def discover_test_files(workspace: Path) -> List[str]: """Return sorted POSIX relative paths of all test files in workspace.""" all_py = discover_python_files(workspace) tests_first = [p for p in all_py if is_test_file(p) and (p.startswith("tests/") or "/tests/" in p)] others = [p for p in all_py if is_test_file(p) and p not in tests_first] return tests_first + others
def _naming_candidates(rel_posix: str) -> List[str]: parts = [p for p in rel_posix.replace("\\", "/").split("/") if p] if not parts: return [] stem = Path(parts[-1]).stem test_names = (f"test_{stem}.py", f"{stem}_test.py") candidates: List[str] = [] for tname in test_names: if len(parts) > 1: candidates.append("/".join([*parts[:-1], tname])) else: candidates.append(tname) candidates.append(f"tests/{tname}") candidates.append(f"tests/{stem}/{tname}") if len(parts) > 2 and parts[0] in ("src", "lib", "python"): sub_dir = "/".join(parts[1:-1]) candidates.append(f"tests/{sub_dir}/{tname}") return candidates
def _imported_names_in_file(path: Path) -> Set[str]: try: source = path.read_text(encoding="utf-8", errors="replace") tree = ast.parse(source, filename=str(path)) except (OSError, SyntaxError): return set()
imported: Set[str] = set() for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: imported.add(alias.name) imported.add(alias.name.split(".")[-1]) elif isinstance(node, ast.ImportFrom): if node.module: imported.add(node.module) imported.add(node.module.split(".")[-1]) for alias in node.names: if alias.name != "*": imported.add(alias.name) if node.module: imported.add(f"{node.module}.{alias.name}") return imported
def select_python_tests(workspace: Path, changed_files: Sequence[str]) -> List[str]: """Select test file paths relevant to changed_files using naming and AST imports.""" root = workspace.resolve() all_tests = discover_test_files(root) if not all_tests: return []
chosen: List[str] = [] test_set = set(all_tests)
# 1. Direct test file edits and naming conventions for raw in changed_files: rel = raw.replace("\\", "/") if rel in test_set and rel not in chosen: chosen.append(rel) continue for candidate in _naming_candidates(rel): if candidate in test_set and candidate not in chosen: chosen.append(candidate)
# 2. Transitive reverse-dependency closure across discovered Python files all_py = discover_python_files(root) _, graph_edges = extract_python_graph(root, all_py) dependents_of: Dict[str, Set[str]] = {} for src, dst in graph_edges: src_file = src.split("::", 1)[0] dst_file = dst.split("::", 1)[0] if src_file != dst_file: dependents_of.setdefault(dst_file, set()).add(src_file)
impacted: Set[str] = {raw.replace("\\", "/") for raw in changed_files if raw} queue: List[str] = list(impacted) while queue: current = queue.pop(0) for dep in sorted(dependents_of.get(current, ())): if dep not in impacted: impacted.add(dep) queue.append(dep)
for test_rel in all_tests: if test_rel in impacted and test_rel not in chosen: chosen.append(test_rel)
# 3. Fallback direct AST token scan for any remaining test files target_tokens: Dict[str, Set[str]] = {} for rel in impacted: tokens = set(module_names_for_file(rel)) stem = Path(rel).stem if stem and stem != "__init__": tokens.add(stem) target_tokens[rel] = tokens
combined_tokens: Set[str] = set() for tok_set in target_tokens.values(): combined_tokens.update(tok_set)
if combined_tokens: for test_rel in all_tests: if test_rel in chosen: continue test_path = root / Path(*test_rel.split("/")) imported = _imported_names_in_file(test_path) if imported & combined_tokens: chosen.append(test_rel)
return chosen123456789101112131415161718192021-- Node adversary (to arbiter): runs full Python suite and detects failure loops.-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.abstract PythonAdversary = { cat Check ; Verdict ; fun Challenge : Verdict -> Check ; Confirmed : Verdict ; Rejected : Verdict ; Abstain : Verdict ;}
concrete PythonAdversaryEng of PythonAdversary = { lincat Check, Verdict = Str ; lin Challenge v = "adversary" ++ v ; Confirmed = "CONFIRMED" ; Rejected = "REJECTED" ; Abstain = "ABSTAIN" ;}12345; SMT-LIB 2 ontology for external Python topology node adversary.(set-option :timeout 8000)(declare-const stall_detected Int)(assert (>= stall_detected 0))(assert (<= stall_detected 1))12345678910111213141516171819{ "kind": "lingologos-codex-envelope-1", "sender": "adversary", "turn": 0, "volatileState": { "internalTimeTick": 0 }, "payload": { "naturalLanguage": "Idle Python adversary awaiting independent suite verification.", "abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_adversary\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}", "smtConstraints": { "declarations": [], "assertions": [ "(assert true)" ], "z3Status": "sat" } }}1234567891011121314151617181920212223-- Node arbiter (to planner): applies lgcodex.decision.decide without adding evidence.-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.abstract PythonArbiter = { cat Outcome ; Verdict ; Reason ; fun Rule : Verdict -> Reason -> Outcome ; Verified : Verdict ; SingleProver : Verdict ; Unknown : Verdict ; ReasonCode : String -> Reason ;}
concrete PythonArbiterEng of PythonArbiter = { lincat Outcome, Verdict, Reason = Str ; lin Rule v r = v ++ "because" ++ r ; Verified = "VERIFIED" ; SingleProver = "SINGLE_PROVER" ; Unknown = "UNKNOWN" ; ReasonCode s = s.s ;}1234567; SMT-LIB 2 ontology for external Python topology node arbiter.(set-option :timeout 8000)(declare-const assurance Int)(assert (or (= assurance 0) (= assurance 2) (= assurance 3)))(declare-const confirming_checkers Int)(assert (>= confirming_checkers 0))(assert (=> (< confirming_checkers 2) (<= assurance 2)))12345678910111213141516171819{ "kind": "lingologos-codex-envelope-1", "sender": "arbiter", "turn": 0, "volatileState": { "internalTimeTick": 0 }, "payload": { "naturalLanguage": "Idle Python arbiter awaiting gate_checker and adversary reports.", "abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_arbiter\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}", "smtConstraints": { "declarations": [], "assertions": [ "(assert true)" ], "z3Status": "sat" } }}12345678910111213141516171819-- Node executor (to gate_checker and adversary): proposes a Python search-replace patch.-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.abstract PythonExecutor = { cat Proposal ; Path ; Status ; fun Propose : Path -> Status -> Proposal ; FilePath : String -> Path ; PatchState : String -> Status ;}
concrete PythonExecutorEng of PythonExecutor = { lincat Proposal, Path, Status = Str ; lin Propose p s = "patch" ++ p ++ "status" ++ s ; FilePath p = p.s ; PatchState s = s.s ;}123456; SMT-LIB 2 ontology for external Python topology node executor.(set-option :timeout 8000)(declare-const protected_hits Int)(assert (>= protected_hits 0))(declare-const executor_assurance Int)(assert (= executor_assurance 0))12345678910111213141516171819{ "kind": "lingologos-codex-envelope-1", "sender": "executor", "turn": 0, "volatileState": { "internalTimeTick": 0 }, "payload": { "naturalLanguage": "Idle Python executor awaiting patch proposal.", "abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_executor\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}", "smtConstraints": { "declarations": [], "assertions": [ "(assert true)" ], "z3Status": "sat" } }}1234567891011121314151617181920212223-- Node gate_checker (to arbiter): runs Python syntax, static checks, and selected tests.-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.abstract PythonGateChecker = { cat Report ; Gate ; Verdict ; fun Record : Gate -> Verdict -> Report ; Named : String -> Gate ; Confirmed : Verdict ; Rejected : Verdict ; Abstain : Verdict ;}
concrete PythonGateCheckerEng of PythonGateChecker = { lincat Report, Gate, Verdict = Str ; lin Record g v = g ++ "=" ++ v ; Named s = s.s ; Confirmed = "CONFIRMED" ; Rejected = "REJECTED" ; Abstain = "ABSTAIN" ;}123456; SMT-LIB 2 ontology for external Python topology node gate_checker.(set-option :timeout 8000)(declare-const gate_abstain Int)(declare-const gate_rejected Int)(assert (>= gate_abstain 0))(assert (>= gate_rejected 0))12345678910111213141516171819{ "kind": "lingologos-codex-envelope-1", "sender": "gate_checker", "turn": 0, "volatileState": { "internalTimeTick": 0 }, "payload": { "naturalLanguage": "Idle Python gate checker awaiting commands to run.", "abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_gate_checker\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}", "smtConstraints": { "declarations": [], "assertions": [ "(assert true)" ], "z3Status": "sat" } }}12345678910111213141516171819202122232425-- Node planner (to retriever): fixes the Python task order and required gates.-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.abstract PythonPlan = { cat Plan ; Tasks ; Task ; Gate ; Gates ; fun Schedule : Tasks -> Gates -> Plan ; Start : Task -> Tasks ; Then : Task -> Tasks -> Tasks ; GateNamed : String -> Gate ; Required : Gate -> Gates ; Demand : Gate -> Gates -> Gates ;}
concrete PythonPlanEng of PythonPlan = { lincat Plan, Tasks, Task, Gate, Gates = Str ; lin Schedule ts gs = "plan" ++ ts ++ "gates" ++ gs ; Start t = t ; Then t ts = t ++ "then" ++ ts ; GateNamed s = s.s ; Required g = g ; Demand g gs = g ++ "and" ++ gs ;}123456; SMT-LIB 2 ontology for external Python topology node planner.(set-option :timeout 8000)(declare-const planned_tasks Int)(assert (= planned_tasks 6))(declare-const planner_assurance Int)(assert (= planner_assurance 0))12345678910111213141516171819{ "kind": "lingologos-codex-envelope-1", "sender": "planner", "turn": 0, "volatileState": { "internalTimeTick": 0 }, "payload": { "naturalLanguage": "Idle Python planner awaiting workspace task.", "abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_planner\", \"checkers\": [], \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"plan\": {\"order\": [], \"parallelGroups\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}", "smtConstraints": { "declarations": [], "assertions": [ "(assert true)" ], "z3Status": "sat" } }}12345678910111213141516171819-- Node retriever (to executor): gathers Python AST symbols, imports, and call edges.-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.abstract PythonRetriever = { cat Context ; Symbol ; Edge ; fun Gather : Symbol -> Edge -> Context ; Sym : String -> Symbol ; Dep : String -> String -> Edge ;}
concrete PythonRetrieverEng of PythonRetriever = { lincat Context, Symbol, Edge = Str ; lin Gather s e = "context" ++ s ++ "edges" ++ e ; Sym n = n.s ; Dep a b = a.s ++ "->" ++ b.s ;}123456; SMT-LIB 2 ontology for external Python topology node retriever.(set-option :timeout 8000)(declare-const context_budget Int)(assert (>= context_budget 0))(declare-const retriever_assurance Int)(assert (= retriever_assurance 0))12345678910111213141516171819{ "kind": "lingologos-codex-envelope-1", "sender": "retriever", "turn": 0, "volatileState": { "internalTimeTick": 0 }, "payload": { "naturalLanguage": "Idle Python retriever awaiting symbol graph request.", "abstractSyntaxTree": "{\"adapter\": \"lgpython.adapter:PythonLanguageAdapter\", \"case_id\": \"python_idle_retriever\", \"checkers\": [], \"context\": {\"edges\": [], \"symbols\": []}, \"gates\": [], \"patch\": {\"outside_allowed\": [], \"protected_hits\": [], \"similarity\": 0.0, \"status\": \"\", \"touched_files\": []}, \"required_gates\": [\"typecheck\", \"tests\"]}", "smtConstraints": { "declarations": [], "assertions": [ "(assert true)" ], "z3Status": "sat" } }}123456789101112131415161718192021222324252627282930313233[build-system]requires = ["setuptools>=61.0"]build-backend = "setuptools.build_meta"
[project]name = "lingologos-python"version = "0.1.0"description = "External Python language adapter, workspace session, and topology built on LingoLOGOS codex"readme = "README.md"requires-python = ">=3.10"dependencies = []
[project.optional-dependencies]dev = [ "pytest>=8.0.0",]lint = [ "mypy>=1.0.0", "ruff>=0.4.0",]
[project.entry-points."lingologos.codex.adapters"]python = "lgpython.adapter:PythonLanguageAdapter"
[project.scripts]lgpython = "lgpython.cli:main"
[tool.setuptools.packages.find]include = ["lgpython*"]
[tool.pytest.ini_options]testpaths = ["tests"]pythonpath = ["."]1pytest>=8.0.01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{
"schema": "lingologos-python-gates-1",
"verdict": "CONFIRMED",
"counts": {
"CONFIRMED": 6,
"REJECTED": 0,
"ABSTAIN": 0
},
"gates": [
{
"name": "adapter_contract",
"verdict": "CONFIRMED",
"check": "check_adapter_contract on PythonLanguageAdapter",
"note": "no violations for lingologos-python",
"failed_targets": []
},
{
"name": "ast_symbol_graph",
"verdict": "CONFIRMED",
"check": "Python AST symbol, method, inheritance, and import graph",
"note": "13 symbols, 10 edges extracted",
"failed_targets": []
},
{
"name": "test_selection",
"verdict": "CONFIRMED",
"check": "import-aware Python test selection",
"note": "selected 2 dependent test file(s)",
"failed_targets": []
},
{
"name": "strict_abstain_control",
"verdict": "CONFIRMED",
"check": "missing optional tools produce ABSTAIN and block verdict",
"note": "missing static tools abstained and ended in UNKNOWN/GATE_ABSTAIN",
"failed_targets": []
},
{
"name": "session_transactions",
"verdict": "CONFIRMED",
"check": "staged edit commit on VERIFIED and disk isolation on refusal",
"note": "clean edit committed VERIFIED (3); syntax error and protected path refused",
"failed_targets": []
},
{
"name": "external_topology",
"verdict": "CONFIRMED",
"check": "external topology.json, node folders, and six subprocess turns",
"note": "6 node folders valid, 7 subprocess envelopes reached VERIFIED (3)",
"failed_targets": []
}
]
}12345678910111213141516171819202122232425262728"""Shared pytest fixtures for the external datasets/codex-python package."""
from __future__ import annotations
import shutilimport sysfrom pathlib import Path
import pytest
sys.dont_write_bytecode = True
PYTHON_ROOT = Path(__file__).resolve().parent.parentif str(PYTHON_ROOT) not in sys.path: sys.path.insert(0, str(PYTHON_ROOT))
from lgpython._codex_bridge import ensure_codex_on_path # noqa: E402
ensure_codex_on_path(PYTHON_ROOT)
@pytest.fixturedef sample_pkg(tmp_path: Path) -> Path: """Copy fixtures/sample_pkg into a clean temporary directory per test.""" src = PYTHON_ROOT / "fixtures" / "sample_pkg" dst = tmp_path / "sample_pkg" shutil.copytree(src, dst) return dst123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Tests for PythonLanguageAdapter, StrictPythonLanguageAdapter, and codex loading."""
from __future__ import annotations
from pathlib import Path
import pytest
from lgcodex.adapter_contract import ( ADAPTER_SPEC_VERSION, CommandLanguageAdapter, WorkspaceBoundaryError, check_adapter_contract, load_adapter_from_file, load_adapter_from_ref,)from lgcodex.types import ABSTAIN, CONFIRMED, REJECTED
from lgpython.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapterfrom lgpython.ast_graph import discover_python_filesfrom lgpython.gates import resolve_tool_gate_prefix
def test_python_adapter_passes_full_codex_contract(sample_pkg: Path) -> None: adapter = PythonLanguageAdapter(sample_pkg) files = discover_python_files(sample_pkg) violations = check_adapter_contract(adapter, str(sample_pkg), files) assert violations == []
def test_adapter_metadata_and_env(sample_pkg: Path) -> None: adapter = PythonLanguageAdapter(sample_pkg) meta = adapter.meta() assert meta.name == "lingologos-python" assert meta.languages == ("python",) assert ".py" in meta.extensions assert meta.spec_version == ADAPTER_SPEC_VERSION env = adapter.command_env() assert env["PYTHONDONTWRITEBYTECODE"] == "1" assert str(sample_pkg.resolve()) in env["PYTHONPATH"]
def test_syntax_gate_rejects_broken_python_file(sample_pkg: Path) -> None: broken = sample_pkg / "src" / "broken.py" broken.write_text("def bad(:\n return 1\n", encoding="utf-8")
adapter = PythonLanguageAdapter(sample_pkg) gates = adapter.run_typecheck_and_lint(str(sample_pkg), ["src/broken.py"]) assert len(gates) == 1 assert gates[0].verdict == REJECTED assert "src/broken.py" in gates[0].failed_targets
def test_strict_adapter_abstains_when_tool_is_missing(sample_pkg: Path) -> None: adapter = StrictPythonLanguageAdapter(sample_pkg) gates = adapter.run_typecheck_and_lint(str(sample_pkg), ["src/mathops.py"]) assert gates[0].verdict == CONFIRMED for tool_name, gate in zip(("mypy", "ruff"), gates[1:]): if resolve_tool_gate_prefix(tool_name) is None: assert gate.verdict == ABSTAIN assert tool_name in gate.note
def test_custom_missing_tool_always_abstains(sample_pkg: Path) -> None: adapter = PythonLanguageAdapter(sample_pkg, require_tools=("nonexistent_checker_xyz",)) gates = adapter.run_typecheck_and_lint(str(sample_pkg), ["src/mathops.py"]) assert gates[0].verdict == CONFIRMED assert gates[1].verdict == ABSTAIN assert "nonexistent_checker_xyz" in gates[1].note
def test_workspace_escape_is_refused(sample_pkg: Path) -> None: adapter = PythonLanguageAdapter(sample_pkg) with pytest.raises(WorkspaceBoundaryError): adapter.run_tests("..", [], full_suite=True)
def test_load_adapter_via_codex_ref_and_declarative_spec(sample_pkg: Path) -> None: python_root = Path(__file__).resolve().parent.parent
by_module = load_adapter_from_ref("lgpython.adapter:PythonLanguageAdapter", sample_pkg) assert isinstance(by_module, PythonLanguageAdapter)
adapter_file = python_root / "lgpython" / "adapter.py" by_file = load_adapter_from_ref(f"{adapter_file}:PythonLanguageAdapter", sample_pkg) assert by_file.meta().name == "lingologos-python"
spec_adapter = load_adapter_from_file(python_root / "codex.python.json", sample_pkg) assert isinstance(spec_adapter, CommandLanguageAdapter) assert spec_adapter.meta().languages == ("python",)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Tests for Python AST symbol, inheritance, import, and call graph extraction."""
from __future__ import annotations
from pathlib import Path
from lgpython.ast_graph import discover_python_files, extract_python_graph, module_names_for_file
def test_discover_python_files_ignores_caches_and_venvs(sample_pkg: Path) -> None: (sample_pkg / "__pycache__").mkdir() (sample_pkg / "__pycache__" / "junk.py").write_text("x = 1\n", encoding="utf-8") (sample_pkg / ".venv" / "lib").mkdir(parents=True) (sample_pkg / ".venv" / "lib" / "site.py").write_text("x = 2\n", encoding="utf-8")
files = discover_python_files(sample_pkg) assert files == [ "src/mathops.py", "src/textops.py", "tests/test_mathops.py", "tests/test_textops.py", ]
def test_module_names_for_file_strips_src_and_init() -> None: assert "mathops" in module_names_for_file("src/mathops.py") assert "src.mathops" in module_names_for_file("src/mathops.py") assert "pkg" in module_names_for_file("src/pkg/__init__.py")
def test_extract_python_graph_captures_classes_methods_inheritance_and_calls( sample_pkg: Path,) -> None: files = discover_python_files(sample_pkg) symbols, edges = extract_python_graph(sample_pkg, files)
assert "src/mathops.py::Accumulator" in symbols assert "src/mathops.py::BoundedAccumulator" in symbols assert "src/mathops.py::BoundedAccumulator.add" in symbols assert "src/mathops.py::double_sum" in symbols assert ("src/mathops.py::BoundedAccumulator", "src/mathops.py::Accumulator") in edges assert ("src/mathops.py::double_sum", "src/mathops.py::add_numbers") in edges assert ("src/textops.py", "src/mathops.py") in edges assert ("src/textops.py::format_sum", "src/mathops.py::add_numbers") in edges
def test_extract_python_graph_handles_relative_imports_and_syntax_errors(tmp_path: Path) -> None: pkg = tmp_path / "pkg" pkg.mkdir() (pkg / "__init__.py").write_text("", encoding="utf-8") (pkg / "core.py").write_text("def compute():\n return 42\n", encoding="utf-8") (pkg / "caller.py").write_text( "from .core import compute\n\ndef run():\n return compute()\n", encoding="utf-8", ) (pkg / "broken.py").write_text("def oops(:\n", encoding="utf-8")
files = discover_python_files(tmp_path) symbols, edges = extract_python_graph(tmp_path, files) assert "pkg/broken.py" in symbols assert ("pkg/caller.py", "pkg/core.py") in edges assert ("pkg/caller.py::run", "pkg/core.py::compute") in edges1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Tests for PythonWorkspaceSession transactional editing, verification, and rollback."""
from __future__ import annotations
from pathlib import Path
from lgpython.session import PythonWorkspaceSession
def test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py") assert res.verdict == "VERIFIED" assert res.assurance == 3 assert res.committed is False
def test_edit_file_commits_only_when_verified(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg)
res = session.edit_file( "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=True, ) assert res.verdict == "VERIFIED" assert res.assurance == 3 assert res.committed is True assert "return int(left) + int(right)" in (sample_pkg / "src" / "mathops.py").read_text( encoding="utf-8" )
def test_edit_file_does_not_touch_disk_when_tests_fail(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg) before = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8")
res = session.edit_file( "src/mathops.py", "return left + right", "return left - right", commit=True, ) after = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8") assert res.verdict == "UNKNOWN" assert res.reason == "GATE_REJECTED" assert res.committed is False assert before == after
def test_edit_file_refuses_protected_and_traversal_paths(sample_pkg: Path) -> None: (sample_pkg / ".env").write_text("KEY=1\n", encoding="utf-8") session = PythonWorkspaceSession(sample_pkg)
env_res = session.edit_file(".env", "KEY=1", "KEY=2", commit=True) assert env_res.verdict == "UNKNOWN" assert env_res.reason == "PROTECTED_PATH" assert env_res.committed is False assert (sample_pkg / ".env").read_text(encoding="utf-8") == "KEY=1\n"
esc_res = session.edit_file("../outside.py", "a = 1", "a = 2", commit=True) assert esc_res.verdict == "UNKNOWN" assert esc_res.reason in ("PROTECTED_PATH", "NOT_APPLIED") assert esc_res.committed is False
def test_create_and_delete_file_transactions(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg)
created = session.create_file( "src/helper.py", '"""Extra module."""\n\n\ndef square(x: int) -> int:\n return x * x\n', commit=True, ) assert created.verdict == "VERIFIED" assert created.committed is True assert (sample_pkg / "src" / "helper.py").is_file()
deleted = session.delete_file("src/helper.py", commit=True) assert deleted.verdict == "VERIFIED" assert deleted.committed is True assert not (sample_pkg / "src" / "helper.py").exists()
def test_retry_loop_stops_on_identical_failure_stall(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg)
def repeated_bad_edit(attempt: int, last_result: object) -> tuple[str, str]: return ("return left + right", "return left - right")
final, attempts = session.run_retry_loop("src/mathops.py", repeated_bad_edit, max_attempts=5) assert final.verdict == "UNKNOWN" assert len(attempts) == 2 assert any(c.get("role") == "adversary_loop" for c in final.dossier.get("checkers", []))12345678910111213141516171819202122232425262728293031323334"""Tests for import-aware Python test selection."""
from __future__ import annotations
from pathlib import Path
from lgpython.test_selector import discover_test_files, is_test_file, select_python_tests
def test_is_test_file_conventions() -> None: assert is_test_file("tests/test_alpha.py") assert is_test_file("pkg/alpha_test.py") assert not is_test_file("src/alpha.py")
def test_discover_test_files_prefers_tests_dir(sample_pkg: Path) -> None: found = discover_test_files(sample_pkg) assert found == ["tests/test_mathops.py", "tests/test_textops.py"]
def test_select_python_tests_follows_cross_file_imports(sample_pkg: Path) -> None: selected_math = select_python_tests(sample_pkg, ["src/mathops.py"]) assert selected_math == ["tests/test_mathops.py", "tests/test_textops.py"]
selected_text = select_python_tests(sample_pkg, ["src/textops.py"]) assert selected_text == ["tests/test_textops.py"]
def test_select_python_tests_returns_self_when_test_file_changed(sample_pkg: Path) -> None: assert select_python_tests(sample_pkg, ["tests/test_textops.py"]) == ["tests/test_textops.py"]
def test_select_python_tests_returns_empty_for_unknown_file(sample_pkg: Path) -> None: assert select_python_tests(sample_pkg, ["src/unrelated_missing.py"]) == []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Tests for the external topology, node subprocesses, CLI, and gate script."""
from __future__ import annotations
import jsonimport subprocessimport sysfrom pathlib import Path
from lgcodex.agents import ROLESfrom lgcodex.decision import dossier_from_dictfrom lgcodex.envelope import ENVELOPE_KIND
from lgpython import clifrom lgpython.session import PythonWorkspaceSession
PYTHON_ROOT = Path(__file__).resolve().parent.parent
def test_external_topology_json_and_node_folders_are_valid() -> None: topo = json.loads((PYTHON_ROOT / "topology.json").read_text(encoding="utf-8")) assert topo["sessionId"] == "lingologos-python-01" assert topo["terminationCondition"] == "FIXED_PIPELINE" assert sorted(inst["id"] for inst in topo["instances"]) == sorted(ROLES)
for role in ROLES: node_dir = PYTHON_ROOT / "nodes" / role assert (node_dir / "grammar.gf").is_file() assert (node_dir / "ontology.smt2").is_file() seed = json.loads((node_dir / "seed_payload.json").read_text(encoding="utf-8")) assert seed["kind"] == ENVELOPE_KIND assert seed["sender"] == role dossier_from_dict(json.loads(seed["payload"]["abstractSyntaxTree"]))
def test_six_isolated_subprocess_nodes_verify_workspace(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg, use_subprocesses=True) res = session.verify("src/mathops.py") assert res.verdict == "VERIFIED" assert res.assurance == 3 assert [env["sender"] for env in res.trace] == ["arbiter", *ROLES]
def test_python_agent_stdin_stdout_roundtrip(sample_pkg: Path) -> None: seed = (PYTHON_ROOT / "nodes" / "arbiter" / "seed_payload.json").read_text(encoding="utf-8") proc = subprocess.run( [ sys.executable, "-B", str(PYTHON_ROOT / "agents" / "python_agent.py"), "--role", "planner", "--node-id", "planner", ], input=seed, capture_output=True, text=True, encoding="utf-8", check=True, ) out = json.loads(proc.stdout) assert out["sender"] == "planner" assert out["turn"] == 1 dossier = json.loads(out["payload"]["abstractSyntaxTree"]) assert dossier["plan"]["order"][0] == "planner"
def test_cli_subcommands(sample_pkg: Path, capsys: object) -> None: assert cli.main(["check-adapter", "--workspace", str(sample_pkg)]) == 0 assert cli.main(["symbols", "--workspace", str(sample_pkg), "--json"]) == 0 assert ( cli.main( [ "select-tests", "--workspace", str(sample_pkg), "--files", "src/mathops.py", "--json", ] ) == 0 ) assert cli.main(["verify", "--workspace", str(sample_pkg), "--file", "src/mathops.py"]) == 0 assert ( cli.main( [ "edit", "--workspace", str(sample_pkg), "--file", "src/mathops.py", "--search", "return left + right", "--replace", "return int(left + right)", ] ) == 0 )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370"""Publish this folder as the dataset on the hub, and check that it arrived.
Run from inside the folder:
python tools/publish_dataset.py # token taken from HF_TOKEN python tools/publish_dataset.py --token-env TOKEN # another environment variable python tools/publish_dataset.py --plan # build the card, stage, upload nothing python tools/publish_dataset.py --prune # also drop files the folder no longer holds
The name follows the other topology bundles (`datasets/codex/tools/publish_dataset.py` and itssiblings) and deliberately avoids `publish_to_hub.py`: that name belongs to the release builder ofthe multilingual track.
This bundle carries no corpora and no kernel. It is the Python layer over `lgcodex`, so the card hasto say how the two find each other on the hub, and every number the card states (6 gates, 26 tests,18 node files, the staged file count) is re-derived from this tree before a single object isuploaded. A card that contradicts the code beside it stops the run instead of publishing.
The folder README is the body of the dataset card. A short list of wording pairs turns the sentencesthat only make sense inside a LingoLOGOS checkout, and three sections are added for readers who metthe bundle on the hub. Every pair has to match the README exactly, or the tool stops.
Nothing here runs during a test, and the token is never a command line argument, only the name of anenvironment variable."""
import argparseimport astimport hashlibimport jsonimport osimport shutilimport sysimport tempfilefrom pathlib import Pathfrom typing import List, Tuple
ROOT = Path(__file__).resolve().parents[1]
REPO = "tailot/codex-python"EXPECTED_FILES = 47 # the staged tree: 47 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 48 # those 47 plus the .gitattributes the hub addsEXPECTED_GATES = 6EXPECTED_TESTS = 26EXPECTED_TEST_FILES = 5EXPECTED_NODE_FILES = 18EXPECTED_GATE_LINE = "GATES: CONFIRMED (6 gates: 6 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"ROLES = ("planner", "retriever", "executor", "gate_checker", "adversary", "arbiter")ENVELOPE_KIND = "lingologos-codex-envelope-1"IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git", ".venv", ".venv-train"}IGNORED_SUFFIXES = (".pyc", ".pyo")
FRONT_MATTER = """---language: - entags: - code - program-synthesis - multi-agent-systems - software-engineering - static-analysis - testing - formal-verification - pythonpretty_name: "LingoLOGOS codex-python: a Python programming layer over the codex kernel"size_categories: - n<1K---
"""
# Sentences that are true in a checkout and misleading on the hub. Each pair is (here, there), and the# first has to appear in the README of this folder.REPLACEMENTS: List[Tuple[str, str]] = [ ( "An external Python programming package and six-node topology built on top of the LingoLOGOS\n" "`codex` kernel (`datasets/codex`) without modifying `datasets/codex`. Inside this repository the\n" "folder is `datasets/codex-python`, and the executables `topology.json` names are written relative to\n" "`datasets/`, so its six instances point at `codex-python/agents/python_agent.py`.", "An external Python programming package and six-node topology built on top of the LingoLOGOS\n" "`codex` kernel, a kernel this folder neither modifies nor carries. This dataset is that folder\n" "published as it stands: the package under `lgpython/`, the six node folders with their grammar,\n" "ontology and seed envelope, the one executable the six roles share, the fixture package under\n" "`fixtures/`, the tests, the gate runner and the publisher, and this card in place of the folder\n" "README. The kernel is a separate dataset, https://huggingface.co/datasets/tailot/lingologos-codex,\n" "and the section \"What this bundle needs from the codex kernel\" below says how the two find each\n" "other.", ), ( "The gate runner is where this bundle states its numbers out loud: 6 gates, 26 tests across 5 files,\n" "18 files under `nodes/`, and a kernel it does not carry.", "The gate runner is where this bundle states its numbers out loud: 6 gates, 26 tests across 5 files,\n" "18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives every\n" "one of those numbers from the tree it is standing in and stops the upload when the card and the code\n" "beside it disagree.", ), ( "From `datasets/codex-python`:", "From the folder of this dataset, with `LGCODEX_ROOT` pointing at the folder of the kernel dataset:", ), ( "- `topology.json`, `agents/python_agent.py`, `nodes/<role>/`: external six-node topology using\n" " `datasets/codex` as its kernel base.", "- `topology.json`, `agents/python_agent.py`, `nodes/<role>/`: external six-node topology using the\n" " `codex` kernel as its base. The six executables it names are written relative to `datasets/`, so in\n" " a standalone copy that leading name is simply the folder you are standing in.", ),]
# Sections a reader who found the bundle here needs and a reader inside a checkout does not.CARD_TAIL = """
## What this bundle needs from the codex kernel
`lgpython` imports `lgcodex`, and `lgpython/_codex_bridge.py` resolves that import in one step: analready importable `lgcodex`, then the folder named by `LGCODEX_ROOT`, then a sibling `codex/` or a`datasets/codex/` among the ancestors of the package. Downloaded from here the two orders are the samefolder, and the resolution is:
pip install -r requirements.txt git clone https://huggingface.co/datasets/tailot/lingologos-codex LGCODEX_ROOT=/path/to/lingologos-codex python -B -m pytest -p no:cacheprovider tests -q
Nothing in this bundle downloads anything at run time: the kernel is a second download you make once,and the tests fail with a named reason when it is missing rather than passing without it. The kernelnever imports this folder, so the dependency has exactly one direction, and one copy of the kernel canserve any number of workspaces.
## Rights
The dataset is published by the author of LingoLOGOS under the same account, `tailot`. The source treeis the `codex-python/` folder of https://github.com/tailot/LingoLOGOS, where the project states its ownterms. Neither that repository root nor this folder carries a `LICENSE` file, so no license is claimedhere beyond what the publisher states on the repository and on this dataset page; ask there beforereusing the code. The fixture package under `fixtures/sample_pkg/` was written for this dataset and isnot taken from a third-party project.
## Citation
@misc{lingologos_codex_python, title = {LingoLOGOS codex-python: a Python programming layer over the codex kernel}, author = {{LingoLOGOS}}, year = {2026}, howpublished = {\\url{https://huggingface.co/datasets/tailot/codex-python}}, }
"""
def local_files() -> List[Path]: """The files of this folder, caches out.
The underscore rule the other bundles use cannot be copied here. This package holds `lgpython/_codex_bridge.py`, a private module that resolves the kernel, and `lgpython/__main__.py`, the entry point of `python -m lgpython`: a rule that drops names starting with an underscore would upload a package that cannot import itself. Only caches and bytecode stay out. """
files: List[Path] = [] for path in ROOT.rglob("*"): if not path.is_file(): continue if any(part in IGNORED_DIRS for part in path.parts): continue if path.suffix in IGNORED_SUFFIXES: continue files.append(path) return sorted(files)
def build_card() -> str: text = (ROOT / "README.md").read_text(encoding="utf-8").replace("\r\n", "\n") for here, there in REPLACEMENTS: if here not in text: raise SystemExit( "the README no longer holds this sentence, so the card would be wrong:\n" + here[:160] ) text = text.replace(here, there) return FRONT_MATTER + text + CARD_TAIL
def count_tests() -> Tuple[int, int]: """Return the number of test functions in tests/ and the number of files holding them."""
total = 0 holders = 0 for path in sorted((ROOT / "tests").glob("*.py")): tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) found = [ node.name for node in tree.body if isinstance(node, ast.FunctionDef) and node.name.startswith("test_") ] if found: holders += 1 total += len(found) return total, holders
def sha256(data: bytes) -> str: return hashlib.sha256(data).hexdigest()
def check_gates_report() -> None: """The committed gate report has to agree with what this folder claims."""
payload = json.loads((ROOT / "results" / "gates.json").read_text(encoding="utf-8")) if payload.get("verdict") != "CONFIRMED": raise SystemExit(f"results/gates.json holds verdict '{payload.get('verdict')}'") gates = payload.get("gates") or [] if len(gates) != EXPECTED_GATES: raise SystemExit(f"results/gates.json holds {len(gates)} gates, the card states {EXPECTED_GATES}") if any(g.get("verdict") != "CONFIRMED" for g in gates): raise SystemExit("results/gates.json holds a gate that is not CONFIRMED") if sum((payload.get("counts") or {}).values()) != EXPECTED_GATES: raise SystemExit("results/gates.json counts do not add up to the gates it lists") readme = (ROOT / "README.md").read_text(encoding="utf-8") if EXPECTED_GATE_LINE not in readme: raise SystemExit(f"the README no longer prints this gate verdict line: {EXPECTED_GATE_LINE}")
def check_topology_and_nodes() -> None: """Six roles in the topology, six node folders of three files each, ASCII everywhere."""
topo = json.loads((ROOT / "topology.json").read_text(encoding="utf-8")) if sorted(inst["id"] for inst in topo.get("instances", [])) != sorted(ROLES): raise SystemExit("topology.json does not name exactly the six codex roles") for inst in topo.get("instances", []): if not str(inst.get("executable", "")).startswith("codex-python/"): raise SystemExit(f"topology.json executable '{inst.get('executable')}' is not folder relative") if len(topo.get("routingMatrix", [])) != 6: raise SystemExit("topology.json routing matrix does not hold six rows")
node_files = [p for role in ROLES for p in (ROOT / "nodes" / role).glob("*") if p.is_file()] if len(node_files) != EXPECTED_NODE_FILES: raise SystemExit(f"nodes/ holds {len(node_files)} files, the card states {EXPECTED_NODE_FILES}") for role in ROLES: for name in ("grammar.gf", "ontology.smt2", "seed_payload.json"): if not (ROOT / "nodes" / role / name).is_file(): raise SystemExit(f"nodes/{role}/{name} is missing") seed = json.loads((ROOT / "nodes" / role / "seed_payload.json").read_text(encoding="utf-8")) if seed.get("kind") != ENVELOPE_KIND or seed.get("sender") != role: raise SystemExit(f"nodes/{role}/seed_payload.json is not an envelope of this role") dossier = json.loads(seed["payload"]["abstractSyntaxTree"]) if "typecheck" not in dossier.get("required_gates", []) or "tests" not in dossier.get( "required_gates", [] ): raise SystemExit(f"nodes/{role}/seed_payload.json requires no gates")
if (ROOT / "lgcodex").exists(): raise SystemExit("the kernel must not be vendored here: lgcodex/ is present in this folder")
offenders = [] for path in local_files(): try: path.read_bytes().decode("ascii") except UnicodeDecodeError: offenders.append(str(path.relative_to(ROOT))) if offenders: raise SystemExit(f"non-ASCII text in {offenders}: this repository keeps every byte of prose ASCII")
def main(argv: List[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--repo", default=REPO) parser.add_argument("--token-env", default="HF_TOKEN") parser.add_argument("--plan", action="store_true", help="build the card and stage, upload nothing") parser.add_argument( "--prune", action="store_true", help="delete remote files the folder no longer holds instead of leaving them beside the new ones", ) args = parser.parse_args(argv)
readme = (ROOT / "README.md").read_text(encoding="utf-8") notes = [word for word in ("TODO", "FIXME", "lorem") if word.lower() in readme.lower()] if notes: raise SystemExit(f"README.md still holds working notes: {notes}")
check_gates_report() check_topology_and_nodes() tests, holders = count_tests() if tests != EXPECTED_TESTS or holders != EXPECTED_TEST_FILES: raise SystemExit( f"tests/ holds {tests} test functions in {holders} files, " f"the card states {EXPECTED_TESTS} in {EXPECTED_TEST_FILES}" )
staging = Path(tempfile.mkdtemp(prefix="publish-codex-python-")) try: files = local_files() if len(files) != EXPECTED_FILES: raise SystemExit(f"the staged tree has {len(files)} files, the tool expects {EXPECTED_FILES}") for path in files: target = staging / path.relative_to(ROOT) target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, target) (staging / "README.md").write_text(build_card(), encoding="utf-8")
sources = sorted(p for p in staging.rglob("*.py")) for path in sources: compile(path.read_text(encoding="utf-8"), str(path), "exec") executable = staging / "agents" / "python_agent.py" if not executable.is_file(): raise SystemExit("the staged tree is missing agents/python_agent.py")
print( f"{EXPECTED_GATES} gates CONFIRMED, {tests} tests in {holders} files, " f"{EXPECTED_NODE_FILES} node files" ) print(f"staged tree: {len(files)} files, sources compiled: {len(sources)}") if args.plan: print(f"card: {(staging / 'README.md').stat().st_size} bytes, nothing uploaded") return 0
token = os.environ.get(args.token_env, "") if not token: raise SystemExit(f"no token: set {args.token_env}, or pass --token-env NAME")
from huggingface_hub import HfApi, hf_hub_download # noqa: E402 (only needed to publish)
api = HfApi(token=token) who = 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")
expected = {str(p.relative_to(ROOT)).replace("\\", "/") for p in files} missing = sorted(expected - set(remote)) extra = sorted(set(remote) - expected - {".gitattributes"}) differ: List[str] = [] 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()) if local != hub: differ.append(name)
print(f"{len(remote)} objects on the hub, expected {EXPECTED_HUB_OBJECTS}, missing {missing}") print(f"extra {extra}, content differs {differ}")
if args.prune and extra: print("pruning files the folder no longer holds") 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") missing = sorted(expected - set(remote)) extra = sorted(set(remote) - expected - {".gitattributes"}) print( "after the removal: %d objects, missing %d, unexpected %d" % (len(remote), len(missing), len(extra)) ) finally: shutil.rmtree(staging, ignore_errors=True)
ok = (len(remote) == EXPECTED_HUB_OBJECTS and not missing and not extra and not differ) print("RESULT: %s" % ("ok" if ok else "check the numbers above")) return 0 if ok else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226"""Run deterministic gates for the external datasets/codex-python package."""
from __future__ import annotations
import argparseimport jsonimport shutilimport sysimport tempfilefrom pathlib import Pathfrom typing import Callable, Dict, List, Sequence, Tuple
ROOT = Path(__file__).resolve().parents[1]if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))sys.dont_write_bytecode = True
from lgpython._codex_bridge import ensure_codex_on_path # noqa: E402
ensure_codex_on_path(ROOT)
from lgcodex.adapter_contract import check_adapter_contract # noqa: E402from lgcodex.agents import ROLES # noqa: E402from lgcodex.decision import dossier_from_dict # noqa: E402from lgcodex.envelope import ENVELOPE_KIND # noqa: E402from lgcodex.types import ABSTAIN, CONFIRMED, REJECTED, VERDICTS, GateResult # noqa: E402
from lgpython.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter # noqa: E402from lgpython.ast_graph import discover_python_files, extract_python_graph # noqa: E402from lgpython.session import PythonWorkspaceSession # noqa: E402from lgpython.test_selector import select_python_tests # noqa: E402
FIXTURE_PKG = ROOT / "fixtures" / "sample_pkg"
def _confirmed(check: str, note: str) -> GateResult: return GateResult(CONFIRMED, check, note=note)
def _rejected(check: str, note: str, failed: Sequence[str] = ()) -> GateResult: return GateResult(REJECTED, check, failed_targets=tuple(failed), note=note)
def gate_adapter_contract() -> GateResult: check = "check_adapter_contract on PythonLanguageAdapter" adapter = PythonLanguageAdapter(FIXTURE_PKG) files = discover_python_files(FIXTURE_PKG) violations = check_adapter_contract(adapter, str(FIXTURE_PKG), files) if violations: return _rejected(check, "; ".join(violations), violations) return _confirmed(check, f"no violations for {adapter.meta().name}")
def gate_ast_graph() -> GateResult: check = "Python AST symbol, method, inheritance, and import graph" files = discover_python_files(FIXTURE_PKG) symbols, edges = extract_python_graph(FIXTURE_PKG, files) expected_syms = { "src/mathops.py::Accumulator", "src/mathops.py::BoundedAccumulator.add", "src/mathops.py::double_sum", "src/textops.py::format_sum", } missing = sorted(expected_syms - set(symbols)) if missing: return _rejected(check, f"missing symbols: {missing}", missing) expected_edges = { ("src/mathops.py::BoundedAccumulator", "src/mathops.py::Accumulator"), ("src/mathops.py::double_sum", "src/mathops.py::add_numbers"), ("src/textops.py", "src/mathops.py"), } missing_edges = sorted(str(e) for e in (expected_edges - set(edges))) if missing_edges: return _rejected(check, f"missing edges: {missing_edges}", missing_edges) return _confirmed(check, f"{len(symbols)} symbols, {len(edges)} edges extracted")
def gate_test_selection() -> GateResult: check = "import-aware Python test selection" selected = select_python_tests(FIXTURE_PKG, ["src/mathops.py"]) if "tests/test_mathops.py" not in selected or "tests/test_textops.py" not in selected: return _rejected(check, f"unexpected selection: {selected}", selected) return _confirmed(check, f"selected {len(selected)} dependent test file(s)")
def gate_strict_abstain_control() -> GateResult: check = "missing optional tools produce ABSTAIN and block verdict" adapter = StrictPythonLanguageAdapter(FIXTURE_PKG) gates = adapter.run_typecheck_and_lint(str(FIXTURE_PKG), ["src/mathops.py"]) if not any(g.verdict == ABSTAIN for g in gates): return _confirmed(check, "mypy and ruff are installed and ran cleanly") session = PythonWorkspaceSession(FIXTURE_PKG, strict_tools=True) res = session.verify("src/mathops.py") if res.verdict != "UNKNOWN" or res.reason != "GATE_ABSTAIN": return _rejected(check, f"expected UNKNOWN/GATE_ABSTAIN, got {res.verdict}/{res.reason}") return _confirmed(check, "missing static tools abstained and ended in UNKNOWN/GATE_ABSTAIN")
def gate_session_transactions() -> GateResult: check = "staged edit commit on VERIFIED and disk isolation on refusal" with tempfile.TemporaryDirectory(prefix="lgpython_gate_") as tmp_dir: ws = Path(tmp_dir) / "pkg" shutil.copytree(FIXTURE_PKG, ws) session = PythonWorkspaceSession(ws)
# 1. Clean edit commits atomically with assurance 3 clean = session.edit_file( "src/mathops.py", "return left + right", "return int(left + right)", commit=True, ) if clean.verdict != "VERIFIED" or clean.assurance != 3 or not clean.committed: return _rejected(check, f"clean edit failed: {clean.verdict}/{clean.reason}")
# 2. Broken syntax edit is refused and leaves file unchanged before = (ws / "src" / "mathops.py").read_text(encoding="utf-8") broken = session.edit_file( "src/mathops.py", "return int(left + right)", "return int(left +", commit=True, ) after = (ws / "src" / "mathops.py").read_text(encoding="utf-8") if broken.verdict != "UNKNOWN" or broken.committed or before != after: return _rejected(check, f"broken edit leaked or committed: {broken.verdict}")
# 3. Protected path is refused (ws / ".env").write_text("A=1\n", encoding="utf-8") secret = session.edit_file(".env", "A=1", "A=2", commit=True) if secret.verdict != "UNKNOWN" or secret.reason != "PROTECTED_PATH" or secret.committed: return _rejected(check, f"protected path was not blocked: {secret.verdict}/{secret.reason}")
return _confirmed(check, "clean edit committed VERIFIED (3); syntax error and protected path refused")
def gate_external_topology() -> GateResult: check = "external topology.json, node folders, and six subprocess turns" topo = json.loads((ROOT / "topology.json").read_text(encoding="utf-8")) ids = sorted(inst["id"] for inst in topo.get("instances", [])) if ids != sorted(ROLES) or topo.get("terminationCondition") != "FIXED_PIPELINE": return _rejected(check, f"unexpected topology instances: {ids}")
for role in ROLES: folder = ROOT / "nodes" / role for fname in ("grammar.gf", "ontology.smt2", "seed_payload.json"): if not (folder / fname).is_file(): return _rejected(check, f"missing {folder / fname}") seed = json.loads((folder / "seed_payload.json").read_text(encoding="utf-8")) if seed.get("kind") != ENVELOPE_KIND or seed.get("sender") != role: return _rejected(check, f"invalid seed in {folder}") dossier_from_dict(json.loads(seed["payload"]["abstractSyntaxTree"]))
with tempfile.TemporaryDirectory(prefix="lgpython_subproc_") as tmp_dir: ws = Path(tmp_dir) / "pkg" shutil.copytree(FIXTURE_PKG, ws) session = PythonWorkspaceSession(ws, use_subprocesses=True) res = session.verify("src/mathops.py") if res.verdict != "VERIFIED" or res.assurance != 3 or len(res.trace) != 7: return _rejected( check, f"subprocess topology returned {res.verdict}/{res.assurance} with {len(res.trace)} envelopes", ) return _confirmed(check, "6 node folders valid, 7 subprocess envelopes reached VERIFIED (3)")
GATES: Tuple[Tuple[str, Callable[[], GateResult]], ...] = ( ("adapter_contract", gate_adapter_contract), ("ast_symbol_graph", gate_ast_graph), ("test_selection", gate_test_selection), ("strict_abstain_control", gate_strict_abstain_control), ("session_transactions", gate_session_transactions), ("external_topology", gate_external_topology),)
def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser( description="Run deterministic gates for datasets/codex-python." ) parser.add_argument("--report", default=None, help="Optional path to write JSON report.") args = parser.parse_args(argv)
results: Dict[str, GateResult] = {} for name, fn in GATES: results[name] = fn()
counts = {v: 0 for v in VERDICTS} for res in results.values(): counts[res.verdict] = counts.get(res.verdict, 0) + 1
overall = REJECTED if counts[REJECTED] else (ABSTAIN if counts[ABSTAIN] else CONFIRMED) for name, _ in GATES: r = results[name] print(f"{name:<24} {r.verdict:<9} {r.note}") print( f"GATES: {overall} ({len(GATES)} gates: " + ", ".join(f"{counts[v]} {v}" for v in VERDICTS) + ")" )
if args.report: out_path = Path(args.report) out_path.parent.mkdir(parents=True, exist_ok=True) payload = { "schema": "lingologos-python-gates-1", "verdict": overall, "counts": counts, "gates": [ { "name": name, "verdict": results[name].verdict, "check": results[name].command, "note": results[name].note, "failed_targets": list(results[name].failed_targets), } for name, _ in GATES ], } out_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
return 1 if overall == REJECTED else 0
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677{ "$schema": "https://lingologos.spec/schemas/topology-v1.json", "sessionId": "lingologos-python-01", "maxTurns": 6, "terminationCondition": "FIXED_PIPELINE", "instances": [ { "id": "planner", "executable": "codex-python/agents/python_agent.py", "role": "planner" }, { "id": "retriever", "executable": "codex-python/agents/python_agent.py", "role": "retriever" }, { "id": "executor", "executable": "codex-python/agents/python_agent.py", "role": "executor" }, { "id": "gate_checker", "executable": "codex-python/agents/python_agent.py", "role": "gate_checker" }, { "id": "adversary", "executable": "codex-python/agents/python_agent.py", "role": "adversary" }, { "id": "arbiter", "executable": "codex-python/agents/python_agent.py", "role": "arbiter" } ], "routingMatrix": [ { "from": "planner", "to": [ "retriever" ] }, { "from": "retriever", "to": [ "executor" ] }, { "from": "executor", "to": [ "gate_checker", "adversary" ] }, { "from": "gate_checker", "to": [ "arbiter" ] }, { "from": "adversary", "to": [ "arbiter" ] }, { "from": "arbiter", "to": [ "planner" ] } ]}.gitignoreAdded+7
README.mdAdded+109
agents/python_agent.pyAdded+57
codex.python.jsonAdded+35
fixtures/sample_pkg/src/mathops.pyAdded+37
fixtures/sample_pkg/src/textops.pyAdded+11
fixtures/sample_pkg/tests/test_mathops.pyAdded+17
fixtures/sample_pkg/tests/test_textops.pyAdded+7
lgpython/__init__.pyAdded+45
lgpython/__main__.pyAdded+6
lgpython/_codex_bridge.pyAdded+59
lgpython/adapter.pyAdded+125
lgpython/ast_graph.pyAdded+298
lgpython/cli.pyAdded+197
lgpython/gates.pyAdded+174
lgpython/session.pyAdded+571
lgpython/test_selector.pyAdded+140
nodes/adversary/grammar.gfAdded+21
nodes/adversary/ontology.smt2Added+5
nodes/adversary/seed_payload.jsonAdded+19
nodes/arbiter/grammar.gfAdded+23
nodes/arbiter/ontology.smt2Added+7
nodes/arbiter/seed_payload.jsonAdded+19
nodes/executor/grammar.gfAdded+19
nodes/executor/ontology.smt2Added+6
nodes/executor/seed_payload.jsonAdded+19
nodes/gate_checker/grammar.gfAdded+23
nodes/gate_checker/ontology.smt2Added+6
nodes/gate_checker/seed_payload.jsonAdded+19
nodes/planner/grammar.gfAdded+25
nodes/planner/ontology.smt2Added+6
nodes/planner/seed_payload.jsonAdded+19
nodes/retriever/grammar.gfAdded+19
nodes/retriever/ontology.smt2Added+6
nodes/retriever/seed_payload.jsonAdded+19
pyproject.tomlAdded+33
requirements.txtAdded+1
results/gates.jsonAdded+53
tests/conftest.pyAdded+28
tests/test_adapter.pyAdded+90
tests/test_ast_graph.pyAdded+62
tests/test_session.pyAdded+95
tests/test_test_selector.pyAdded+34
tests/test_topology_and_cli.pyAdded+102
tools/publish_dataset.pyAdded+370
tools/run_gates.pyAdded+226
topology.jsonAdded+77