Upload folder using huggingface_hub
Browse filesFiles changed (10)
34 unmodified lines35363738394041424344454647484950511 unmodified line535455565758596061626364656667686921 unmodified lines91929394959697121 unmodified lines21922022122222322422534 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,18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives everyone of those numbers from the tree it is standing in and stops the upload when the card and the codebeside it disagree.## Contents- - `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 theancestors.- - `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`).1 unmodified line- `lingologos_python/gates.py`: bytecode-free `ast.parse` + in-memory `compile` gate, optional staticcheckers (`mypy`, `ruff`, `pyright`, `flake8`) that return `ABSTAIN` when missing, and `pytest`/ `unittest` test runner with failed-target parsing.- - `lingologos_python/rules.py`: five shape rules over a named function. Each rule reads the functionthrough its syntax tree, refuses with a named reason code when the shape is not the one it claims, andreturns 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, whythat shape is worth changing, what must hold before the rule runs, what test locks the change, and thereason 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 diskcommits 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`,`select-tests`, `patterns list|show|scan|apply`, `check-adapter`).- `fixtures/pattern_lab/`: a small package with one function planted in the shape of each card andone planted to be refused, used by the tests and by the coverage counts.21 unmodified linesarguments (`BRANCH_SHAPE_MISMATCH`), `open-to-context-manager` refuses a handle that escapes the functionit opened (`HANDLE_ESCAPE`), `mutable-default-to-none` refuses a default that already carries anannotation (`ANNOTATED_MUTABLE_DEFAULT`). A refusal is an answer, not a failure: it names the reason codeand writes nothing.Every change this bundle makes is a pair. The rule returns two edits, the change in the source fileand 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 askingfor a change. With `--strict-tools` the run demands `mypy` and `ruff`: a gate that cannot run abstains,and the session answers UNKNOWN with the reason `GATE_ABSTAIN` instead of reporting a check that neverhappened.`check-adapter` says whether the Python adapter holds the contract of the kernel, and exits non-zerowhen it does not.34 unmodified lines35363738394041424344454647484950511 unmodified line53545556575859606162636465666768697021 unmodified lines9293949596979899100101121 unmodified lines22322422522622722822923034 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, 90 tests across 9 files,18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives everyone of those numbers from the tree it is standing in and stops the upload when the card and the codebeside it disagree.## Contents- `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 theancestors.- `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`).1 unmodified line- `lingologos_python/gates.py`: bytecode-free `ast.parse` + in-memory `compile` gate, optional staticcheckers (`mypy`, `ruff`, `pyright`, `flake8`) that return `ABSTAIN` when missing, and `pytest`/ `unittest` test runner with failed-target parsing.- `lingologos_python/rules.py`: five shape rules over a named function. Each rule reads the functionthrough its syntax tree, refuses with a named reason code when the shape is not the one it claims, andreturns 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, whythat shape is worth changing, what must hold before the rule runs, what test locks the change, and thereason 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 diskcommits 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 diskand 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 andone 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 functionit opened (`HANDLE_ESCAPE`), `mutable-default-to-none` refuses a default that already carries anannotation (`ANNOTATED_MUTABLE_DEFAULT`). A refusal is an answer, not a failure: it names the reason codeand writes nothing. Each card also lists the refusals the plan around a rule shares: a target that is notthere (`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 assertwhose 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 fileand 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 askingfor a change. With `--strict-tools` the run demands `mypy` and `ruff`: a gate that cannot run abstains,and the session answers UNKNOWN with the reason `GATE_ABSTAIN` instead of reporting a check that neverhappened. `patterns apply` also takes `--subprocesses`, which runs the six nodes as separate processesinstead of in this one.`check-adapter` says whether the Python adapter holds the contract of the kernel, and exits non-zerowhen it does not.
82 unmodified lines83848586878848 unmodified lines137138139140141142143112 unmodified lines25625725825926026126282 unmodified linesp_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("--json", action="store_true", help="Print JSON output.")# check-adapter48 unmodified linesif args.command == "create":content = Path(args.content_file).read_text(encoding="utf-8", newline="")session = PythonWorkspaceSession(args.workspace, strict_tools=args.strict_tools)res = session.create_file(args.file, content, commit=not args.dry_run)if args.json:print(json.dumps(res.to_dict(), indent=2, sort_keys=True))else:112 unmodified linesfor line in hit.evidence:print(" why: %s" % line)return 0session = PythonWorkspaceSession(args.workspace, strict_tools=args.strict_tools)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))82 unmodified lines8384858687888948 unmodified lines138139140141142143144145146147148112 unmodified lines26126226326426526626726826927027182 unmodified linesp_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 linesif 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)except FileExistsError as exc:print("REFUSED: %s" % exc, file=sys.stderr)return 1if args.json:print(json.dumps(res.to_dict(), indent=2, sort_keys=True))else:112 unmodified linesfor line in hit.evidence:print(" why: %s" % line)return 0session = 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 lines139140141142143144145146138 unmodified linesfull_suite: bool = False,) -> GateResult:"""Run pytest (no cacheprovider) or fall back to unittest discovery."""if resolve_tool_argv("pytest") is not None:argv = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"]if full_suite or not targets:return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression")return adapter.run_command(138 unmodified lines139140141142143144145146147148149150151152153154138 unmodified linesfull_suite: bool = False,) -> GateResult:"""Run pytest (no cacheprovider) or fall back to unittest discovery."""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 = Noneif 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 lines313233343536373849 unmodified lines8889909192934 unmodified lines9899100101102103104201 unmodified lines30630730830931031131231336 unmodified lines35035135235335435535612 unmodified lines36937037137237337437530 unmodified lines# Target syntax: a workspace-relative path, then the module level function, split by "::".TARGET_SEPARATOR = "::"FAMILIES: Tuple[str, ...] = ("contracts", "mutation", "resources", "shape", "typing")@dataclass(frozen=True)class PatternSpec:49 unmodified lineslock_claims: str,refuses_as: Sequence[str],) -> PatternSpec:return PatternSpec(pattern_id=pattern_id,family=family,4 unmodified linespreconditions=tuple(preconditions),companions=tuple(companions),lock_claims=lock_claims,refuses_as=tuple(refuses_as),)201 unmodified linestext = reader(rel)if text is None:continuefor symbol in module_level_functions(text):target, miss = rules.open_target(rel, symbol, reader)if target is None:continueoutcome = rule(target)36 unmodified linesevidence=(),min_assurance=spec.min_assurance,refused=True,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 linesdetail=miss.detail,)assert opened is not Noneoutcome = rule(opened)if isinstance(outcome, rules.RuleMiss):return PatternPlan(pattern_id=pattern_id,30 unmodified lines3132333435363738394041424344454647484950515253545556575849 unmodified lines1081091101111121131141151161174 unmodified lines122123124125126127128201 unmodified lines33033133233333433533633733833934034136 unmodified lines37837938038138238338412 unmodified lines39739839940040140240340440540640740840941041141241341441541641730 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 lineslock_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 linespreconditions=tuple(preconditions),companions=tuple(companions),lock_claims=lock_claims,refuses_as=tuple(merged),)201 unmodified linestext = reader(rel)if text is None:continuetry:tree = ast.parse(text)except SyntaxError:continuefor 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:continueoutcome = rule(target)36 unmodified linesevidence=(),min_assurance=spec.min_assurance,refused=True,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 linesdetail=miss.detail,)assert opened is not Nonetry: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 lines28293031323319 unmodified lines535455565758168 unmodified lines2272282292302312321 unmodified line2342352362372382392 unmodified lines24224324424524624735 unmodified lines28328428528628728820 unmodified lines30931031131231331449 unmodified lines364365366367368369143 unmodified lines51351451551651751851952052152252352411 unmodified lines536537538539540541542339 unmodified lines88288388488588688788884 unmodified lines9739749759769779789799801 unmodified line98298398498598698798898999099199299399499599627 unmodified linesfrom __future__ import annotationsimport astfrom dataclasses import dataclassfrom typing import Callable, Dict, List, Optional, Sequence, Tuple, Union19 unmodified linesNO_BARE_OPEN = "NO_BARE_OPEN"HANDLE_ESCAPE = "HANDLE_ESCAPE"NOT_THE_FIRST_STATEMENT = "NOT_THE_FIRST_STATEMENT"INDENT = " "_MUTABLE_LITERALS = (ast.List, ast.Dict, ast.Set)168 unmodified linestext = read(rel_posix)if text is None:return None, _miss(rel_posix, symbol, MISSING_TARGET_FILE, "no such file: '%s'" % rel_posix)code = _shape_rejection(text)if code:return None, _miss(rel_posix, symbol, code, _SHAPE_DETAIL[code])1 unmodified linetree = ast.parse(text)except SyntaxError as exc:return None, _miss(rel_posix, symbol, NOT_PARSEABLE, "the file does not parse: %s" % exc.msg)return Target(rel_posix=rel_posix, symbol=symbol, text=text, tree=tree, read=read), None2 unmodified linesfor node in target.tree.body:if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol:return node, Nonefor node in ast.walk(target.tree):if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol:35 unmodified linesreturn "import %s" % stem, stemdef lock_source(rel_posix: str,test_name: str,20 unmodified linestext = target.read(test_rel)if text is None:return None, _miss(test_rel, target.symbol, NO_TEST_FILE, "no test file: '%s'" % test_rel)try:tree = ast.parse(text)except SyntaxError as exc:49 unmodified linesreturn list(function.args.posonlyargs) + list(function.args.args) + list(function.args.kwonlyargs)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),)body_start = starts[function.body[0].lineno - 1]guard_indent = " " * function.body[0].col_offsetfor 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: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),))339 unmodified linesbreakblock.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:]):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 linesreturn missassert function is not Nonestarts = line_starts(target.text)first = function.body[0]check = first.value if isinstance(first, ast.Expr) else firstif not isinstance(check, ast.Assert):return _miss(target.rel_posix,1 unmodified lineNOT_THE_FIRST_STATEMENT,"the first statement of '%s' is not an assert, so it is not a precondition" % target.symbol,)indent = " " * first.col_offsettest_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: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)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]27 unmodified lines2829303132333419 unmodified lines54555657585960616263168 unmodified lines2322332342352362372382392402412422431 unmodified line2452462472482492502512522532542552562572582592 unmodified lines26226326426526626726826927027127227327435 unmodified lines31031131231331431531631731831932032132232332432520 unmodified lines34634734834935035135235335435535635735835936036136249 unmodified lines412413414415416417418419420421422423424425426427143 unmodified lines57157257357457557657757857958058158258358458558658758858959059111 unmodified lines603604605606607608609610339 unmodified lines95095195295395495595684 unmodified lines10411042104310441045104610471 unmodified line104910501051105210531054105510561057105810591060106110621063106410651066106710681069107027 unmodified linesfrom __future__ import annotationsimport astimport keywordfrom dataclasses import dataclassfrom typing import Callable, Dict, List, Optional, Sequence, Tuple, Union19 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 linestext = 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 linetree = 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), None2 unmodified linesfor 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, Nonefor node in ast.walk(target.tree):if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol:35 unmodified linesreturn "import %s" % stem, stemdef _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 Falsenames = [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 linestext = 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 linesreturn 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 0if head < len(function.body):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_offsetguard_lead, guard_trail = "\n", ""guard_indent = " " * function.body[0].col_offsetfor 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 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="%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 linesbreakblock.append(statement)last_use = max(index for index, statement in enumerate(function.body) if uses(statement))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 linesreturn missassert function is not Nonestarts = line_starts(target.text)check = function.body[0]if not isinstance(check, ast.Assert):return _miss(target.rel_posix,1 unmodified lineNOT_THE_FIRST_STATEMENT,"the first statement of '%s' is not an assert, so it is not a precondition" % target.symbol,)indent = " " * check.col_offsettest_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, 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 lines9101112131435 unmodified lines50515253545541 unmodified lines979899100101102149 unmodified lines252253254255256257258259260261262263264265266267105 unmodified lines373374375376377378379380381382383384385386387388389390391392393105 unmodified lines4995005015025035045054 unmodified lines51051151251351451551634 unmodified lines5515525535545555565575585595605615625635645653 unmodified lines56957057157257357457557648 unmodified lines625626627628629630631632633634635636637638639640641642643644100 unmodified lines7457467477487497507517528 unmodified linesfrom __future__ import annotationsimport jsonimport osimport shutil35 unmodified linesDEFAULT_TOPOLOGY_PATH = PYTHON_ROOT / "topology.json"DEFAULT_ALLOWED_PATTERNS: Tuple[str, ...] = ("*.py", "*.pyi")DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ("*.env",".env*",41 unmodified lines}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_lineprobe_replace = first_line.rstrip("\r\n") + " # codex-verify-probe\n"original_for_patch = textelse:probe_search = "# empty"probe_replace = "# empty verified"original_for_patch = "# empty\n"case: Dict[str, Any] = {"case_id": case_id,105 unmodified linesdecision = dict(dossier.get("decision", {}))verdict = str(decision.get("verdict", "UNKNOWN"))assurance = int(decision.get("assurance", 0))committed = Falseif commit and patch_res.applied and not plan.rejected and assurance >= self.min_assurance: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 = Truereturn SessionResult(case_id=case_id,verdict=verdict,assurance=assurance,reason=str(decision.get("reason", "")),detail=str(decision.get("detail", "")),committed=committed,touched_files=(rel_posix,),trace=tuple(trace),105 unmodified linescase_id=chosen_case_id,verdict="REFUSED",assurance=0,reason="PATH_POLICY" if planned.rejected else "PATCH_NOT_APPLIED",detail=("the path policy rejected the pair: " + ", ".join(plan.files)if planned.rejected4 unmodified linesdossier={"pattern": pattern_id,"target": plan.target,"refusal": "PATH_POLICY" if planned.rejected else "PATCH_NOT_APPLIED","decision": {"verdict": "REFUSED", "assurance": 0},"gates": [],"checkers": [],34 unmodified linesdecision = dict(dossier.get("decision", {}))verdict = str(decision.get("verdict", "UNKNOWN"))assurance = int(decision.get("assurance", 0))committed = Falseif commit and assurance >= needed: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 = Truedossier["pattern"] = pattern_iddossier["target"] = plan.target3 unmodified linescase_id=chosen_case_id,verdict=verdict,assurance=assurance,reason=str(decision.get("reason", "")),detail=str(decision.get("detail", "")),committed=committed,touched_files=plan.files,trace=tuple(trace),48 unmodified linesdecision = dict(dossier.get("decision", {}))verdict = str(decision.get("verdict", "UNKNOWN"))assurance = int(decision.get("assurance", 0))committed = Falseif commit and not plan.rejected and assurance >= self.min_assurance: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 = Truereturn SessionResult(case_id=case_id,verdict=verdict,assurance=assurance,reason=str(decision.get("reason", "")),detail=str(decision.get("detail", "")),committed=committed,touched_files=(rel_posix,),trace=tuple(trace),100 unmodified linesattempts.append(result)last = resultsig = str(result.dossier.get("patchSignature", ""))if sig:history.append(sig)if result.assurance >= self.min_assurance:return result, attemptsif detect_stall_from_hashes(history) is not None:8 unmodified lines91011121314151635 unmodified lines5253545556575859606141 unmodified lines103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149149 unmodified lines299300301302303304305105 unmodified lines411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442105 unmodified lines5485495505515525535544 unmodified lines55956056156256356456534 unmodified lines6006016026036046056066076086096106116126136146156166176186196206216226236246256266276286293 unmodified lines63363463563663763863964048 unmodified lines689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719100 unmodified lines8208218228238248258268278288298308318 unmodified linesfrom __future__ import annotationsimport 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 acomment is appended to it, so the probe cannot turn a valid workspace file into asyntax error. When nothing safer is found the first line is used as it has alwaysbeen, 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 = Noneif 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):continueline = lines[node.lineno - 1].rstrip("\r\n")if not line:continuecandidate = line + probe_notetry:ast.parse(text.replace(line, candidate, 1))except SyntaxError:continuereturn line, candidate, textfirst = lines[0].rstrip("\r\n")return first, first + probe_note, textdef _copy_workspace_for_staging(src_root: Path, dst_root: Path) -> None:"""Copy a workspace cleanly without caches or virtual environments."""for dirpath, dirnames, filenames in os.walk(src_root):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.probe_search, probe_replace, original_for_patch = _verify_probe(text)case: Dict[str, Any] = {"case_id": case_id,105 unmodified linesdecision = 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 = Falseif commit and patch_res.applied and not plan.rejected and assurance >= self.min_assurance:if _disk_text(self.workspace_root, rel_posix) != original_text:# The workspace moved while the six nodes were running: the patch that# was verified is no longer the patch for the file on disk, so nothing# is written and the run reports the named refusal instead.verdict = "REFUSED"assurance = 0reason = PATCH_NOT_APPLIEDdetail = "the file changed on disk after the run verified the patch: '%s'" % rel_posixelse: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 = Truereturn SessionResult(case_id=case_id,verdict=verdict,assurance=assurance,reason=reason,detail=detail,committed=committed,touched_files=(rel_posix,),trace=tuple(trace),105 unmodified linescase_id=chosen_case_id,verdict="REFUSED",assurance=0,reason=PATH_POLICY if planned.rejected else PATCH_NOT_APPLIED,detail=("the path policy rejected the pair: " + ", ".join(plan.files)if planned.rejected4 unmodified linesdossier={"pattern": pattern_id,"target": plan.target,"refusal": PATH_POLICY if planned.rejected else PATCH_NOT_APPLIED,"decision": {"verdict": "REFUSED", "assurance": 0},"gates": [],"checkers": [],34 unmodified linesdecision = 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 = Falseif commit and assurance >= needed:drifted = [edit.file for edit in plan.editsif _disk_text(self.workspace_root, edit.file) != originals[edit.file]]if drifted:# The pair was verified against the workspace as it was at staging time.# If a file of the pair moved since, the anchors proven in staging are# not the anchors of what is on disk, so the pair is not written.verdict = "REFUSED"assurance = 0reason = PATCH_NOT_APPLIEDdetail = "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 = Truedossier["pattern"] = pattern_iddossier["target"] = plan.target3 unmodified linescase_id=chosen_case_id,verdict=verdict,assurance=assurance,reason=reason,detail=detail,committed=committed,touched_files=plan.files,trace=tuple(trace),48 unmodified linesdecision = 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 = Falseif commit and not plan.rejected and assurance >= self.min_assurance:if target.is_file():# The verified text was staged as a new file. If a file landed at that# path while the run was going, writing would replace something the# six nodes never saw, so the create is not committed.verdict = "REFUSED"assurance = 0reason = PATCH_NOT_APPLIEDdetail = "a file appeared at '%s' while the create was being verified" % rel_posixelse: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 = Truereturn SessionResult(case_id=case_id,verdict=verdict,assurance=assurance,reason=reason,detail=detail,committed=committed,touched_files=(rel_posix,),trace=tuple(trace),100 unmodified linesattempts.append(result)last = resultsig = str(result.dossier.get("patchSignature", ""))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, attemptsif detect_stall_from_hashes(history) is not None:
5 unmodified lines67891011121 unmodified line141516171819187 unmodified lines2072082095 unmodified linesimport subprocessimport sysfrom pathlib import Pathfrom typing import Dict, Listfrom lingologos_codex.casecorpus import read_rows, validate_case_rows1 unmodified lineFAMILIES,PATTERNS,PATTERN_IDS,PatternSpec,pattern_card,plan_pattern,187 unmodified linesassert POSITIVE[str(entry["pattern_id"])] in entry["targets_in_shape"]assert len(entry["refusals_recorded"]) == 1assert entry["refusals_recorded"][0] in _card(str(entry["pattern_id"])).refuses_as5 unmodified lines67891011121 unmodified line14151617181920187 unmodified lines2082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392405 unmodified linesimport subprocessimport sysfrom pathlib import Pathfrom typing import Any, Dict, Listfrom lingologos_codex.casecorpus import read_rows, validate_case_rows1 unmodified lineFAMILIES,PATTERNS,PATTERN_IDS,SHARED_REFUSALS,PatternSpec,pattern_card,plan_pattern,187 unmodified linesassert POSITIVE[str(entry["pattern_id"])] in entry["targets_in_shape"]assert len(entry["refusals_recorded"]) == 1assert entry["refusals_recorded"][0] in _card(str(entry["pattern_id"])).refuses_asdef 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_asassert 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 rulesroot = 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.refusedassert plan.reason_code == rules.ANCHOR_OVERLAP
2 unmodified lines3456789243 unmodified lines2532542552 unmodified linesfrom __future__ import annotationsfrom pathlib import Pathfrom typing import Callable, Dict, Optionalfrom lingologos_codex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch243 unmodified linesoutcome = _outcome("src/crlf.py", "pick", "mutable-default-to-none", root)assert isinstance(outcome, rules.RuleMiss)assert outcome.reason_code == rules.CRLF_TARGET2 unmodified lines3456789243 unmodified lines2532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663672 unmodified linesfrom __future__ import annotationsfrom pathlib import Pathfrom typing import Any, Callable, Dict, Optionalfrom lingologos_codex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch243 unmodified linesoutcome = _outcome("src/crlf.py", "pick", "mutable-default-to-none", root)assert isinstance(outcome, rules.RuleMiss)assert outcome.reason_code == rules.CRLF_TARGETdef _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.filereturn result.updated_textdef 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_ESCAPEdef 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 seconddef 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_MESSAGEdef 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_TARGETdef 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_TARGETdef 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_PATH
2 unmodified lines34567891082 unmodified lines9394952 unmodified linesfrom __future__ import annotationsfrom pathlib import Pathfrom lingologos_python.session import PythonWorkspaceSessiondef test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None:82 unmodified linesassert final.verdict == "UNKNOWN"assert len(attempts) == 2assert any(c.get("role") == "adversary_loop" for c in final.dossier.get("checkers", []))2 unmodified lines3456789101182 unmodified lines9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801812 unmodified linesfrom __future__ import annotationsfrom pathlib import Pathfrom typing import Any, Dict, Tuplefrom lingologos_python.session import PythonWorkspaceSession, SessionResult, _verify_probedef test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None:82 unmodified linesassert final.verdict == "UNKNOWN"assert len(attempts) == 2assert 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 textcompile(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_textdef 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_nodesdef 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 Falseon_disk = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8")assert "# moved" in on_diskassert "int(left)" not in on_diskdef 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_nodesdef 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 Falseassert (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) == 2
13 unmodified lines1415161718192021 unmodified lines4243444546474840 unmodified lines89909192939495969713 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 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_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""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""18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives every\n""one of those numbers from the tree it is standing in and stops the upload when the card and the code\n""beside it disagree.",13 unmodified lines1415161718192021 unmodified lines4243444546474840 unmodified lines89909192939495969713 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,90 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 = 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, 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, 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