tailot's picture
Upload folder using huggingface_hub
339ddd8 verified
Raw History Blame
8.93 kB
"""Command-line interface for the external LingoLOGOS Python programming package."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import List, Optional, Sequence
from lgpython._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lgcodex.adapter_contract import check_adapter_contract # noqa: E402
from lgcodex.graph import compute_symbol_pagerank, top_symbols # noqa: E402
from lgpython.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter # noqa: E402
from lgpython.ast_graph import discover_python_files, extract_python_graph # noqa: E402
from lgpython.session import PythonWorkspaceSession # noqa: E402
from lgpython.test_selector import select_python_tests # noqa: E402
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="lgpython",
description="Python programming workbench and language adapter powered by LingoLOGOS codex.",
)
sub = parser.add_subparsers(dest="command", required=True)
# verify
p_verify = sub.add_parser("verify", 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("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.")
p_verify.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.")
p_verify.add_argument("--json", action="store_true", help="Print JSON output.")
# edit
p_edit = sub.add_parser("edit", 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", required=True, help="Search text block.")
p_edit.add_argument("--replace", required=True, help="Replacement text block.")
p_edit.add_argument("--dry-run", action="store_true", help="Verify without committing to disk.")
p_edit.add_argument("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.")
p_edit.add_argument("--subprocesses", action="store_true", help="Run the six topology nodes as separate subprocesses.")
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", 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("--strict-tools", action="store_true", help="Demand mypy and ruff; abstain when absent.")
p_create.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.")
# 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 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,
)
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,
)
res = session.edit_file(
args.file,
args.search,
args.replace,
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}"
)
return 0 if 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)
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:
print(
f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) "
f"{res.reason}: {res.detail}"
)
return 0 if 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 == "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())