value / scripts /inventory_functions.py
bonita2026's picture
Claude Fable 5
Deploy v20: engine-driven UI + SES email delivery (replaces v8 prompt wrapper)
7fd88a5 verified
Raw History Blame Contribute Delete
7.85 kB
#!/usr/bin/env python3
"""Generate an exact Markdown inventory of routes, commands, skills, and Python callables.
The version label and default output filename follow the package VERSION file
(``FUNCIONES_V20.md`` for 20.x); nothing about the version is hard-coded here.
"""
from __future__ import annotations
import argparse
import ast
import importlib.util
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parent))
from agent_version import AGENT_VERSION, major_label # noqa: E402
LABEL = major_label() # e.g. "v16"
def format_signature(node: ast.FunctionDef | ast.AsyncFunctionDef) -> str:
"""Render a stable source-level function signature from an AST node."""
arguments = ast.unparse(node.args)
prefix = "async " if isinstance(node, ast.AsyncFunctionDef) else ""
returns = f" -> {ast.unparse(node.returns)}" if node.returns else ""
return f"{prefix}{node.name}({arguments}){returns}"
class CallableVisitor(ast.NodeVisitor):
"""Collect functions and methods with their qualified names."""
def __init__(self):
self.scope: list[str] = []
self.items: list[tuple[str, str, str]] = []
def visit_ClassDef(self, node: ast.ClassDef) -> None:
self.scope.append(node.name)
self.generic_visit(node)
self.scope.pop()
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
qualified = ".".join(self.scope + [node.name])
doc = (ast.get_docstring(node) or "").splitlines()
self.items.append((qualified, format_signature(node), doc[0] if doc else ""))
self.scope.append(node.name)
self.generic_visit(node)
self.scope.pop()
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
self.visit_FunctionDef(node)
def python_inventory(path: Path) -> list[tuple[str, str, str]]:
"""Return every function and method declared in one Python file."""
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
visitor = CallableVisitor()
visitor.visit(tree)
return visitor.items
def first_heading(path: Path) -> str:
"""Return the first Markdown heading, falling back to the filename."""
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
start = 0
if lines and lines[0].strip() == "---":
for index, line in enumerate(lines[1:], 1):
if line.strip() == "---":
start = index + 1
break
for line in lines[start:]:
if line.startswith("# "):
return line[2:].strip()
return path.stem
def load_routes() -> dict:
"""Load app.py in place and return its route map."""
spec = importlib.util.spec_from_file_location("re_infra_app", ROOT / "app.py")
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(module)
return module.ROUTES
def generate_inventory() -> str:
"""Generate the complete Spanish function inventory as Markdown."""
routes = load_routes()
commands = sorted((ROOT / "commands").glob("*.md"))
skills = sorted((ROOT / "skills").glob("*/SKILL.md"))
scripts = sorted((ROOT / "scripts").glob("*.py"))
data_files = sorted((ROOT / "data").glob("*.json"))
references = sorted((ROOT / "references").rglob("*.md"))
lines = [
f"# Funciones exactas — Real Estate & Infrastructure Agent {LABEL} ({AGENT_VERSION})",
"",
f"Este inventario se genera desde los archivos reales de {LABEL}. Incluye rutas,",
"comandos, skills, scripts y todas las funciones/métodos Python declarados.",
"",
"## Rutas del agente",
"",
]
for route, (route_commands, route_skills, route_scripts) in routes.items():
lines.extend([
f"### `{route}`",
"",
f"- Comandos: {', '.join(f'`{item}`' for item in route_commands)}",
f"- Skills: {', '.join(f'`{item}`' for item in route_skills)}",
f"- Scripts: {', '.join(f'`{item}.py`' for item in route_scripts)}",
"",
])
lines.extend(["## Comandos disponibles", ""])
for path in commands:
lines.append(f"- `{path.stem}` — {first_heading(path)} (`commands/{path.name}`)")
lines.extend(["", "## Skills disponibles", ""])
lines.append(f"- `real-estate-infra-agent` — skill raíz y router (`SKILL.md`)")
for path in skills:
lines.append(f"- `{path.parent.name}` — {first_heading(path)} (`skills/{path.parent.name}/SKILL.md`)")
lines.extend(["", "## Programa de toma y validación de datos", ""])
lines.extend([
"- `update_market_data.py`: descarga una instantánea trazable de Catastro, INE e Idealista; no sustituye una descarga fallida por precios incrustados.",
"- `catastro_idealista_real.py`: cliente Catastro por coordenadas, referencia o dirección, y cliente Idealista con OAuth.",
"- `market_intelligence.py`: clasifica suelo, obtiene precios, calcula tendencias/proyecciones y bloquea conclusiones sin datos web vivos.",
"- `legal_monitor.py`: descarga y clasifica novedades del BOE y boletines autonómicos para el período solicitado.",
"- `opposition_tierra.py`: comprueba trazabilidad, actualidad, soporte de claims, cálculos y lagunas antes del arbitraje adversarial.",
"- Validadores deterministas: jurisdicción, DSCR, LTV, impuestos de transmisión, fiscalidad, contratos y pre-visado.",
"",
"## Todas las funciones y métodos Python",
"",
])
total_callables = 0
for path in [ROOT / "app.py", *scripts, *sorted((ROOT / "tests").glob("*.py"))]:
relative = path.relative_to(ROOT)
items = python_inventory(path)
total_callables += len(items)
lines.extend([f"### `{relative}`", ""])
if not items:
lines.append("- No declara funciones o métodos.")
for qualified, signature, doc in items:
description = f" — {doc}" if doc else ""
lines.append(f"- `{qualified}`: `{signature}`{description}")
lines.append("")
lines.extend([
"## Datos y referencias conservados",
"",
f"- Archivos JSON de datos: **{len(data_files)}**",
f"- Referencias Markdown: **{len(references)}**",
f"- Comandos: **{len(commands)}**",
f"- Skills especializados: **{len(skills)}** más el skill raíz",
f"- Scripts Python: **{len(scripts)}** más `app.py`",
f"- Funciones y métodos Python declarados: **{total_callables}**",
"",
f"Los archivos heredados de v14/v15/v16 permanecen en su ruta original. {LABEL}",
"lee el IPV del INE de la tabla base 2025 (80270) y detecta tablas STALE por",
"calendario de publicación; re-verifica las fuentes CCAA del monitor legal",
"(BOPV RSS, BOJA Atom s51+s54, DOGC datos abiertos; DOGV sin feed) con estado",
"PARTIAL por fuente; y conserva las correcciones de v16 (identidad de versión,",
"matriz de jurisdicciones, idioma, series INE, HTTPS Catastro, CLI del monitor).",
])
return "\n".join(lines) + "\n"
def build_parser() -> argparse.ArgumentParser:
"""Build the inventory CLI parser."""
parser = argparse.ArgumentParser(
description=f"Generate the {LABEL} function inventory")
parser.add_argument("--output", type=Path,
default=ROOT / f"FUNCIONES_{LABEL.upper()}.md")
return parser
def main() -> int:
"""Write the generated inventory to the requested path."""
args = build_parser().parse_args()
args.output.write_text(generate_inventory(), encoding="utf-8")
print(args.output)
return 0
if __name__ == "__main__":
raise SystemExit(main())