Upload folder using huggingface_hub
Browse filesFiles changed (11)
34 unmodified lines3536373839404137 unmodified lines7980818283848586177 unmodified lines2642652662672682692706 unmodified lines27727827928028128228334 unmodified linesGATES: CONFIRMED (11 gates: 11 CONFIRMED, 0 REJECTED, 0 ABSTAIN)```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 everyone of those numbers from the tree it is standing in and stops the upload when the card and the codebeside it disagree.37 unmodified lineschange 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. Asymlink 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` refusesbefore any node runs, so no verdict is ever earned on a tree that is not the one on disk. Insubprocess mode each node has a budget (one hundred and twenty seconds by default) and an exhaustednode is killed together with the gates it had started, because a budget that leaks the node's ownchildren is not a budget; `--total-timeout SEC` caps the sum of the six waits. A run that exhausts177 unmodified linesfive 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 budgetand the time the total still allows; a run that exhausts one is answered `NODE_TIMEOUT`, not awaitedforever. 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-zerowhen it does not.6 unmodified linesEvery 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 theregistry and this list disagree.- Refusals the session raises itself: `PATH_POLICY`, `PATCH_NOT_APPLIED`, `NODE_TIMEOUT`,`LINKED_PATH_IN_WORKSPACE`.34 unmodified lines3536373839404137 unmodified lines798081828384858687177 unmodified lines2652662672682692702712722732742756 unmodified lines28228328428528628728828934 unmodified linesGATES: CONFIRMED (11 gates: 11 CONFIRMED, 0 REJECTED, 0 ABSTAIN)```The gate runner is where this bundle states its numbers out loud: 11 gates, 138 tests across 11 files,18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives everyone of those numbers from the tree it is standing in and stops the upload when the card and the codebeside it disagree.37 unmodified lineschange 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. Asymlink 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, `verify` refusesbefore any node runs, and every commit re-asks the question before it writes, so a link that appearedwhile the six nodes were running is refused too, not landed through. Insubprocess mode each node has a budget (one hundred and twenty seconds by default) and an exhaustednode is killed together with the gates it had started, because a budget that leaks the node's ownchildren is not a budget; `--total-timeout SEC` caps the sum of the six waits. A run that exhausts177 unmodified linesfive 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 budgetand the time the total still allows; a run that exhausts one is answered `NODE_TIMEOUT`, not awaitedforever. Node budgets belong to subprocess mode: a run in this process is awaited without one. Everyrun, in whichever mode, also budgets each runner command it launches, the test gate and any staticchecker, through `--gate-timeout SEC`, one hundred and twenty seconds by default: a runner that outrunsit is killed and answered with the named abstain `GATE_ABSTAIN`, because a hung test run is not apassing test run.`check-adapter` says whether the Python adapter holds the contract of the kernel, and exits non-zerowhen it does not.6 unmodified linesEvery 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 theregistry and this list disagree, or when a name the Contents promises in parentheses is one no moduleof the package defines.- Refusals the session raises itself: `PATH_POLICY`, `PATCH_NOT_APPLIED`, `NODE_TIMEOUT`,`LINKED_PATH_IN_WORKSPACE`.
26 unmodified lines27282930313218 unmodified lines51525354555657585956 unmodified lines11611711811912012112226 unmodified linesADAPTER_NAME = "lingologos-python"ADAPTER_VERSION = "0.1.0"DEFAULT_TOOL_ARGS: Dict[str, Tuple[str, ...]] = {"mypy": ("--ignore-missing-imports", "--no-incremental"),"pyright": (),18 unmodified lines*,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)56 unmodified linesclass 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"),26 unmodified lines272829303132333435363738394041424344454647484918 unmodified lines68697071727374757656 unmodified lines13313413513613713813926 unmodified linesADAPTER_NAME = "lingologos-python"ADAPTER_VERSION = "0.1.0"# The wall-clock budget every runner command obeys. The kernel instantiates this# class from a reference string and cannot pass it a per-session number, so the# environment is the channel the session uses to hand it down.GATE_TIMEOUT_ENV = "LINGOLOGOS_PY_GATE_TIMEOUT"DEFAULT_GATE_TIMEOUT_SEC = 120.0def _resolve_gate_timeout(timeout_sec: float | None) -> float:"""An explicit argument wins; otherwise the environment names it; otherwise 120 s."""if timeout_sec is not None:return float(timeout_sec)try:value = float(os.environ.get(GATE_TIMEOUT_ENV, ""))except ValueError:return DEFAULT_GATE_TIMEOUT_SECreturn value if value > 0 else DEFAULT_GATE_TIMEOUT_SECDEFAULT_TOOL_ARGS: Dict[str, Tuple[str, ...]] = {"mypy": ("--ignore-missing-imports", "--no-incremental"),"pyright": (),18 unmodified lines*,require_tools: Sequence[str] = (),use_installed_tools: bool = False,timeout_sec: float | None = None,) -> None:super().__init__(workspace_root, timeout_sec=_resolve_gate_timeout(timeout_sec))self.require_tools: Tuple[str, ...] = tuple(require_tools)self.use_installed_tools: bool = bool(use_installed_tools)56 unmodified linesclass StrictPythonLanguageAdapter(PythonLanguageAdapter):"""Variant that always demands mypy and ruff, abstaining when either is absent."""def __init__(self, workspace_root: str | Path, timeout_sec: float | None = None) -> None:super().__init__(workspace_root,require_tools=("mypy", "ruff"),
36 unmodified lines37383940414276 unmodified lines11912012112212312411 unmodified lines13613713813914014120 unmodified lines16216316416516616718 unmodified lines186187188189190191126 unmodified lines31831932032132232336 unmodified linessession_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.")# verifyp_verify = sub.add_parser("verify", parents=[session_flags], help="Verify a Python workspace through the six-node codex pipeline.")76 unmodified linesuse_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:11 unmodified linesmin_assurance=min_assurance,node_timeout_sec=args.node_timeout,total_budget_sec=args.total_timeout,)res = session.edit_file(args.file,20 unmodified linesuse_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)18 unmodified linesuse_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)126 unmodified linesuse_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:36 unmodified lines3738394041424376 unmodified lines12012112212312412512611 unmodified lines13813914014114214314420 unmodified lines16516616716816917017118 unmodified lines190191192193194195196126 unmodified lines32332432532632732832936 unmodified linessession_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.")session_flags.add_argument("--gate-timeout", type=float, default=None, metavar="SEC", help="Wall-clock budget for each gate command (test runner, static checker); a runner that exhausts it abstains.")# verifyp_verify = sub.add_parser("verify", parents=[session_flags], help="Verify a Python workspace through the six-node codex pipeline.")76 unmodified linesuse_subprocesses=args.subprocesses,node_timeout_sec=args.node_timeout,total_budget_sec=args.total_timeout,gate_timeout_sec=args.gate_timeout,)res = session.verify(target_file=args.file)if args.json:11 unmodified linesmin_assurance=min_assurance,node_timeout_sec=args.node_timeout,total_budget_sec=args.total_timeout,gate_timeout_sec=args.gate_timeout,)res = session.edit_file(args.file,20 unmodified linesuse_subprocesses=args.subprocesses,node_timeout_sec=args.node_timeout,total_budget_sec=args.total_timeout,gate_timeout_sec=args.gate_timeout,)try:res = session.create_file(args.file, content, commit=not args.dry_run)18 unmodified linesuse_subprocesses=args.subprocesses,node_timeout_sec=args.node_timeout,total_budget_sec=args.total_timeout,gate_timeout_sec=args.gate_timeout,)try:res = session.delete_file(args.file, commit=not args.dry_run)126 unmodified linesuse_subprocesses=args.subprocesses,node_timeout_sec=args.node_timeout,total_budget_sec=args.total_timeout,gate_timeout_sec=args.gate_timeout,)res = session.apply_pattern(args.pattern, target=args.target, commit=not args.dry_run)if args.json:
48 unmodified lines495051525354374 unmodified lines4294304314324334345 unmodified lines44044144244344444544644744844934 unmodified lines48448548648748848949013 unmodified lines50450550650750850928 unmodified lines538539540541542543141 unmodified lines685686687688689690691193 unmodified lines88588688788888989089189289389489591 unmodified lines98798898999099199299388 unmodified lines108210831084108510861087108848 unmodified linesapply_controlled_fuzzy_patch,)from lingologos_python.ast_graph import ( # noqa: E402IGNORED_DIRS,discover_python_files,374 unmodified linesmin_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 linesself.spec_path = str(Path(spec_path).resolve()) if spec_path else Noneself.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 Nonedef policy_dict(self, root: Optional[Path] = None) -> Dict[str, Any]:return {34 unmodified linesreturn {"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]]:try:if self.use_subprocesses:return run_topology_subprocesses(13 unmodified lines"detail": str(exc),}}def _link_refusal(self, case_id: str, rel_posix: str, exc: WorkspaceLinkError) -> SessionResult:"""A workspace held together by links cannot be copied to staging faithfully."""28 unmodified linesreturn ("file", (rel_dir / name).as_posix())return Nonedef list_files(self) -> List[str]:"""Return all Python source files in the workspace."""return discover_python_files(self.workspace_root)141 unmodified linescommitted = Falseif commit and patch_res.applied and not plan.rejected and assurance >= self.min_assurance:if _disk_text(self.workspace_root, rel_posix) != original_text:# The workspace moved while the six nodes were running: the patch that# was verified is no longer the patch for the file on disk, so nothing# is written and the run reports the named refusal instead.193 unmodified linescommitted = Falseif commit and assurance >= needed:drifted = [edit.file for edit in plan.editsif _disk_text(self.workspace_root, edit.file) != originals[edit.file]]if drifted:# The pair was verified against the workspace as it was at staging time.# If a file of the pair moved since, the anchors proven in staging are# not the anchors of what is on disk, so the pair is not written.91 unmodified linesdetail = str(decision.get("detail", ""))committed = Falseif commit and not plan.rejected and assurance >= self.min_assurance:if target.is_file():# The verified text was staged as a new file. If a file landed at that# path while the run was going, writing would replace something the# six nodes never saw, so the create is not committed.88 unmodified linesdetail = str(decision.get("detail", ""))committed = Falseif commit and not plan.rejected and assurance >= self.min_assurance:if _disk_text(self.workspace_root, rel_posix) != original_text:# The file moved while the six nodes were running: the removal that was# verified is no longer the removal of what is on disk.verdict = "REFUSED"48 unmodified lines49505152535455374 unmodified lines4304314324334344354365 unmodified lines44244344444544644744844945045145245345445545634 unmodified lines49149249349449549649749849950050150250350450550650750850951051151251351451551651751813 unmodified lines53253353453553653753853928 unmodified lines568569570571572573574575576577578579580581582583584585586587588589590591141 unmodified lines733734735736737738739740741742193 unmodified lines93693793893994094194294394494594694794894991 unmodified lines104110421043104410451046104710481049105088 unmodified lines113911401141114211431144114511461147114848 unmodified linesapply_controlled_fuzzy_patch,)from lingologos_python.adapter import GATE_TIMEOUT_ENV # noqa: E402from lingologos_python.ast_graph import ( # noqa: E402IGNORED_DIRS,discover_python_files,374 unmodified linesmin_assurance: int = 3,node_timeout_sec: float = 120.0,total_budget_sec: Optional[float] = None,gate_timeout_sec: Optional[float] = None,) -> None:self.workspace_root = Path(workspace_root).resolve()if not self.workspace_root.is_dir():5 unmodified linesself.spec_path = str(Path(spec_path).resolve()) if spec_path else Noneself.use_subprocesses = bool(use_subprocesses)self.min_assurance = int(min_assurance)if (node_timeout_sec <= 0or (total_budget_sec is not None and total_budget_sec <= 0)or (gate_timeout_sec is not None and gate_timeout_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 Noneself.gate_timeout_sec = float(gate_timeout_sec) if gate_timeout_sec else Nonedef policy_dict(self, root: Optional[Path] = None) -> Dict[str, Any]:return {34 unmodified linesreturn {"spec": self.spec_path}return {"adapter": ADAPTER_REF_STRICT if self.strict_tools else ADAPTER_REF_DEFAULT}def _enter_gate_timeout_env(self) -> Optional[str]:"""Hand the gate budget down to the adapter, which reads its own environment.The kernel instantiates the adapter from a reference string, so thesession cannot pass it a constructor argument. The environment is thechannel both the in-process pipeline and the node subprocesses read."""if self.gate_timeout_sec is None:return Noneprevious = os.environ.get(GATE_TIMEOUT_ENV)os.environ[GATE_TIMEOUT_ENV] = repr(self.gate_timeout_sec)return previous@staticmethoddef _exit_gate_timeout_env(previous: Optional[str]) -> None:if previous is None:os.environ.pop(GATE_TIMEOUT_ENV, None)else:os.environ[GATE_TIMEOUT_ENV] = previousdef _run_six_nodes(self, case: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:previous_env = self._enter_gate_timeout_env()try:if self.use_subprocesses:return run_topology_subprocesses(13 unmodified lines"detail": str(exc),}}finally:self._exit_gate_timeout_env(previous_env)def _link_refusal(self, case_id: str, rel_posix: str, exc: WorkspaceLinkError) -> SessionResult:"""A workspace held together by links cannot be copied to staging faithfully."""28 unmodified linesreturn ("file", (rel_dir / name).as_posix())return Nonedef _late_link_at_commit(self) -> Optional[Tuple[str, int, str, str]]:"""The link question, asked again at the moment of writing.A link can appear after the run judged the tree. The commit alreadyre-reads the bytes to catch a workspace that moved; it re-asks the samequestion those bytes still belong to the tree the six nodes verified."""linked = self._linked_path_in_workspace()if linked is None:return Nonekind, rel = linkedreturn ("REFUSED",0,LINKED_PATH_IN_WORKSPACE,"a linked %s appeared in the workspace before the commit: '%s'" % (kind, rel),)def list_files(self) -> List[str]:"""Return all Python source files in the workspace."""return discover_python_files(self.workspace_root)141 unmodified linescommitted = Falseif commit and patch_res.applied and not plan.rejected and assurance >= self.min_assurance:late_link = self._late_link_at_commit()if late_link is not None:verdict, assurance, reason, detail = late_linkelif _disk_text(self.workspace_root, rel_posix) != original_text:# The workspace moved while the six nodes were running: the patch that# was verified is no longer the patch for the file on disk, so nothing# is written and the run reports the named refusal instead.193 unmodified linescommitted = Falseif commit and assurance >= needed:late_link = self._late_link_at_commit()drifted = [] if late_link is not None else [edit.file for edit in plan.editsif _disk_text(self.workspace_root, edit.file) != originals[edit.file]]if late_link is not None:verdict, assurance, reason, detail = late_linkelif drifted:# The pair was verified against the workspace as it was at staging time.# If a file of the pair moved since, the anchors proven in staging are# not the anchors of what is on disk, so the pair is not written.91 unmodified linesdetail = str(decision.get("detail", ""))committed = Falseif commit and not plan.rejected and assurance >= self.min_assurance:late_link = self._late_link_at_commit()if late_link is not None:verdict, assurance, reason, detail = late_linkelif target.is_file():# The verified text was staged as a new file. If a file landed at that# path while the run was going, writing would replace something the# six nodes never saw, so the create is not committed.88 unmodified linesdetail = str(decision.get("detail", ""))committed = Falseif commit and not plan.rejected and assurance >= self.min_assurance:late_link = self._late_link_at_commit()if late_link is not None:verdict, assurance, reason, detail = late_linkelif _disk_text(self.workspace_root, rel_posix) != original_text:# The file moved while the six nodes were running: the removal that was# verified is no longer the removal of what is on disk.verdict = "REFUSED"
79 unmodified lines808182838485868779 unmodified lines{"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": []}]79 unmodified lines808182838485868779 unmodified lines{"name": "self_lint","verdict": "CONFIRMED","check": "the package reads itself: modules compile, the graph spans them, the reason registry matches the card, the promised names exist","note": "12 modules parse, compile, and carry docstrings; own graph has 153 symbols and 321 edges; 38 reason codes, every one named in the card; 34 names promised in the Contents, all defined","failed_targets": []}]
18 unmodified lines19202122232425136 unmodified lines16216316418 unmodified linesfrom lingologos_codex.types import ABSTAIN, CONFIRMED, GateResult, REJECTEDfrom lingologos_python import gates as gates_modulefrom lingologos_python.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapterfrom lingologos_python.ast_graph import discover_python_filesfrom lingologos_python.gates import resolve_tool_gate_prefix136 unmodified linesgate = gates_module.run_python_tests(runner, sample_pkg, ["tests/test_mathops.py"])assert gate.verdict == ABSTAINassert "collected no tests" in gate.note18 unmodified lines1920212223242526272829136 unmodified lines16616716816917017117217317417517617717817918018118 unmodified linesfrom lingologos_codex.types import ABSTAIN, CONFIRMED, GateResult, REJECTEDfrom lingologos_python import gates as gates_modulefrom lingologos_python.adapter import (GATE_TIMEOUT_ENV,PythonLanguageAdapter,StrictPythonLanguageAdapter,)from lingologos_python.ast_graph import discover_python_filesfrom lingologos_python.gates import resolve_tool_gate_prefix136 unmodified linesgate = gates_module.run_python_tests(runner, sample_pkg, ["tests/test_mathops.py"])assert gate.verdict == ABSTAINassert "collected no tests" in gate.notedef test_the_gate_budget_arrives_through_the_environment(sample_pkg: Path, monkeypatch) -> None:"""The kernel builds the adapter from a ref string, so its budget comes from the environment."""monkeypatch.setenv(GATE_TIMEOUT_ENV, "7.5")assert PythonLanguageAdapter(sample_pkg).timeout_sec == 7.5assert StrictPythonLanguageAdapter(sample_pkg).timeout_sec == 7.5monkeypatch.delenv(GATE_TIMEOUT_ENV)assert PythonLanguageAdapter(sample_pkg).timeout_sec == 120.0assert PythonLanguageAdapter(sample_pkg, timeout_sec=5.0).timeout_sec == 5.0monkeypatch.setenv(GATE_TIMEOUT_ENV, "not a number")assert PythonLanguageAdapter(sample_pkg).timeout_sec == 120.0
254 unmodified lines255256257258259260254 unmodified lines"60","--total-timeout","300",)assert proc.returncode == 0, proc.stdout + proc.stderrassert "committed=True" in proc.stdout254 unmodified lines255256257258259260261262254 unmodified lines"60","--total-timeout","300","--gate-timeout","60",)assert proc.returncode == 0, proc.stdout + proc.stderrassert "committed=True" in proc.stdout
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Tests for the self-lint gate, which makes the card answerable from the package."""
from __future__ import annotations
import importlib.utilfrom pathlib import Path
_ROOT = Path(__file__).resolve().parent.parent# The kernel bundle carries a tools/run_gates.py of its own, so this file loads# the bundle runner by path instead of by package name._spec = importlib.util.spec_from_file_location( "codex_python_gates_runner", _ROOT / "tools" / "run_gates.py")assert _spec is not None and _spec.loader is not None_run_gates = importlib.util.module_from_spec(_spec)_spec.loader.exec_module(_run_gates)
_card_promises = _run_gates._card_promises_defined_names = _run_gates._defined_namesgate_self_lint = _run_gates.gate_self_lint
def test_the_self_lint_gate_confirms_the_real_package() -> None: res = gate_self_lint() assert res.verdict == "CONFIRMED" assert "all defined" in res.note
def test_a_name_the_card_promises_that_no_module_defines_is_not_a_promise_kept() -> None: fake_card = ( "# Card\n\n## Contents\n\n" "- `x/mod.py`: does a thing (`real_name`, `invented_name`).\n\n" "## Next\n\nNothing.\n" ) promises = _card_promises(fake_card) assert promises == ["real_name", "invented_name"] own = _defined_names({"mod.py": "def real_name():\n return 1\n"}) assert "real_name" in own assert "invented_name" not in own
def test_the_defined_names_see_cli_verbs_choices_tools_and_constants() -> None: cli_text = ( '"""Cli."""\n' "import argparse\n\n\n" "TOOLS = {'mypy': ()}\n\n\n" "def build_parser():\n" " parser = argparse.ArgumentParser()\n" " sub = parser.add_subparsers()\n" " sub.add_parser('select-tests')\n" " check = sub.add_parser('patterns')\n" " check.add_argument('action', choices=('list', 'apply'))\n" " return parser\n" ) own = _defined_names({"cli.py": cli_text}) for name in ("select-tests", "patterns", "list", "apply", "TOOLS", "mypy", "build_parser"): assert name in own
def test_names_outside_parentheses_are_not_checked_promises() -> None: fake_card = ( "# Card\n\n## Contents\n\n" "- `x/mod.py`: carries `unparenthesised` outside any parentheses.\n\n" "## Next\n\nNothing.\n" ) assert _card_promises(fake_card) == []2 unmodified lines3456782 unmodified lines111213141516375 unmodified lines3923933943953963972 unmodified linesfrom __future__ import annotationsimport osfrom pathlib import Pathfrom typing import Any, Dict, Tuple2 unmodified linesfrom lingologos_codex.fsadapter import FileSystemAdapterErrorimport lingologos_python.session as session_modulefrom lingologos_python.session import (LINKED_PATH_IN_WORKSPACE,NODE_TIMEOUT,375 unmodified linessession_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(2 unmodified lines34567892 unmodified lines12131415161718375 unmodified lines3943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794802 unmodified linesfrom __future__ import annotationsimport osimport timefrom pathlib import Pathfrom typing import Any, Dict, Tuple2 unmodified linesfrom lingologos_codex.fsadapter import FileSystemAdapterErrorimport lingologos_python.session as session_modulefrom lingologos_python.adapter import GATE_TIMEOUT_ENVfrom lingologos_python.session import (LINKED_PATH_IN_WORKSPACE,NODE_TIMEOUT,375 unmodified linessession_module.run_topology_subprocesses({"case_id": "bad"}, timeout_sec=0.0)with pytest.raises(ValueError):PythonWorkspaceSession(sample_pkg, total_budget_sec=-1.0)with pytest.raises(ValueError):PythonWorkspaceSession(sample_pkg, gate_timeout_sec=0.0)def test_the_session_hands_its_gate_budget_to_the_environment(sample_pkg: Path, monkeypatch) -> None:"""The kernel builds the adapter from a ref string, so the environment carries the number."""monkeypatch.delenv(GATE_TIMEOUT_ENV, raising=False)session = PythonWorkspaceSession(sample_pkg, gate_timeout_sec=2.5)previous = session._enter_gate_timeout_env()try:assert os.environ[GATE_TIMEOUT_ENV] == "2.5"finally:session._exit_gate_timeout_env(previous)assert GATE_TIMEOUT_ENV not in os.environdef test_a_test_runner_that_outruns_its_gate_budget_abstains(sample_pkg: Path) -> None:"""A runner that hangs is answered with a named abstain, not an endless wait."""sleeper = sample_pkg / "tests" / "conftest.py"sleeper.write_text("import time\n\ntime.sleep(60)\n", encoding="ascii", newline="")session = PythonWorkspaceSession(sample_pkg, gate_timeout_sec=2.0)started = time.monotonic()res = session.verify("src/mathops.py")elapsed = time.monotonic() - startedassert res.verdict == "UNKNOWN"assert res.reason == "GATE_ABSTAIN"assert res.committed is False# The runner sleeps for a minute; a run that comes back long before it was# waited out, and abstains instead of passing, was cut by the budget.assert elapsed < 30.0assert "abstained" in res.detaildef test_a_junction_created_while_the_gates_run_is_refused_at_commit(sample_pkg: Path, tmp_path: Path, dir_link) -> None:"""The commit re-asks the link question, so a link that appeared mid-run is refused too."""vendor = tmp_path / "vendor"vendor.mkdir()(vendor / "helper.py").write_text("VALUE = 1\n", encoding="ascii", newline="")if not dir_link(tmp_path / "probe_link", vendor):pytest.skip("this host offers no way to create a directory link")link = sample_pkg / "vendor_link"hook = sample_pkg / "tests" / "conftest.py"hook.write_text("import subprocess\n""import sys\n\n""VENDOR = %r\n""LINK = %r\n\n\n""def pytest_configure(config):\n"" try:\n"" if sys.platform == 'win32':\n"" subprocess.run(\n"" ['cmd', '/c', 'mklink', '/J', LINK, VENDOR],\n"" stdin=subprocess.DEVNULL,\n"" stdout=subprocess.DEVNULL,\n"" stderr=subprocess.DEVNULL,\n"" )\n"" else:\n"" import os\n\n"" os.symlink(VENDOR, LINK, target_is_directory=True)\n"" except OSError:\n"" pass\n" % (str(vendor), str(link)),encoding="ascii",newline="",)session = PythonWorkspaceSession(sample_pkg)res = session.edit_file("src/mathops.py","return left + right","return int(left) + int(right)",commit=True,)assert res.verdict == "REFUSED"assert res.reason == LINKED_PATH_IN_WORKSPACEassert res.committed is Falseassert "before the commit" in res.detailtext = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")assert "return left + right" in textdef test_verify_refuses_a_workspace_held_together_by_a_link(
13 unmodified lines1415161718192019 unmodified lines404142434445464748495039 unmodified lines90919293949596979813 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(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 = 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 (11 gates: 11 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"ROLES = ("planner", "retriever", "executor", "gate_checker", "adversary", "arbiter")39 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: 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: 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.",13 unmodified lines1415161718192019 unmodified lines404142434445464748495039 unmodified lines90919293949596979813 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(11 gates, 138 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 = 75 # the staged tree: 75 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 76 # those 75 plus the .gitattributes the hub addsEXPECTED_GATES = 11EXPECTED_TESTS = 138EXPECTED_TEST_FILES = 11EXPECTED_NODE_FILES = 18EXPECTED_GATE_LINE = "GATES: CONFIRMED (11 gates: 11 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"ROLES = ("planner", "retriever", "executor", "gate_checker", "adversary", "arbiter")39 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: 11 gates, 138 tests across 11 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: 11 gates, 138 tests across 11 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.",
4 unmodified lines5678910111213141516348 unmodified lines36536636736836937037137237337437537637737837938011 unmodified lines3923933943953963973987 unmodified lines4064074084094104114124134144154164 unmodified linesimport argparseimport astimport jsonimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Pathfrom typing import Callable, Dict, List, Sequence, TupleROOT = Path(__file__).resolve().parents[1]if str(ROOT) not in sys.path:348 unmodified linesreturn codesdef 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")11 unmodified linesreturn _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(7 unmodified linesreturn _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)),)4 unmodified lines567891011121314151617348 unmodified lines36636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344411 unmodified lines4564574584594604614627 unmodified lines4704714724734744754764774784794804814824834844854864874884894 unmodified linesimport argparseimport astimport jsonimport reimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Pathfrom typing import Callable, Dict, List, Sequence, Set, TupleROOT = Path(__file__).resolve().parents[1]if str(ROOT) not in sys.path:348 unmodified linesreturn codesdef _defined_names(texts: Dict[str, str]) -> Set[str]:"""Names the package itself defines: functions, classes, methods, constants, dict keys, CLI verbs."""names: Set[str] = set()for text in texts.values():for node in ast.walk(ast.parse(text)):if isinstance(node, ast.Assign):for target in node.targets:if isinstance(target, ast.Name):names.add(target.id)elif isinstance(node, ast.AnnAssign):if isinstance(node.target, ast.Name):names.add(node.target.id)elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):names.add(node.name)elif isinstance(node, ast.Dict):for key in node.keys:if isinstance(key, ast.Constant) and isinstance(key.value, str):names.add(key.value)elif (isinstance(node, ast.Call)and isinstance(node.func, ast.Attribute)and node.func.attr == "add_parser"and node.argsand isinstance(node.args[0], ast.Constant)and isinstance(node.args[0].value, str)):names.add(node.args[0].value)elif (isinstance(node, ast.Call)and isinstance(node.func, ast.Attribute)and node.func.attr == "add_argument"):for keyword in node.keywords:if keyword.arg == "choices" and isinstance(keyword.value, (ast.Tuple, ast.List)):for element in keyword.value.elts:if isinstance(element, ast.Constant) and isinstance(element.value, str):names.add(element.value)return namesdef _card_promises(readme: str) -> List[str]:"""Backticked identifiers inside parentheses in the Contents section of the card.Those parentheses are promises: the bullet says the module carries that name.Listing them and checking them against the modules is what keeps the card adescription and not a hope."""if "## Contents" not in readme:return []section = readme.split("## Contents", 1)[1].split("\n## ", 1)[0]promises: List[str] = []for group in re.finditer(r"\(([^()]*)\)", section):for span in re.findall(r"`([^`]*)`", group.group(1)):for token in re.split(r"[|\s]+", span):if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*(?:-[A-Za-z0-9_]+)*", token):continueif token not in promises:promises.append(token)return promisesdef gate_self_lint() -> GateResult:check = "the package reads itself: modules compile, the graph spans them, the reason registry matches the card, the promised names exist"pkg = ROOT / "lingologos_python"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] = []texts: Dict[str, str] = {}for rel in files:text = (pkg / rel).read_text(encoding="utf-8", newline="")texts[rel] = texttry:tree = ast.parse(text)compile(tree, rel, "exec")11 unmodified linesreturn _rejected(check, "the package graph came back empty")defined: List[str] = []for rel in files:defined.extend(_self_valued_codes(texts[rel]))unregistered = sorted(set(defined) - REASON_CODES)if unregistered:return _rejected(7 unmodified linesreturn _rejected(check, f"reason codes the card never names: {unnamed}", unnamed)promises = _card_promises(readme)own_names = _defined_names(texts)unmet = sorted(name for name in promises if name not in own_names)if unmet:return _rejected(check,f"names the card promises in parentheses that no module defines: {unmet}",unmet,)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; %d names promised in the Contents, all defined"% (len(files), len(symbols), len(edges), len(REASON_CODES), len(promises)),)
README.md+11-5
lingologos_python/adapter.py+20-3
lingologos_python/cli.py+6
lingologos_python/session.py+66-6
results/gates.json+2-2
tests/test_adapter.py+18-1
tests/test_cli.py+2
tests/test_self_lint.pyAdded+66
tests/test_session.py+83
tools/publish_dataset.py+7-7
tools/run_gates.py+78-5