Upload folder using huggingface_hub
Browse filesFiles changed (14)
- README.md+21-7
- lingologos_python/ast_graph.py+35-2
- lingologos_python/cli.py+9-3
- lingologos_python/gates.py+94-15
- lingologos_python/session.py+192-36
- results/gates.json+8-1
- tests/test_adapter.py+75-1
- tests/test_ast_graph.py+38-1
- tests/test_cli.py+18
- tests/test_pattern_session.py+33
- tests/test_session.py+99
- tests/test_topology_and_cli.py+69-1
- tools/publish_dataset.py+6-6
- tools/run_gates.py+66
31 unmodified lines3233343535363738383940416 unmodified lines484950515152535455555657585960614 unmodified lines666768666970717273747536 unmodified lines112113114109115116117118119120121122123124125126127147 unmodified lines27527627726627827928028128228331 unmodified lines
```
python -B tools/run_gates.py
GATES: CONFIRMED (9 gates: 9 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
GATES: CONFIRMED (10 gates: 10 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
```
The gate runner is where this bundle states its numbers out loud: 9 gates, 99 tests across 9 files,
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 every
one of those numbers from the tree it is standing in and stops the upload when the card and the code
beside it disagree.6 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 call
graph extraction (`discover_python_files`, `extract_python_graph`).
graph extraction (`discover_python_files`, `extract_python_graph`, `importers_of`). A file whose bytes
are not UTF-8 text is named as a file and given no symbols, rather than decoded into inventions.
- `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 static
checkers (`mypy`, `ruff`, `pyright`, `flake8`) that return `ABSTAIN` when missing, and `pytest`
/ `unittest` test runner with failed-target parsing.
/ `unittest` test runner with failed-target parsing. The unittest fallback runs importable module
names rather than paths, and a runner that collected zero tests abstains instead of confirming
or rejecting.
- `lingologos_python/rules.py`: eight shape rules over a named function. Each rule reads the function
through its syntax tree, refuses with a named reason code when the shape is not the one it claims, and
returns the edit texts when it is (`RULES`, `RULE_IDS`, `open_target`).4 unmodified lines- `lingologos_python/session.py`: `PythonWorkspaceSession` for safe staged verification and atomic disk
commits via `lingologos_codex.fsadapter` (`verify`, `edit_file`, `create_file`, `delete_file`,
`apply_pattern`, `run_retry_loop`, and `run_topology_subprocesses`). A commit re-reads what is on disk
and refuses with `PATCH_NOT_APPLIED` when the workspace moved while the six nodes were running.
and refuses with `PATCH_NOT_APPLIED` when the workspace moved while the six nodes were running. A
write the disk refuses part way is undone from the in-memory originals, so a run never reports a
change it did not land. A delete names the surviving files that import the module being removed,
and goes through the kernel's delete transaction rather than an unlink of the session's own.
- `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 and36 unmodified lines
Every change this bundle makes is a pair. The rule returns two edits, the change in the source file
and a lock test appended to the test file paired with it, and `apply_pattern` puts both in one
transaction: the pair commits together, or nothing is written. The lock test is what makes the
transaction: the pair commits together, or nothing is written. If the disk refuses that transaction
part way, the session restores both files from the originals it kept in memory and reports the named
refusal, and `committed` is true only after each written file has been read back and matched against
the verified text. The lock test is what makes the
second run honest. Run `chain-to-registry` on `src/registry.py::render` and the lock asserts that
the mapping is there, that each kind reaches its handler, that the chain is gone, and that the
refusal still refuses; take only the lock test and leave the source alone, and the test suite fails.
The `pattern_pair_honesty` gate runs exactly that experiment for every card: it writes only the test
side of the pair into a copy of the laboratory and reruns its suite, and it fails the gates if any
such copy still passes.
The three newest cards write their lock as a reading rather than a call: the test opens the function
with `inspect` and asserts on the text the rewrite leaves behind and the text it removes, so the lock
still fails while the old shape stands, but it answers about the source and not about a behavior.147 unmodified lines
`patterns apply` without `--dry-run` commits, and only on a verdict the kernel accepts: it commits
when the assurance reaches the higher of the session floor and the card's own floor, and reports a
refusal with the reason code of the rule that stopped it. `fixtures/pattern_lab/` is a copy candidate:
refusal with the reason code of the rule that stopped it. The exit code follows the write, not the
verdict: `edit`, `create` and `patterns apply` exit 0 only when the change landed on disk, or when a
`--dry-run` was accepted. `fixtures/pattern_lab/` is a copy candidate:
the commands above either read it or verify against a copy, and the tests copy it to a temporary folder
before writing, so the folder as published keeps the exact shape the coverage numbers were counted on.
80 unmodified lines81828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117899011811912012112212312412512680 unmodified lines return candidates
def importers_of(workspace: Path, files: Sequence[str], target_rel: str) -> List[str]: """Return the files whose import statements could bind to the module at target_rel.
This is a naming check over the import lines, not full import resolution: a surviving file that names a module the target could provide is a candidate for the break a delete can cause, which is exactly the evidence a delete gate wants. """ wanted = set(module_names_for_file(target_rel)) if not wanted: return [] found: List[str] = [] for rel in files: if rel == target_rel: continue source = _read_source(workspace, rel) if source is None: continue try: tree = ast.parse(source, filename=rel) except (SyntaxError, ValueError): continue modules, _ = _extract_imports(rel, tree) for name in modules: if name in wanted or name.rsplit(".", 1)[0] in wanted: found.append(rel) break return found
def _read_source(workspace: Path, rel_posix: str) -> Optional[str]: target = workspace / Path(*rel_posix.replace("\\", "/").split("/")) if not target.is_file() or target.is_symlink(): return None try: return target.read_text(encoding="utf-8", errors="replace") except OSError: # utf-8-sig: a source file that starts with a byte-order mark is still the # UTF-8 text the compiler would read, and the mark is not part of the code. return target.read_text(encoding="utf-8-sig") except (OSError, UnicodeDecodeError): # A file that is not decodable text carries no syntax tree to extract, and # guessing it with replacement characters would invent symbols. return None
132 unmodified lines13313413513613613713813914014110 unmodified lines152153154153155156157158159160119 unmodified lines280281282279283284285286287288132 unmodified lines f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) " f"{res.reason}: {res.detail}" ) return 0 if res.assurance >= min_assurance else 1 # Exit 0 only when the edit landed on disk, or a dry run cleared the bar. # An accepted verdict whose commit never landed is a failure to report. return 0 if res.committed or (args.dry_run and res.assurance >= min_assurance) else 1
if args.command == "create": content = Path(args.content_file).read_text(encoding="utf-8", newline="")10 unmodified lines f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) " f"{res.reason}: {res.detail}" ) return 0 if res.accepted else 1 # Exit 0 only when the file landed, or a dry run was accepted; a verdict # that never wrote anything is a failure, whatever its assurance says. return 0 if res.committed or (args.dry_run and res.accepted) else 1
if args.command == "symbols": root = Path(args.workspace).resolve()119 unmodified lines ) if res.verdict == "REFUSED" and not args.json: print("nothing was written; the card named this reason before any node ran") return 0 if res.accepted else 1 # Exit 0 only when the pair landed, or a dry run was accepted: a card can # be verified in staging and still lose the commit to the disk. return 0 if res.committed or (args.dry_run and res.accepted) else 1
if args.command == "check-adapter": root = Path(args.workspace).resolve()41 unmodified lines424344454546474848495051525053545556525758596019 unmodified lines8081828384798081858687888990919293949596979813 unmodified lines11211311411511611711811912012112212312426 unmodified lines15115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619712 unmodified lines21021121221321421515315415515615721621721821922022122222322422522616316416522722822923023123223323423523623723823924024124224324424524624741 unmodified lines)
def _read_text_safe(cwd: Path, rel: str) -> str | None:def _read_text_state(cwd: Path, rel: str) -> Tuple[str | None, str]: """Return (source, state) for one workspace file: ok, missing, undecodable or unreadable.""" target = cwd / Path(*rel.replace("\\", "/").split("/")) if not target.is_file() or target.is_symlink(): return None return None, "missing" try: # utf-8-sig: a byte-order mark is not part of the code, and the compiler # reading the file would skip it the same way. return target.read_text(encoding="utf-8", errors="replace") return target.read_text(encoding="utf-8-sig"), "ok" except UnicodeDecodeError: return None, "undecodable" except OSError: return None return None, "unreadable"
def has_python_module(module_name: str) -> bool:19 unmodified lines
broken: List[str] = [] failed: List[str] = [] silent: List[str] = [] for rel in files: source = _read_text_safe(cwd, rel) if source is None: broken.append(f"{rel}: unreadable or missing") source, state = _read_text_state(cwd, rel) if state == "missing": broken.append(f"{rel}: missing") failed.append(rel) continue if source is None: # A file that is not UTF-8 text gives the gate nothing to parse. Calling # that a syntax error would be a lie about the file, and calling it a # pass would be a lie about the gate: it simply has no judgement. silent.append(f"{rel}: {state}") continue try: tree = ast.parse(source, filename=rel) compile(tree, filename=rel, mode="exec", dont_inherit=True)13 unmodified lines failed_targets=tuple(failed), note=f"{len(broken)} file(s) failed syntax verification", ) if silent: return GateResult( ABSTAIN, command, output="\n".join(silent), note=f"{len(silent)} file(s) could not be read as UTF-8 text, the gate has no judgement on them", ) return GateResult(CONFIRMED, command)
26 unmodified lines return resolve_tool_argv(tool)
def _ran_no_tests(output: str) -> bool: """True when a test runner reported that it ran zero tests.""" low = (output or "").lower() return "no tests ran" in low or "ran 0 tests" in low
def _zero_run_is_an_abstain(gate: GateResult) -> GateResult: """A runner that collected nothing cannot confirm or reject anything.
The unittest fallback imports the target module and asks unittest to collect it. Tests written for pytest stay invisible there, so unittest reports an empty run and exits. Reporting that as REJECTED would invent a failure, and as CONFIRMED would invent a pass, so the gate abstains and says so. """ if _ran_no_tests(gate.output or ""): return GateResult( ABSTAIN, gate.command, output=gate.output, note="the test runner collected no tests, the gate has no judgement", ) return gate
def _unittest_module_names(targets: Sequence[str]) -> Tuple[List[str], List[str]]: """Map relative test paths to importable dotted module names for unittest.""" names: List[str] = [] unmapped: List[str] = [] for target in targets: parts = [p for p in target.replace("\\", "/").split("/") if p and p != "."] if parts and parts[-1].endswith(".py"): parts = [*parts[:-1], parts[-1][:-3]] if parts and parts[-1] == "__init__": parts = parts[:-1] if not parts or ".." in parts or not all(p.isidentifier() for p in parts): unmapped.append(target) continue names.append(".".join(parts)) return names, unmapped
def run_python_tests( adapter: BaseLanguageAdapter, cwd: Path,12 unmodified lines argv = None if argv is not None: if full_suite or not targets: return _zero_run_is_an_abstain( adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") ) return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") return adapter.run_command( cwd.as_posix(), argv + [t.replace("\\", "/") for t in targets], gate_name="selected_tests", return _zero_run_is_an_abstain( adapter.run_command( cwd.as_posix(), argv + [t.replace("\\", "/") for t in targets], gate_name="selected_tests", ) )
if has_python_module("unittest"): if full_suite or not targets: argv = [sys.executable, "-m", "unittest", "discover", "-q"] return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") argv = [sys.executable, "-m", "unittest", "-q", *[t.replace("\\", "/") for t in targets]] return adapter.run_command(cwd.as_posix(), argv, gate_name="selected_tests") return _zero_run_is_an_abstain( adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") ) modules, unmapped = _unittest_module_names(targets) if unmapped: # unittest takes importable names, not file paths. Passing a path # through would exit with an import error that says nothing about # the code, so the gate refuses to judge rather than misjudge. return GateResult( ABSTAIN, "python -m unittest -q " + " ".join(str(t) for t in unmapped), note="these targets are not importable module names for the unittest fallback: " + ", ".join(str(t) for t in unmapped), ) argv = [sys.executable, "-m", "unittest", "-q", *modules] return _zero_run_is_an_abstain( adapter.run_command(cwd.as_posix(), argv, gate_name="selected_tests") )
return GateResult( ABSTAIN,27 unmodified lines28293031313233343536379 unmodified lines47484947505152535455565759 unmodified lines117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224309 unmodified lines53453553642842943043143253753853954054154254354454554654754854955024 unmodified lines575576577578579580581582152 unmodified lines73573673762162262362462562673873974074174274374474574674774874975075122 unmodified lines77477577665565665765877777877978078178278378478578678778878979079179279379479534 unmodified lines83083183270570670770870983383483583683783883984084184284384484584637 unmodified lines8848858867538878888898907558918928938948958964 unmodified lines9019029039049059069071 unmodified line90991091191291391491577577677777877978078178278378491691791891992092192292392492592692792892993093193293393493593693793893994094194294394478979094594694794894927 unmodified linesfrom lingologos_codex import envelope as _envelope # noqa: E402from lingologos_codex.agents import ROLES, run_pipeline # noqa: E402from lingologos_codex.failures import detect_stall_from_hashes # noqa: E402from lingologos_codex.fsadapter import create_os_filesystem_adapter # noqa: E402from lingologos_codex.fsadapter import ( # noqa: E402 FileSystemAdapterError, create_os_filesystem_adapter,)from lingologos_codex.fspolicy import ( # noqa: E402 EOL_PRESERVE, FSPolicy,9 unmodified lines apply_controlled_fuzzy_patch,)
from lingologos_python.ast_graph import IGNORED_DIRS, discover_python_files # noqa: E402from lingologos_python.ast_graph import ( # noqa: E402 IGNORED_DIRS, discover_python_files, importers_of,)from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E402
PYTHON_ROOT = Path(__file__).resolve().parent.parent59 unmodified lines return path.read_text(encoding="utf-8", newline="") if path.is_file() else ""
def _restore_originals( root: Path, originals: Dict[str, str], recreate: Sequence[str] = (),) -> List[str]: """Put every named workspace path back to the text held in memory, listing failures."""
problems: List[str] = [] for rel_posix, text in originals.items(): target = root / Path(*rel_posix.split("/")) try: if text == "" and rel_posix not in recreate: # The pre-image of a created file is an absent path, so undoing a # create means removing the file the transaction left behind. if target.is_file(): target.unlink() else: target.parent.mkdir(parents=True, exist_ok=True) target.write_text(text, encoding="utf-8", newline="") except OSError: problems.append(rel_posix) return problems
def _commit_or_restore( fs: Any, root: Path, writes: Dict[str, str], originals: Dict[str, str], recreate: Sequence[str] = (),) -> Tuple[bool, str]: """Commit the verified writes, and restore the in-memory pre-images when the commit fails.
The kernel transaction replaces one file at a time and attempts a best-effort rollback of its own when a replace fails part way, swallowing the errors of that rollback. The session does not trust it: it keeps every pre-image in memory, writes them back itself after any failure, and re-reads each written file once the commit reports success, so committed is only ever true when the verified text is the text on disk. """
tx = fs.begin_transaction() try: for rel_posix, text in writes.items(): fs.stage_write_text(tx, rel_posix, text) fs.commit_transaction(tx) except FileSystemAdapterError as exc: problems = _restore_originals(root, originals, recreate) if problems: return False, ( "the commit failed and these paths could not be restored from memory: " + ", ".join(problems) + " (" + str(exc) + ")" ) return False, "the commit failed, the workspace was restored from the in-memory originals: " + str(exc) drifted: List[str] = [] for rel_posix, text in writes.items(): on_disk = _disk_text(root, rel_posix) if on_disk != text and on_disk.replace("\r\n", "\n") != text.replace("\r\n", "\n"): drifted.append(rel_posix) if drifted: problems = _restore_originals(root, originals, recreate) if problems: return False, ( "the commit landed the wrong text and these paths could not be restored: " + ", ".join(problems) + " (drifted: " + ", ".join(drifted) + ")" ) return False, "the text on disk after the commit is not the verified text: " + ", ".join(drifted) return True, ""
def _delete_or_restore( fs: Any, root: Path, rel_posix: str, original_text: str,) -> Tuple[bool, str, str]: """Delete one workspace file through the kernel transaction, honestly reporting the outcome.
Returns committed, the refusal reason code when it did not land, and the detail. A path the policy refuses is a named refusal, not a crash, and a transaction the disk refuses puts the file back from the in-memory original. """
tx = fs.begin_transaction() try: fs.stage_delete(tx, rel_posix) fs.commit_transaction(tx) except PathSecurityError as exc: return False, PATH_POLICY, "the path policy refused the delete: " + str(exc) except FileSystemAdapterError as exc: problems = _restore_originals(root, {rel_posix: original_text}, recreate=(rel_posix,)) if problems: return False, PATCH_NOT_APPLIED, ( "the delete failed and the file could not be restored from memory: " + str(exc) ) return False, PATCH_NOT_APPLIED, "the delete failed, the file was restored from the in-memory original: " + str(exc) target = root / Path(*rel_posix.split("/")) if target.exists(): return False, PATCH_NOT_APPLIED, "the file is still on disk after the delete commit: '%s'" % rel_posix return True, "", ""
def _verify_probe(text: str) -> Tuple[str, str, str]: """A search, replace, text triple that annotates one line without breaking the file.
309 unmodified lines reason = PATCH_NOT_APPLIED detail = "the file changed on disk after the run verified the patch: '%s'" % rel_posix else: real_fs = self._os_fs(self.workspace_root) tx = real_fs.begin_transaction() real_fs.stage_write_text(tx, rel_posix, patch_res.updated_text) real_fs.commit_transaction(tx) committed = True committed, failure = _commit_or_restore( self._os_fs(self.workspace_root), self.workspace_root, {rel_posix: patch_res.updated_text}, {rel_posix: original_text}, ) if not committed: verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = failure
return SessionResult( case_id=case_id,24 unmodified lines The kernel claim stays the primary edit, because that is the edit the six nodes are asked to judge, and the companion paths are announced on the same case. The commit is one transaction: the source replaced and the test file replaced, or neither. If the disk refuses that transaction part way, the session restores both files from the in-memory originals and reports the named refusal instead.
A card that refuses is not a failed run. It reports the reason code the rule named and never reaches the six nodes, because there is nothing there to verify. A card152 unmodified lines reason = PATCH_NOT_APPLIED detail = "these files changed on disk after the pair was verified: " + ", ".join(drifted) else: real_fs = self._os_fs(self.workspace_root) tx = real_fs.begin_transaction() for edit in plan.edits: real_fs.stage_write_text(tx, edit.file, patched[edit.file]) real_fs.commit_transaction(tx) committed = True committed, failure = _commit_or_restore( self._os_fs(self.workspace_root), self.workspace_root, {edit.file: patched[edit.file] for edit in plan.edits}, {edit.file: originals[edit.file] for edit in plan.edits}, ) if not committed: verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = failure
dossier["pattern"] = pattern_id dossier["target"] = plan.target22 unmodified lines ) -> SessionResult: """Create a new Python file, verifying it in isolation before committing.""" rel_posix = rel_path.replace("\\", "/") target = self.workspace_root / Path(*rel_posix.split("/")) if target.exists(): raise FileExistsError(f"target already exists: '{rel_posix}'")
guard = PathGuard(self.policy()) try: plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content=content)]) except PathSecurityError: # The policy answers first. Probing the named path before the guard would let # an absolute path replace the workspace root on Windows and touch a file # outside the workspace, naming it back in the error. return self.edit_file(rel_posix, "# NEW_FILE", content, case_id=case_id, note=note, commit=False)
# The guard has resolved the path inside the workspace by now; build the target # from the resolved rel path, never from the raw input. safe_rel = plan.touched_files[0] if plan.touched_files else rel_posix target = self.workspace_root / Path(*safe_rel.split("/")) if target.exists(): raise FileExistsError(f"target already exists: '{rel_posix}'")
marker = "# __LINGOLOGOS_PYTHON_NEW_FILE__\n" with tempfile.TemporaryDirectory(prefix="lingologos_python_create_") as tmp_dir: staged_root = Path(tmp_dir).resolve()34 unmodified lines reason = PATCH_NOT_APPLIED detail = "a file appeared at '%s' while the create was being verified" % rel_posix else: real_fs = self._os_fs(self.workspace_root) tx = real_fs.begin_transaction() real_fs.stage_write_text(tx, rel_posix, content) real_fs.commit_transaction(tx) committed = True committed, failure = _commit_or_restore( self._os_fs(self.workspace_root), self.workspace_root, {rel_posix: content}, {rel_posix: ""}, ) if not committed: verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = failure
return SessionResult( case_id=case_id,37 unmodified lines if staged_target.is_file() and not staged_target.is_symlink(): staged_target.unlink()
# Evaluate syntax over remaining files by targeting a surviving file if available # A delete is judged where it can actually hurt: the surviving files that # import the module being removed are the gate target and its companions, # not the alphabetically first file of the copy. remaining = [p for p in discover_python_files(staged_root) if p != rel_posix] gate_target = remaining[0] if remaining else rel_posix importers = importers_of(staged_root, remaining, rel_posix) gate_target = importers[0] if importers else (remaining[0] if remaining else rel_posix) companion_files = [p for p in importers if p != gate_target] case = { "case_id": case_id, "workspace": str(staged_root),4 unmodified lines "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), "companionFiles": companion_files, **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case)1 unmodified line decision = dict(dossier.get("decision", {})) verdict = str(decision.get("verdict", "UNKNOWN")) assurance = int(decision.get("assurance", 0)) reason = str(decision.get("reason", "")) detail = str(decision.get("detail", "")) committed = False if commit and not plan.rejected and assurance >= self.min_assurance: guard.resolve_safe(rel_posix, for_write=True) current = self.workspace_root for part in Path(*rel_posix.split("/")).parts: current = current / part if current.is_symlink(): raise PathSecurityError(f"refusing to delete across symlink: '{rel_posix}'") if target.is_file(): target.unlink() committed = True
if _disk_text(self.workspace_root, rel_posix) != original_text: # The file moved while the six nodes were running: the removal that was # verified is no longer the removal of what is on disk. verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = "the file changed on disk after the run verified the delete: '%s'" % rel_posix else: committed, refusal_reason, failure = _delete_or_restore( # The guard above has already decided the policy for this delete; # the kernel stage_delete re-walks the parent directories against # the allowed set and refuses legitimate paths, so the adapter # only enforces the protected patterns here. self._os_fs(self.workspace_root, check_allowed=False), self.workspace_root, rel_posix, original_text, ) if not committed: verdict = "REFUSED" assurance = 0 reason = refusal_reason detail = failure
dossier["companionFiles"] = companion_files return SessionResult( case_id=case_id, verdict=verdict, assurance=assurance, reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), reason=reason, detail=detail, committed=committed, touched_files=(rel_posix,), trace=tuple(trace),1 unmodified line2345567854 unmodified lines636465666768697071727374751 unmodified line "schema": "lingologos-python-gates-1", "verdict": "CONFIRMED", "counts": { "CONFIRMED": 9, "CONFIRMED": 10, "REJECTED": 0, "ABSTAIN": 0 },54 unmodified lines "note": "16 rows re-planned: 8 pairs land and compile, 8 refusals repeat with the same code", "failed_targets": [] }, { "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": [] }, { "name": "pattern_coverage", "verdict": "CONFIRMED",1 unmodified line234567896 unmodified lines1617181719202122232466 unmodified lines9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641 unmodified line
from __future__ import annotations
import codecsimport sysfrom pathlib import Path
import pytest6 unmodified lines load_adapter_from_file, load_adapter_from_ref,)from lingologos_codex.types import ABSTAIN, CONFIRMED, REJECTEDfrom lingologos_codex.types import ABSTAIN, CONFIRMED, GateResult, REJECTED
from lingologos_python import gates as gates_modulefrom lingologos_python.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapterfrom lingologos_python.ast_graph import discover_python_filesfrom lingologos_python.gates import resolve_tool_gate_prefix66 unmodified lines spec_adapter = load_adapter_from_file(python_root / "codex.python.json", sample_pkg) assert isinstance(spec_adapter, CommandLanguageAdapter) assert spec_adapter.meta().languages == ("python",)
def test_syntax_gate_compiles_a_file_that_starts_with_a_byte_order_mark(sample_pkg: Path) -> None: marked = sample_pkg / "src" / "marked.py" marked.write_bytes(codecs.BOM_UTF8 + b"def go() -> int:\n return 1\n")
adapter = PythonLanguageAdapter(sample_pkg) gates = adapter.run_typecheck_and_lint(str(sample_pkg), ["src/marked.py"]) assert gates[0].verdict == CONFIRMED, gates[0].output
def test_syntax_gate_abstains_on_a_file_that_is_not_utf8_text(sample_pkg: Path) -> None: garbled = sample_pkg / "src" / "garbled.py" garbled.write_bytes(b"def caf\xe9():\n pass\n")
adapter = PythonLanguageAdapter(sample_pkg) gates = adapter.run_typecheck_and_lint(str(sample_pkg), ["src/garbled.py"]) assert gates[0].verdict == ABSTAIN assert "UTF-8" in gates[0].note
class _RecordingRunner: """A stand-in adapter that records the argv the gate chose for the fallback runner."""
def __init__(self, output: str) -> None: self.argvs = [] self._output = output
def run_command(self, cwd: str, argv, gate_name: str = "") -> GateResult: self.argvs.append(list(argv)) return GateResult(REJECTED, " ".join(argv), output=self._output)
def test_unittest_fallback_imports_test_modules_and_abstains_on_an_empty_run( sample_pkg: Path, monkeypatch) -> None: """Paths are not import names, and an empty unittest run carries no verdict.
On this host the fallback received tests/test_mathops.py, could not import it, and the gate reported a failure the code never caused. Importable names and a named abstention are the honest shape of that fallback. """ monkeypatch.setattr(gates_module.shutil, "which", lambda name: None) monkeypatch.setattr(gates_module, "has_python_module", lambda name: name == "unittest") runner = _RecordingRunner("Ran 0 tests in 0.000s\nNO TESTS RAN\n")
gate = gates_module.run_python_tests(runner, sample_pkg, ["tests/test_mathops.py"]) assert runner.argvs == [[sys.executable, "-m", "unittest", "-q", "tests.test_mathops"]] assert gate.verdict == ABSTAIN
def test_unittest_fallback_refuses_targets_it_cannot_name(sample_pkg: Path, monkeypatch) -> None: monkeypatch.setattr(gates_module.shutil, "which", lambda name: None) monkeypatch.setattr(gates_module, "has_python_module", lambda name: name == "unittest") runner = _RecordingRunner("")
gate = gates_module.run_python_tests(runner, sample_pkg, ["tests/test-mathops.py"]) assert runner.argvs == [] assert gate.verdict == ABSTAIN assert "not importable module names" in gate.note
def test_a_runner_that_collected_nothing_abstains_under_pytest_too( sample_pkg: Path, monkeypatch) -> None: monkeypatch.setattr(gates_module, "has_python_module", lambda name: name == "pytest") runner = _RecordingRunner("no tests ran in 0.01s\n")
gate = gates_module.run_python_tests(runner, sample_pkg, ["tests/test_mathops.py"]) assert gate.verdict == ABSTAIN assert "collected no tests" in gate.note1 unmodified line2345677891011121314151649 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991 unmodified line
from __future__ import annotations
import codecsfrom pathlib import Path
from lingologos_python.ast_graph import discover_python_files, extract_python_graph, module_names_for_filefrom lingologos_python.ast_graph import ( discover_python_files, extract_python_graph, importers_of, module_names_for_file,)
def test_discover_python_files_ignores_caches_and_venvs(sample_pkg: Path) -> None:49 unmodified lines assert "pkg/broken.py" in symbols assert ("pkg/caller.py", "pkg/core.py") in edges assert ("pkg/caller.py::run", "pkg/core.py::compute") in edges
def test_importers_of_names_the_survivors_that_import_the_target(tmp_path: Path) -> None: (tmp_path / "src").mkdir() (tmp_path / "src" / "tokens.py").write_text( "def count_words(text: str) -> int:\n return len(text.split())\n", encoding="utf-8", ) (tmp_path / "src" / "report.py").write_text( "from src.tokens import count_words\n\n\ndef render(text: str) -> int:\n return count_words(text)\n", encoding="utf-8", ) (tmp_path / "src" / "unused.py").write_text("VALUE = 1\n", encoding="utf-8")
survivors = ["src/report.py", "src/unused.py"] assert importers_of(tmp_path, survivors, "src/tokens.py") == ["src/report.py"]
def test_the_graph_reads_a_byte_order_mark_as_text(tmp_path: Path) -> None: (tmp_path / "bom.py").write_bytes(codecs.BOM_UTF8 + b"def go() -> int:\n return 1\n") files = discover_python_files(tmp_path) symbols, _ = extract_python_graph(tmp_path, files) assert "bom.py::go" in symbols
def test_the_graph_invents_no_symbols_from_undecodable_bytes(tmp_path: Path) -> None: (tmp_path / "bytes.py").write_bytes(b"def \xffbad():\n pass\n") files = discover_python_files(tmp_path) symbols, _ = extract_python_graph(tmp_path, files) assert "bytes.py" in symbols assert not any(name.startswith("bytes.py::") for name in symbols)186 unmodified lines187188189190191192193194195196197198199200201202203204205206207208209210186 unmodified lines assert _tree_state(pattern_lab) == before
def test_apply_exits_zero_only_once_the_pair_has_landed(pattern_lab: Path) -> None: before = _tree_state(pattern_lab) proc = run_cli( "patterns", "apply", "--workspace", str(pattern_lab), "--pattern", "chain-to-registry", "--target", "src/registry.py::render", ) assert proc.returncode == 0, proc.stdout + proc.stderr assert "VERIFIED" in proc.stdout assert "committed=True" in proc.stdout assert _tree_state(pattern_lab) != before
def test_symbols_names_the_functions_of_a_workspace_and_ranks_them() -> None: proc = run_cli("symbols", "--workspace", str(LAB), "--limit", "200") assert proc.returncode == 0, proc.stdout + proc.stderr7 unmodified lines89101112131415117 unmodified lines1331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651667 unmodified linesfrom pathlib import Pathfrom typing import Dict
from lingologos_codex.fsadapter import FileSystemAdapterError
from lingologos_python.patterns import PATTERNS, plan_patternfrom lingologos_python.session import DEFAULT_PROTECTED_PATTERNS, PythonWorkspaceSession
117 unmodified lines assert result.reason == "PATH_POLICY" assert result.committed is False assert _tree_state(pattern_lab) == before
def test_a_commit_refused_by_the_disk_restores_the_whole_pair(pattern_lab: Path, monkeypatch) -> None: """A pair is written as one commit; a commit the disk refuses leaves both files as they were.""" session = PythonWorkspaceSession(pattern_lab) real_os_fs = session._os_fs
class CommitRefusingFs: def __init__(self, inner: object) -> None: self._inner = inner
def __getattr__(self, name: str) -> object: return getattr(self._inner, name)
def commit_transaction(self, tx: object) -> None: raise FileSystemAdapterError("the disk refused the replace")
def os_fs(root: Path, *, check_allowed: bool = True) -> object: fs = real_os_fs(root, check_allowed=check_allowed) if Path(root).resolve() == pattern_lab.resolve(): return CommitRefusingFs(fs) return fs
monkeypatch.setattr(session, "_os_fs", os_fs) before = _tree_state(pattern_lab) result = session.apply_pattern("chain-to-registry", target=POSITIVE["chain-to-registry"]) assert result.verdict == "REFUSED" assert result.reason == "PATCH_NOT_APPLIED" assert result.committed is False assert "refused the replace" in result.detail assert _tree_state(pattern_lab) == before4 unmodified lines56789101112168 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792804 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, Tuple
from lingologos_codex.fsadapter import FileSystemAdapterError
from lingologos_python.session import PythonWorkspaceSession, SessionResult, _verify_probe
168 unmodified lines final, attempts = session.run_retry_loop("src/mathops.py", same_proposal, max_attempts=5) assert final.verdict == "UNKNOWN" assert len(attempts) == 2
def test_create_file_refuses_an_escaping_path_before_touching_it(tmp_path: Path) -> None: """The path policy answers before the workspace code probes the named path.
Joining the workspace root with an absolute path replaces the root on Windows, so an exists probe placed before the guard reaches files outside the workspace and can even name one back in an error. """ ws = tmp_path / "ws" ws.mkdir() (ws / "value.py").write_text("VALUE = 1\n", encoding="utf-8") outside = tmp_path / "outside.py" outside.write_text("VALUE = 1\n", encoding="utf-8", newline="")
session = PythonWorkspaceSession(ws) res = session.create_file(str(outside), "VALUE = 2\n", commit=True) assert res.committed is False assert res.verdict in ("UNKNOWN", "REFUSED") assert outside.read_text(encoding="utf-8", newline="") == "VALUE = 1\n"
def test_a_commit_refused_by_the_disk_restores_the_file_from_memory( sample_pkg: Path, monkeypatch) -> None: """A commit that fails mid flight must not leave the run claiming a write it lost.""" session = PythonWorkspaceSession(sample_pkg) real_os_fs = session._os_fs
class CommitRefusingFs: def __init__(self, inner: Any) -> None: self._inner = inner
def __getattr__(self, name: str) -> Any: return getattr(self._inner, name)
def commit_transaction(self, tx: Any) -> None: raise FileSystemAdapterError("the disk refused the replace")
def os_fs(root: Path, *, check_allowed: bool = True) -> Any: fs = real_os_fs(root, check_allowed=check_allowed) if Path(root).resolve() == sample_pkg.resolve(): return CommitRefusingFs(fs) return fs
monkeypatch.setattr(session, "_os_fs", os_fs) before = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="") res = session.edit_file( "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=True, ) after = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="") assert res.verdict == "REFUSED" assert res.reason == "PATCH_NOT_APPLIED" assert res.committed is False assert "refused the replace" in res.detail assert before == after
def test_a_delete_refused_by_the_disk_leaves_the_file_in_place( sample_pkg: Path, monkeypatch) -> None: """A delete goes through the kernel transaction, and committed only says the file is gone.""" session = PythonWorkspaceSession(sample_pkg) created = session.create_file( "src/helper.py", '"""Extra module."""\n\nVALUE = 1\n', commit=True ) assert created.committed is True
real_os_fs = session._os_fs
class DeleteRefusingFs: def __init__(self, inner: Any) -> None: self._inner = inner
def __getattr__(self, name: str) -> Any: return getattr(self._inner, name)
def stage_delete(self, tx: Any, rel_path: str) -> None: raise FileSystemAdapterError("the disk refused the removal")
def os_fs(root: Path, *, check_allowed: bool = True) -> Any: fs = real_os_fs(root, check_allowed=check_allowed) if Path(root).resolve() == sample_pkg.resolve(): return DeleteRefusingFs(fs) return fs
monkeypatch.setattr(session, "_os_fs", os_fs) res = session.delete_file("src/helper.py", commit=True) assert res.verdict == "REFUSED" assert res.reason == "PATCH_NOT_APPLIED" assert res.committed is False helper = sample_pkg / "src" / "helper.py" assert helper.is_file() assert helper.read_text(encoding="utf-8", newline="") == '"""Extra module."""\n\nVALUE = 1\n'11 unmodified lines121314151516171881 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917011 unmodified linesfrom lingologos_codex.envelope import ENVELOPE_KIND
from lingologos_python import clifrom lingologos_python.session import PythonWorkspaceSessionfrom lingologos_python.session import PythonWorkspaceSession, SessionResult
PYTHON_ROOT = Path(__file__).resolve().parent.parent81 unmodified lines ) == 0 )
def test_the_cli_exits_non_zero_when_a_verified_write_never_landed( sample_pkg: Path, monkeypatch) -> None: """The exit code reports the write, not the verdict.
The session can verify a change in staging and then lose the commit to the disk. A command line that exits 0 on that run promises a file it did not write, so the process reports failure whenever committed is false outside a dry run. """
def fake_create(self, rel_path, content, **kwargs) -> SessionResult: return SessionResult( case_id="python-create", verdict="VERIFIED", assurance=3, reason="OK_DUAL_CONFIRMATION", detail="the commit failed, the workspace was restored from the in-memory originals", committed=False, )
def fake_apply(self, pattern_id, **kwargs) -> SessionResult: return SessionResult( case_id="python-pattern", verdict="VERIFIED", assurance=3, reason="OK_DUAL_CONFIRMATION", detail="the text on disk after the commit is not the verified text", committed=False, )
content_file = sample_pkg / "newcomer.txt" content_file.write_text("VALUE = 1\n", encoding="utf-8")
monkeypatch.setattr(PythonWorkspaceSession, "create_file", fake_create) assert ( cli.main( [ "create", "--workspace", str(sample_pkg), "--file", "src/newcomer.py", "--content-file", str(content_file), ] ) == 1 )
monkeypatch.setattr(PythonWorkspaceSession, "apply_pattern", fake_apply) assert ( cli.main( [ "patterns", "apply", "--workspace", str(sample_pkg), "--pattern", "chain-to-registry", "--target", "src/mathops.py::double_sum", ] ) == 1 )13 unmodified lines141516171718192021 unmodified lines424344454645464748494950515237 unmodified lines909192939394959596979813 unmodified linesThis bundle carries no kernel. It carries one corpus of its own, the sixteen pattern cases under`patterns/`, generated from the rules and the fixture beside them, and the card states theirdenominator rather than letting sixteen rows look like a benchmark. Every number the card states(9 gates, 99 tests, 18 node files, the staged file count) is re-derived from this tree before a(10 gates, 113 tests, 18 node files, the staged file count) is re-derived from this tree before asingle object is uploaded. A card that contradicts the code beside it stops the run instead ofpublishing.
21 unmodified linesREPO = "tailot/codex-python"EXPECTED_FILES = 72 # the staged tree: 72 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 73 # those 72 plus the .gitattributes the hub addsEXPECTED_GATES = 9EXPECTED_TESTS = 99EXPECTED_GATES = 10EXPECTED_TESTS = 113EXPECTED_TEST_FILES = 9EXPECTED_NODE_FILES = 18EXPECTED_GATE_LINE = "GATES: CONFIRMED (9 gates: 9 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"EXPECTED_GATE_LINE = "GATES: CONFIRMED (10 gates: 10 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"ROLES = ("planner", "retriever", "executor", "gate_checker", "adversary", "arbiter")ENVELOPE_KIND = "lingologos-codex-envelope-1"IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git", ".venv", ".venv-train"}37 unmodified lines "\"What this bundle needs from the codex kernel\" below says how the two find each other.", ), ( "The gate runner is where this bundle states its numbers out loud: 9 gates, 99 tests across 9 files,\n" "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: 9 gates, 99 tests across 9 files,\n" "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.",4 unmodified lines567891011236 unmodified lines24824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631736 unmodified lines3543553563573583593604 unmodified linesimport argparseimport jsonimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Path236 unmodified lines )
def _pytest_return_code(lab: Path) -> int: proc = subprocess.run( [sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider"], cwd=str(lab), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) return proc.returncode
def gate_pattern_pair_honesty() -> GateResult: check = "each card's lock test fails until the source edit of its pair lands" positives: Dict[str, str] = {} for row in read_rows(PATTERN_CASES): if row["expect"] == "VERIFIED" and str(row["pattern_id"]) not in positives: positives[str(row["pattern_id"])] = str(row["targets"][0]) missing = sorted(set(PATTERNS) - set(positives)) if missing: return _rejected(check, "no positive corpus row names a target for: " + ", ".join(missing), missing)
failures: List[str] = [] with tempfile.TemporaryDirectory(prefix="lingologos_python_honesty_") as tmp: base = Path(tmp) / "lab" shutil.copytree(PATTERN_LAB, base) if _pytest_return_code(base) != 0: return _rejected(check, "the pattern_lab fixture does not pass its own suite as published") for pattern_id in sorted(positives): lab = Path(tmp) / ("lab_" + pattern_id) shutil.copytree(PATTERN_LAB, lab) plan = plan_pattern(lab, pattern_id, positives[pattern_id]) if plan.refused: failures.append("%s: the positive row no longer plans: %s" % (pattern_id, plan.detail)) continue companions = plan.companions() if not companions: failures.append("%s: the card carries no lock test in its pair" % pattern_id) continue broke = False for edit in companions: path = lab / Path(*edit.file.split("/")) original = path.read_text(encoding="utf-8", newline="") outcome = apply_controlled_fuzzy_patch( original, SearchReplaceBlock(edit.search, edit.replace), FuzzyPatchConfig() ) if not outcome.applied: failures.append("%s: the lock test anchor for '%s' does not apply" % (pattern_id, edit.file)) broke = True break path.write_text(outcome.updated_text, encoding="utf-8", newline="") if broke: continue if _pytest_return_code(lab) == 0: failures.append( "%s: the suite still passes with only the test side of the pair written" % pattern_id ) if failures: return _rejected(check, "; ".join(failures), failures) return _confirmed( check, "%d cards: every lock test fails while its source edit is missing, so the pair is not decoration" % len(positives), )
def gate_pattern_coverage() -> GateResult: check = "patterns/coverage.json states a denominator this fixture still supports" if not PATTERN_COVERAGE.is_file():36 unmodified lines ("external_topology", gate_external_topology), ("pattern_corpus_schema", gate_pattern_corpus_schema), ("pattern_round_trip", gate_pattern_round_trip), ("pattern_pair_honesty", gate_pattern_pair_honesty), ("pattern_coverage", gate_pattern_coverage),)
README.md+21-7
lingologos_python/ast_graph.py+35-2
lingologos_python/cli.py+9-3
lingologos_python/gates.py+94-15
lingologos_python/session.py+192-36
results/gates.json+8-1
tests/test_adapter.py+75-1
tests/test_ast_graph.py+38-1
tests/test_cli.py+18
tests/test_pattern_session.py+33
tests/test_session.py+99
tests/test_topology_and_cli.py+69-1
tools/publish_dataset.py+6-6
tools/run_gates.py+66