Upload folder using huggingface_hub
Browse filesFiles changed (9)
31 unmodified lines323334353637383940411 unmodified line4344454647483 unmodified lines5253545556575859606162636416 unmodified lines81828384858687881 unmodified line90919293949596979899100101102103104105106219 unmodified lines32632732832933033133231 unmodified lines```python -B tools/run_gates.pyGATES: CONFIRMED (12 gates: 12 CONFIRMED, 0 REJECTED, 0 ABSTAIN)```The gate runner is where this bundle states its numbers out loud: 12 gates, 159 tests across 15 files,18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives everyone of those numbers from the tree it is standing in and stops the upload when the card and the codebeside it disagrees.1 unmodified lineThe report names the tree it describes. `results/gates.json` embeds a digest of every byte of the bundleexcept the reports folder itself, and the publisher refuses to upload a tree that the report does notdescribe byte for byte; `tests/test_self_lint.py` holds the report sitting in this folder to that bar.## Contents3 unmodified lines- `lingologos_python/adapter.py`: `PythonLanguageAdapter` and `StrictPythonLanguageAdapter`implementing the five-method `lingologos_codex.adapter_contract.LanguageAdapter` contract.- `lingologos_python/ast_graph.py`: AST symbol, method, inheritance, relative/absolute import, and callgraph 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.An aliased `from x import y as z` keeps its edge to the submodule `x.y` even though the name isrenamed, and a dotted relative import crosses the same number of packages in the graph as in thesource.`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 noimport edge shows.16 unmodified lines- `lingologos_python/session.py`: `PythonWorkspaceSession` for safe staged verification and atomic diskcommits via `lingologos_codex.fsadapter` (`verify`, `edit_file`, `create_file`, `delete_file`,`apply_pattern`, `run_retry_loop`, and `run_topology_subprocesses`). A proposer that accepts a third argument is handed a `RetryContext`with the attempts so far, their traces and their reasons; a two-argument proposer keeps itssignature. A commit re-reads what is on diskand 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,1 unmodified linesymlink 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 exhaustseither budget answers UNKNOWN with the reason `NODE_TIMEOUT`. One tree is judged by onerun at a time: every verb takes an exclusive lock at the workspace root before it readsanything and releases it in a finally even when the run was refused; a lock left behindby a process that no longer runs is taken over, one whose owner cannot be read is neverstolen, and a live holder is answered REFUSED with the reason `SESSION_LOCKED`. The lock names its holder by processnumber, and a number recycled by a young process can keep a tree locked past the death of the runthat planted it; deleting the lock file is the operator's remedy, not an unlock verb the bundle offers.- `lingologos_python/cli.py`: `lingologos_python` CLI (`verify`, `edit`, `create`, `delete`, `symbols`,`select-tests`, `patterns list|show|scan|apply`, `check-adapter`).- `fixtures/pattern_lab/`: a small package with one function planted in the shape of each card and219 unmodified linesof the package defines.- Refusals the session raises itself: `PATH_POLICY`, `PATCH_NOT_APPLIED`, `NODE_TIMEOUT`,`LINKED_PATH_IN_WORKSPACE`, `SESSION_LOCKED`.- Verdicts the codex kernel brings back: `GATE_REJECTED`, `GATE_ABSTAIN`, `GATE_MISSING`, `CHECKER_REJECTED`, `CHECKER_ABSTAIN`, `NOT_APPLIED`, `PROTECTED_PATH`, `NO_INDEPENDENT_CONFIRMATION`.- The refusal the catalog layer adds above the rules: `AMBIGUOUS_TARGET`.- Preflight and shape refusals of the rules: `MISSING_TARGET_FILE`, `NO_SUCH_FUNCTION`,31 unmodified lines323334353637383940411 unmodified line43444546474849503 unmodified lines545556575859606162636465666768697016 unmodified lines87888990919293941 unmodified line96979899100101102103104105106107108109110111112113114115116117219 unmodified lines33733833934034134234331 unmodified lines```python -B tools/run_gates.pyGATES: CONFIRMED (13 gates: 13 CONFIRMED, 0 REJECTED, 0 ABSTAIN)```The gate runner is where this bundle states its numbers out loud: 13 gates, 167 tests across 15 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 disagrees.1 unmodified lineThe report names the tree it describes. `results/gates.json` embeds a digest of every byte of the bundleexcept the reports folder itself, and the publisher refuses to upload a tree that the report does notdescribe byte for byte; `tests/test_self_lint.py` holds the report sitting in this folder to that bar.The runner takes that digest before the first gate and asks it again before writing: a tree that movedwhile the gates ran gets no report, and the report says how many seconds each gate took.## Contents3 unmodified lines- `lingologos_python/adapter.py`: `PythonLanguageAdapter` and `StrictPythonLanguageAdapter`implementing the five-method `lingologos_codex.adapter_contract.LanguageAdapter` contract.- `lingologos_python/ast_graph.py`: AST symbol, method, inheritance, relative/absolute import, and callgraph extraction (`discover_python_files`, `extract_python_graph`, `importers_of`, `reexported_names`,`hardlinked_file`). A file whose bytesare not UTF-8 text is named as a file and given no symbols, rather than decoded into inventions.An aliased `from x import y as z` keeps its edge to the submodule `x.y` even though the name isrenamed, and a dotted relative import crosses the same number of packages in the graph as in thesource.`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, and `hardlinked_file` answers fora file whose bytes sit under two names in the tree. A package that re-exports through its `__init__`is read as a table from name to file, so a change behind the re-export still selects the test thatonly named the package.- `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.16 unmodified lines- `lingologos_python/session.py`: `PythonWorkspaceSession` for safe staged verification and atomic diskcommits via `lingologos_codex.fsadapter` (`verify`, `edit_file`, `create_file`, `delete_file`,`apply_pattern`, `run_retry_loop`, and `run_topology_subprocesses`). A proposer that accepts a third argument is handed a `RetryContext`with the attempts so far, their traces, their reasons, and the patch signatures the loop detector compares, which read the fate ofa patch and not its words; a two-argument proposer keeps its signature. A commit re-reads what is on diskand 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,1 unmodified linesymlink 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. A hardlinked pair, two names carrying the same diskbytes, is refused the same three ways with `HARDLINKED_PATH_IN_WORKSPACE`, because a staged copywould silently break what the workspace holds as one file. 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 exhaustseither budget answers UNKNOWN with the reason `NODE_TIMEOUT`. One tree is judged by onerun at a time: every verb takes an exclusive lock at the workspace root before it readsanything and releases it in a finally even when the run was refused. The lock record names itsholder three times over: the process number, the birth time that process had when the lock wastaken, and a token that only that acquisition knows. A live number whose birth time does not matchis not the holder the lock recorded, so a recycled process id cannot keep a tree locked past thedeath of its run; a leftover lock is claimed by renaming it first, so two runs racing over onecorpse leave exactly one holder; and release deletes the lock only while the token in it is the onethis run wrote, so a run never unlinks a lock another run took over. A live holder is answeredREFUSED with the reason `SESSION_LOCKED`, and one whose owner cannot be read is never stolen.- `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 and219 unmodified linesof the package defines.- Refusals the session raises itself: `PATH_POLICY`, `PATCH_NOT_APPLIED`, `NODE_TIMEOUT`,`LINKED_PATH_IN_WORKSPACE`, `HARDLINKED_PATH_IN_WORKSPACE`, `SESSION_LOCKED`.- Verdicts the codex kernel brings back: `GATE_REJECTED`, `GATE_ABSTAIN`, `GATE_MISSING`, `CHECKER_REJECTED`, `CHECKER_ABSTAIN`, `NOT_APPLIED`, `PROTECTED_PATH`, `NO_INDEPENDENT_CONFIRMATION`.- The refusal the catalog layer adds above the rules: `AMBIGUOUS_TARGET`.- Preflight and shape refusals of the rules: `MISSING_TARGET_FILE`, `NO_SUCH_FUNCTION`,
56 unmodified lines57585960616269 unmodified lines13213313413513613713813914014169 unmodified lines21121221321421521699 unmodified lines31631731831932032156 unmodified linesreturn Falsedef discover_python_files(workspace: Path) -> List[str]:"""Return sorted POSIX relative paths for all Python source files in workspace.69 unmodified linesexcept (SyntaxError, ValueError):continuemodules, _ = _extract_imports(rel, tree)for name in modules:if name in wanted or name.rsplit(".", 1)[0] in wanted:found.append(rel)breakreturn found69 unmodified linesreturn ".".join(base_parts)def _extract_imports(rel_posix: str, tree: ast.Module) -> Tuple[List[str], Dict[str, Tuple[str, str]]]:99 unmodified linesif target_file:edges.add((rel, target_file))# Inheritance edgesfor cls_name, base_list in bases_by_file.get(rel, {}).items():src_sym = f"{rel}::{cls_name}"56 unmodified lines575859606162636465666768697071727374757669 unmodified lines14614714814915015115215315415515615715815916016116216316469 unmodified lines23423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529699 unmodified lines39639739839940040140240340440540640740856 unmodified linesreturn Falsedef hardlinked_file(path: Path) -> bool:"""True when one file stands under two names (its link count is above one).A hard link is not a reparse point: both names are real, both lead to thesame bytes on the disk. A copy of one name makes two files out of what thedisk held as one, and a commit through the other name leaves the first atthe old bytes. The tree is honest about links only if it also counts names."""try:return path.stat().st_nlink > 1except OSError:return Falsedef discover_python_files(workspace: Path) -> List[str]:"""Return sorted POSIX relative paths for all Python source files in workspace.69 unmodified linesexcept (SyntaxError, ValueError):continuemodules, _ = _extract_imports(rel, tree)hit = Falsefor name in modules:if name in wanted or name.rsplit(".", 1)[0] in wanted:hit = Truebreakif not hit:# The file binds a name the package re-exports from the target.for dotted in _reexport_dotted_names(workspace, tree):if dotted in wanted:hit = Truebreakif hit:found.append(rel)return found69 unmodified linesreturn ".".join(base_parts)def reexported_names(workspace: Path, init_rel: str) -> Dict[str, List[str]]:"""External name -> dotted candidates, for a package __init__ that re-exports names.A package that answers for a function living in another file is ordinary andhonest: the __init__ imports the name from where it stands. A caller bindingto pkg.name never names the file holding the code, so the naming checkfollows this table and still credits the file the code lives in."""source = _read_source(workspace, init_rel)if source is None:return {}try:tree = ast.parse(source, filename=init_rel)except (SyntaxError, ValueError):return {}parts = [p for p in init_rel.replace("\\", "/").split("/") if p]prefix = ".".join(parts[:-1]) # empty for a package sitting at the workspace roottable: Dict[str, List[str]] = {}for node in tree.body:if not isinstance(node, ast.ImportFrom) or node.level != 1:continueif node.module:base = f"{prefix}.{node.module}" if prefix else node.moduleelif prefix:base = prefix # from . import name: name may be a sibling moduleelse:continuefor alias in node.names:if alias.name == "*":continuekey = alias.asname or alias.nameoptions = table.setdefault(key, [])# The from-import can name a submodule (pkg.deep) or a name defined# inside one (pkg.deep.thing), and the two resolve to different files.for dotted in (base, f"{base}.{alias.name}"):if dotted not in options:options.append(dotted)return tabledef _reexport_dotted_names(workspace: Path, tree: ast.Module) -> List[str]:"""Dotted submodules a file reaches through a package __init__ re-export."""reached: List[str] = []for node in ast.walk(tree):if not isinstance(node, ast.ImportFrom) or node.level > 0 or not node.module:continuetable = reexported_names(workspace, node.module.replace(".", "/") + "/__init__.py")for alias in node.names:if alias.name == "*":continuekey = alias.asname or alias.namefor dotted in table.get(key, ()):if dotted not in reached:reached.append(dotted)return reacheddef _extract_imports(rel_posix: str, tree: ast.Module) -> Tuple[List[str], Dict[str, Tuple[str, str]]]:99 unmodified linesif target_file:edges.add((rel, target_file))# Re-export edges: a package __init__ can hand a name over to the file# that defines it, and the caller never names that file itself.for dotted in _reexport_dotted_names(workspace, parsed[rel]):target_file = _match_module_file(dotted, files_by_module, normalized_files, rel)if target_file:edges.add((rel, target_file))# Inheritance edgesfor cls_name, base_list in bases_by_file.get(rel, {}).items():src_sym = f"{rel}::{cls_name}"
16 unmodified lines1718192021221 unmodified line24252627282916 unmodified linesPATCH_NOT_APPLIED = "PATCH_NOT_APPLIED"NODE_TIMEOUT = "NODE_TIMEOUT"LINKED_PATH_IN_WORKSPACE = "LINKED_PATH_IN_WORKSPACE"SESSION_LOCKED = "SESSION_LOCKED"SESSION_REASONS: Tuple[str, ...] = (1 unmodified linePATCH_NOT_APPLIED,NODE_TIMEOUT,LINKED_PATH_IN_WORKSPACE,SESSION_LOCKED,)16 unmodified lines171819202122231 unmodified line2526272829303116 unmodified linesPATCH_NOT_APPLIED = "PATCH_NOT_APPLIED"NODE_TIMEOUT = "NODE_TIMEOUT"LINKED_PATH_IN_WORKSPACE = "LINKED_PATH_IN_WORKSPACE"HARDLINKED_PATH_IN_WORKSPACE = "HARDLINKED_PATH_IN_WORKSPACE"SESSION_LOCKED = "SESSION_LOCKED"SESSION_REASONS: Tuple[str, ...] = (1 unmodified linePATCH_NOT_APPLIED,NODE_TIMEOUT,LINKED_PATH_IN_WORKSPACE,HARDLINKED_PATH_IN_WORKSPACE,SESSION_LOCKED,)
20 unmodified lines21222324252628 unmodified lines555657585960616263646517 unmodified lines838485868788893 unmodified lines9394959697989910015 unmodified lines11611711811912012148 unmodified lines170171172173174175176177178179180181182183144 unmodified lines32832933033133233333415 unmodified lines350351352353354355237 unmodified lines5935945955965975985996006016026036046056066076086096105 unmodified lines6166176186196206216226237 unmodified lines6316326336346356364 unmodified lines64164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369445 unmodified lines740741742743744745746702 unmodified lines14491450145114521453145420 unmodified linesimport sysimport tempfileimport timefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple28 unmodified linesfrom lingologos_python.ast_graph import ( # noqa: E402IGNORED_DIRS,discover_python_files,importers_of,is_linked_path,)from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E402from lingologos_python.reasons import ( # noqa: E402LINKED_PATH_IN_WORKSPACE,NODE_TIMEOUT,PATCH_NOT_APPLIED,17 unmodified linesclass WorkspaceLinkError(ValueError):"""The workspace holds a symlink or a junction whose copy cannot match the disk."""class SessionLockError(RuntimeError):3 unmodified lines# Two sessions committing to one workspace corrupt each other: each staged its# own copy from a disk the other has already rewritten. The lock is taken with# an exclusive create, so claiming it is never a polite ask, and released in a# finally even when the run was refused.SESSION_LOCK_NAME = ".lingologos-session.lock"def _process_alive(pid: int) -> bool:15 unmodified linesreturn TrueDEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ("*.env",".env*",48 unmodified linesA loop that hands the proposer only the index and the last result teaches itnothing about why the nodes refused. A proposer that accepts a thirdargument receives all of it: every prior result with its verdict, reason,trace lines and the dossier the kernel returned. A two-argument proposerkeeps working unchanged."""attempt: intrel_path: strattempts: Tuple[SessionResult, ...] = ()failure_reasons: Tuple[str, ...] = ()def _disk_text(root: Path, rel_posix: str) -> str:144 unmodified linesA 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):15 unmodified linesraise WorkspaceLinkError("linked file in the workspace: '%s'" % (rel_dir / name).as_posix())shutil.copy2(src_file, target_dir / name)237 unmodified linescase_id=case_id,verdict="REFUSED",assurance=0,reason=LINKED_PATH_IN_WORKSPACE,detail=str(exc),committed=False,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 torefuse for it, so it asks the same question the copy asks: is any partof this tree somewhere else."""root = Path(self.workspace_root).resolve()for dirpath, dirnames, filenames in os.walk(root):5 unmodified linesif 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 Nonedef _late_link_at_commit(self) -> Optional[Tuple[str, int, str, str]]:7 unmodified linesif linked is None:return Nonekind, rel = linkedreturn ("REFUSED",0,4 unmodified linesdef _lock_path(self) -> Path:return Path(self.workspace_root) / SESSION_LOCK_NAMEdef _lock_owner(self) -> Optional[int]:try:return int(self._lock_path().read_text(encoding="ascii"))except (OSError, ValueError):return None@staticmethoddef _lock_detail(lock: Path, owner: Optional[int]) -> str:if owner is None:return "a lock file sits at '%s' and its owner cannot be read" % lockreturn "another session run holds the workspace: '%s' names process %d" % (lock, owner)def _acquire_session_lock(self) -> None:"""Take the workspace lock with an exclusive create, never a polite ask.A lock left behind by a process that no longer runs is taken over; alock whose owner is alive, or whose owner cannot even be read, is arefusal the caller can read: the lock file names the process holdingthe workspace."""lock = self._lock_path()for attempt in (0, 1):try:handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)except FileExistsError:owner = self._lock_owner()if attempt or owner is None or _process_alive(owner):raise SessionLockError(self._lock_detail(lock, owner))try:lock.unlink()except OSError:raise SessionLockError("the leftover lock at '%s' could not be cleared" % lock)continuetry:os.write(handle, str(os.getpid()).encode("ascii"))finally:os.close(handle)self._held_lock = lockreturndef _release_session_lock(self) -> None:lock = getattr(self, "_held_lock", None)if lock is not None:self._held_lock = Nonetry:lock.unlink()except OSError:passdef _lock_refusal(self, case_id: str, rel_posix: Optional[str], exc: SessionLockError45 unmodified lineslinked = self._linked_path_in_workspace()if linked is not None:kind, rel = linkedexc = 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("\\", "/")702 unmodified linesrel_path=rel_path,attempts=tuple(attempts),failure_reasons=tuple(r.reason for r in attempts),),)else:20 unmodified lines2122232425262728 unmodified lines5657585960616263646566676817 unmodified lines86878889909192939495963 unmodified lines10010110210310410510610710810911011111215 unmodified lines12812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421548 unmodified lines264265266267268269270271272273274275276277278279144 unmodified lines42442542642742842943043143215 unmodified lines448449450451452453454455456457458237 unmodified lines6966976986997007017027037047057067077087097107117127137145 unmodified lines7207217227237247257267277287297307 unmodified lines7387397407417427437447457467477487497504 unmodified lines75575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683745 unmodified lines883884885886887888889890891892893894895702 unmodified lines159815991600160116021603160420 unmodified linesimport sysimport tempfileimport timeimport uuidfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple28 unmodified linesfrom lingologos_python.ast_graph import ( # noqa: E402IGNORED_DIRS,discover_python_files,hardlinked_file,importers_of,is_linked_path,)from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E402from lingologos_python.reasons import ( # noqa: E402HARDLINKED_PATH_IN_WORKSPACE,LINKED_PATH_IN_WORKSPACE,NODE_TIMEOUT,PATCH_NOT_APPLIED,17 unmodified linesclass WorkspaceLinkError(ValueError):"""The workspace holds a link, or a name counted twice, whose copy cannot match the disk."""def __init__(self, message: str, reason: str = LINKED_PATH_IN_WORKSPACE) -> None:super().__init__(message)self.reason = reasonclass SessionLockError(RuntimeError):3 unmodified lines# Two sessions committing to one workspace corrupt each other: each staged its# own copy from a disk the other has already rewritten. The lock is taken with# an exclusive create, so claiming it is never a polite ask, and released in a# finally even when the run was refused. The lock file names the holder's pid,# the creation time of that pid, and a token unique to the acquisition: the pid# separates live from dead, the birth time separates the holder that was# written down from a recycled pid wearing the same number, and the token keeps# a run from unlinking a lock another run retook after it stalled.SESSION_LOCK_NAME = ".lingologos-session.lock"SESSION_LOCK_CLAIM_SUFFIX = ".stale"def _process_alive(pid: int) -> bool:15 unmodified linesreturn Truedef _process_creation_time(pid: int) -> Optional[int]:"""When the process behind this pid was born, or None when the host will not say.A pid alone says a number is answered; it does not say the answeringprocess is the one that was written down. Birth times are the cheapestwitness of a recycled pid."""if pid <= 0:return Noneif os.name == "nt":kernel32 = ctypes.windll.kernel32kernel32.OpenProcess.restype = ctypes.c_void_pkernel32.OpenProcess.argtypes = [ctypes.c_ulong, ctypes.c_bool, ctypes.c_ulong]handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATIONif not handle:return Nonetry:low = ctypes.c_ulong(0)high = ctypes.c_ulong(0)unused = ctypes.c_ulong(0)kernel32.GetProcessTimes.argtypes = [ctypes.c_void_p,ctypes.POINTER(ctypes.c_ulong),ctypes.POINTER(ctypes.c_ulong),ctypes.POINTER(ctypes.c_ulong),ctypes.POINTER(ctypes.c_ulong),]if not kernel32.GetProcessTimes(handle, ctypes.byref(low), ctypes.byref(high), ctypes.byref(unused), ctypes.byref(unused)):return Nonereturn (int(high.value) << 32) | int(low.value)finally:kernel32.CloseHandle(handle)try:# Field 22 of /proc/<pid>/stat is the start time in clock ticks; the# comm field before it may itself hold spaces, so count from the last.with open("/proc/%d/stat" % pid, encoding="ascii") as handle:after_name = handle.read().rsplit(")", 1)[-1].split()return int(after_name[19])except (OSError, ValueError, IndexError):return Nonedef _read_lock_record(lock: Path) -> Optional[Tuple[int, Optional[int], Optional[str]]]:"""The (pid, birth, token) a lock file names, or None when it names nothing readable."""try:parts = lock.read_text(encoding="ascii").split()except (OSError, UnicodeDecodeError):return Noneif not parts:return Nonetry:pid = int(parts[0])except ValueError:return Nonebirth: Optional[int] = Noneif len(parts) > 1 and parts[1] != "-":try:birth = int(parts[1])except ValueError:return Nonetoken = parts[2] if len(parts) > 2 else Nonereturn (pid, birth, token)def _lock_holder_is_alive(record: Tuple[int, Optional[int], Optional[str]]) -> bool:"""A holder lives when its pid answers and is the same process it was when written.A pid recycled by a young process looks alive; the recorded birth time saysthe process now wearing the number is somebody else."""pid, birth, _token = recordif not _process_alive(pid):return Falseif birth is not None:now = _process_creation_time(pid)if now is not None and now != birth:return Falsereturn TrueDEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ("*.env",".env*",48 unmodified linesA loop that hands the proposer only the index and the last result teaches itnothing about why the nodes refused. A proposer that accepts a thirdargument receives all of it: every prior result with its verdict, reason,trace lines and the dossier the kernel returned, plus the patch signaturesthe loop detector compares, which read the fate of a patch and not itswords. A two-argument proposer keeps working unchanged."""attempt: intrel_path: strattempts: Tuple[SessionResult, ...] = ()failure_reasons: Tuple[str, ...] = ()patch_signatures: Tuple[str, ...] = ()def _disk_text(root: Path, rel_posix: str) -> str:144 unmodified linesA 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. Afile standing under two names is refused too: the copy would split onefile into two, and a later commit could not tell the names apart."""root = src_root.resolve()for dirpath, dirnames, filenames in os.walk(src_root):15 unmodified linesraise WorkspaceLinkError("linked file in the workspace: '%s'" % (rel_dir / name).as_posix())if hardlinked_file(src_file):raise WorkspaceLinkError("hardlinked file in the workspace: '%s'" % (rel_dir / name).as_posix(),HARDLINKED_PATH_IN_WORKSPACE,)shutil.copy2(src_file, target_dir / name)237 unmodified linescase_id=case_id,verdict="REFUSED",assurance=0,reason=getattr(exc, "reason", LINKED_PATH_IN_WORKSPACE),detail=str(exc),committed=False,touched_files=(rel_posix,),)def _linked_path_in_workspace(self) -> Optional[Tuple[str, str]]:"""Return ('directory'|'file'|'hardlink', rel_posix) for the first anomaly under the root.Verify judges the workspace where it stands, with no staging copy torefuse for it, so it asks the same question the copy asks: is any partof this tree somewhere else, or does any single file answer under twonames."""root = Path(self.workspace_root).resolve()for dirpath, dirnames, filenames in os.walk(root):5 unmodified linesif is_linked_path(Path(dirpath) / name):return ("directory", (rel_dir / name).as_posix())for name in filenames:entry = Path(dirpath) / nameif is_linked_path(entry):return ("file", (rel_dir / name).as_posix())if hardlinked_file(entry):return ("hardlink", (rel_dir / name).as_posix())return Nonedef _late_link_at_commit(self) -> Optional[Tuple[str, int, str, str]]:7 unmodified linesif linked is None:return Nonekind, rel = linkedif kind == "hardlink":return ("REFUSED",0,HARDLINKED_PATH_IN_WORKSPACE,"a hardlinked file appeared in the workspace before the commit: '%s'" % rel,)return ("REFUSED",0,4 unmodified linesdef _lock_path(self) -> Path:return Path(self.workspace_root) / SESSION_LOCK_NAMEdef _lock_owner(self) -> Optional[Tuple[int, Optional[int], Optional[str]]]:return _read_lock_record(self._lock_path())@staticmethoddef _lock_detail(lock: Path, record: Optional[Tuple[int, Optional[int], Optional[str]]]) -> str:if record is None:return "a lock file sits at '%s' and its owner cannot be read" % lockreturn "another session run holds the workspace: '%s' names process %d" % (lock, record[0])def _acquire_session_lock(self) -> None:"""Take the workspace lock with an exclusive create, never a polite ask.The lock names the holder's pid, its birth time, and a token unique tothis acquisition. A lock left behind by a process that no longer runs istaken over through a rename: two runs that find the same leftover racefor the rename, only one proceeds, and the loser is refused rather thanhanded a second silent holder. A lock whose owner is alive, or that hasrecycled only its pid number, or whose owner cannot even be read, is arefusal the caller can read."""lock = self._lock_path()claim = Path(str(lock) + SESSION_LOCK_CLAIM_SUFFIX)if claim.exists():try:# Bookkeeping of a takeover that finished or died mid-step; the# exclusive create below is what actually grants the workspace.claim.unlink()except OSError:passtoken = uuid.uuid4().hexfor attempt in (0, 1):try:handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)except FileExistsError:record = self._lock_owner()if attempt or record is None or _lock_holder_is_alive(record):raise SessionLockError(self._lock_detail(lock, record))try:os.rename(str(lock), str(claim))except OSError:raise SessionLockError("the leftover lock at '%s' is being taken over by another run" % lock)continuebirth = _process_creation_time(os.getpid())try:os.write(handle,("%d %s %s" % (os.getpid(), "-" if birth is None else birth, token)).encode("ascii"),)finally:os.close(handle)self._held_lock = lockself._lock_token = tokenif claim.exists():try:claim.unlink()except OSError:passreturndef _release_session_lock(self) -> None:lock = getattr(self, "_held_lock", None)if lock is None:returnself._held_lock = Nonetoken = getattr(self, "_lock_token", None)self._lock_token = Nonerecord = _read_lock_record(lock)if token is None or record is None or record[2] != token:# The lock under this name is no longer ours: a takeover happened# while this run stalled, and unlinking it would steal that holder.returntry:lock.unlink()except OSError:passdef _lock_refusal(self, case_id: str, rel_posix: Optional[str], exc: SessionLockError45 unmodified lineslinked = self._linked_path_in_workspace()if linked is not None:kind, rel = linkedif kind == "hardlink":exc = WorkspaceLinkError("hardlinked file in the workspace: '%s'" % rel,HARDLINKED_PATH_IN_WORKSPACE,)else: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("\\", "/")702 unmodified linesrel_path=rel_path,attempts=tuple(attempts),failure_reasons=tuple(r.reason for r in attempts),patch_signatures=tuple(history),),)else:
1234567891 unmodified line1112131415161 unmodified line1819202122231 unmodified line2526272829301 unmodified line3233343536371 unmodified line394041424344454647484950511 unmodified line5354555657581 unmodified line6061626364651 unmodified line6768697071721 unmodified line7475767778791 unmodified line8182838485861 unmodified line8889909192939495{"schema": "lingologos-python-gates-1","verdict": "CONFIRMED","sources_sha256": "b65bae4a72d222f72e68b45b176d7dfa814de9314cf604e7cc497e063dac5125","counts": {"CONFIRMED": 12,"REJECTED": 0,"ABSTAIN": 0},1 unmodified line{"name": "adapter_contract","verdict": "CONFIRMED","check": "check_adapter_contract on PythonLanguageAdapter","note": "no violations for lingologos-python","failed_targets": []1 unmodified line{"name": "ast_symbol_graph","verdict": "CONFIRMED","check": "Python AST symbol, method, inheritance, and import graph","note": "13 symbols, 10 edges extracted","failed_targets": []1 unmodified line{"name": "test_selection","verdict": "CONFIRMED","check": "import-aware Python test selection","note": "selected 2 dependent test file(s)","failed_targets": []1 unmodified line{"name": "strict_abstain_control","verdict": "CONFIRMED","check": "missing optional tools produce ABSTAIN and block verdict","note": "missing static tools abstained and ended in UNKNOWN/GATE_ABSTAIN","failed_targets": []1 unmodified line{"name": "session_transactions","verdict": "CONFIRMED","check": "staged edit commit on VERIFIED and disk isolation on refusal","note": "clean edit committed VERIFIED (3); syntax error and protected path refused","failed_targets": []},{"name": "external_topology","verdict": "CONFIRMED","check": "external topology.json, node folders, and six subprocess turns","note": "6 node folders valid, 7 subprocess envelopes reached VERIFIED (3)","failed_targets": []1 unmodified line{"name": "pattern_corpus_schema","verdict": "CONFIRMED","check": "patterns/pattern_cases.jsonl is a valid case-1 corpus with one pair per card","note": "16 rows over 8 cards, each with its lock test and its refusal","failed_targets": []1 unmodified line{"name": "pattern_round_trip","verdict": "CONFIRMED","check": "every row of the pattern corpus re-plans on the fixture as written","note": "16 rows re-planned: 8 pairs land and compile, 8 refusals repeat with the same code","failed_targets": []1 unmodified line{"name": "pattern_pair_honesty","verdict": "CONFIRMED","check": "each card's lock test fails until the source edit of its pair lands","note": "8 cards: every lock test fails while its source edit is missing, so the pair is not decoration","failed_targets": []1 unmodified line{"name": "pattern_coverage","verdict": "CONFIRMED","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": []1 unmodified line{"name": "cli_card_agreement","verdict": "CONFIRMED","check": "every verb and flag the card prints exists in the real parser","note": "13 printed command lines agree with the 8 verbs of the parser","failed_targets": []1 unmodified line{"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 168 symbols and 350 edges; 45 reason codes, every one named in the card; 34 names promised in the Contents, all defined","failed_targets": []}]1234567891 unmodified line111213141516171 unmodified line192021222324251 unmodified line272829303132331 unmodified line353637383940411 unmodified line43444546474849505152535455565758596061626364651 unmodified line676869707172731 unmodified line757677787980811 unmodified line838485868788891 unmodified line919293949596971 unmodified line991001011021031041051 unmodified line107108109110111112113114115{"schema": "lingologos-python-gates-1","verdict": "CONFIRMED","sources_sha256": "c67f159b042510540c5ceaeed6cb105d706b1af6c84c4956460676ed22d85bcf","counts": {"CONFIRMED": 13,"REJECTED": 0,"ABSTAIN": 0},1 unmodified line{"name": "adapter_contract","verdict": "CONFIRMED","seconds": 0.829,"check": "check_adapter_contract on PythonLanguageAdapter","note": "no violations for lingologos-python","failed_targets": []1 unmodified line{"name": "ast_symbol_graph","verdict": "CONFIRMED","seconds": 0.002,"check": "Python AST symbol, method, inheritance, and import graph","note": "13 symbols, 10 edges extracted","failed_targets": []1 unmodified line{"name": "test_selection","verdict": "CONFIRMED","seconds": 0.003,"check": "import-aware Python test selection","note": "selected 2 dependent test file(s)","failed_targets": []1 unmodified line{"name": "strict_abstain_control","verdict": "CONFIRMED","seconds": 0.848,"check": "missing optional tools produce ABSTAIN and block verdict","note": "missing static tools abstained and ended in UNKNOWN/GATE_ABSTAIN","failed_targets": []1 unmodified line{"name": "session_transactions","verdict": "CONFIRMED","seconds": 3.11,"check": "staged edit commit on VERIFIED and disk isolation on refusal","note": "clean edit committed VERIFIED (3); syntax error and protected path refused","failed_targets": []},{"name": "session_sweep","verdict": "CONFIRMED","seconds": 6.659,"check": "fixed-seed sweep of session verbs over a copied package","note": "12 seeded operations: 3 committed, 9 refused or raised, tree state compared after each one","failed_targets": []},{"name": "external_topology","verdict": "CONFIRMED","seconds": 1.887,"check": "external topology.json, node folders, and six subprocess turns","note": "6 node folders valid, 7 subprocess envelopes reached VERIFIED (3)","failed_targets": []1 unmodified line{"name": "pattern_corpus_schema","verdict": "CONFIRMED","seconds": 0.0,"check": "patterns/pattern_cases.jsonl is a valid case-1 corpus with one pair per card","note": "16 rows over 8 cards, each with its lock test and its refusal","failed_targets": []1 unmodified line{"name": "pattern_round_trip","verdict": "CONFIRMED","seconds": 0.01,"check": "every row of the pattern corpus re-plans on the fixture as written","note": "16 rows re-planned: 8 pairs land and compile, 8 refusals repeat with the same code","failed_targets": []1 unmodified line{"name": "pattern_pair_honesty","verdict": "CONFIRMED","seconds": 5.182,"check": "each card's lock test fails until the source edit of its pair lands","note": "8 cards: every lock test fails while its source edit is missing, so the pair is not decoration","failed_targets": []1 unmodified line{"name": "pattern_coverage","verdict": "CONFIRMED","seconds": 0.003,"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": []1 unmodified line{"name": "cli_card_agreement","verdict": "CONFIRMED","seconds": 0.005,"check": "every verb and flag the card prints exists in the real parser","note": "13 printed command lines agree with the 8 verbs of the parser","failed_targets": []1 unmodified line{"name": "self_lint","verdict": "CONFIRMED","seconds": 0.145,"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 175 symbols and 361 edges; 46 reason codes, every one named in the card; 36 names promised in the Contents, all defined","failed_targets": []}]
4 unmodified lines56789101173 unmodified lines8586874 unmodified linesfrom pathlib import Pathfrom typing import List, Tuplefrom lingologos_python.ast_graph import discover_python_files, extract_python_graphfrom lingologos_python.test_selector import select_python_tests73 unmodified lines_hard_package(tmp_path)selected = select_python_tests(tmp_path, ["app/plugins/extra.py"])assert selected == ["tests/test_ns.py"]4 unmodified lines567891011121314151673 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271284 unmodified linesfrom pathlib import Pathfrom typing import List, Tuplefrom lingologos_python.ast_graph import (discover_python_files,extract_python_graph,importers_of,reexported_names,)from lingologos_python.test_selector import select_python_tests73 unmodified lines_hard_package(tmp_path)selected = select_python_tests(tmp_path, ["app/plugins/extra.py"])assert selected == ["tests/test_ns.py"]def _reexport_package(root: Path) -> None:"""One package that answers with names its __init__ imports from inside itself."""_write(root, "app/__init__.py", "from .impl import helper\nfrom . import tools\n")_write(root, "app/impl.py", "def helper() -> int:\n return 2\n")_write(root, "app/tools.py", "X = 1\n")_write(root,"tests/test_app.py","from app import helper\n\n\ndef test_helper():\n assert helper() == 2\n",)_write(root,"tests/test_tools.py","from app.tools import X\n\n\ndef test_x():\n assert X == 1\n",)def test_a_reexport_table_names_every_file_a_package_answer_for(tmp_path: Path) -> None:_reexport_package(tmp_path)table = reexported_names(tmp_path, "app/__init__.py")assert "app.impl" in table["helper"]assert "app.tools" in table["tools"]def test_a_change_behind_a_reexport_reaches_the_test_that_never_named_the_file(tmp_path: Path,) -> None:_reexport_package(tmp_path)files = discover_python_files(tmp_path)assert "tests/test_app.py" in importers_of(tmp_path, files, "app/impl.py")edges = set(_file_edges(tmp_path))assert ("tests/test_app.py", "app/impl.py") in edgesselected = select_python_tests(tmp_path, ["app/impl.py"])assert "tests/test_app.py" in selected
12 unmodified lines13141516171819 unmodified lines38394041424324 unmodified lines6869707172737412 unmodified linesGATE_ABSTAIN,GATE_MISSING,GATE_REJECTED,KERNEL_REASONS,LINKED_PATH_IN_WORKSPACE,NODE_TIMEOUT,19 unmodified linesPATCH_NOT_APPLIED,NODE_TIMEOUT,LINKED_PATH_IN_WORKSPACE,SESSION_LOCKED,}assert set(KERNEL_REASONS) == {24 unmodified linesdef 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", "SESSION_LOCKED"):assert getattr(session_module, name) in REASON_CODESassert getattr(session_module, name) == name12 unmodified lines1314151617181919 unmodified lines3940414243444524 unmodified lines707172737475767778798081828312 unmodified linesGATE_ABSTAIN,GATE_MISSING,GATE_REJECTED,HARDLINKED_PATH_IN_WORKSPACE,KERNEL_REASONS,LINKED_PATH_IN_WORKSPACE,NODE_TIMEOUT,19 unmodified linesPATCH_NOT_APPLIED,NODE_TIMEOUT,LINKED_PATH_IN_WORKSPACE,HARDLINKED_PATH_IN_WORKSPACE,SESSION_LOCKED,}assert set(KERNEL_REASONS) == {24 unmodified linesdef 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","HARDLINKED_PATH_IN_WORKSPACE","SESSION_LOCKED",):assert getattr(session_module, name) in REASON_CODESassert getattr(session_module, name) == name
2 unmodified lines3456785 unmodified lines141516171819105 unmodified lines1251261271281291302 unmodified lines133134135136137138462 unmodified lines6016026032 unmodified linesfrom __future__ import annotationsimport osimport timefrom pathlib import Pathfrom typing import Any, Dict, Tuple5 unmodified linesimport lingologos_python.session as session_modulefrom lingologos_python.adapter import GATE_TIMEOUT_ENVfrom lingologos_python.session import (LINKED_PATH_IN_WORKSPACE,NODE_TIMEOUT,NodeTimeoutError,105 unmodified linesseen["trace"] = context.attempts[0].traceseen["attempt"] = context.attemptseen["path"] = context.rel_pathreturn ("return left + right", "return left + right # proposed again")final, _attempts = session.run_retry_loop("src/mathops.py", learning_proposer, max_attempts=3)2 unmodified linesassert len(seen["trace"]) >= 6assert seen["attempt"] == 2assert seen["path"] == "src/mathops.py"def test_verify_probe_annotates_a_line_that_keeps_the_file_parsable() -> None:462 unmodified linesassert res.reason == session_module.SESSION_LOCKEDassert "cannot be read" in res.detaillock.unlink()2 unmodified lines34567895 unmodified lines15161718192021105 unmodified lines1271281291301311321332 unmodified lines136137138139140141142143144145462 unmodified lines6086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307312 unmodified linesfrom __future__ import annotationsimport osimport threadingimport timefrom pathlib import Pathfrom typing import Any, Dict, Tuple5 unmodified linesimport lingologos_python.session as session_modulefrom lingologos_python.adapter import GATE_TIMEOUT_ENVfrom lingologos_python.session import (HARDLINKED_PATH_IN_WORKSPACE,LINKED_PATH_IN_WORKSPACE,NODE_TIMEOUT,NodeTimeoutError,105 unmodified linesseen["trace"] = context.attempts[0].traceseen["attempt"] = context.attemptseen["path"] = context.rel_pathseen["signatures"] = tuple(context.patch_signatures)return ("return left + right", "return left + right # proposed again")final, _attempts = session.run_retry_loop("src/mathops.py", learning_proposer, max_attempts=3)2 unmodified linesassert len(seen["trace"]) >= 6assert seen["attempt"] == 2assert seen["path"] == "src/mathops.py"# The fate of the first patch, not its words: the signature the stall# detector read is handed to the proposer that should learn from it.assert len(seen["signatures"]) == 1assert seen["signatures"][0].startswith("sha256:") or len(seen["signatures"][0]) == 40def test_verify_probe_annotates_a_line_that_keeps_the_file_parsable() -> None:462 unmodified linesassert res.reason == session_module.SESSION_LOCKEDassert "cannot be read" in res.detaillock.unlink()def test_the_lock_file_names_pid_birth_and_a_token_this_run_can_prove(sample_pkg: Path, monkeypatch) -> None:"""The written record carries three fields, and the token belongs to this acquisition."""lock = sample_pkg / session_module.SESSION_LOCK_NAMEseen: Dict[str, str] = {}real_pipeline = session_module.run_pipelinedef spy_pipeline(case):seen["record"] = lock.read_text(encoding="ascii")return real_pipeline(case)monkeypatch.setattr(session_module, "run_pipeline", spy_pipeline)session = PythonWorkspaceSession(sample_pkg)res = session.verify("src/mathops.py")assert res.verdict == "VERIFIED"parts = seen["record"].split()assert parts[0] == str(os.getpid())assert parts[1] != "-" and int(parts[1]) > 0assert len(parts[2]) == 32assert not lock.exists()def test_a_recycled_pid_with_a_different_birth_is_not_the_recorded_holder(sample_pkg: Path,) -> None:"""A live pid is not proof: the birth time written in the lock has to match."""birth = session_module._process_creation_time(os.getpid())if birth is None:pytest.skip("this host does not report process birth times")lock = sample_pkg / session_module.SESSION_LOCK_NAMElock.write_text("%d %d t0k0n\n" % (os.getpid(), birth + 10**9), encoding="ascii", newline="")session = PythonWorkspaceSession(sample_pkg)res = session.verify("src/mathops.py")# The number answers, the birth does not: the holder recorded is gone and# the takeover is honest.assert res.verdict == "VERIFIED"assert not lock.exists()def test_two_runs_taking_over_one_leftover_lock_leave_a_single_holder(sample_pkg: Path) -> None:"""The takeover renames the corpse first: the loser of the rename is refused."""lock = sample_pkg / session_module.SESSION_LOCK_NAMElock.write_text("99999999\n", encoding="ascii", newline="")sessions = [PythonWorkspaceSession(sample_pkg) for _ in range(2)]outcomes: Dict[int, str] = {}gate = threading.Barrier(2)def grab(index: int) -> None:try:gate.wait()sessions[index]._acquire_session_lock()outcomes[index] = "held"except session_module.SessionLockError:outcomes[index] = "refused"threads = [threading.Thread(target=grab, args=(i,)) for i in range(2)]for thread in threads:thread.start()for thread in threads:thread.join()assert sorted(outcomes.values()) == ["held", "refused"]record = session_module._read_lock_record(lock)assert record is not None and record[0] == os.getpid()winner = sessions[next(i for i, v in outcomes.items() if v == "held")]winner._release_session_lock()assert not lock.exists()stale = sample_pkg / (session_module.SESSION_LOCK_NAME + session_module.SESSION_LOCK_CLAIM_SUFFIX)assert not stale.exists()def test_a_run_never_unlinks_a_lock_another_run_retook(sample_pkg: Path, monkeypatch) -> None:"""Release checks its own token: a lock rewritten while we run is not ours to delete."""lock = sample_pkg / session_module.SESSION_LOCK_NAMEreal_pipeline = session_module.run_pipelinedef hijack_pipeline(case):# Mid-run, a different holder takes the workspace over under our name.lock.write_text("99999999 - someone-elses-token\n", encoding="ascii", newline="")return real_pipeline(case)monkeypatch.setattr(session_module, "run_pipeline", hijack_pipeline)session = PythonWorkspaceSession(sample_pkg)res = session.verify("src/mathops.py")assert res.verdict == "VERIFIED"# Our release read the token, found it was not ours, and left the lock alone.assert lock.exists()assert "someone-elses-token" in lock.read_text(encoding="ascii")lock.unlink()def test_a_hardlinked_pair_in_the_workspace_is_refused_by_name(sample_pkg: Path) -> None:"""Two names, one file: the copy would split what the disk holds as one."""twin = sample_pkg / "src" / "mathops_twin.py"os.link(sample_pkg / "src" / "mathops.py", twin)session = PythonWorkspaceSession(sample_pkg)res = session.verify("src/mathops.py")assert res.verdict == "REFUSED"assert res.reason == HARDLINKED_PATH_IN_WORKSPACEassert "src/mathops" in res.detailtwin.unlink()def test_an_edit_does_not_commit_through_a_hardlinked_name(sample_pkg: Path) -> None:"""The staging copy refuses the hardlink and the real file keeps its bytes."""twin = sample_pkg / "src" / "mathops_twin.py"os.link(sample_pkg / "src" / "mathops.py", twin)session = PythonWorkspaceSession(sample_pkg)res = session.edit_file("src/mathops.py", "return left + right", "return left * right", commit=True)assert res.verdict == "REFUSED"assert res.reason == HARDLINKED_PATH_IN_WORKSPACEassert res.committed is Falsetext = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")assert "return left + right" in texttwin.unlink()
5 unmodified lines67891011121314151618 unmodified lines35363738394041132 unmodified lines174175176177178179423 unmodified lines60360460560660760811 unmodified lines62062162262362462562662762810 unmodified lines6396406416426436446456466476486496506516526536546555 unmodified linesimport astimport hashlibimport jsonimport reimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Pathfrom typing import Callable, Dict, List, Sequence, Set, Tuple18 unmodified linesfrom 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: E402FIXTURE_PKG = ROOT / "fixtures" / "sample_pkg"132 unmodified linesreturn _confirmed(check, "clean edit committed VERIFIED (3); syntax error and protected path refused")def gate_external_topology() -> GateResult:check = "external topology.json, node folders, and six subprocess turns"topo = json.loads((ROOT / "topology.json").read_text(encoding="utf-8"))423 unmodified lines("test_selection", gate_test_selection),("strict_abstain_control", gate_strict_abstain_control),("session_transactions", gate_session_transactions),("external_topology", gate_external_topology),("pattern_corpus_schema", gate_pattern_corpus_schema),("pattern_round_trip", gate_pattern_round_trip),11 unmodified linesparser.add_argument("--report", default=None, help="Optional path to write JSON report.")args = parser.parse_args(argv)results: Dict[str, GateResult] = {}for name, fn in GATES:results[name] = fn()counts = {v: 0 for v in VERDICTS}for res in results.values():10 unmodified lines)if args.report:out_path = Path(args.report)out_path.parent.mkdir(parents=True, exist_ok=True)payload = {"schema": "lingologos-python-gates-1","verdict": overall,"sources_sha256": bundle_digest(digest_input_files(ROOT)),"counts": counts,"gates": [{"name": name,"verdict": results[name].verdict,"check": results[name].command,"note": results[name].note,"failed_targets": list(results[name].failed_targets),5 unmodified lines67891011121314151617181918 unmodified lines38394041424344132 unmodified lines177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320423 unmodified lines74474574674774874975011 unmodified lines76276376476576676776876977077177277377477577677777877910 unmodified lines7907917927937947957967977987998008018028038048058068078088098108118128138145 unmodified linesimport astimport hashlibimport jsonimport osimport randomimport reimport shutilimport subprocessimport sysimport tempfileimport timefrom pathlib import Pathfrom typing import Callable, Dict, List, Sequence, Set, Tuple18 unmodified linesfrom 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 SESSION_LOCK_NAME, PythonWorkspaceSession # noqa: E402from lingologos_python.test_selector import select_python_tests # noqa: E402FIXTURE_PKG = ROOT / "fixtures" / "sample_pkg"132 unmodified linesreturn _confirmed(check, "clean edit committed VERIFIED (3); syntax error and protected path refused")# The sweep the fuzz test runs at full length gets a short, seeded twin here:# the same invariant, a dozen operations, a fixed seed so the gate answers the# same way on every machine. It exists because the card promises that no change# lands without a commit and no refusal leaves a trace, and a gate, not only a# test file, has to keep that promise under review.SESSION_SWEEP_SEED = 20260301SESSION_SWEEP_PLAN: List[str] = (["valid_edit_commit"] * 2+ ["valid_create_commit"]+ ["verify"]+ ["traversal_edit"] * 2+ ["protected_create"]+ ["missing_edit"]+ ["missing_delete"]+ ["create_existing"]+ ["empty_edit"]+ ["bad_pattern"])def _sweep_tree_state(root: Path) -> Dict[str, bytes]:state: Dict[str, bytes] = {}for path in root.rglob("*"):if not path.is_file():continuerel = path.relative_to(root).as_posix()parts = rel.split("/")if any(part in ("__pycache__", ".pytest_cache") for part in parts[:-1]):continueif path.suffix in (".pyc", ".pyo"):continuestate[rel] = path.read_bytes()return statedef gate_session_sweep() -> GateResult:check = "fixed-seed sweep of session verbs over a copied package"rng = random.Random(SESSION_SWEEP_SEED)kinds = list(SESSION_SWEEP_PLAN)rng.shuffle(kinds)files = ["src/mathops.py", "src/textops.py", "tests/test_mathops.py", "tests/test_textops.py"]ops = [(kind, rng.choice(files)) for kind in kinds]with tempfile.TemporaryDirectory(prefix="lingologos_python_sweep_") as tmp_dir:ws = Path(tmp_dir) / "pkg"shutil.copytree(FIXTURE_PKG, ws)failures: List[str] = []committed = 0refused = 0raised = 0for index, (kind, rel) in enumerate(ops):session = PythonWorkspaceSession(ws)lock_held = Falseif index == 5:# Plant a live holder: our own process is alive, so the lock is real.(ws / SESSION_LOCK_NAME).write_text(str(os.getpid()), encoding="ascii")lock_held = Truebefore = _sweep_tree_state(ws)try:res = Noneif kind == "valid_edit_commit":path = ws / Path(*rel.split("/"))text = path.read_text(encoding="utf-8", newline="")anchor = [line for line in text.split("\n") if line.strip()][-1]res = session.edit_file(rel, anchor, anchor + "\n# swept", commit=True)elif kind == "valid_create_commit":res = session.create_file("src/extra_%d.py" % index,"def extra_%d() -> int:\n return %d\n" % (index, index),commit=True,)elif kind == "verify":res = session.verify(rel)elif kind == "traversal_edit":res = session.edit_file("../outside_the_tree.py", "a", "b", commit=True)elif kind == "protected_create":res = session.create_file(".env", "SECRET=1\n", commit=True)elif kind == "missing_edit":res = session.edit_file("src/absent_%d.py" % index, "a", "b", commit=True)elif kind == "missing_delete":try:res = session.delete_file("src/gone_%d.py" % index, commit=True)except FileNotFoundError:raised += 1elif kind == "create_existing":try:res = session.create_file(rel, "x = 1\n", commit=True)except FileExistsError:raised += 1elif kind == "empty_edit":res = session.edit_file(rel, "", "", commit=True)elif kind == "bad_pattern":try:res = session.apply_pattern("ghost-card-%d" % index, commit=True)except KeyError:raised += 1after = _sweep_tree_state(ws)if res is None:if after != before:failures.append("%d %s: an expected exception still wrote to disk" % (index, kind))continueif res.verdict in ("REFUSED", "UNKNOWN") and res.reason not in REASON_CODES:failures.append("%d %s: unregistered reason %s" % (index, kind, res.reason))if res.committed:committed += 1if res.verdict not in ("VERIFIED", "SINGLE_PROVER") or not res.accepted:failures.append("%d %s: committed with verdict %s" % (index, kind, res.verdict))changed = {r for r in set(before) | set(after) if before.get(r) != after.get(r)}if changed and not changed <= set(res.touched_files):failures.append("%d %s: changed files the result did not name" % (index, kind))else:refused += 1if after != before:failures.append("%d %s (%s): disk moved without a commit" % (index, kind, res.reason))if lock_held and res.verdict != "REFUSED":failures.append("%d %s: a planted lock did not refuse the run" % (index, kind))except Exception as exc: # a crash of the sweep is a finding, not a passfailures.append("%d %s: %s: %s" % (index, kind, type(exc).__name__, exc))finally:if lock_held:(ws / SESSION_LOCK_NAME).unlink(missing_ok=True)if failures:return _rejected(check, "; ".join(failures), failures)if committed < 2 or refused + raised < len(SESSION_SWEEP_PLAN) - 3:return _rejected(check,"sweep landed %d commits and %d refusals out of %d operations"% (committed, refused + raised, len(SESSION_SWEEP_PLAN)),)return _confirmed(check,"%d seeded operations: %d committed, %d refused or raised, tree state compared after each one"% (len(ops), committed, refused + raised),)def gate_external_topology() -> GateResult:check = "external topology.json, node folders, and six subprocess turns"topo = json.loads((ROOT / "topology.json").read_text(encoding="utf-8"))423 unmodified lines("test_selection", gate_test_selection),("strict_abstain_control", gate_strict_abstain_control),("session_transactions", gate_session_transactions),("session_sweep", gate_session_sweep),("external_topology", gate_external_topology),("pattern_corpus_schema", gate_pattern_corpus_schema),("pattern_round_trip", gate_pattern_round_trip),11 unmodified linesparser.add_argument("--report", default=None, help="Optional path to write JSON report.")args = parser.parse_args(argv)# The digest anchors the report to a tree, so it is taken before the first# gate runs and asked for again when the report is written: the numbers# inside describe the tree that was judged at the start, and a tree that# moved while the gates ran earns no report at all.opening_digest = bundle_digest(digest_input_files(ROOT))results: Dict[str, GateResult] = {}seconds: Dict[str, float] = {}for name, fn in GATES:started = time.monotonic()results[name] = fn()seconds[name] = round(time.monotonic() - started, 3)counts = {v: 0 for v in VERDICTS}for res in results.values():10 unmodified lines)if args.report:closing_digest = bundle_digest(digest_input_files(ROOT))if closing_digest != opening_digest:print("REPORT: REFUSED (the tree changed while the gates ran, before %s and after %s): ""rerun on a quiet tree" % (opening_digest[:12], closing_digest[:12]))return 1out_path = Path(args.report)out_path.parent.mkdir(parents=True, exist_ok=True)payload = {"schema": "lingologos-python-gates-1","verdict": overall,"sources_sha256": opening_digest,"counts": counts,"gates": [{"name": name,"verdict": results[name].verdict,"seconds": seconds[name],"check": results[name].command,"note": results[name].note,"failed_targets": list(results[name].failed_targets),
README.md+24-13
lingologos_python/ast_graph.py+88-1
lingologos_python/reasons.py+2
lingologos_python/session.py+184-34
results/gates.json+23-3
tests/test_ast_imports.py+42-1
tests/test_reasons.py+10-1
tests/test_session.py+128
tools/run_gates.py+161-2