""" app.py — Real Estate & Infrastructure Agent (version read from VERSION file) Route-selective system prompt builder. v16: AGENT_VERSION comes from the package VERSION file; banners and the manifest no longer carry a hand-copied number (v14 audit F-02, still partially open in v15: validate_visado.py emitted 11.0.0 and output-contracts.md printed "v11" into user-facing PDF headers). Inherited v11 fixes (from v10 audit): - FIX 1: 9 orphans reconnected (5 commands + 4 skills now routed) - FIX 2: output-contracts.md (plan-aware) loaded in ALL routes - FIX 3: fail-loud startup audit — missing refs = AssertionError, orphans = AssertionError - FIX 6: scripts injected as INTERFACE CARDS (docstring), not full source (~45K tokens saved) - FIX 7: Spain guard on market route - FIX 8: Moves are route-scoped (see SKILL.md table) - FIX 10: Check route sub-loads visado refs per project_type (fallback: all) - MINOR: token estimator calibrated for ES/CA mixed content (chars/3.6) """ import os import glob BASE_DIR = os.path.dirname(os.path.abspath(__file__)) def _read_version(): with open(os.path.join(BASE_DIR, "VERSION"), encoding="utf-8") as fh: return fh.read().strip() AGENT_VERSION = _read_version() AGENT_LABEL = "v" + AGENT_VERSION.split(".")[0] def load_file(relative_path): path = os.path.join(BASE_DIR, relative_path) if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: return f.read() return "" SKILL_MD = load_file("SKILL.md") PLAYBOOK = load_file("re-infra.local.md") OUTPUT_CONTRACTS = load_file("references/output-contracts.md") # FIX 2 COMMANDS = {} for fp in glob.glob(os.path.join(BASE_DIR, "commands", "*.md")): COMMANDS[os.path.splitext(os.path.basename(fp))[0]] = open(fp, encoding="utf-8").read() SKILLS = {} for sd in glob.glob(os.path.join(BASE_DIR, "skills", "*")): if os.path.isdir(sd): sf = os.path.join(sd, "SKILL.md") if os.path.exists(sf): SKILLS[os.path.basename(sd)] = open(sf, encoding="utf-8").read() SCRIPTS = {} for sp in glob.glob(os.path.join(BASE_DIR, "scripts", "*.py")): SCRIPTS[os.path.splitext(os.path.basename(sp))[0]] = open(sp, encoding="utf-8").read() REFERENCES = {} for root, dirs, files in os.walk(os.path.join(BASE_DIR, "references")): for fname in files: if fname.endswith(".md"): fp = os.path.join(root, fname) rel = os.path.relpath(fp, os.path.join(BASE_DIR, "references")) key = rel.replace(os.sep, "/").replace(".md", "") REFERENCES[key] = open(fp, encoding="utf-8").read() # ═══════════════════════════════════════════════════════════ # ROUTE DEFINITIONS — v11: orphans reconnected (FIX 1) # ═══════════════════════════════════════════════════════════ VIABILITY_COMMANDS = [ "analyze-investment", "assess-risk", "stress-test", "audit-financials", "build-investment-memo", "evaluate-lending", "evaluate-infrastructure", "compare-projects", "brief", # v11 reconnected ] VIABILITY_SKILLS = [ "investment-analysis", "risk-categorization", "financial-reporting", "investment-memo", "secured-lending", "jurisdiction-router", "infrastructure-quality", "cross-case-comparison", "opposition-tierra", # v15 adversarial review ] VIABILITY_SCRIPTS = ["validate_jurisdiction", "validate_dscr", "validate_ltv", "opposition_tierra"] CHECK_COMMANDS = [ "check-visado", "check-zoning", "check-tax-compliance", "track-approvals", "abstract-lease", "support-transaction", # v11 reconnected ] CHECK_SKILLS = [ "pre-visado-checker", "zoning-compliance", "tax-legal-compliance", "government-approvals", "jurisdiction-router", "lease-abstraction", "property-transactions", "opposition-tierra", # v15 adversarial review ] CHECK_SCRIPTS = ["validate_jurisdiction", "validate_visado", "validate_stamp_duty", "validate_tax", "validate_lease", "opposition_tierra"] MARKET_COMMANDS = ["analyze-market"] MARKET_SKILLS = ["market-intelligence", "jurisdiction-router", "opposition-tierra"] MARKET_SCRIPTS = ["update_market_data", "market_intelligence", "catastro_idealista_real", "validate_jurisdiction", "opposition_tierra"] MONITOR_COMMANDS = ["monitor-legal"] MONITOR_SKILLS = ["legal-monitoring", "jurisdiction-router", "opposition-tierra"] MONITOR_SCRIPTS = ["legal_monitor", "validate_jurisdiction", "opposition_tierra"] ROUTES = { "viability": (VIABILITY_COMMANDS, VIABILITY_SKILLS, VIABILITY_SCRIPTS), "check": (CHECK_COMMANDS, CHECK_SKILLS, CHECK_SCRIPTS), "market": (MARKET_COMMANDS, MARKET_SKILLS, MARKET_SCRIPTS), "monitor": (MONITOR_COMMANDS, MONITOR_SKILLS, MONITOR_SCRIPTS), "opposition": (["review-opposition"], ["opposition-tierra"], ["opposition_tierra", "validate_jurisdiction"]), } # FIX 10: Check route sub-loading — visado refs per project type CHECK_TYPE_REFS = { "valoracion_eco805": [ "visado/checklists/tipos-1-2-4-5-6-7-8", "visado/normativa/eco-805", "visado/normativa/ecm-599-2025", "visado/reparos/common-reparos", "visado/normativa/loe", ], "proyecto_basico_ejecucion": [ "visado/checklists/tipo3-proyecto-basico-ejecucion", "visado/normativa/cte-dbs", "visado/normativa/loe", "visado/reparos/common-reparos", "visado/normativa/rd-164-2025-rsciei", ], "_default": [ "visado/checklists/tipos-1-2-4-5-6-7-8", "visado/normativa/cte-dbs", "visado/normativa/loe", "visado/reparos/common-reparos", ], } # ═══════════════════════════════════════════════════════════ # FIX 3: FAIL-LOUD STARTUP AUDIT # ═══════════════════════════════════════════════════════════ def audit_routes(strict=True): """Detect missing referenced files AND orphans. Raise if strict.""" problems = {"missing_commands": [], "missing_skills": [], "missing_scripts": [], "orphan_commands": [], "orphan_skills": []} routed_cmds, routed_skills, routed_scripts = set(), set(), set() for cmds, skills, scripts in ROUTES.values(): routed_cmds |= set(cmds) routed_skills |= set(skills) routed_scripts |= set(scripts) routed_cmds.add("detect-jurisdiction") # always loaded for c in routed_cmds: if c not in COMMANDS: problems["missing_commands"].append(c) for s in routed_skills: if s not in SKILLS: problems["missing_skills"].append(s) for s in routed_scripts: if s not in SCRIPTS: problems["missing_scripts"].append(s) problems["orphan_commands"] = sorted(set(COMMANDS) - routed_cmds) problems["orphan_skills"] = sorted(set(SKILLS) - routed_skills) has_missing = any(problems[k] for k in ("missing_commands", "missing_skills", "missing_scripts")) has_orphans = problems["orphan_commands"] or problems["orphan_skills"] if strict: assert not has_missing, f"ROUTE REFERENCES MISSING FILES: {problems}" assert not has_orphans, f"ORPHAN FILES NOT ROUTED (silent feature loss): {problems}" return problems # ═══════════════════════════════════════════════════════════ # FIX 6: SCRIPT INTERFACE CARDS (docstring only, not full source) # ═══════════════════════════════════════════════════════════ def script_interface_card(name): """Extract module docstring as interface card. LLM needs CLI + schema, not source.""" src = SCRIPTS.get(name, "") doc = "" if '"""' in src: parts = src.split('"""') if len(parts) >= 2: doc = parts[1].strip() if not doc: doc = f"(no docstring) Execute: python scripts/{name}.py --help" return (f"### SCRIPT INTERFACE: {name}\n{doc}\n" f"Execute via bash: python scripts/{name}.py [args]. " f"Full source on disk at scripts/{name}.py — do not need it in context.") # ═══════════════════════════════════════════════════════════ # ROUTE-SELECTIVE SYSTEM PROMPT BUILDER # ═══════════════════════════════════════════════════════════ def build_system_prompt(route="viability", jurisdiction=None, project_type=None): """ project_type enables Check sub-loading (inherited FIX 10, unchanged since v11). """ if route not in ROUTES: raise ValueError(f"Unknown route: {route}. Valid: {list(ROUTES)}") parts = [SKILL_MD, "---", PLAYBOOK] # FIX 2: plan-aware output contract in ALL routes if OUTPUT_CONTRACTS: parts.append("\n\n## OUTPUT CONTRACTS (PLAN / FORMAT / LANG)\n" + OUTPUT_CONTRACTS) if "detect-jurisdiction" in COMMANDS: parts.append(f"### COMMAND: detect-jurisdiction\n{COMMANDS['detect-jurisdiction']}") cmds, skills, scripts = ROUTES[route] parts.append("\n\n## COMMAND PROTOCOLS\n") for cmd in cmds: parts.append(f"### COMMAND: {cmd}\n{COMMANDS[cmd]}") parts.append("\n\n## SKILL PROTOCOLS\n") for skill in skills: parts.append(f"### SKILL: {skill}\n{SKILLS[skill]}") # FIX 6: interface cards instead of source parts.append("\n\n## SCRIPT INTERFACES (execute via bash; source stays on disk)\n") for script in scripts: parts.append(script_interface_card(script)) if route == "check": # FIX 10: sub-load per project type; fallback all if project_type: keys = CHECK_TYPE_REFS.get(project_type, CHECK_TYPE_REFS["_default"]) parts.append(f"\n\n## VISADO REFERENCES (type: {project_type})\n") for key in keys: if key in REFERENCES: parts.append(f"### {key}\n{REFERENCES[key]}") if jurisdiction and jurisdiction.lower() in ("spain", "españa", "espana", "catalunya", "cataluña"): if "visado/coac/coac-specifics" in REFERENCES: parts.append("### visado/coac/coac-specifics\n" + REFERENCES["visado/coac/coac-specifics"]) else: parts.append("\n\n## VISADO REFERENCE LIBRARY (all — project type unknown)\n") for key, content in sorted(REFERENCES.items()): if key.startswith("visado"): parts.append(f"### {key}\n{content}") if route == "market": if "market-data-policy" in REFERENCES: parts.append("\n\n## MARKET DATA POLICY\n" + REFERENCES["market-data-policy"]) # FIX 7: Spain guard — data sources are Spain-only j = (jurisdiction or "").lower() if j and j not in ("spain", "españa", "espana", "catalunya", "cataluña"): parts.append( "\n\n## ⚠ JURISDICTION GUARD (MARKET ROUTE)\n" f"Detected jurisdiction '{jurisdiction}' is NOT Spain. " "Catastro, SIU and INE cover Spain only. You MUST refuse the market " "analysis explicitly, state why, and suggest the Viability route " "for non-Spain properties. Do NOT return Spanish reference data " "for a non-Spanish location.") else: parts.append( "\n\n## JURISDICTION SCOPE (MARKET ROUTE)\n" "This route covers SPAIN ONLY (Catastro/SIU/INE). If during analysis " "the location resolves outside Spain, stop and redirect to Viability.") # Jurisdiction references (viability + check mainly) if jurisdiction: parts.append("\n\n## JURISDICTION REFERENCE\n") jl = jurisdiction.lower() for key, content in sorted(REFERENCES.items()): if jl in key.lower(): parts.append(f"### {key}\n{content}") return "\n\n".join(parts) def estimate_tokens(text): """Calibrated for ES/CA-heavy mixed content: ~3.6 chars/token (English-only ~4.0; Spanish tokenizes denser).""" return int(len(text) / 3.6) # ═══════════════════════════════════════════════════════════ # DIAGNOSTICS # ═══════════════════════════════════════════════════════════ if __name__ == "__main__": print("=" * 62) print(f"REAL ESTATE AGENT {AGENT_LABEL} ({AGENT_VERSION}) — STARTUP AUDIT + PROMPT DIAGNOSTICS") print("=" * 62) problems = audit_routes(strict=True) print("\n✓ FAIL-LOUD AUDIT PASSED: 0 missing refs, 0 orphans") print(f" Commands routed: {len(COMMANDS)} | Skills routed: {len(SKILLS)} " f"| Scripts: {len(SCRIPTS)} | References: {len(REFERENCES)}") print("\nRoute sizes (Spain jurisdiction; Check with/without project_type):") scenarios = [ ("viability", "spain", None), ("check", "spain", None), ("check", "spain", "valoracion_eco805"), ("check", "spain", "proyecto_basico_ejecucion"), ("market", "spain", None), ("monitor", "spain", None), ("opposition", "spain", None), ] for route, j, pt in scenarios: p = build_system_prompt(route, j, pt) t = estimate_tokens(p) label = f"{route}" + (f"[{pt}]" if pt else "") print(f" {label:42s}: {t:>7,} tok | headroom: {200_000 - t:>7,}") print("\nMarket guard test (Toronto):") p = build_system_prompt("market", "canada") print(" Guard present:", "JURISDICTION GUARD" in p)