File size: 12,615 Bytes
339ddd8 1600cd6 339ddd8 1600cd6 339ddd8 1600cd6 339ddd8 1600cd6 79a3ba9 1600cd6 79a3ba9 1600cd6 79a3ba9 1600cd6 339ddd8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | """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 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.patterns import PATTERNS, pattern_card, render_card, scan_pattern # 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.")
# 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, "targets": found}, indent=2))
else:
for item in found:
print(item)
if not found:
print("no function in this workspace has the shape of this card")
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())
|