Upload folder using huggingface_hub
Browse filesFiles changed (8)
34 unmodified lines353637383940419 unmodified lines51525354555612 unmodified lines6970717273747576163 unmodified lines24024124224324424524624724824925025125234 unmodified linesGATES: CONFIRMED (10 gates: 10 CONFIRMED, 0 REJECTED, 0 ABSTAIN)```The gate runner is where this bundle states its numbers out loud: 10 gates, 113 tests across 9 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.9 unmodified linesgraph extraction (`discover_python_files`, `extract_python_graph`, `importers_of`). A file whose bytesare not UTF-8 text is named as a file and given no symbols, rather than decoded into inventions.- `lingologos_python/test_selector.py`: import-aware Python test selection (`select_python_tests`).- `lingologos_python/gates.py`: bytecode-free `ast.parse` + in-memory `compile` gate, optional staticcheckers (`mypy`, `ruff`, `pyright`, `flake8`) that return `ABSTAIN` when missing, and `pytest`/ `unittest` test runner with failed-target parsing. The unittest fallback runs importable module12 unmodified linesand refuses with `PATCH_NOT_APPLIED` when the workspace moved while the six nodes were running. Awrite the disk refuses part way is undone from the in-memory originals, so a run never reports achange 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.- `lingologos_python/cli.py`: `lingologos_python` CLI (`verify`, `edit`, `create`, `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 andone planted to be refused, used by the tests and by the coverage counts.163 unmodified lines--search "def load(path):" --replace "def load(path: Path) -> dict:" --dry-run```and so does `create --file ... --content-file ...`. The command line has no `delete` verb: deleting is a`delete_file` transaction on the session and on the kernel, exercised in `tests/test_session.py`, and itis not offered as a command from here. `verify --file ...` reports a verdict for a file without askingfor 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 neverhappened. `patterns apply` also takes `--subprocesses`, which runs the six nodes as separate processesinstead of in this one.`check-adapter` says whether the Python adapter holds the contract of the kernel, and exits non-zerowhen it does not.34 unmodified lines353637383940419 unmodified lines515253545556575812 unmodified lines717273747576777879808182163 unmodified lines24624724824925025125225325425525625725825934 unmodified linesGATES: CONFIRMED (10 gates: 10 CONFIRMED, 0 REJECTED, 0 ABSTAIN)```The gate runner is where this bundle states its numbers out loud: 10 gates, 121 tests across 9 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.9 unmodified linesgraph extraction (`discover_python_files`, `extract_python_graph`, `importers_of`). A file whose bytesare not UTF-8 text is named as a file and given no symbols, rather than decoded into inventions.- `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 noimport edge shows.- `lingologos_python/gates.py`: bytecode-free `ast.parse` + in-memory `compile` gate, optional staticcheckers (`mypy`, `ruff`, `pyright`, `flake8`) that return `ABSTAIN` when missing, and `pytest`/ `unittest` test runner with failed-target parsing. The unittest fallback runs importable module12 unmodified linesand refuses with `PATCH_NOT_APPLIED` when the workspace moved while the six nodes were running. Awrite the disk refuses part way is undone from the in-memory originals, so a run never reports achange 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. Thestaging copy refuses a symlink or a Windows junction anywhere in the workspace, naming the linkedpath with `LINKED_PATH_IN_WORKSPACE`, instead of judging a tree that is not the one on disk. Insubprocess mode each node has a budget (one hundred and twenty seconds by default); a node thatexhausts it ends the run as 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 andone planted to be refused, used by the tests and by the coverage counts.163 unmodified lines--search "def load(path):" --replace "def load(path: Path) -> dict:" --dry-run```and so does `create --file ... --content-file ...`, and `delete --file ...` removes a file through thesame six-node gate: its exit code is zero only once the file is really gone, and `--dry-run` verifiesthe removal without touching the disk. `verify --file ...` reports a verdict for a file without askingfor 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 neverhappened. `patterns apply` also takes `--subprocesses`, which runs the six nodes as separate processesinstead of in this one, and `verify`, `edit` and `patterns apply` take `--node-timeout SEC` to set eachnode's budget; a node that runs past it is answered `NODE_TIMEOUT`, not awaited forever.`check-adapter` says whether the Python adapter holds the contract of the kernel, and exits non-zerowhen it does not.
35 unmodified lines3637383940415 unmodified lines4748495051526 unmodified lines59606162636419 unmodified lines84858687888914 unmodified lines1041051061071081099 unmodified lines11912012112212312431 unmodified lines156157158159160161107 unmodified lines26927027127227327435 unmodified linesp_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.")# edit5 unmodified linesp_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.")6 unmodified linesp_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.")# symbolsp_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.")19 unmodified linesp_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("--json", action="store_true", help="Print JSON output.")# check-adapter14 unmodified linesargs.workspace,strict_tools=args.strict_tools,use_subprocesses=args.subprocesses,)res = session.verify(target_file=args.file)if args.json:9 unmodified linesstrict_tools=args.strict_tools,use_subprocesses=args.subprocesses,min_assurance=min_assurance,)res = session.edit_file(args.file,31 unmodified lines# that never wrote anything is a failure, whatever its assurance says.return 0 if res.committed or (args.dry_run and res.accepted) else 1if args.command == "symbols":root = Path(args.workspace).resolve()files: List[str] = args.files if args.files else discover_python_files(root)107 unmodified linesargs.workspace,strict_tools=args.strict_tools,use_subprocesses=args.subprocesses,)res = session.apply_pattern(args.pattern, target=args.target, commit=not args.dry_run)if args.json:35 unmodified lines363738394041425 unmodified lines484950515253546 unmodified lines616263646566676869707172737475767719 unmodified lines97989910010110210314 unmodified lines1181191201211221231249 unmodified lines13413513613713813914031 unmodified lines172173174175176177178179180181182183184185186187188189190191192193194195107 unmodified lines30330430530630730830935 unmodified linesp_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.")# edit5 unmodified linesp_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.")6 unmodified linesp_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.")# deletep_delete = sub.add_parser("delete",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.")# symbolsp_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.")19 unmodified linesp_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-adapter14 unmodified linesargs.workspace,strict_tools=args.strict_tools,use_subprocesses=args.subprocesses,node_timeout_sec=args.node_timeout,)res = session.verify(target_file=args.file)if args.json:9 unmodified linesstrict_tools=args.strict_tools,use_subprocesses=args.subprocesses,min_assurance=min_assurance,node_timeout_sec=args.node_timeout,)res = session.edit_file(args.file,31 unmodified lines# that never wrote anything is a failure, whatever its assurance says.return 0 if res.committed or (args.dry_run and res.accepted) else 1if args.command == "delete":session = PythonWorkspaceSession(args.workspace, strict_tools=args.strict_tools)try:res = session.delete_file(args.file, commit=not args.dry_run)except FileNotFoundError as exc:print("REFUSED: %s" % exc, file=sys.stderr)return 1if 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}")# A removal lands or it does not: exit 0 only when the file is gone,# or when a dry run verified the removal without touching the disk.return 0 if res.committed or (args.dry_run and res.accepted) else 1if args.command == "symbols":root = Path(args.workspace).resolve()files: List[str] = args.files if args.files else discover_python_files(root)107 unmodified linesargs.workspace,strict_tools=args.strict_tools,use_subprocesses=args.subprocesses,node_timeout_sec=args.node_timeout,)res = session.apply_pattern(args.pattern, target=args.target, commit=not args.dry_run)if args.json:
13 unmodified lines14151617181943 unmodified lines636465666768184 unmodified lines25325425525625725825926026126226326426526626726826927027113 unmodified lines28528628728828929029129229329429529629729829930030130230330430530630730830931031131217 unmodified lines3303313323333343355 unmodified lines34134234334434534635 unmodified lines382383384385386387388389390100 unmodified lines491492493494495496497188 unmodified lines686687688689690691692100 unmodified lines79379479579679779879977 unmodified lines87787887988088188288313 unmodified linesimport jsonimport osimport shutilimport subprocessimport sysimport tempfile43 unmodified lines# Named session refusals, alongside the reason codes the rule catalog answers with.PATH_POLICY = "PATH_POLICY"PATCH_NOT_APPLIED = "PATCH_NOT_APPLIED"DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ("*.env",".env*",184 unmodified linesreturn first, first + probe_note, textdef _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_dirtarget_dir.mkdir(parents=True, exist_ok=True)for name in filenames:src_file = Path(dirpath) / nameif src_file.is_symlink():continueshutil.copy2(src_file, target_dir / name)13 unmodified linesdef 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 = seedenv = _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()}"17 unmodified linesspec_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():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)def policy_dict(self, root: Optional[Path] = None) -> Dict[str, Any]:return {35 unmodified linesreturn {"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."""100 unmodified lineswith tempfile.TemporaryDirectory(prefix="lingologos_python_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()188 unmodified linesneeded = max(self.min_assurance, plan.min_assurance)with tempfile.TemporaryDirectory(prefix="lingologos_python_pattern_stage_") as tmp_dir:staged_root = Path(tmp_dir).resolve()_copy_workspace_for_staging(self.workspace_root, staged_root)staged_fs = self._os_fs(staged_root)tx = staged_fs.begin_transaction()for edit in plan.edits:100 unmodified linesmarker = "# __LINGOLOGOS_PYTHON_NEW_FILE__\n"with tempfile.TemporaryDirectory(prefix="lingologos_python_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()77 unmodified lineswith tempfile.TemporaryDirectory(prefix="lingologos_python_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; lingologos_codex.fsadapter.stage_delete walks parent dirs.staged_target = staged_root / Path(*rel_posix.split("/"))13 unmodified lines1415161718192043 unmodified lines64656667686970717273747576777879184 unmodified lines26426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231313 unmodified lines32732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436517 unmodified lines3833843853863873883895 unmodified lines39539639739839940040135 unmodified lines437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469100 unmodified lines570571572573574575576577578579188 unmodified lines768769770771772773774775776777100 unmodified lines87887988088188288388488588688777 unmodified lines96596696796896997097197297397413 unmodified linesimport jsonimport osimport shutilimport statimport subprocessimport sysimport tempfile43 unmodified lines# 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"class NodeTimeoutError(RuntimeError):"""A node subprocess exhausted its time budget instead of answering."""class WorkspaceLinkError(ValueError):"""The workspace holds a symlink or a junction whose copy cannot match the disk."""DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ("*.env",".env*",184 unmodified linesreturn first, first + probe_note, textdef _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 adirectory walk still descends into it. The reparse attribute is the honest test."""if path.is_symlink():return Trueif os.name == "nt":try:attributes = path.lstat().st_file_attributesexcept OSError:return Falsereturn bool(attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT)return Falsedef _copy_workspace_for_staging(src_root: Path, dst_root: Path) -> None:"""Copy a workspace cleanly without caches or virtual environments.A symlink or a junction anywhere under the root is refused by name: a copythat quietly omits a link is not the workspace the six nodes were asked tojudge, and a copy that follows one reaches files outside the workspace."""root = src_root.resolve()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(root)for name in dirnames:entry = Path(dirpath) / nameif _is_linked(entry):raise WorkspaceLinkError("linked directory in the workspace: '%s'" % (rel_dir / name).as_posix())target_dir = dst_root / rel_dirtarget_dir.mkdir(parents=True, exist_ok=True)for name in filenames:src_file = Path(dirpath) / nameif _is_linked(src_file):raise WorkspaceLinkError("linked file in the workspace: '%s'" % (rel_dir / name).as_posix())shutil.copy2(src_file, target_dir / name)13 unmodified linesdef run_topology_subprocesses(case: Dict[str, Any],*,agent_script: Optional[Path] = None,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.The agent script is read from the module at call time, so a caller that namesa different six-node executable gets it, and the per-node budget is the oneasked for rather than one frozen at import."""script = Path(agent_script) if agent_script else DEFAULT_AGENT_SCRIPTseed = _envelope.make_envelope("arbiter", 0, 0, "task received", dict(case))trace: List[Dict[str, Any]] = [seed]current = seedenv = _subprocess_env()for role in ROLES:cmd = [sys.executable, "-B", str(script), "--role", role, "--node-id", role]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,)except subprocess.TimeoutExpired as exc:raise NodeTimeoutError("node '%s' exhausted its %s s budget without answering" % (role, timeout_sec)) from excif completed.returncode != 0:raise RuntimeError(f"node '{role}' exited with {completed.returncode}: {completed.stderr.strip()}"17 unmodified linesspec_path: Optional[str | Path] = None,use_subprocesses: bool = False,min_assurance: int = 3,node_timeout_sec: float = 120.0,) -> 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)self.node_timeout_sec = float(node_timeout_sec)def policy_dict(self, root: Optional[Path] = None) -> Dict[str, Any]:return {35 unmodified linesreturn {"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(case, timeout_sec=self.node_timeout_sec)return run_pipeline(case)except NodeTimeoutError as exc:# A node that exhausts its budget abstains: the session answers# UNKNOWN with the named reason instead of a traceback or a verdict.return [], {"decision": {"verdict": "UNKNOWN","assurance": 0,"reason": NODE_TIMEOUT,"detail": str(exc),}}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."""return SessionResult(case_id=case_id,verdict="REFUSED",assurance=0,reason=LINKED_PATH_IN_WORKSPACE,detail=str(exc),committed=False,touched_files=(rel_posix,),)def list_files(self) -> List[str]:"""Return all Python source files in the workspace."""100 unmodified lineswith tempfile.TemporaryDirectory(prefix="lingologos_python_stage_") as tmp_dir:staged_root = Path(tmp_dir).resolve()try:_copy_workspace_for_staging(self.workspace_root, staged_root)except WorkspaceLinkError as exc:return self._link_refusal(case_id, rel_posix, exc)if patch_res.applied and not plan.rejected:staged_fs = self._os_fs(staged_root)tx = staged_fs.begin_transaction()188 unmodified linesneeded = max(self.min_assurance, plan.min_assurance)with tempfile.TemporaryDirectory(prefix="lingologos_python_pattern_stage_") as tmp_dir:staged_root = Path(tmp_dir).resolve()try:_copy_workspace_for_staging(self.workspace_root, staged_root)except WorkspaceLinkError as exc:return self._link_refusal(chosen_case_id, primary.file, exc)staged_fs = self._os_fs(staged_root)tx = staged_fs.begin_transaction()for edit in plan.edits:100 unmodified linesmarker = "# __LINGOLOGOS_PYTHON_NEW_FILE__\n"with tempfile.TemporaryDirectory(prefix="lingologos_python_create_") as tmp_dir:staged_root = Path(tmp_dir).resolve()try:_copy_workspace_for_staging(self.workspace_root, staged_root)except WorkspaceLinkError as exc:return self._link_refusal(case_id, rel_posix, exc)if not plan.rejected:staged_fs = self._os_fs(staged_root)tx = staged_fs.begin_transaction()77 unmodified lineswith tempfile.TemporaryDirectory(prefix="lingologos_python_delete_") as tmp_dir:staged_root = Path(tmp_dir).resolve()try:_copy_workspace_for_staging(self.workspace_root, staged_root)except WorkspaceLinkError as exc:return self._link_refusal(case_id, rel_posix, exc)if not plan.rejected:# Unlink only the target file; lingologos_codex.fsadapter.stage_delete walks parent dirs.staged_target = staged_root / Path(*rel_posix.split("/"))
18 unmodified lines19202122232460 unmodified lines85868788899018 unmodified linesreturn 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)60 unmodified lines# 1. Direct test file edits and naming conventionsfor raw in changed_files:rel = raw.replace("\\", "/")if rel in test_set and rel not in chosen:chosen.append(rel)continue18 unmodified lines192021222324252627282960 unmodified lines9091929394959697989910010110210310418 unmodified linesreturn name.startswith("test_") and name.endswith(".py") or name.endswith("_test.py")def is_conftest(rel_posix: str) -> bool:"""Return True when a relative path is a pytest conftest module."""return Path(rel_posix).name == "conftest.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)60 unmodified lines# 1. Direct test file edits and naming conventionsfor raw in changed_files:rel = raw.replace("\\", "/")if is_conftest(rel):# A conftest carries fixtures and hooks that no import edge shows:# every test at or below its folder runs through it, so a change to# it selects that whole folder of tests rather than nothing.scope = rel[: rel.rfind("/")] if "/" in rel else ""for test_rel in all_tests:if (not scope or test_rel.startswith(scope + "/")) and test_rel not in chosen:chosen.append(test_rel)continueif rel in test_set and rel not in chosen:chosen.append(rel)continue
9 unmodified lines101112131415206 unmodified lines2222232249 unmodified linesimport hashlibimport jsonimport subprocessimport sysfrom pathlib import Path206 unmodified linesproc = run_cli("check-adapter", "--workspace", str(SAMPLE))assert proc.returncode == 0, proc.stdout + proc.stderrassert "ADAPTER OK" in proc.stdout9 unmodified lines10111213141516206 unmodified lines2232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582599 unmodified linesimport hashlibimport jsonimport shutilimport subprocessimport sysfrom pathlib import Path206 unmodified linesproc = run_cli("check-adapter", "--workspace", str(SAMPLE))assert proc.returncode == 0, proc.stdout + proc.stderrassert "ADAPTER OK" in proc.stdoutdef _delete_workspace(tmp_path: Path) -> Path:ws = tmp_path / "delete_pkg"shutil.copytree(SAMPLE, ws)(ws / "src" / "helper.py").write_text('"""Extra module."""\n\nVALUE = 1\n', encoding="utf-8", newline="")return wsdef test_delete_dry_run_verifies_the_removal_without_touching_the_disk(tmp_path: Path) -> None:ws = _delete_workspace(tmp_path)proc = run_cli("delete", "--workspace", str(ws), "--file", "src/helper.py", "--dry-run")assert proc.returncode == 0, proc.stdout + proc.stderrassert "VERIFIED" in proc.stdoutassert "committed=False" in proc.stdoutassert (ws / "src" / "helper.py").is_file()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")assert proc.returncode == 0, proc.stdout + proc.stderrassert "committed=True" in proc.stdoutassert not (ws / "src" / "helper.py").exists()def test_delete_answers_a_refusal_for_a_file_that_is_not_there(tmp_path: Path) -> None:ws = tmp_path / "delete_empty"shutil.copytree(SAMPLE, ws)proc = run_cli("delete", "--workspace", str(ws), "--file", "src/absent.py")assert proc.returncode == 1assert "REFUSED" in proc.stderr
1 unmodified line2345678910111213264 unmodified lines2782792801 unmodified linefrom __future__ import annotationsfrom pathlib import Pathfrom typing import Any, Dict, Tuplefrom lingologos_codex.fsadapter import FileSystemAdapterErrorfrom lingologos_python.session import PythonWorkspaceSession, SessionResult, _verify_probedef test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None:264 unmodified lineshelper = sample_pkg / "src" / "helper.py"assert helper.is_file()assert helper.read_text(encoding="utf-8", newline="") == '"""Extra module."""\n\nVALUE = 1\n'1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849264 unmodified lines3143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853861 unmodified linefrom __future__ import annotationsimport osimport statimport subprocessfrom pathlib import Pathfrom typing import Any, Dict, Tupleimport pytestfrom lingologos_codex.fsadapter import FileSystemAdapterErrorimport lingologos_python.session as session_modulefrom lingologos_python.session import (LINKED_PATH_IN_WORKSPACE,NODE_TIMEOUT,NodeTimeoutError,PythonWorkspaceSession,SessionResult,WorkspaceLinkError,_verify_probe,)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):passif 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 Falsedef test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None:264 unmodified lineshelper = sample_pkg / "src" / "helper.py"assert helper.is_file()assert helper.read_text(encoding="utf-8", newline="") == '"""Extra module."""\n\nVALUE = 1\n'def test_a_linked_directory_in_the_workspace_refuses_any_staged_run(sample_pkg: Path, tmp_path: Path) -> 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):pytest.skip("this host offers no way to create a directory link")session = PythonWorkspaceSession(sample_pkg)res = session.edit_file("src/mathops.py","return left + right","return int(left) + int(right)",commit=False,)assert res.verdict == "REFUSED"assert res.reason == LINKED_PATH_IN_WORKSPACEassert "vendor" in res.detailassert res.committed is Falsecreated = session.create_file("src/newcomer.py", "VALUE = 1\n", commit=True)assert created.verdict == "REFUSED"assert created.reason == LINKED_PATH_IN_WORKSPACEassert created.committed is Falseassert not (sample_pkg / "src" / "newcomer.py").exists()assert (outside / "elsewhere.py").read_text(encoding="utf-8") == "SECRET = 1\n"def test_the_staging_copy_refuses_a_linked_file_by_name(sample_pkg: Path, tmp_path: Path) -> None:"""The refusal is not limited to directories: one linked file is enough."""target = tmp_path / "outside_helper.py"target.write_text("VALUE = 1\n", encoding="ascii", newline="")link = sample_pkg / "src" / "linked.py"try:os.symlink(str(target), str(link))except (OSError, NotImplementedError):pytest.skip("this host does not allow creating a file symlink")with pytest.raises(WorkspaceLinkError) as caught:session_module._copy_workspace_for_staging(sample_pkg, tmp_path / "staged")assert "src/linked.py" in str(caught.value)def test_a_node_that_exhausts_its_budget_raises_a_named_error(tmp_path: Path) -> None:"""The subprocess runner turns an exhausted per-node budget into NodeTimeoutError."""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": "budget"}, agent_script=stub, timeout_sec=1.0)assert "exhausted its" in str(caught.value)def test_a_timed_out_node_answers_unknown_instead_of_a_traceback(sample_pkg: Path, tmp_path: Path, monkeypatch) -> None:"""The session reports the budget refusal with a reason, like any other abstain."""stub = tmp_path / "sleeping_agent.py"stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="")monkeypatch.setattr(session_module, "DEFAULT_AGENT_SCRIPT", stub)session = PythonWorkspaceSession(sample_pkg, use_subprocesses=True, node_timeout_sec=1.0)res = session.verify("src/mathops.py")assert res.verdict == "UNKNOWN"assert res.reason == NODE_TIMEOUTassert res.assurance == 0assert res.committed is False
3 unmodified lines4567891011121314151615 unmodified lines3233343 unmodified linesfrom pathlib import Pathfrom lingologos_python.test_selector import discover_test_files, is_test_file, select_python_testsdef 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:15 unmodified linesdef test_select_python_tests_returns_empty_for_unknown_file(sample_pkg: Path) -> None:assert select_python_tests(sample_pkg, ["src/unrelated_missing.py"]) == []3 unmodified lines4567891011121314151617181920212223242515 unmodified lines4142434445464748495051525354555657585960616263646566676869703 unmodified linesfrom pathlib import Pathfrom lingologos_python.test_selector import (discover_test_files,is_conftest,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")assert not is_test_file("tests/conftest.py")assert is_conftest("tests/conftest.py")assert is_conftest("conftest.py")assert not is_conftest("src/alpha.py")def test_discover_test_files_prefers_tests_dir(sample_pkg: Path) -> None:15 unmodified linesdef test_select_python_tests_returns_empty_for_unknown_file(sample_pkg: Path) -> None:assert select_python_tests(sample_pkg, ["src/unrelated_missing.py"]) == []def test_a_conftest_change_selects_the_folder_of_tests_it_carries(tmp_path: Path) -> None:"""A conftest holds fixtures no import edge shows, so its whole folder is selected."""root = tmp_path / "conf_pkg"(root / "tests" / "sub").mkdir(parents=True)(root / "tests" / "conftest.py").write_text("import pytest\n\n\n@pytest.fixture\ndef shared():\n return 1\n",encoding="ascii",newline="\n",)(root / "tests" / "test_a.py").write_text("def test_a(shared):\n assert shared == 1\n", encoding="ascii", newline="\n")(root / "tests" / "sub" / "conftest.py").write_text("import pytest\n\n\n@pytest.fixture\ndef deeper():\n return 2\n",encoding="ascii",newline="\n",)(root / "tests" / "sub" / "test_b.py").write_text("def test_b(deeper):\n assert deeper == 2\n", encoding="ascii", newline="\n")broad = select_python_tests(root, ["tests/conftest.py"])assert broad == ["tests/sub/test_b.py", "tests/test_a.py"]narrow = select_python_tests(root, ["tests/sub/conftest.py"])assert narrow == ["tests/sub/test_b.py"]
42 unmodified lines4344454647484940 unmodified lines90919293949596979842 unmodified linesEXPECTED_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 = 113EXPECTED_TEST_FILES = 9EXPECTED_NODE_FILES = 18EXPECTED_GATE_LINE = "GATES: CONFIRMED (10 gates: 10 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"40 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, 113 tests across 9 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, 113 tests across 9 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.",42 unmodified lines4344454647484940 unmodified lines90919293949596979842 unmodified linesEXPECTED_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_NODE_FILES = 18EXPECTED_GATE_LINE = "GATES: CONFIRMED (10 gates: 10 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"40 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""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""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.",
README.md+14-7
lingologos_python/cli.py+35
lingologos_python/session.py+116-25
lingologos_python/test_selector.py+14
tests/test_cli.py+35
tests/test_session.py+107-1
tests/test_test_selector.py+37-1
tools/publish_dataset.py+3-3