tailot's picture
Upload folder using huggingface_hub
62eac4a verified
Raw History Blame
13.8 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.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.",
)
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.")
# patterns
p_pat = sub.add_parser(
"patterns",
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("--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-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 == "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)
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")
return 0 if 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())