Upload folder using huggingface_hub
Browse filesFiles changed (10)
34 unmodified lines35363738383940414243444545464748484950511 unmodified line5354555656575859596061626364656665666768697021 unmodified lines929394949596979899100101121 unmodified lines22322422522222622722822923034 unmodified linesGATES: CONFIRMED (9 gates: 9 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
```
The gate runner is where this bundle states its numbers out loud: 9 gates, 77 tests across 9 files,
The gate runner is where this bundle states its numbers out loud: 9 gates, 90 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.
## Contents
- - `lingologos_python/_codex_bridge.py`: finds the kernel without copying it: an already importable
- `lingologos_python/_codex_bridge.py`: finds the kernel without copying it: an already importable
`lingologos_codex`, then `LINGOLOGOS_CODEX_ROOT`, then a sibling `codex/` or `datasets/codex/` among the
ancestors.
- - `lingologos_python/adapter.py`: `PythonLanguageAdapter` and `StrictPythonLanguageAdapter`
- `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`).1 unmodified line- `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.
- - `lingologos_python/rules.py`: five shape rules over a named function. Each rule reads the function
- `lingologos_python/rules.py`: five 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`).
- - `lingologos_python/patterns.py`: the catalog above the rules. A card states the shape it claims, why
- `lingologos_python/patterns.py`: the catalog above the rules. A card states the shape it claims, why
that shape is worth changing, what must hold before the rule runs, what test locks the change, and the
reason codes it answers with when it refuses (`PATTERNS`, `pattern_card`, `scan_pattern`,
`plan_pattern`).
- `lingologos_python/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`).
- - `lingologos_python/cli.py`: `lingologos_python` CLI (`verify`, `edit`, `create`, `symbols`,
`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.
- `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 and
one planted to be refused, used by the tests and by the coverage counts.21 unmodified linesarguments (`BRANCH_SHAPE_MISMATCH`), `open-to-context-manager` refuses a handle that escapes the function
it opened (`HANDLE_ESCAPE`), `mutable-default-to-none` refuses a default that already carries an
annotation (`ANNOTATED_MUTABLE_DEFAULT`). A refusal is an answer, not a failure: it names the reason code
and writes nothing.
and writes nothing. Each card also lists the refusals the plan around a rule shares: a target that is not
there (`MISSING_TARGET_FILE`), a test file that cannot carry the lock (`NO_TEST_FILE`, `CRLF_TARGET`,
`INVALID_COMPANION_PATH`), a coroutine the lock tests could not call directly (`ASYNC_TARGET`), an assert
whose message is built at call time (`NON_LITERAL_ASSERT_MESSAGE`), and anchors that collide (`ANCHOR_OVERLAP`).
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 one121 unmodified linesis not offered as a command from here. `verify --file ...` reports a verdict for a file without asking
for a change. With `--strict-tools` the run demands `mypy` and `ruff`: a gate that cannot run abstains,
and the session answers UNKNOWN with the reason `GATE_ABSTAIN` instead of reporting a check that never
happened.
happened. `patterns apply` also takes `--subprocesses`, which runs the six nodes as separate processes
instead of in this one.
`check-adapter` says whether the Python adapter holds the contract of the kernel, and exits non-zero
when it does not.82 unmodified lines8384858687888948 unmodified lines138139140141140142143144145146147148112 unmodified lines26126226325926426526626726826927027182 unmodified lines p_pat.add_argument("--target", default=None, help="Target as path/to/file.py::function_name.") p_pat.add_argument("--dry-run", action="store_true", help="Verify the pair without committing.") p_pat.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") p_pat.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.") p_pat.add_argument("--json", action="store_true", help="Print JSON output.")
# check-adapter48 unmodified lines if args.command == "create": content = Path(args.content_file).read_text(encoding="utf-8", newline="") session = PythonWorkspaceSession(args.workspace, strict_tools=args.strict_tools) try: res = session.create_file(args.file, content, commit=not args.dry_run) res = session.create_file(args.file, content, commit=not args.dry_run) except FileExistsError as exc: print("REFUSED: %s" % exc, file=sys.stderr) return 1 if args.json: print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) else:112 unmodified lines for line in hit.evidence: print(" why: %s" % line) return 0 session = PythonWorkspaceSession(args.workspace, strict_tools=args.strict_tools) session = PythonWorkspaceSession( args.workspace, strict_tools=args.strict_tools, use_subprocesses=args.subprocesses, ) res = session.apply_pattern(args.pattern, target=args.target, commit=not args.dry_run) if args.json: print(json.dumps(res.to_dict(), indent=2, sort_keys=True))138 unmodified lines139140141142142143144145146147148149150151152153154138 unmodified lines full_suite: bool = False,) -> GateResult: """Run pytest (no cacheprovider) or fall back to unittest discovery.""" if resolve_tool_argv("pytest") is not None: pytest_binary = shutil.which("pytest") if has_python_module("pytest"): # The active interpreter runs its own pytest, so the gate judges the same # environment the adapter and the kernel are running in. argv = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"] elif pytest_binary: argv = [pytest_binary, "-q", "-p", "no:cacheprovider"] else: argv = None if argv is not None: if full_suite or not targets: return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") return adapter.run_command(30 unmodified lines3132333435363738394041424344454647484950515253545556575849 unmodified lines1081091101111121131141151161174 unmodified lines122123124101125126127128201 unmodified lines33033133230931033333433533633733833934034136 unmodified lines37837938035338138238338412 unmodified lines39739839940037240140240340440540640740840941041141241341441541641730 unmodified lines# Target syntax: a workspace-relative path, then the module level function, split by "::".TARGET_SEPARATOR = "::"
# The refusal when a scan finds the card fits more than one target and the caller named none.AMBIGUOUS_TARGET = "AMBIGUOUS_TARGET"
FAMILIES: Tuple[str, ...] = ("contracts", "mutation", "resources", "shape", "typing")
# Refusals every card can answer with before its rule looks at the shape at all: the# target or its paired test file is simply not in a shape this catalog anchors on.SHARED_REFUSALS: Tuple[str, ...] = ( rules.MISSING_TARGET_FILE, rules.NO_SUCH_FUNCTION, rules.NOT_PARSEABLE, rules.NOT_ASCII_TARGET, rules.TAB_INDENTED_TARGET, rules.CRLF_TARGET, rules.ASYNC_TARGET, rules.NO_TEST_FILE, rules.NO_TEST_ANCHOR, rules.AMBIGUOUS_TEST_ANCHOR, rules.INVALID_COMPANION_PATH, rules.ANCHOR_OVERLAP,)
@dataclass(frozen=True)class PatternSpec:49 unmodified lines lock_claims: str, refuses_as: Sequence[str],) -> PatternSpec: merged: List[str] = [] for code in tuple(refuses_as) + SHARED_REFUSALS: if code not in merged: merged.append(code) return PatternSpec( pattern_id=pattern_id, family=family,4 unmodified lines preconditions=tuple(preconditions), companions=tuple(companions), lock_claims=lock_claims, refuses_as=tuple(refuses_as), refuses_as=tuple(merged), )
201 unmodified lines text = reader(rel) if text is None: continue for symbol in module_level_functions(text): target, miss = rules.open_target(rel, symbol, reader) try: tree = ast.parse(text) except SyntaxError: continue for symbol in tuple(node.name for node in tree.body if isinstance(node, ast.FunctionDef)): target, miss = rules.open_target_with_tree(rel, symbol, text, tree, reader) if target is None: continue outcome = rule(target)36 unmodified lines evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code="AMBIGUOUS_TARGET", reason_code=AMBIGUOUS_TARGET, detail="this card fits %d targets, name one: %s" % (len(found), ", ".join(label for label, _hit in found)), ) target = found[0][0]12 unmodified lines detail=miss.detail, ) assert opened is not None try: outcome = rule(opened) outcome = rule(opened) except ValueError as exc: # A rule builds text anchors; if two of them collide the rule cannot say which # one to trust, and the plan reports that as a named refusal, not a traceback. return PatternPlan( pattern_id=pattern_id, target=rules.target_label(rel_posix, symbol), edits=(), evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code=rules.ANCHOR_OVERLAP, detail="the anchors this rule builds collide: %s" % exc, ) if isinstance(outcome, rules.RuleMiss): return PatternPlan( pattern_id=pattern_id,27 unmodified lines2829303132333419 unmodified lines54555657585960616263168 unmodified lines2322332342352362372382392402412422431 unmodified line2452462472482492502512522532542552562572582592 unmodified lines26226326426526626726826927027127227327435 unmodified lines31031131231331431531631731831932032132232332432520 unmodified lines34634734834935035135235335435535635735835936036136249 unmodified lines412413414415416417418419420421422423424425426427143 unmodified lines57157257357457557657751657857958058158258358458558658752158858959059111 unmodified lines603604605539606607608609610339 unmodified lines95095195288595395495595684 unmodified lines10411042104397697710441045104610471 unmodified line104910501051985105210531054105510561057105810591060106110621063106410651066993106710681069107027 unmodified linesfrom __future__ import annotations
import astimport keywordfrom dataclasses import dataclassfrom typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
19 unmodified linesNO_BARE_OPEN = "NO_BARE_OPEN"HANDLE_ESCAPE = "HANDLE_ESCAPE"NOT_THE_FIRST_STATEMENT = "NOT_THE_FIRST_STATEMENT"ASYNC_TARGET = "ASYNC_TARGET"NON_LITERAL_ASSERT_MESSAGE = "NON_LITERAL_ASSERT_MESSAGE"INVALID_COMPANION_PATH = "INVALID_COMPANION_PATH"ANCHOR_OVERLAP = "ANCHOR_OVERLAP"
INDENT = " "_MUTABLE_LITERALS = (ast.List, ast.Dict, ast.Set)168 unmodified lines text = read(rel_posix) if text is None: return None, _miss(rel_posix, symbol, MISSING_TARGET_FILE, "no such file: '%s'" % rel_posix) return open_target_from_text(rel_posix, symbol, text, read)
def open_target_from_text(rel_posix: str, symbol: str, text: str, read: Callable[[str], Optional[str]]) -> Tuple[Optional[Target], Optional[RuleMiss]]: """The target for one file already read, with the shape refusal the reader cannot see."""
code = _shape_rejection(text) if code: return None, _miss(rel_posix, symbol, code, _SHAPE_DETAIL[code])1 unmodified line tree = ast.parse(text) except SyntaxError as exc: return None, _miss(rel_posix, symbol, NOT_PARSEABLE, "the file does not parse: %s" % exc.msg) return open_target_with_tree(rel_posix, symbol, text, tree, read)
def open_target_with_tree(rel_posix: str, symbol: str, text: str, tree: ast.Module, read: Callable[[str], Optional[str]]) -> Tuple[Optional[Target], Optional[RuleMiss]]: """The target for a caller that has already read and parsed the file."""
code = _shape_rejection(text) if code: return None, _miss(rel_posix, symbol, code, _SHAPE_DETAIL[code]) return Target(rel_posix=rel_posix, symbol=symbol, text=text, tree=tree, read=read), None
2 unmodified lines
for node in target.tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol: if isinstance(node, ast.AsyncFunctionDef): return None, _miss( target.rel_posix, target.symbol, ASYNC_TARGET, "'%s' is a coroutine, and the lock tests of this catalog call their target directly" % target.symbol, ) return node, None for node in ast.walk(target.tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol:35 unmodified lines return "import %s" % stem, stem
def _companion_path_is_importable(rel_posix: str) -> bool: """True when the lock import for this path binds a module by a plain Python name."""
parts = [part for part in rel_posix.split("/") if part] if not parts or not parts[-1].endswith(".py"): return False names = [part for part in parts[:-1] if part != "__init__.py"] + [parts[-1][:-3]] return all(part.isidentifier() and not keyword.iskeyword(part) for part in names)
def lock_source( rel_posix: str, test_name: str,20 unmodified lines text = target.read(test_rel) if text is None: return None, _miss(test_rel, target.symbol, NO_TEST_FILE, "no test file: '%s'" % test_rel) code = _shape_rejection(text) if code: return None, _miss(test_rel, target.symbol, code, "the test file: %s" % _SHAPE_DETAIL[code]) if not _companion_path_is_importable(target.rel_posix): return None, _miss( test_rel, target.symbol, INVALID_COMPANION_PATH, "the module path of '%s' has a part that is not a plain Python identifier, " "so no import in a lock test could reach it" % target.rel_posix, ) try: tree = ast.parse(text) except SyntaxError as exc:49 unmodified lines return list(function.args.posonlyargs) + list(function.args.args) + list(function.args.kwonlyargs)
def _is_string_statement(statement: ast.stmt) -> bool: """A statement that is one string literal: the shape of a docstring."""
return ( isinstance(statement, ast.Expr) and isinstance(statement.value, ast.Constant) and isinstance(statement.value.value, str) )
def _defaults_by_name(function: ast.FunctionDef) -> Dict[str, ast.expr]: """Map each plain parameter to the default expression it carries, when it has one."""
143 unmodified lines "parameter '%s' of '%s' carries an annotation this rule would have to widen" % (name, target.symbol), )
# The guard goes below a docstring, never above it: a guard inserted before the # leading string statement would take the docstring of the function away. head = 1 if _is_string_statement(function.body[0]) else 0 if head < len(function.body): body_start = starts[function.body[0].lineno - 1] body_start = starts[function.body[head].lineno - 1] guard_lead, guard_trail = "", "\n" else: # A body of nothing but a docstring: the guard takes its own line below it. body_start = starts[function.body[-1].end_lineno - 1] + function.body[-1].end_col_offset guard_lead, guard_trail = "\n", "" guard_indent = " " * function.body[0].col_offset for name in sorted(mutable): literal = segment_of(target.text, starts, mutable[name]) guard = "%sif %s is None:\n%s%s%s = %s\n" % (guard_indent, name, guard_indent, INDENT, name, literal) if target.text[body_start:body_start + len(guard)] == guard: if guard_trail and target.text[body_start:body_start + len(guard)] == guard: return _miss( target.rel_posix, target.symbol,11 unmodified lines _Splice( start=body_start, end=body_start, text="%sif %s is None:\n%s%s%s = %s\n" % (guard_indent, name, guard_indent, INDENT, name, literal), text="%s%sif %s is None:\n%s%s%s = %s%s" % (guard_lead, guard_indent, name, guard_indent, INDENT, name, literal, guard_trail), ) )
339 unmodified lines break block.append(statement) last_use = max(index for index, statement in enumerate(function.body) if uses(statement)) if any(uses(statement) for statement in function.body[last_use + 1:]): if last_use > position + len(block) - 1: return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is used after the run this rule can scope" % handle)
for statement in block[1:]:84 unmodified lines return miss assert function is not None starts = line_starts(target.text) first = function.body[0] check = first.value if isinstance(first, ast.Expr) else first check = function.body[0] if not isinstance(check, ast.Assert): return _miss( target.rel_posix,1 unmodified line NOT_THE_FIRST_STATEMENT, "the first statement of '%s' is not an assert, so it is not a precondition" % target.symbol, ) indent = " " * first.col_offset indent = " " * check.col_offset test_text = segment_of(target.text, starts, check.test) arguments = "" message_evidence = "no message was written, so the raise carries none either" if check.msg is not None: if not (isinstance(check.msg, ast.Constant) and isinstance(check.msg.value, str)): return _miss( target.rel_posix, target.symbol, NON_LITERAL_ASSERT_MESSAGE, "the message of the assert in '%s' is built at call time, so no lock test could name its text" % target.symbol, ) arguments = segment_of(target.text, starts, check.msg) message_evidence = "the message text is kept word for word" replacement = "if not %s:\n%sraise AssertionError(%s)" % (test_text, indent + INDENT, arguments) start, end = node_span(target.text, starts, first) start, end = node_span(target.text, starts, check) edit = _rewrite_function(target, starts, function, [_Splice(start=start, end=end, text=replacement)], "explicit raise of '%s'" % target.symbol)
alias = import_statement_for(target.rel_posix)[1]8 unmodified lines91011121314151635 unmodified lines5253545556575859606141 unmodified lines103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149149 unmodified lines299300301255256257258259260261262263264302303304305105 unmodified lines411412413414415416417418419420421422423424425426427379380381382383428429430431432433434435436437389390438439440441442105 unmodified lines5485495505025515525535544 unmodified lines55956056151356256356456534 unmodified lines6006016026036046056066076086096106116126136146156166176186196205575585595605615626216226236246256266276286293 unmodified lines63363463557257363663763863964048 unmodified lines689690691692693694695696697698699700701702703704630631632633634705706707708709710711712713714640641715716717718719100 unmodified lines8208218227487498238248258268278288298308318 unmodified lines
from __future__ import annotations
import astimport hashlibimport jsonimport osimport shutil35 unmodified linesDEFAULT_TOPOLOGY_PATH = PYTHON_ROOT / "topology.json"
DEFAULT_ALLOWED_PATTERNS: Tuple[str, ...] = ("*.py", "*.pyi")
# Named session refusals, alongside the reason codes the rule catalog answers with.PATH_POLICY = "PATH_POLICY"PATCH_NOT_APPLIED = "PATCH_NOT_APPLIED"DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ( "*.env", ".env*",41 unmodified lines }
def _disk_text(root: Path, rel_posix: str) -> str: """The current text of one workspace file, or an empty string when it is not there."""
path = root / Path(*rel_posix.split("/")) return path.read_text(encoding="utf-8", newline="") if path.is_file() else ""
def _verify_probe(text: str) -> Tuple[str, str, str]: """A search, replace, text triple that annotates one line without breaking the file.
The anchor is the first top level statement whose own line still parses once a comment is appended to it, so the probe cannot turn a valid workspace file into a syntax error. When nothing safer is found the first line is used as it has always been, and an empty file gets a probe text of its own. """
lines = text.splitlines(keepends=True) if not lines: return "# empty", "# empty verified", "# empty\n" probe_note = " # codex-verify-probe\n" try: tree = ast.parse(text) except SyntaxError: tree = None if tree is not None: for node in tree.body: if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str): continue line = lines[node.lineno - 1].rstrip("\r\n") if not line: continue candidate = line + probe_note try: ast.parse(text.replace(line, candidate, 1)) except SyntaxError: continue return line, candidate, text first = lines[0].rstrip("\r\n") return first, first + probe_note, text
def _copy_workspace_for_staging(src_root: Path, dst_root: Path) -> None: """Copy a workspace cleanly without caches or virtual environments.""" for dirpath, dirnames, filenames in os.walk(src_root):149 unmodified lines
# Verify without changing file content by probing a non-mutating exact check # over a temporary staging copy so real workspace files remain untouched. lines = text.splitlines(keepends=True) if lines: first_line = lines[0] probe_search = first_line probe_replace = first_line.rstrip("\r\n") + " # codex-verify-probe\n" original_for_patch = text else: probe_search = "# empty" probe_replace = "# empty verified" original_for_patch = "# empty\n" probe_search, probe_replace, original_for_patch = _verify_probe(text)
case: Dict[str, Any] = { "case_id": case_id,105 unmodified lines 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 patch_res.applied and not plan.rejected and assurance >= self.min_assurance: if _disk_text(self.workspace_root, rel_posix) != original_text: # The workspace moved while the six nodes were running: the patch that # was verified is no longer the patch for the file on disk, so nothing # is written and the run reports the named refusal instead. verdict = "REFUSED" assurance = 0 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 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
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),105 unmodified lines case_id=chosen_case_id, verdict="REFUSED", assurance=0, reason="PATH_POLICY" if planned.rejected else "PATCH_NOT_APPLIED", reason=PATH_POLICY if planned.rejected else PATCH_NOT_APPLIED, detail=( "the path policy rejected the pair: " + ", ".join(plan.files) if planned.rejected4 unmodified lines dossier={ "pattern": pattern_id, "target": plan.target, "refusal": "PATH_POLICY" if planned.rejected else "PATCH_NOT_APPLIED", "refusal": PATH_POLICY if planned.rejected else PATCH_NOT_APPLIED, "decision": {"verdict": "REFUSED", "assurance": 0}, "gates": [], "checkers": [],34 unmodified lines 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 assurance >= needed: drifted = [ edit.file for edit in plan.edits if _disk_text(self.workspace_root, edit.file) != originals[edit.file] ] if drifted: # The pair was verified against the workspace as it was at staging time. # If a file of the pair moved since, the anchors proven in staging are # not the anchors of what is on disk, so the pair is not written. verdict = "REFUSED" assurance = 0 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 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
dossier["pattern"] = pattern_id dossier["target"] = plan.target3 unmodified lines case_id=chosen_case_id, verdict=verdict, assurance=assurance, reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), reason=reason, detail=detail, committed=committed, touched_files=plan.files, trace=tuple(trace),48 unmodified lines 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: if target.is_file(): # The verified text was staged as a new file. If a file landed at that # path while the run was going, writing would replace something the # six nodes never saw, so the create is not committed. verdict = "REFUSED" assurance = 0 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 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
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),100 unmodified lines attempts.append(result) last = result sig = str(result.dossier.get("patchSignature", "")) if sig: history.append(sig) if not sig: # Two attempts that propose the same anchor and the same text have to # share one hash even when the kernel recorded no patch signature, or # the stall detector never sees the repetition. sig = hashlib.sha1((search + "\x00" + replace).encode("utf-8")).hexdigest() history.append(sig) if result.assurance >= self.min_assurance: return result, attempts if detect_stall_from_hashes(history) is not None:5 unmodified lines678991011121 unmodified line14151617181920187 unmodified lines2082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392405 unmodified linesimport subprocessimport sysfrom pathlib import Pathfrom typing import Dict, Listfrom typing import Any, Dict, List
from lingologos_codex.casecorpus import read_rows, validate_case_rows
1 unmodified line FAMILIES, PATTERNS, PATTERN_IDS, SHARED_REFUSALS, PatternSpec, pattern_card, plan_pattern,187 unmodified lines assert POSITIVE[str(entry["pattern_id"])] in entry["targets_in_shape"] assert len(entry["refusals_recorded"]) == 1 assert entry["refusals_recorded"][0] in _card(str(entry["pattern_id"])).refuses_as
def test_every_card_lists_the_refusals_a_plan_can_answer_with() -> None: for pattern_id in PATTERN_IDS: card = _card(pattern_id) for code in SHARED_REFUSALS: assert code in card.refuses_as assert len(set(card.refuses_as)) == len(card.refuses_as)
def test_a_rule_that_breaks_while_building_its_anchors_ends_in_a_named_refusal(tmp_path: Path, monkeypatch) -> None: from lingologos_python import rules
root = tmp_path / "ws" (root / "src").mkdir(parents=True) (root / "tests").mkdir(parents=True) (root / "src" / "widget.py").write_text("def pick(items=[]):\n return items\n", encoding="utf-8", newline="\n") (root / "tests" / "test_widget.py").write_text( "from src.widget import pick\n\n\ndef test_pick_defaults() -> None:\n assert pick() == []\n", encoding="utf-8", newline="\n", )
def colliding(target: Any) -> Any: raise ValueError("the anchors of this rule overlap")
monkeypatch.setitem(rules.RULES, "mutable-default-to-none", colliding) plan = plan_pattern(root, "mutable-default-to-none", "src/widget.py::pick") assert plan.refused assert plan.reason_code == rules.ANCHOR_OVERLAP2 unmodified lines34566789243 unmodified lines2532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663672 unmodified linesfrom __future__ import annotations
from pathlib import Pathfrom typing import Callable, Dict, Optionalfrom typing import Any, Callable, Dict, Optional
from lingologos_codex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch
243 unmodified lines outcome = _outcome("src/crlf.py", "pick", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.CRLF_TARGET
def _apply_to(root: Path, edit: Any) -> str: """Apply one edit of a hit to the workspace on disk and return the resulting text."""
original = (root / Path(*edit.file.split("/"))).read_text(encoding="utf-8", newline="") result = apply_controlled_fuzzy_patch( original, SearchReplaceBlock(edit.search, edit.replace), FuzzyPatchConfig() ) assert result.applied, "the anchor for '%s' does not apply" % edit.file return result.updated_text
def test_a_handle_reused_after_another_statement_is_not_one_scoped_block(tmp_path: Path) -> None: root = tmp_path / "ws" _write( root / "src" / "leaky.py", "def read_twice(path):\n handle = open(path)\n first = handle.read()\n" " step = 1\n second = handle.read()\n handle.close()\n return first, second\n", ) _write( root / "tests" / "test_leaky.py", "from src.leaky import read_twice\n\n\ndef test_read_twice_exists() -> None:\n assert callable(read_twice)\n", ) outcome = _outcome("src/leaky.py", "read_twice", "open-to-context-manager", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.HANDLE_ESCAPE
def test_a_guard_lands_below_the_docstring_it_has_to_keep(tmp_path: Path) -> None: root = tmp_path / "ws" _write( root / "src" / "documented.py", 'def collect(items=[]):\n """Collect one item."""\n items.append(1)\n return items\n', ) _write( root / "tests" / "test_documented.py", "from src.documented import collect\n\n\ndef test_collect_defaults() -> None:\n assert collect() == [1]\n", ) outcome = _outcome("src/documented.py", "collect", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleHit) patched = _apply_to(root, outcome.edits[0]) assert patched.index('"""Collect one item."""') < patched.index("if items is None:") namespace: Dict[str, Any] = {} exec(patched, namespace) assert namespace["collect"].__doc__ == "Collect one item." first = namespace["collect"]() second = namespace["collect"]() assert first == [1] and second == [1] and first is not second
def test_a_docstring_only_body_gets_its_guard_after_the_docstring(tmp_path: Path) -> None: root = tmp_path / "ws" _write(root / "src" / "quiet.py", 'def keep(items=[]):\n """Keep them."""\n') _write( root / "tests" / "test_quiet.py", "from src.quiet import keep\n\n\ndef test_keep_exists() -> None:\n assert callable(keep)\n", ) outcome = _outcome("src/quiet.py", "keep", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleHit) patched = _apply_to(root, outcome.edits[0]) compile(patched, "quiet.py", "exec") namespace: Dict[str, Any] = {} exec(patched, namespace) assert namespace["keep"].__doc__ == "Keep them."
def test_an_assert_whose_message_is_built_at_call_time_is_named_as_outside_the_rule(tmp_path: Path) -> None: root = tmp_path / "ws" _write(root / "src" / "loud.py", 'def shout(value):\n assert value, f"bad {value}"\n return value\n') _write( root / "tests" / "test_loud.py", "from src.loud import shout\n\n\ndef test_shout_exists() -> None:\n assert callable(shout)\n", ) outcome = _outcome("src/loud.py", "shout", "bare-assert-to-explicit-raise", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.NON_LITERAL_ASSERT_MESSAGE
def test_a_coroutine_target_is_refused_by_name_before_any_rewrite(tmp_path: Path) -> None: root = tmp_path / "ws" _write(root / "src" / "coro.py", "async def gather(items=[]):\n items.append(1)\n return items\n") _write( root / "tests" / "test_coro.py", "from src.coro import gather\n\n\ndef test_gather_exists() -> None:\n assert callable(gather)\n", ) outcome = _outcome("src/coro.py", "gather", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.ASYNC_TARGET
def test_a_test_file_the_lock_cannot_append_to_is_refused_as_a_target(tmp_path: Path) -> None: root = tmp_path / "ws" _write(root / "src" / "pairing.py", "def pick(items=[]):\n return items\n") (root / "tests").mkdir(parents=True) with (root / "tests" / "test_pairing.py").open("w", encoding="utf-8", newline="") as handle: handle.write("def test_pairing_defaults() -> None:\r\n assert pick() == []\r\n") outcome = _outcome("src/pairing.py", "pick", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.CRLF_TARGET
def test_a_module_path_no_lock_import_can_reach_is_refused_by_name(tmp_path: Path) -> None: root = tmp_path / "ws" _write(root / "my-src" / "tool.py", "def pick(items=[]):\n return items\n") _write( root / "tests" / "test_tool.py", "from src.tool import pick\n\n\ndef test_pick_defaults() -> None:\n assert pick() == []\n", ) outcome = _outcome("my-src/tool.py", "pick", "mutable-default-to-none", root) assert isinstance(outcome, rules.RuleMiss) assert outcome.reason_code == rules.INVALID_COMPANION_PATH2 unmodified lines34567789101182 unmodified lines9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801812 unmodified linesfrom __future__ import annotations
from pathlib import Pathfrom typing import Any, Dict, Tuple
from lingologos_python.session import PythonWorkspaceSessionfrom lingologos_python.session import PythonWorkspaceSession, SessionResult, _verify_probe
def test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None:82 unmodified lines assert final.verdict == "UNKNOWN" assert len(attempts) == 2 assert any(c.get("role") == "adversary_loop" for c in final.dossier.get("checkers", []))
def test_verify_probe_annotates_a_line_that_keeps_the_file_parsable() -> None: text = '"""Module doc.\n\nSpread over several lines.\n"""\n\n\ndef go() -> int:\n return 1\n' search, replace, original = _verify_probe(text) assert search == "def go() -> int:" assert replace == search + " # codex-verify-probe\n" assert original is text compile(original.replace(search, replace, 1), "module.py", "exec") empty_search, _empty_replace, empty_text = _verify_probe("") assert empty_text == "# empty\n" assert empty_search in empty_text
def test_edit_file_refuses_when_the_file_moved_during_the_run(sample_pkg: Path, monkeypatch) -> None: session = PythonWorkspaceSession(sample_pkg) real_run = session._run_six_nodes
def run_with_a_moving_workspace(case: Dict[str, Any]) -> Tuple[Any, ...]: path = sample_pkg / "src" / "mathops.py" path.write_text( path.read_text(encoding="utf-8", newline="").replace( "return left + right", "return left + right # moved" ), encoding="utf-8", newline="", ) return real_run(case)
monkeypatch.setattr(session, "_run_six_nodes", run_with_a_moving_workspace) res = session.edit_file( "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=True, ) assert res.verdict == "REFUSED" assert res.reason == "PATCH_NOT_APPLIED" assert res.committed is False on_disk = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8") assert "# moved" in on_disk assert "int(left)" not in on_disk
def test_create_file_refuses_when_a_file_landed_at_its_path_during_the_run( sample_pkg: Path, monkeypatch) -> None: session = PythonWorkspaceSession(sample_pkg) real_run = session._run_six_nodes
def run_that_lands_a_file(case: Dict[str, Any]) -> Tuple[Any, ...]: (sample_pkg / "src" / "landed.py").write_text("VALUE = 1\n", encoding="utf-8", newline="\n") return real_run(case)
monkeypatch.setattr(session, "_run_six_nodes", run_that_lands_a_file) res = session.create_file("src/landed.py", "VALUE = 2\n", commit=True) assert res.verdict == "REFUSED" assert res.reason == "PATCH_NOT_APPLIED" assert res.committed is False assert (sample_pkg / "src" / "landed.py").read_text(encoding="utf-8") == "VALUE = 1\n"
def test_retry_loop_spots_repetition_even_without_a_patch_signature( sample_pkg: Path, monkeypatch) -> None: session = PythonWorkspaceSession(sample_pkg)
def always_unknown(rel_path: str, search: str, replace: str, **kwargs: Any) -> SessionResult: return SessionResult( case_id=str(kwargs.get("case_id", "python-edit")), verdict="UNKNOWN", assurance=0, reason="GATE_REJECTED", detail="", committed=False, )
monkeypatch.setattr(session, "edit_file", always_unknown)
def same_proposal(attempt: int, last_result: object) -> tuple: return ("return left + right", "return left - right")
final, attempts = session.run_retry_loop("src/mathops.py", same_proposal, max_attempts=5) assert final.verdict == "UNKNOWN" assert len(attempts) == 213 unmodified lines141516171718192021 unmodified lines424344454546474840 unmodified lines899091929293949495969713 unmodified linesThis bundle carries no kernel. It carries one corpus of its own, the ten pattern cases under`patterns/`, generated from the rules and the fixture beside them, and the card states theirdenominator rather than letting ten rows look like a benchmark. Every number the card states (9 gates,77 tests, 18 node files, the staged file count) is re-derived from this tree before a single object is90 tests, 18 node files, the staged file count) is re-derived from this tree before a single object isuploaded. A card that contradicts the code beside it stops the run instead of publishing.
The folder README is the body of the dataset card. A short list of wording pairs turns the sentences21 unmodified linesEXPECTED_FILES = 66 # the staged tree: 66 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 67 # those 66 plus the .gitattributes the hub addsEXPECTED_GATES = 9EXPECTED_TESTS = 77EXPECTED_TESTS = 90EXPECTED_TEST_FILES = 9EXPECTED_NODE_FILES = 18EXPECTED_GATE_LINE = "GATES: CONFIRMED (9 gates: 9 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"40 unmodified lines "\"What this bundle needs from the codex kernel\" below says how the two find each other.", ), ( "The gate runner is where this bundle states its numbers out loud: 9 gates, 77 tests across 9 files,\n" "The gate runner is where this bundle states its numbers out loud: 9 gates, 90 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, 77 tests across 9 files,\n" "The gate runner is where this bundle states its numbers out loud: 9 gates, 90 tests across 9 files,\n" "18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives every\n" "one of those numbers from the tree it is standing in and stops the upload when the card and the code\n" "beside it disagree.",README.md+14-9
lingologos_python/cli.py+11-2
lingologos_python/gates.py+9-1
lingologos_python/patterns.py+47-5
lingologos_python/rules.py+82-8
lingologos_python/session.py+115-36
tests/test_patterns.py+32-1
tests/test_rules.py+113-1
tests/test_session.py+87-1
tools/publish_dataset.py+4-4