Download lingologos_python/cli.py from tailot/codex-python: direct link, hf CLI and curl.
- Browser
- Download file 19.3 kB
-
https://huggingface.co/datasets/tailot/codex-python/resolve/f628309aae90cc23b0c4f985dbd6a3cedcde5317/lingologos_python/cli.py
- Command line
-
hf download hf://datasets/tailot/codex-python@f628309aae90cc23b0c4f985dbd6a3cedcde5317/lingologos_python/cli.py
-
curl -L -o cli.py https://huggingface.co/datasets/tailot/codex-python/resolve/f628309aae90cc23b0c4f985dbd6a3cedcde5317/lingologos_python/cli.py
19.3 kB
| """Command-line interface for the external LingoLOGOS Python programming package.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| from dataclasses import asdict | |
| from pathlib import Path | |
| from typing import List, Optional, Sequence | |
| from lingologos_python._codex_bridge import ensure_codex_on_path | |
| ensure_codex_on_path() | |
| from lingologos_codex.adapter_contract import check_adapter_contract # noqa: E402 | |
| from lingologos_codex.envelope import ENVELOPE_KIND # noqa: E402 | |
| from lingologos_codex.graph import compute_symbol_pagerank, top_symbols # noqa: E402 | |
| from lingologos_python.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter # noqa: E402 | |
| from lingologos_python.ast_graph import discover_python_files, extract_python_graph # noqa: E402 | |
| from lingologos_python.patterns import PATTERNS, pattern_card, render_card, scan_pattern # noqa: E402 | |
| from lingologos_python.session import PythonWorkspaceSession # noqa: E402 | |
| from lingologos_python.test_selector import select_python_tests # noqa: E402 | |
| def _build_parser() -> argparse.ArgumentParser: | |
| parser = argparse.ArgumentParser( | |
| prog="lingologos_python", | |
| description="Python programming workbench and language adapter powered by LingoLOGOS codex.", | |
| ) | |
| parser.add_argument( | |
| "--version", | |
| action="version", | |
| version="lingologos_python, codex envelope %s" % ENVELOPE_KIND, | |
| help="Print the envelope this bundle speaks and exit.", | |
| ) | |
| sub = parser.add_subparsers(dest="command", required=True) | |
| # Flags shared by every verb that opens a session: the same tools, the same | |
| # topology, and the same budgets answer from verify to delete. | |
| session_flags = argparse.ArgumentParser(add_help=False) | |
| session_flags.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.") | |
| session_flags.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.") | |
| session_flags.add_argument("--node-timeout", type=float, default=120.0, metavar="SEC", help="Per-node budget when nodes run as subprocesses; an exhausted budget answers UNKNOWN.") | |
| session_flags.add_argument("--total-timeout", type=float, default=None, metavar="SEC", help="Cap the sum of the six node waits; each node gets the smaller of its budget and the remaining time.") | |
| session_flags.add_argument("--gate-timeout", type=float, default=None, metavar="SEC", help="Wall-clock budget for each gate command (test runner, static checker); a runner that exhausts it abstains.") | |
| # verify | |
| p_verify = sub.add_parser("verify", parents=[session_flags], help="Verify a Python workspace through the six-node codex pipeline.") | |
| p_verify.add_argument("--workspace", required=True, help="Target Python workspace directory.") | |
| p_verify.add_argument("--file", default=None, help="Optional relative Python file to focus on.") | |
| p_verify.add_argument("--json", action="store_true", help="Print JSON output.") | |
| # edit | |
| p_edit = sub.add_parser("edit", parents=[session_flags], help="Propose, verify, and atomically commit a Python search-replace edit.") | |
| p_edit.add_argument("--workspace", required=True, help="Target Python workspace directory.") | |
| p_edit.add_argument("--file", required=True, help="Relative Python file to edit.") | |
| p_edit.add_argument("--search", default=None, help="Search text block.") | |
| p_edit.add_argument("--search-file", default=None, help="Path to a file holding the search text block.") | |
| p_edit.add_argument("--replace", default=None, help="Replacement text block.") | |
| p_edit.add_argument("--replace-file", default=None, help="Path to a file holding the replacement text block.") | |
| p_edit.add_argument("--dry-run", action="store_true", help="Verify without committing to disk.") | |
| p_edit.add_argument("--allow-single-prover", action="store_true", help="Allow commit at assurance 2.") | |
| p_edit.add_argument("--json", action="store_true", help="Print JSON output.") | |
| # create | |
| p_create = sub.add_parser("create", parents=[session_flags], help="Create a new Python file after full codex verification.") | |
| p_create.add_argument("--workspace", required=True, help="Target Python workspace directory.") | |
| p_create.add_argument("--file", required=True, help="Relative Python file path to create.") | |
| p_create.add_argument("--content-file", required=True, help="Path to file holding Python source content.") | |
| p_create.add_argument("--dry-run", action="store_true", help="Verify without committing to disk.") | |
| p_create.add_argument("--allow-single-prover", action="store_true", help="Commit at assurance 2 when the two trusted roles do not both agree.") | |
| p_create.add_argument("--json", action="store_true", help="Print JSON output.") | |
| # delete | |
| p_delete = sub.add_parser( | |
| "delete", | |
| parents=[session_flags], | |
| help="Delete a Python file only when the full regression after its removal verifies.", | |
| ) | |
| p_delete.add_argument("--workspace", required=True, help="Target Python workspace directory.") | |
| p_delete.add_argument("--file", required=True, help="Relative Python file to delete.") | |
| p_delete.add_argument("--dry-run", action="store_true", help="Verify the removal without deleting from disk.") | |
| p_delete.add_argument("--allow-single-prover", action="store_true", help="Commit at assurance 2 when the two trusted roles do not both agree.") | |
| p_delete.add_argument("--json", action="store_true", help="Print JSON output.") | |
| # symbols | |
| p_sym = sub.add_parser("symbols", help="Extract Python AST symbols, edges, and PageRank.") | |
| p_sym.add_argument("--workspace", required=True, help="Target Python workspace directory.") | |
| p_sym.add_argument("--files", nargs="*", default=None, help="Optional relative Python files.") | |
| p_sym.add_argument("--limit", type=int, default=10, help="Maximum top symbols to display.") | |
| p_sym.add_argument("--json", action="store_true", help="Print JSON output.") | |
| # select-tests | |
| p_tests = sub.add_parser("select-tests", help="Select Python test files impacted by changed files.") | |
| p_tests.add_argument("--workspace", required=True, help="Target Python workspace directory.") | |
| p_tests.add_argument("--files", nargs="+", required=True, help="Changed relative Python files.") | |
| p_tests.add_argument("--json", action="store_true", help="Print JSON output.") | |
| # patterns | |
| p_pat = sub.add_parser( | |
| "patterns", | |
| parents=[session_flags], | |
| help="List, show, scan or apply the verified Python pattern catalog.", | |
| ) | |
| p_pat.add_argument("action", choices=("list", "show", "scan", "apply")) | |
| p_pat.add_argument("--pattern", default=None, help="Pattern id from the catalog.") | |
| p_pat.add_argument("--workspace", default=None, help="Target Python workspace for scan and apply.") | |
| 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("--allow-single-prover", action="store_true", help="Commit at assurance 2 when the two trusted roles do not both agree; a card that states its own bar keeps it.") | |
| p_pat.add_argument("--json", action="store_true", help="Print JSON output.") | |
| # check-adapter | |
| p_check = sub.add_parser("check-adapter", help="Validate PythonLanguageAdapter against the codex contract.") | |
| p_check.add_argument("--workspace", required=True, help="Target Python workspace directory.") | |
| p_check.add_argument("--strict-tools", action="store_true", help="Check StrictPythonLanguageAdapter.") | |
| p_check.add_argument("--json", action="store_true", help="Print JSON output.") | |
| return parser | |
| def _side_text(value: Optional[str], path: Optional[str], side: str) -> Optional[str]: | |
| """One side of the edit pair, from the command line or from a file, never from both.""" | |
| if value is not None and path is not None: | |
| print("give --%s or --%s-file, not both" % (side, side), file=sys.stderr) | |
| return None | |
| if path is not None: | |
| return Path(path).read_text(encoding="utf-8", newline="") | |
| return value | |
| def main(argv: Optional[Sequence[str]] = None) -> int: | |
| parser = _build_parser() | |
| args = parser.parse_args(argv) | |
| if args.command == "verify": | |
| session = PythonWorkspaceSession( | |
| args.workspace, | |
| strict_tools=args.strict_tools, | |
| use_subprocesses=args.subprocesses, | |
| node_timeout_sec=args.node_timeout, | |
| total_budget_sec=args.total_timeout, | |
| gate_timeout_sec=args.gate_timeout, | |
| ) | |
| res = session.verify(target_file=args.file) | |
| if args.json: | |
| print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) | |
| else: | |
| print(f"{res.verdict} (assurance {res.assurance}) {res.reason}: {res.detail}") | |
| return 0 if res.accepted else 1 | |
| if args.command == "edit": | |
| min_assurance = 2 if args.allow_single_prover else 3 | |
| session = PythonWorkspaceSession( | |
| args.workspace, | |
| strict_tools=args.strict_tools, | |
| use_subprocesses=args.subprocesses, | |
| min_assurance=min_assurance, | |
| node_timeout_sec=args.node_timeout, | |
| total_budget_sec=args.total_timeout, | |
| gate_timeout_sec=args.gate_timeout, | |
| ) | |
| search_text = _side_text(args.search, args.search_file, "search") | |
| replace_text = _side_text(args.replace, args.replace_file, "replace") | |
| if search_text is None or replace_text is None: | |
| print("edit needs exactly one source of text on each side of the pair", file=sys.stderr) | |
| return 2 | |
| res = session.edit_file( | |
| args.file, | |
| search_text, | |
| replace_text, | |
| commit=not args.dry_run, | |
| ) | |
| if args.json: | |
| print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) | |
| else: | |
| print( | |
| f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) " | |
| f"{res.reason}: {res.detail}" | |
| ) | |
| # Exit 0 only when the edit landed on disk, or a dry run cleared the bar. | |
| # An accepted verdict whose commit never landed is a failure to report. | |
| return 0 if res.committed or (args.dry_run and res.assurance >= min_assurance) else 1 | |
| if args.command == "create": | |
| content = Path(args.content_file).read_text(encoding="utf-8", newline="") | |
| session = PythonWorkspaceSession( | |
| args.workspace, | |
| strict_tools=args.strict_tools, | |
| use_subprocesses=args.subprocesses, | |
| min_assurance=2 if args.allow_single_prover else 3, | |
| node_timeout_sec=args.node_timeout, | |
| total_budget_sec=args.total_timeout, | |
| gate_timeout_sec=args.gate_timeout, | |
| ) | |
| 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 1 | |
| if args.json: | |
| print(json.dumps(res.to_dict(), indent=2, sort_keys=True)) | |
| else: | |
| print( | |
| f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) " | |
| f"{res.reason}: {res.detail}" | |
| ) | |
| # Exit 0 only when the file landed, or a dry run was accepted; a verdict | |
| # that never wrote anything is a failure, whatever its assurance says. | |
| return 0 if res.committed or (args.dry_run and res.accepted) else 1 | |
| if args.command == "delete": | |
| session = PythonWorkspaceSession( | |
| args.workspace, | |
| strict_tools=args.strict_tools, | |
| use_subprocesses=args.subprocesses, | |
| min_assurance=2 if args.allow_single_prover else 3, | |
| node_timeout_sec=args.node_timeout, | |
| total_budget_sec=args.total_timeout, | |
| gate_timeout_sec=args.gate_timeout, | |
| ) | |
| try: | |
| res = session.delete_file(args.file, commit=not args.dry_run) | |
| except FileNotFoundError 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: | |
| print( | |
| f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) " | |
| f"{res.reason}: {res.detail}" | |
| ) | |
| # A removal lands or it does not: exit 0 only when the file is gone, | |
| # or when a dry run verified the removal without touching the disk. | |
| return 0 if res.committed or (args.dry_run and res.accepted) else 1 | |
| if args.command == "symbols": | |
| root = Path(args.workspace).resolve() | |
| files: List[str] = args.files if args.files else discover_python_files(root) | |
| symbols, edges = extract_python_graph(root, files) | |
| ranks = compute_symbol_pagerank(symbols, edges) | |
| top = top_symbols(ranks, limit=args.limit) | |
| if args.json: | |
| print( | |
| json.dumps( | |
| { | |
| "files": files, | |
| "symbols": symbols, | |
| "edges": [list(e) for e in edges], | |
| "top": [[name, score] for name, score in top], | |
| }, | |
| indent=2, | |
| ) | |
| ) | |
| else: | |
| print(f"files={len(files)} symbols={len(symbols)} edges={len(edges)}") | |
| for name, score in top: | |
| print(f" {score:.4f} {name}") | |
| return 0 | |
| if args.command == "select-tests": | |
| root = Path(args.workspace).resolve() | |
| selected = select_python_tests(root, args.files) | |
| if args.json: | |
| print(json.dumps({"selected_tests": selected}, indent=2)) | |
| else: | |
| for item in selected: | |
| print(item) | |
| return 0 | |
| if args.command == "patterns": | |
| if args.action in ("scan", "apply") and not args.workspace: | |
| print("scan and apply need --workspace", file=sys.stderr) | |
| return 2 | |
| if args.action in ("show", "apply", "scan") and not args.pattern: | |
| print("this action needs --pattern", file=sys.stderr) | |
| return 2 | |
| if args.action == "list": | |
| specs = [PATTERNS[name] for name in sorted(PATTERNS)] | |
| rows = [ | |
| { | |
| "pattern_id": spec.pattern_id, | |
| "family": spec.family, | |
| "intent_tags": list(spec.intent_tags), | |
| "min_assurance": spec.min_assurance, | |
| "rule": spec.rule, | |
| "companions": list(spec.companions), | |
| } | |
| for spec in specs | |
| ] | |
| if args.json: | |
| print(json.dumps({"patterns": rows}, indent=2, sort_keys=True)) | |
| else: | |
| for spec in specs: | |
| print( | |
| "%-28s %-10s %s" | |
| % (spec.pattern_id, spec.family, ", ".join(spec.intent_tags)) | |
| ) | |
| return 0 | |
| if args.action == "show": | |
| try: | |
| spec = pattern_card(args.pattern) | |
| except KeyError as exc: | |
| print(str(exc).strip("'"), file=sys.stderr) | |
| return 2 | |
| if args.json: | |
| print(json.dumps(asdict(spec), indent=2, sort_keys=True)) | |
| else: | |
| print(render_card(spec)) | |
| return 0 | |
| root = Path(args.workspace).resolve() | |
| if args.action == "scan": | |
| found = scan_pattern(root, args.pattern) | |
| if args.json: | |
| print( | |
| json.dumps( | |
| { | |
| "pattern": args.pattern, | |
| "hits": [ | |
| { | |
| "target": target, | |
| "rule": hit.rule, | |
| "edits": [asdict(edit) for edit in hit.edits], | |
| "evidence": list(hit.evidence), | |
| "reason_code": hit.reason_code, | |
| } | |
| for target, hit in found | |
| ], | |
| }, | |
| indent=2, | |
| sort_keys=True, | |
| ) | |
| ) | |
| else: | |
| if not found: | |
| print("no function in this workspace has the shape of this card") | |
| else: | |
| print("%s: %d hit(s) in this workspace" % (args.pattern, len(found))) | |
| for target, hit in found: | |
| print(" %s" % target) | |
| for edit in hit.edits: | |
| print(" %-26s %s" % (edit.file, edit.label)) | |
| for line in hit.evidence: | |
| print(" why: %s" % line) | |
| return 0 | |
| session = PythonWorkspaceSession( | |
| args.workspace, | |
| strict_tools=args.strict_tools, | |
| use_subprocesses=args.subprocesses, | |
| min_assurance=2 if args.allow_single_prover else 3, | |
| node_timeout_sec=args.node_timeout, | |
| total_budget_sec=args.total_timeout, | |
| gate_timeout_sec=args.gate_timeout, | |
| ) | |
| 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)) | |
| else: | |
| print( | |
| "%s (assurance %s, committed=%s) %s: %s" | |
| % (res.verdict, res.assurance, res.committed, res.reason, res.detail) | |
| ) | |
| if res.verdict == "REFUSED" and not args.json: | |
| print("nothing was written; the card named this reason before any node ran") | |
| # Exit 0 only when the pair landed, or a dry run was accepted: a card can | |
| # be verified in staging and still lose the commit to the disk. | |
| return 0 if res.committed or (args.dry_run and res.accepted) else 1 | |
| if args.command == "check-adapter": | |
| root = Path(args.workspace).resolve() | |
| adapter = ( | |
| StrictPythonLanguageAdapter(root) | |
| if args.strict_tools | |
| else PythonLanguageAdapter(root) | |
| ) | |
| sample_files = discover_python_files(root)[:3] | |
| violations = check_adapter_contract(adapter, str(root), sample_files) | |
| if args.json: | |
| print( | |
| json.dumps( | |
| {"adapter": adapter.meta().name, "violations": violations}, | |
| indent=2, | |
| ) | |
| ) | |
| else: | |
| if violations: | |
| for v in violations: | |
| print(f"VIOLATION: {v}") | |
| else: | |
| print(f"ADAPTER OK: {adapter.meta().name}") | |
| return 1 if violations else 0 | |
| return 2 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |