Upload folder using huggingface_hub
Browse filesFiles changed (14)
- README.md+41-10
- lingologos_python/ast_graph.py+31-2
- lingologos_python/cli.py+30-16
- lingologos_python/patterns.py+1-3
- lingologos_python/reasons.pyAdded+53
- lingologos_python/session.py+120-42
- results/gates.json+8-1
- tests/conftest.py+31
- tests/test_ast_graph.py+19
- tests/test_cli.py+11-1
- tests/test_reasons.pyAdded+63
- tests/test_session.py+53-26
- tools/publish_dataset.py+9-9
- tools/run_gates.py+70
31 unmodified lines3233343535363738383940418 unmodified lines50515253545556579 unmodified lines6768697071727374757677787974757677788081828384858687888990169 unmodified lines2602612622542552562632642652662672682692702 unmodified lines27327427527627727827928028128228328428528628728828929029129229329429529629729831 unmodified lines
```
python -B tools/run_gates.py
GATES: CONFIRMED (10 gates: 10 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
GATES: CONFIRMED (11 gates: 11 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
```
The gate runner is where this bundle states its numbers out loud: 10 gates, 121 tests across 9 files,
The gate runner is where this bundle states its numbers out loud: 11 gates, 130 tests across 10 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.8 unmodified lines- `lingologos_python/ast_graph.py`: AST symbol, method, inheritance, relative/absolute import, and call
graph extraction (`discover_python_files`, `extract_python_graph`, `importers_of`). A file whose bytes
are not UTF-8 text is named as a file and given no symbols, rather than decoded into inventions.
`discover_python_files` prunes a symlinked or junctioned directory instead of walking into it, and
`is_linked_path` answers for both kinds of link on every platform.
- `lingologos_python/test_selector.py`: import-aware Python test selection (`select_python_tests`).
A changed `conftest.py` selects every test under its folder, because a conftest carries fixtures no
import edge shows.9 unmodified lines that shape is worth changing, what must hold before the rule runs, what test locks the change, and the
reason codes it answers with when it refuses (`PATTERNS`, `pattern_card`, `scan_pattern`,
`plan_pattern`).
- `lingologos_python/reasons.py`: the single registry of every reason code this bundle answers with
(`REASON_CODES`), with the rule codes collected from `rules` so the registry cannot fall behind the
rules that raise them and the `self_lint` gate refusing to confirm when the registry and the card
below disagree.
- `lingologos_python/session.py`: `PythonWorkspaceSession` for safe staged verification and atomic disk
commits via `lingologos_codex.fsadapter` (`verify`, `edit_file`, `create_file`, `delete_file`,
`apply_pattern`, `run_retry_loop`, and `run_topology_subprocesses`). A commit re-reads what is on disk
and refuses with `PATCH_NOT_APPLIED` when the workspace moved while the six nodes were running. A
write the disk refuses part way is undone from the in-memory originals, so a run never reports a
change it did not land. A delete names the surviving files that import the module being removed,
and goes through the kernel's delete transaction rather than an unlink of the session's own. The
staging copy refuses a symlink or a Windows junction anywhere in the workspace, naming the linked
path with `LINKED_PATH_IN_WORKSPACE`, instead of judging a tree that is not the one on disk. In
subprocess mode each node has a budget (one hundred and twenty seconds by default); a node that
exhausts it ends the run as UNKNOWN with the reason `NODE_TIMEOUT`.
and goes through the kernel's delete transaction rather than an unlink of the session's own. A
symlink or a Windows junction anywhere in the workspace makes the session refuse with
`LINKED_PATH_IN_WORKSPACE`, naming the linked path: the staging copy refuses it and `verify` refuses
before any node runs, so no verdict is ever earned on a tree that is not the one on disk. In
subprocess mode each node has a budget (one hundred and twenty seconds by default) and an exhausted
node is killed together with the gates it had started, because a budget that leaks the node's own
children is not a budget; `--total-timeout SEC` caps the sum of the six waits. A run that exhausts
either budget answers UNKNOWN with the reason `NODE_TIMEOUT`.
- `lingologos_python/cli.py`: `lingologos_python` CLI (`verify`, `edit`, `create`, `delete`, `symbols`,
`select-tests`, `patterns list|show|scan|apply`, `check-adapter`).
- `fixtures/pattern_lab/`: a small package with one function planted in the shape of each card and169 unmodified linesthe removal without touching the disk. `verify --file ...` reports a verdict for a file without asking
for a change. With `--strict-tools` the run demands `mypy` and `ruff`: a gate that cannot run abstains,
and the session answers UNKNOWN with the reason `GATE_ABSTAIN` instead of reporting a check that never
happened. `patterns apply` also takes `--subprocesses`, which runs the six nodes as separate processes
instead of in this one, and `verify`, `edit` and `patterns apply` take `--node-timeout SEC` to set each
node's budget; a node that runs past it is answered `NODE_TIMEOUT`, not awaited forever.
happened. `--subprocesses` runs the six nodes as separate processes instead of in this one, and the
five session verbs all take the same budget flags: `--node-timeout SEC` sets each node's budget and
`--total-timeout SEC` caps the sum of the six waits, each node then getting the smaller of its budget
and the time the total still allows; a run that exhausts one is answered `NODE_TIMEOUT`, not awaited
forever. The budgets belong to subprocess mode: a run in this process is awaited without one.
`check-adapter` says whether the Python adapter holds the contract of the kernel, and exits non-zero
when it does not.2 unmodified linestheir answers, because a documented command that crashes breaks a promise even when every library call
beside it is correct.
## Reason codes
Every refusal names one code, and the set is a registry rather than a legend written for the card:
`lingologos_python/reasons.py` collects it, and the `self_lint` gate refuses to confirm when the
registry and this list disagree.
- Refusals the session raises itself: `PATH_POLICY`, `PATCH_NOT_APPLIED`, `NODE_TIMEOUT`,
`LINKED_PATH_IN_WORKSPACE`.
- Verdicts the codex kernel brings back: `GATE_REJECTED`, `GATE_ABSTAIN`.
- The refusal the catalog layer adds above the rules: `AMBIGUOUS_TARGET`.
- Preflight and shape refusals of the rules: `MISSING_TARGET_FILE`, `NO_SUCH_FUNCTION`,
`NOT_A_MODULE_FUNCTION`, `NOT_PARSEABLE`, `NOT_ASCII_TARGET`, `TAB_INDENTED_TARGET`, `CRLF_TARGET`,
`NO_TEST_FILE`, `NO_TEST_ANCHOR`, `AMBIGUOUS_TEST_ANCHOR`, `ALREADY_ANNOTATED`,
`NOT_A_MUTABLE_DEFAULT`, `ANNOTATED_MUTABLE_DEFAULT`, `GUARD_ALREADY_PRESENT`, `NO_DISPATCH_CHAIN`,
`BRANCH_SHAPE_MISMATCH`, `ALREADY_SCOPED`, `NO_BARE_OPEN`, `HANDLE_ESCAPE`,
`NOT_THE_FIRST_STATEMENT`, `ASYNC_TARGET`, `NON_LITERAL_ASSERT_MESSAGE`, `INVALID_COMPANION_PATH`,
`ANCHOR_OVERLAP`, `NO_BARE_EXCEPT`, `BARE_EXCEPT_RE_RAISES`, `EXCEPT_HANDLER_UNREADABLE`,
`NO_NONE_COMPARISON`, `NONE_COMPARISON_IS_CHAINED`, `NO_EMPTY_LEN_CHECK`,
`LEN_TARGET_IS_NOT_A_NAME`.
## Running
From the folder of this dataset, with `LINGOLOGOS_CODEX_ROOT` pointing at the folder of the kernel7 unmodified lines89101112131425 unmodified lines4041424344454647484950515253545556575859604361626364656667686970487172737475767778798081828384857 unmodified lines
import astimport osimport statfrom pathlib import Pathfrom typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple
25 unmodified lines return False
def is_linked_path(path: Path) -> bool: """True when the path is a symlink or, on Windows, any reparse point such as a junction.
Since Python 3.12 a Windows junction is no longer reported as a symlink, yet a directory walk still descends into it. The reparse attribute is the honest test. """ if path.is_symlink(): return True if os.name == "nt": try: attributes = path.lstat().st_file_attributes except OSError: return False return bool(attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT) return False
def discover_python_files(workspace: Path) -> List[str]: """Return sorted POSIX relative paths for all Python source files in workspace.""" """Return sorted POSIX relative paths for all Python source files in workspace.
Links are pruned rather than followed: a graph that quietly crossed a junction would describe files that are not part of the workspace. A session asked to change such a workspace refuses and names the link instead. """ 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") d for d in dirnames if d not in IGNORED_DIRS and not d.endswith(".egg-info") and not is_linked_path(Path(dirpath) / d) ) rel_dir = Path(dirpath).resolve().relative_to(root) for filename in sorted(filenames): if not filename.endswith(".py"): continue if is_linked_path(Path(dirpath) / filename): 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)29 unmodified lines3031323334353637383940413442434437383945464743484950515253495051545556575658596061626163646566676869707172737274757612 unmodified lines899091929394951 unmodified line979899989910010010110215 unmodified lines11811912012112212312410 unmodified lines13513613713813914014114 unmodified lines15615715815815916016116216316416516616716811 unmodified lines180181182176183184185186187188189190191192124 unmodified lines31731831932032132232329 unmodified lines ) sub = parser.add_subparsers(dest="command", required=True)
# Flags shared by every verb that opens a session: the same tools, the same # topology, and the same budgets answer from verify to delete. session_flags = argparse.ArgumentParser(add_help=False) session_flags.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") session_flags.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.") session_flags.add_argument("--node-timeout", type=float, default=120.0, metavar="SEC", help="Per-node budget when nodes run as subprocesses; an exhausted budget answers UNKNOWN.") session_flags.add_argument("--total-timeout", type=float, default=None, metavar="SEC", help="Cap the sum of the six node waits; each node gets the smaller of its budget and the remaining time.")
# verify p_verify = sub.add_parser("verify", help="Verify a Python workspace through the six-node codex pipeline.") p_verify = sub.add_parser("verify", parents=[session_flags], 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("--node-timeout", type=float, default=120.0, metavar="SEC", help="Per-node budget when nodes run as subprocesses; an exhausted budget answers UNKNOWN.") 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 = sub.add_parser("edit", parents=[session_flags], help="Propose, verify, and atomically commit a Python search-replace edit.") p_edit.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_edit.add_argument("--file", required=True, help="Relative Python file to edit.") p_edit.add_argument("--search", required=True, help="Search text block.") p_edit.add_argument("--replace", required=True, help="Replacement text block.") p_edit.add_argument("--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("--node-timeout", type=float, default=120.0, metavar="SEC", help="Per-node budget when nodes run as subprocesses; an exhausted budget answers UNKNOWN.") 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 = sub.add_parser("create", parents=[session_flags], 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.")
# delete p_delete = sub.add_parser( "delete", parents=[session_flags], help="Delete a Python file only when the full regression after its removal verifies.", ) p_delete.add_argument("--workspace", required=True, help="Target Python workspace directory.") p_delete.add_argument("--file", required=True, help="Relative Python file to delete.") p_delete.add_argument("--dry-run", action="store_true", help="Verify the removal without deleting from disk.") p_delete.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") p_delete.add_argument("--json", action="store_true", help="Print JSON output.")
# symbols12 unmodified lines # patterns p_pat = sub.add_parser( "patterns", parents=[session_flags], help="List, show, scan or apply the verified Python pattern catalog.", ) p_pat.add_argument("action", choices=("list", "show", "scan", "apply"))1 unmodified line p_pat.add_argument("--workspace", default=None, help="Target Python workspace for scan and apply.") p_pat.add_argument("--target", default=None, help="Target as path/to/file.py::function_name.") p_pat.add_argument("--dry-run", action="store_true", help="Verify the pair without committing.") p_pat.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") p_pat.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.") p_pat.add_argument("--node-timeout", type=float, default=120.0, metavar="SEC", help="Per-node budget when nodes run as subprocesses; an exhausted budget answers UNKNOWN.") p_pat.add_argument("--json", action="store_true", help="Print JSON output.")
# check-adapter15 unmodified lines strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, node_timeout_sec=args.node_timeout, total_budget_sec=args.total_timeout, ) res = session.verify(target_file=args.file) if args.json:10 unmodified lines use_subprocesses=args.subprocesses, min_assurance=min_assurance, node_timeout_sec=args.node_timeout, total_budget_sec=args.total_timeout, ) res = session.edit_file( args.file,14 unmodified lines
if args.command == "create": content = Path(args.content_file).read_text(encoding="utf-8", newline="") session = PythonWorkspaceSession(args.workspace, strict_tools=args.strict_tools) session = PythonWorkspaceSession( args.workspace, strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, node_timeout_sec=args.node_timeout, total_budget_sec=args.total_timeout, ) try: res = session.create_file(args.file, content, commit=not args.dry_run) except FileExistsError as exc:11 unmodified lines return 0 if res.committed or (args.dry_run and res.accepted) else 1
if args.command == "delete": session = PythonWorkspaceSession(args.workspace, strict_tools=args.strict_tools) session = PythonWorkspaceSession( args.workspace, strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, node_timeout_sec=args.node_timeout, total_budget_sec=args.total_timeout, ) try: res = session.delete_file(args.file, commit=not args.dry_run) except FileNotFoundError as exc:124 unmodified lines strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, node_timeout_sec=args.node_timeout, total_budget_sec=args.total_timeout, ) res = session.apply_pattern(args.pattern, target=args.target, commit=not args.dry_run) if args.json:26 unmodified lines272829303132333434353635363726 unmodified lines
from lingologos_python import rulesfrom lingologos_python.ast_graph import discover_python_filesfrom lingologos_python.reasons import AMBIGUOUS_TARGET # the refusal when a scan fits more than one target
# Target syntax: a workspace-relative path, then the module level function, split by "::".TARGET_SEPARATOR = "::"
# The refusal when a scan finds the card fits more than one target and the caller named none.AMBIGUOUS_TARGET = "AMBIGUOUS_TARGET"
FAMILIES: Tuple[str, ...] = ("contracts", "mutation", "resources", "shape", "typing")
# Refusals every card can answer with before its rule looks at the shape at all: the1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""One registry of every reason code this bundle can answer with.
A verdict is only useful when its reason can be looked up. Every REFUSED andevery UNKNOWN result names one of these codes: the pattern cases anchor theirnegative rows on them, the card lists all of them, and the self_lint gatechecks that the registry and the card agree so the two can never drift apart."""
from __future__ import annotations
from typing import Tuple
from lingologos_python import rules
# Refusals the session raises itself, before or around the six-node run.PATH_POLICY = "PATH_POLICY"PATCH_NOT_APPLIED = "PATCH_NOT_APPLIED"NODE_TIMEOUT = "NODE_TIMEOUT"LINKED_PATH_IN_WORKSPACE = "LINKED_PATH_IN_WORKSPACE"
SESSION_REASONS: Tuple[str, ...] = ( PATH_POLICY, PATCH_NOT_APPLIED, NODE_TIMEOUT, LINKED_PATH_IN_WORKSPACE,)
# Verdicts the codex kernel brings back when the gates fail or decline to answer.GATE_REJECTED = "GATE_REJECTED"GATE_ABSTAIN = "GATE_ABSTAIN"
KERNEL_REASONS: Tuple[str, ...] = (GATE_REJECTED, GATE_ABSTAIN)
# The refusal the catalog layer adds above the rules: a scan found the card fits# more than one target and the caller named none.AMBIGUOUS_TARGET = "AMBIGUOUS_TARGET"
PATTERN_REASONS: Tuple[str, ...] = (AMBIGUOUS_TARGET,)
# Preflight and shape refusals of the pattern rules, collected from the rules# module so the registry cannot fall behind the rules that raise them.RULE_REASONS: Tuple[str, ...] = tuple( value for name, value in vars(rules).items() if name.isupper() and isinstance(value, str) and value == name)
REASON_CODES = ( frozenset(SESSION_REASONS) | frozenset(KERNEL_REASONS) | frozenset(PATTERN_REASONS) | frozenset(RULE_REASONS))13 unmodified lines14151617171819202122232428 unmodified lines5354555657585960616263646566671 unmodified line6970716465666768727374757677192 unmodified lines2702712722672682692702712722732742752762772782792802812822832732742759 unmodified lines2852862872992882892902911 unmodified line29329429530729629729829913 unmodified lines31331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335433735535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439534834935035135235335435535635735839639739839940040140240336140440540636340740836540941036741141241341413 unmodified lines4284294304314324334345 unmodified lines44044144244344444544644744844937 unmodified lines48748848944249049149249349449549649719 unmodified lines5175185195205215225235245255265275285295305315325335345355365375385395405415425436 unmodified lines55055155255355455555655755855956013 unmodified linesimport jsonimport osimport shutilimport statimport signalimport subprocessimport sysimport tempfileimport timefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple28 unmodified lines IGNORED_DIRS, discover_python_files, importers_of, is_linked_path,)from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E402from lingologos_python.reasons import ( # noqa: E402 LINKED_PATH_IN_WORKSPACE, NODE_TIMEOUT, PATCH_NOT_APPLIED, PATH_POLICY,)
PYTHON_ROOT = Path(__file__).resolve().parent.parentDEFAULT_AGENT_SCRIPT = PYTHON_ROOT / "agents" / "python_agent.py"1 unmodified line
DEFAULT_ALLOWED_PATTERNS: Tuple[str, ...] = ("*.py", "*.pyi")
# Named session refusals, alongside the reason codes the rule catalog answers with.PATH_POLICY = "PATH_POLICY"PATCH_NOT_APPLIED = "PATCH_NOT_APPLIED"NODE_TIMEOUT = "NODE_TIMEOUT"LINKED_PATH_IN_WORKSPACE = "LINKED_PATH_IN_WORKSPACE"# The clock the budgets read. A module attribute so a test can name a deadline# without touching the clock of every other process on the machine._MONOTONIC = time.monotonic
class NodeTimeoutError(RuntimeError):192 unmodified lines return first, first + probe_note, text
def _is_linked(path: Path) -> bool: """True when the path is a symlink or, on Windows, any reparse point such as a junction.
Since Python 3.12 a Windows junction is no longer reported as a symlink, yet a directory walk still descends into it. The reparse attribute is the honest test. """ if path.is_symlink(): return True if os.name == "nt": try: attributes = path.lstat().st_file_attributes except OSError: return False return bool(attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT) return False
def _copy_workspace_for_staging(src_root: Path, dst_root: Path) -> None: """Copy a workspace cleanly without caches or virtual environments.
9 unmodified lines rel_dir = Path(dirpath).resolve().relative_to(root) for name in dirnames: entry = Path(dirpath) / name if _is_linked(entry): if is_linked_path(entry): raise WorkspaceLinkError( "linked directory in the workspace: '%s'" % (rel_dir / name).as_posix() )1 unmodified line target_dir.mkdir(parents=True, exist_ok=True) for name in filenames: src_file = Path(dirpath) / name if _is_linked(src_file): if is_linked_path(src_file): raise WorkspaceLinkError( "linked file in the workspace: '%s'" % (rel_dir / name).as_posix() )13 unmodified lines return env
def _kill_process_tree(proc: subprocess.Popen) -> None: """Kill a node and everything it started: a budget that leaks grandchildren is not a budget.
A node runs its own gates as children (pytest, a static checker), so killing only the direct child would leave those processes running past the budget. Windows gets the process tree through taskkill; elsewhere the node leads its own process group and the whole group is signalled. """ if os.name == "nt": done = subprocess.run( ["taskkill", "/T", "/F", "/PID", str(proc.pid)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) if done.returncode == 0: return else: try: os.killpg(os.getpgid(proc.pid), signal.SIGKILL) except OSError: pass try: proc.kill() except OSError: pass
def run_topology_subprocesses( case: Dict[str, Any], *, agent_script: Optional[Path] = None, timeout_sec: float = 120.0, total_budget_sec: Optional[float] = None,) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: """Execute the six roles via isolated node subprocesses communicating over JSON stdio.
The agent script is read from the module at call time, so a caller that names a different six-node executable gets it, and the per-node budget is the one asked for rather than one frozen at import. asked for rather than one frozen at import. A budget is honest only if it reaches the whole tree: an exhausted node is killed together with the gates it had started. ``total_budget_sec`` caps the sum of the six waits, and each node then gets the smaller of its own budget and the time the total still allows. """ script = Path(agent_script) if agent_script else DEFAULT_AGENT_SCRIPT if timeout_sec <= 0 or (total_budget_sec is not None and total_budget_sec <= 0): raise ValueError("budgets must be positive numbers of seconds") seed = _envelope.make_envelope("arbiter", 0, 0, "task received", dict(case)) trace: List[Dict[str, Any]] = [seed] current = seed env = _subprocess_env() deadline = _MONOTONIC() + total_budget_sec if total_budget_sec else None
for role in ROLES: node_timeout = timeout_sec if deadline is not None: remaining = deadline - _MONOTONIC() if remaining <= 0: raise NodeTimeoutError( "the run exhausted its %s s total budget before node '%s' started" % (total_budget_sec, role) ) node_timeout = min(timeout_sec, remaining) cmd = [sys.executable, "-B", str(script), "--role", role, "--node-id", role] popen_kwargs: Dict[str, Any] = dict( stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", cwd=str(PYTHON_ROOT), env=env, ) if os.name == "nt": popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP else: popen_kwargs["start_new_session"] = True proc = subprocess.Popen(cmd, **popen_kwargs) try: 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, ) stdout, stderr = proc.communicate(input=json.dumps(current), timeout=node_timeout) except subprocess.TimeoutExpired as exc: _kill_process_tree(proc) try: proc.communicate(timeout=5) except (subprocess.TimeoutExpired, ValueError, OSError): pass raise NodeTimeoutError( "node '%s' exhausted its %s s budget without answering" % (role, timeout_sec) "node '%s' exhausted its %s s budget without answering" % (role, round(node_timeout, 3)) ) from exc if completed.returncode != 0: if proc.returncode != 0: raise RuntimeError( f"node '{role}' exited with {completed.returncode}: {completed.stderr.strip()}" f"node '{role}' exited with {proc.returncode}: {(stderr or '').strip()}" ) current = json.loads(completed.stdout) current = json.loads(stdout) trace.append(current) return trace, _envelope.read_dossier(current)
13 unmodified lines use_subprocesses: bool = False, min_assurance: int = 3, node_timeout_sec: float = 120.0, total_budget_sec: Optional[float] = None, ) -> None: self.workspace_root = Path(workspace_root).resolve() if not self.workspace_root.is_dir():5 unmodified lines 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) if node_timeout_sec <= 0 or (total_budget_sec is not None and total_budget_sec <= 0): raise ValueError("budgets must be positive numbers of seconds") self.node_timeout_sec = float(node_timeout_sec) self.total_budget_sec = float(total_budget_sec) if total_budget_sec else None
def policy_dict(self, root: Optional[Path] = None) -> Dict[str, Any]: return {37 unmodified lines def _run_six_nodes(self, case: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: try: if self.use_subprocesses: return run_topology_subprocesses(case, timeout_sec=self.node_timeout_sec) return run_topology_subprocesses( case, timeout_sec=self.node_timeout_sec, total_budget_sec=self.total_budget_sec, ) return run_pipeline(case) except NodeTimeoutError as exc: # A node that exhausts its budget abstains: the session answers19 unmodified lines touched_files=(rel_posix,), )
def _linked_path_in_workspace(self) -> Optional[Tuple[str, str]]: """Return ('directory'|'file', rel_posix) for the first link under the root.
Verify judges the workspace where it stands, with no staging copy to refuse for it, so it asks the same question the copy asks: is any part of this tree somewhere else. """ root = Path(self.workspace_root).resolve() for dirpath, dirnames, filenames in os.walk(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(root) for name in dirnames: if is_linked_path(Path(dirpath) / name): return ("directory", (rel_dir / name).as_posix()) for name in filenames: if is_linked_path(Path(dirpath) / name): return ("file", (rel_dir / name).as_posix()) return None
def list_files(self) -> List[str]: """Return all Python source files in the workspace.""" return discover_python_files(self.workspace_root)6 unmodified lines note: str = "verify Python workspace against codex gates", ) -> SessionResult: """Verify an existing file or the whole Python workspace without modifying disk.""" linked = self._linked_path_in_workspace() if linked is not None: kind, rel = linked exc = WorkspaceLinkError("linked %s in the workspace: '%s'" % (kind, rel)) return self._link_refusal(case_id, rel, exc) 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("/"))1 unmodified line2345567867 unmodified lines767778798081828384858687881 unmodified line "schema": "lingologos-python-gates-1", "verdict": "CONFIRMED", "counts": { "CONFIRMED": 10, "CONFIRMED": 11, "REJECTED": 0, "ABSTAIN": 0 },67 unmodified lines "check": "patterns/coverage.json states a denominator this fixture still supports", "note": "8 cards over 8 source files and 21 module level functions, denominator stated as the fixture", "failed_targets": [] }, { "name": "self_lint", "verdict": "CONFIRMED", "check": "the package reads itself: modules compile, the graph spans them, the reason registry matches the card", "note": "12 modules parse, compile, and carry docstrings; own graph has 149 symbols and 312 edges; 38 reason codes, every one named in the card", "failed_targets": [] } ]}1 unmodified line23456789101110 unmodified lines222324252627282930313233343536373839404142434445464748495051525354551 unmodified line
from __future__ import annotations
import osimport shutilimport statimport subprocessimport sysfrom pathlib import Path
10 unmodified linesensure_codex_on_path(PYTHON_ROOT)
def make_dir_link(link: Path, target: Path) -> bool: """Create a directory link, junction on Windows, and report whether it exists.""" try: os.symlink(str(target), str(link), target_is_directory=True) return link.is_symlink() except (OSError, NotImplementedError): pass if os.name == "nt": done = subprocess.run( ["cmd", "/c", "mklink", "/J", str(link), str(target)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) if done.returncode != 0: return False # Python 3.12 no longer calls a junction a symlink, so check the reparse bit. attributes = getattr(link.lstat(), "st_file_attributes", 0) return bool(attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT) return False
@pytest.fixturedef dir_link() -> "object": """Fixture form of make_dir_link, for tests that must skip when the host refuses.""" return make_dir_link
@pytest.fixturedef sample_pkg(tmp_path: Path) -> Path: """Copy fixtures/sample_pkg into a clean temporary directory per test."""4 unmodified lines56789101112131415161713 unmodified lines313233343536373839404142434445464748495051524 unmodified linesimport codecsfrom pathlib import Path
import pytest
from lingologos_python.ast_graph import ( discover_python_files, extract_python_graph, importers_of, is_linked_path, module_names_for_file,)
13 unmodified lines ]
def test_discover_python_files_prunes_links_instead_of_following_them( sample_pkg: Path, tmp_path: Path, dir_link) -> None: """A junction must not drag files that live outside the workspace into the graph.""" outside = tmp_path / "outside" outside.mkdir() (outside / "faraway.py").write_text("x = 1\n", encoding="utf-8", newline="") if not dir_link(sample_pkg / "vendor", outside): pytest.skip("this host offers no way to create a directory link") files = discover_python_files(sample_pkg) assert not any(rel.startswith("vendor/") for rel in files) assert "vendor/faraway.py" not in files assert is_linked_path(sample_pkg / "vendor") assert not is_linked_path(sample_pkg / "src" / "mathops.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")244 unmodified lines245246247248248249250251252253254255256257258259260261244 unmodified lines
def test_delete_exits_zero_only_once_the_file_is_really_gone(tmp_path: Path) -> None: ws = _delete_workspace(tmp_path) proc = run_cli("delete", "--workspace", str(ws), "--file", "src/helper.py") proc = run_cli( "delete", "--workspace", str(ws), "--file", "src/helper.py", "--node-timeout", "60", "--total-timeout", "300", ) assert proc.returncode == 0, proc.stdout + proc.stderr assert "committed=True" in proc.stdout assert not (ws / "src" / "helper.py").exists()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""Tests for the reason registry: the alphabet every refusal of this bundle answers in."""
from __future__ import annotations
from pathlib import Path
from lingologos_python import rulesfrom lingologos_python import session as session_modulefrom lingologos_python.reasons import ( AMBIGUOUS_TARGET, GATE_ABSTAIN, GATE_REJECTED, KERNEL_REASONS, LINKED_PATH_IN_WORKSPACE, NODE_TIMEOUT, PATCH_NOT_APPLIED, PATH_POLICY, PATTERN_REASONS, REASON_CODES, RULE_REASONS, SESSION_REASONS,)
ROOT = Path(__file__).resolve().parents[1]
def test_the_registry_holds_the_session_and_the_kernel_answers() -> None: """The refusals the session and the catalog raise, and the verdicts the kernel returns, are codes.""" assert set(SESSION_REASONS) == { PATH_POLICY, PATCH_NOT_APPLIED, NODE_TIMEOUT, LINKED_PATH_IN_WORKSPACE, } assert set(KERNEL_REASONS) == {GATE_REJECTED, GATE_ABSTAIN} assert set(PATTERN_REASONS) == {AMBIGUOUS_TARGET} assert set(SESSION_REASONS) | set(KERNEL_REASONS) | set(PATTERN_REASONS) <= REASON_CODES
def test_the_registry_keeps_pace_with_the_rules() -> None: """Every self-valued constant in rules is a registered code, in definition order.""" self_valued = { value for name, value in vars(rules).items() if name.isupper() and isinstance(value, str) and value == name } assert set(RULE_REASONS) == self_valued assert self_valued <= REASON_CODES assert len(RULE_REASONS) == len(self_valued)
def test_the_session_still_answers_with_registered_codes() -> None: """The names the session and its tests import are the registry names, not copies.""" for name in ("PATH_POLICY", "PATCH_NOT_APPLIED", "NODE_TIMEOUT", "LINKED_PATH_IN_WORKSPACE"): assert getattr(session_module, name) in REASON_CODES assert getattr(session_module, name) == name
def test_every_registered_code_is_named_in_the_card() -> None: """A code the bundle can answer with must be listed in the card a reader holds.""" readme = (ROOT / "README.md").read_text(encoding="utf-8", newline="") unnamed = sorted(code for code in REASON_CODES if "`%s`" % code not in readme) assert unnamed == []2 unmodified lines3456767813 unmodified lines22232427282930313233343536373839404142434445464748252627265 unmodified lines29329429532029629729829930030130232730330430530653 unmodified lines3603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124132 unmodified linesfrom __future__ import annotations
import osimport statimport subprocessfrom pathlib import Pathfrom typing import Any, Dict, Tuple
13 unmodified lines)
def _make_dir_link(link: Path, target: Path) -> bool: """Create a directory link, junction on Windows, and report whether it exists.""" try: os.symlink(str(target), str(link), target_is_directory=True) return link.is_symlink() except (OSError, NotImplementedError): pass if os.name == "nt": done = subprocess.run( ["cmd", "/c", "mklink", "/J", str(link), str(target)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) if done.returncode != 0: return False # Python 3.12 no longer calls a junction a symlink, so check the reparse bit. attributes = getattr(link.lstat(), "st_file_attributes", 0) return bool(attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT) return False
def test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py")265 unmodified lines
def test_a_linked_directory_in_the_workspace_refuses_any_staged_run( sample_pkg: Path, tmp_path: Path sample_pkg: Path, tmp_path: Path, dir_link) -> None: """A junction or symlink makes the staging copy lie, so the session refuses by name.""" outside = tmp_path / "outside" outside.mkdir() (outside / "elsewhere.py").write_text("SECRET = 1\n", encoding="ascii", newline="") link = sample_pkg / "vendor" if not _make_dir_link(link, outside): if not dir_link(link, outside): pytest.skip("this host offers no way to create a directory link")
session = PythonWorkspaceSession(sample_pkg)53 unmodified lines assert res.reason == NODE_TIMEOUT assert res.assurance == 0 assert res.committed is False
def test_a_total_budget_shrinks_the_wait_of_the_first_node(tmp_path: Path) -> None: """A node gets the smaller of its own budget and what the total still allows.""" stub = tmp_path / "sleeping_agent.py" stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="") with pytest.raises(NodeTimeoutError) as caught: session_module.run_topology_subprocesses( {"case_id": "total"}, agent_script=stub, timeout_sec=30.0, total_budget_sec=1.0 ) assert "exhausted its 1.0 s budget" in str(caught.value)
def test_a_spent_total_budget_refuses_a_node_before_starting_it(tmp_path: Path, monkeypatch) -> None: """Once the total is gone, the run says so instead of paying for one more node.""" echo = tmp_path / "echo_agent.py" echo.write_text("import sys\n\nsys.stdout.write(sys.stdin.read())\n", encoding="ascii", newline="") clock = iter([1000.0, 1000.5, 2000.0]) monkeypatch.setattr(session_module, "_MONOTONIC", lambda: next(clock)) with pytest.raises(NodeTimeoutError) as caught: session_module.run_topology_subprocesses( {"case_id": "late"}, agent_script=echo, timeout_sec=10.0, total_budget_sec=5.0 ) assert "total budget" in str(caught.value)
def test_a_nonpositive_budget_is_refused_before_anything_runs(sample_pkg: Path) -> None: """A budget of zero seconds is a mistake, not a promise to abstain instantly.""" with pytest.raises(ValueError): session_module.run_topology_subprocesses({"case_id": "bad"}, timeout_sec=0.0) with pytest.raises(ValueError): PythonWorkspaceSession(sample_pkg, total_budget_sec=-1.0)
def test_verify_refuses_a_workspace_held_together_by_a_link( sample_pkg: Path, tmp_path: Path, dir_link) -> None: """verify has no staging copy to refuse for it, so it asks the link question itself.""" outside = tmp_path / "outside" outside.mkdir() (outside / "elsewhere.py").write_text("VALUE = 1\n", encoding="ascii", newline="") link = sample_pkg / "vendor" if not dir_link(link, outside): pytest.skip("this host offers no way to create a directory link") session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py") assert res.verdict == "REFUSED" assert res.reason == LINKED_PATH_IN_WORKSPACE assert res.assurance == 0 assert "vendor" in res.detail assert res.touched_files == ("vendor",)13 unmodified lines141516171718192019 unmodified lines4041424344454647434445464748494950515237 unmodified lines909192939394959596979813 unmodified linesThis bundle carries no kernel. It carries one corpus of its own, the sixteen pattern cases under`patterns/`, generated from the rules and the fixture beside them, and the card states theirdenominator rather than letting sixteen rows look like a benchmark. Every number the card states(10 gates, 113 tests, 18 node files, the staged file count) is re-derived from this tree before a(11 gates, 130 tests, 18 node files, the staged file count) is re-derived from this tree before asingle object is uploaded. A card that contradicts the code beside it stops the run instead ofpublishing.
19 unmodified linesROOT = Path(__file__).resolve().parents[1]
REPO = "tailot/codex-python"EXPECTED_FILES = 72 # the staged tree: 72 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 73 # those 72 plus the .gitattributes the hub addsEXPECTED_GATES = 10EXPECTED_TESTS = 121EXPECTED_TEST_FILES = 9EXPECTED_FILES = 74 # the staged tree: 74 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 75 # those 74 plus the .gitattributes the hub addsEXPECTED_GATES = 11EXPECTED_TESTS = 130EXPECTED_TEST_FILES = 10EXPECTED_NODE_FILES = 18EXPECTED_GATE_LINE = "GATES: CONFIRMED (10 gates: 10 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"EXPECTED_GATE_LINE = "GATES: CONFIRMED (11 gates: 11 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"}37 unmodified lines "\"What this bundle needs from the codex kernel\" below says how the two find each other.", ), ( "The gate runner is where this bundle states its numbers out loud: 10 gates, 121 tests across 9 files,\n" "The gate runner is where this bundle states its numbers out loud: 11 gates, 130 tests across 10 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: 10 gates, 121 tests across 9 files,\n" "The gate runner is where this bundle states its numbers out loud: 11 gates, 130 tests across 10 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.",2 unmodified lines345678922 unmodified lines32333435363738308 unmodified lines3473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184195 unmodified lines4254264274284294304312 unmodified linesfrom __future__ import annotations
import argparseimport astimport jsonimport shutilimport subprocess22 unmodified linesfrom lingologos_python.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter # noqa: E402from lingologos_python.ast_graph import discover_python_files, extract_python_graph # noqa: E402from lingologos_python.patterns import PATTERNS, module_level_functions, plan_pattern # noqa: E402from lingologos_python.reasons import REASON_CODES # noqa: E402from lingologos_python.session import PythonWorkspaceSession # noqa: E402from lingologos_python.test_selector import select_python_tests # noqa: E402
308 unmodified lines )
def _self_valued_codes(text: str) -> List[str]: """Reason-code constants of the form NAME = "NAME" at the top level of a module.""" codes: List[str] = [] for node in ast.parse(text).body: if not isinstance(node, ast.Assign) or len(node.targets) != 1: continue target = node.targets[0] if ( isinstance(target, ast.Name) and target.id.isupper() and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str) and node.value.value == target.id ): codes.append(target.id) return codes
def gate_self_lint() -> GateResult: check = "the package reads itself: modules compile, the graph spans them, the reason registry matches the card" pkg = ROOT / "lingologos_python" files = discover_python_files(pkg) if len(files) < 10: return _rejected(check, f"only {len(files)} modules discovered inside the package") broken: List[str] = [] undocumented: List[str] = [] for rel in files: text = (pkg / rel).read_text(encoding="utf-8", newline="") try: tree = ast.parse(text) compile(tree, rel, "exec") except SyntaxError: broken.append(rel) continue if not ast.get_docstring(tree): undocumented.append(rel) if broken: return _rejected(check, f"modules that no longer compile: {broken}", broken) if undocumented: return _rejected(check, f"modules without a module docstring: {undocumented}", undocumented) symbols, edges = extract_python_graph(pkg, files) if not symbols or not edges: return _rejected(check, "the package graph came back empty") defined: List[str] = [] for rel in files: defined.extend(_self_valued_codes((pkg / rel).read_text(encoding="utf-8", newline=""))) unregistered = sorted(set(defined) - REASON_CODES) if unregistered: return _rejected( check, f"reason codes raised somewhere but absent from the registry: {unregistered}", unregistered, ) readme = (ROOT / "README.md").read_text(encoding="utf-8", newline="") unnamed = sorted(code for code in REASON_CODES if "`%s`" % code not in readme) if unnamed: return _rejected( check, f"reason codes the card never names: {unnamed}", unnamed ) return _confirmed( check, "%d modules parse, compile, and carry docstrings; own graph has %d symbols and %d edges; " "%d reason codes, every one named in the card" % (len(files), len(symbols), len(edges), len(REASON_CODES)), )
GATES: Tuple[Tuple[str, Callable[[], GateResult]], ...] = ( ("adapter_contract", gate_adapter_contract), ("ast_symbol_graph", gate_ast_graph),5 unmodified lines ("pattern_round_trip", gate_pattern_round_trip), ("pattern_pair_honesty", gate_pattern_pair_honesty), ("pattern_coverage", gate_pattern_coverage), ("self_lint", gate_self_lint),)
README.md+41-10
lingologos_python/ast_graph.py+31-2
lingologos_python/cli.py+30-16
lingologos_python/patterns.py+1-3
lingologos_python/reasons.pyAdded+53
lingologos_python/session.py+120-42
results/gates.json+8-1
tests/conftest.py+31
tests/test_ast_graph.py+19
tests/test_cli.py+11-1
tests/test_reasons.pyAdded+63
tests/test_session.py+53-26
tools/publish_dataset.py+9-9
tools/run_gates.py+70