"""Build public discovery files for indx.earth. Outputs: - public/robots.txt - public/sitemap.xml - public/llms.txt - public/agents.md - public/skills.md - public/.well-known/ai-catalog.json - public/.well-known/security.txt - public/.well-known/agent-card.json """ from __future__ import annotations import html import json import re from dataclasses import dataclass from datetime import date, datetime, timezone from pathlib import Path from urllib.parse import urlparse from xml.etree import ElementTree as ET REPO_ROOT = Path(__file__).resolve().parents[1] CONTENT_ROOT = REPO_ROOT / "content" PUBLIC_ROOT = REPO_ROOT / "public" SKILLS_ROOT = REPO_ROOT / "skills-scripts" HUGO_PUBLIC = REPO_ROOT / "hugo-html-builder" / "public" SITE_URL = "https://indx.earth" SITE_DOMAIN = urlparse(SITE_URL).netloc SITE_TITLE = "iNDX Earth" PUBLISHER = "Eddie Soehnel" SECURITY_CONTACT = "https://indx.earth/#contact-us" SITEMAP_ROOT_HELPER_FILES = ( "ai-index.json", "llms.txt", "skills.md", ) SITEMAP_ROOT_HELPER_URLS = {f"{SITE_URL}/{filename}" for filename in SITEMAP_ROOT_HELPER_FILES} @dataclass(frozen=True) class SitemapEntry: loc: str lastmod: str changefreq: str priority: str def read_text(path: Path) -> str: return path.read_text(encoding="utf-8-sig") def write_text(path: Path, content: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(content, encoding="utf-8", newline="\n") def parse_frontmatter(path: Path) -> dict[str, object]: text = read_text(path) if not text.startswith("---"): return {} end = text.find("\n---", 3) if end == -1: return {} fields: dict[str, object] = {} current_key: str | None = None for raw_line in text[3:end].splitlines(): line = raw_line.rstrip() if not line.strip(): continue if line.startswith(" - ") and current_key: fields.setdefault(current_key, []) assert isinstance(fields[current_key], list) fields[current_key].append(line[4:].strip().strip('"')) continue match = re.match(r"^([A-Za-z0-9_-]+):\s*(.*)$", line) if not match: continue key, value = match.groups() current_key = key value = value.strip() if not value: fields[key] = [] else: fields[key] = value.strip('"') return fields def file_date(path: Path) -> str: timestamp = path.stat().st_mtime return datetime.fromtimestamp(timestamp, timezone.utc).date().isoformat() def latest_date(paths: list[Path]) -> str: existing = [path for path in paths if path.exists()] if not existing: return date.today().isoformat() return max(file_date(path) for path in existing) def section_date_from_content(section_name: str) -> str: section = CONTENT_ROOT / section_name if not section.exists(): return date.today().isoformat() return latest_date([path for path in section.rglob("*.md") if not path.name.startswith("_")]) def slug_for(path: Path, frontmatter: dict[str, object]) -> str: return str(frontmatter.get("slug") or path.stem) def html_route_for_content(path: Path) -> str | None: relative = path.relative_to(CONTENT_ROOT) frontmatter = parse_frontmatter(path) if relative.as_posix() == "home.md": return "/" if relative.as_posix() == "healthz.md": return None if relative.parts[0] == "community-summaries": slug = slug_for(path, frontmatter) return "/" + relative.parent.as_posix() + f"/{slug}.html" return "/" + relative.with_suffix("").as_posix() + "/" def collect_content_pages() -> list[Path]: return sorted(path for path in CONTENT_ROOT.rglob("*.md") if not path.name.startswith("_")) def collect_sitemap_entries() -> list[SitemapEntry]: pages = collect_content_pages() entries: list[SitemapEntry] = [] home = CONTENT_ROOT / "home.md" if home.exists(): entries.append( SitemapEntry( loc=f"{SITE_URL}/", lastmod=file_date(home), changefreq="weekly", priority="1.0", ) ) community_pages = [p for p in pages if p.relative_to(CONTENT_ROOT).parts[0] == "community-summaries"] if community_pages: entries.append( SitemapEntry( loc=f"{SITE_URL}/community-summaries/", lastmod=latest_date(community_pages), changefreq="weekly", priority="0.8", ) ) for rendered_index in sorted(HUGO_PUBLIC.glob("*/index.html")): section_name = rendered_index.parent.name if section_name in {"healthz", "community-summaries"}: continue entries.append( SitemapEntry( loc=f"{SITE_URL}/{section_name}/", lastmod=section_date_from_content(section_name), changefreq="weekly", priority="0.7", ) ) for section in sorted({p.parent for p in community_pages}): if section == CONTENT_ROOT / "community-summaries": continue section_name = section.relative_to(CONTENT_ROOT).as_posix() entries.append( SitemapEntry( loc=f"{SITE_URL}/{section_name}/", lastmod=latest_date(list(section.glob("*.md"))), changefreq="weekly", priority="0.7", ) ) for page in pages: route = html_route_for_content(page) if not route or route == "/": continue entries.append( SitemapEntry( loc=f"{SITE_URL}{route}", lastmod=file_date(page), changefreq="monthly", priority="0.6", ) ) deduped: dict[str, SitemapEntry] = {} for entry in entries: deduped[entry.loc] = entry html_entries = sorted(deduped.values(), key=lambda item: item.loc) return html_entries + collect_root_helper_sitemap_entries() def collect_root_helper_sitemap_entries() -> list[SitemapEntry]: entries: list[SitemapEntry] = [] for filename in SITEMAP_ROOT_HELPER_FILES: path = PUBLIC_ROOT / filename if not path.exists(): continue entries.append( SitemapEntry( loc=f"{SITE_URL}/{filename}", lastmod=file_date(path), changefreq="weekly", priority="0.4", ) ) return entries def build_sitemap(entries: list[SitemapEntry]) -> str: lines = [ '', '', ] for entry in entries: lines.extend( [ " ", f" {html.escape(entry.loc)}", f" {entry.lastmod}", f" {entry.changefreq}", f" {entry.priority}", " ", ] ) lines.append("") return "\n".join(lines) + "\n" def build_robots() -> str: return "\n".join( [ "User-agent: *", "Allow: /", "Disallow: /healthz/", "", f"Sitemap: {SITE_URL}/sitemap.xml", "", ] ) def load_ai_index() -> dict[str, object]: path = PUBLIC_ROOT / "ai-index.json" if not path.exists(): return {} return json.loads(read_text(path)) def resources_from_ai_index() -> list[dict[str, object]]: ai_index = load_ai_index() resources = ai_index.get("resources", []) return resources if isinstance(resources, list) else [] def build_llms_txt(entries: list[SitemapEntry]) -> str: resources = resources_from_ai_index() article_count = sum( 1 for entry in entries if "/community-summaries/" in entry.loc and entry.loc.endswith(".html") ) lines = [ f"# {SITE_TITLE}", "", f"Canonical site: {SITE_URL}/", f"Publisher: {PUBLISHER}", "", "## Summary", "iNDX Earth is a static, AI-readable publishing site for iNDX platform information, community summaries, and open semantic artifacts for AI-era discovery.", "", "## Recommended Retrieval Order", f"1. {SITE_URL}/ai-index.json", f"2. {SITE_URL}/sitemap.xml", f"3. {SITE_URL}/", f"4. {SITE_URL}/community-summaries/", "5. Referenced /data/open/pages/**/chunks.json and qa.json artifacts from ai-index.json.", "", "## Key Human URLs", ] for entry in entries: if entry.loc in SITEMAP_ROOT_HELPER_URLS: continue if entry.loc.endswith(".html") and "/community-summaries/" in entry.loc: continue lines.append(f"- {entry.loc}") lines.extend( [ "", "## Machine-Readable URLs", f"- {SITE_URL}/ai-index.json", f"- {SITE_URL}/.well-known/ai-catalog.json", f"- {SITE_URL}/sitemap.xml", "- /data/open/pages/**/chunks.json", "- /data/open/pages/**/qa.json", f"- License: {SITE_URL}/wiki/license/", "", "## Corpus Notes", f"- Public resource entries in ai-index.json: {len(resources)}", f"- Community summary article pages in sitemap: {article_count}", "- Content is public/open unless a future ai-index entry explicitly says otherwise.", "- Preserve source URLs, license, usageInfo, and attribution metadata when reusing content or semantic artifacts.", "- The contact form is present but the final self-hosted processing endpoint is pending.", "", ] ) return "\n".join(lines) def build_agents_md(entries: list[SitemapEntry]) -> str: human_urls = [entry.loc for entry in entries if entry.loc not in SITEMAP_ROOT_HELPER_URLS] useful_urls = "\n".join(f"- `{url}`" for url in human_urls[:12]) if len(human_urls) > 12: useful_urls += f"\n- See `{SITE_URL}/sitemap.xml` for the remaining canonical URLs." return f"""# Agent Guidance For {SITE_TITLE} Canonical site: {SITE_URL}/ ## Retrieval Policy - Use `{SITE_URL}/.well-known/ai-catalog.json` to discover public agent-usable resources. - Start with `{SITE_URL}/ai-index.json` to understand resources, artifacts, access type, and retrieval priority. - Use `{SITE_URL}/sitemap.xml` for canonical human-facing URLs. - Use `/data/open/pages/**/chunks.json` for semantic retrieval and `/data/open/pages/**/qa.json` for question-answer and workflow hints. - Treat content as public/open only when the relevant `ai-index.json` access entry says `open`. - Preserve source URLs, license, usageInfo, and attribution metadata when reusing content or semantic artifacts. - Prefer stable artifact paths from `ai-index.json` over inferred paths. ## Crawling Policy - Crawl politely and cache responses when possible. - Do not crawl `/healthz/`; it is an uptime check endpoint, not a content resource. - Do not submit contact forms or subscribe forms unless a human explicitly initiates that action. - Do not infer private data, credentials, or unpublished operational details from public files. ## Useful Entry Points - `{SITE_URL}/.well-known/ai-catalog.json` - `{SITE_URL}/ai-index.json` - `{SITE_URL}/llms.txt` {useful_urls} ## Current Sitemap Coverage The generated sitemap currently declares {len(entries)} public URLs with last modification dates, change frequency, and priority. This includes canonical human-facing pages plus selected root AI/helper resources. """ def build_security_txt() -> str: expires_year = date.today().year + 1 return "\n".join( [ f"Contact: {SECURITY_CONTACT}", f"Expires: {expires_year}-12-31T23:59:59Z", f"Canonical: {SITE_URL}/.well-known/security.txt", f"Preferred-Languages: en", "", ] ) def build_agent_card_json() -> str: payload = { "name": SITE_TITLE, "url": f"{SITE_URL}/", "description": "Public, AI-readable discovery website for iNDX platform information, community summaries, and semantic artifacts.", "publisher": PUBLISHER, "contact": SECURITY_CONTACT, "license": f"{SITE_URL}/wiki/license/", "discovery": { "ai_catalog": f"{SITE_URL}/.well-known/ai-catalog.json", "ai_index": f"{SITE_URL}/ai-index.json", "sitemap": f"{SITE_URL}/sitemap.xml", "llms": f"{SITE_URL}/llms.txt", "agents": f"{SITE_URL}/agents.md", "skills": f"{SITE_URL}/skills.md", }, "retrieval": { "preferred_start": f"{SITE_URL}/ai-index.json", "semantic_artifacts": "/data/open/pages/**/chunks.json", "qa_artifacts": "/data/open/pages/**/qa.json", }, "policies": { "crawl": "Crawl politely, cache public resources when possible, and do not submit forms unless a human explicitly initiates the action.", "attribution": "Preserve source URLs, license, usageInfo, and attribution metadata when reusing content or semantic artifacts.", }, } return json.dumps(payload, indent=2, ensure_ascii=False) + "\n" def build_ai_catalog_json() -> str: payload = { "specVersion": "1.0", "host": { "displayName": SITE_TITLE, "identifier": SITE_DOMAIN, "documentationUrl": f"{SITE_URL}/", }, "entries": [ { "identifier": f"urn:air:{SITE_DOMAIN}:dataset:ai-index", "displayName": "iNDX AI-Readable Knowledge Index", "type": "application/json", "url": f"{SITE_URL}/ai-index.json", "description": "Discovery and routing metadata for public iNDX content and semantic artifacts.", "tags": ["knowledge", "structured-content", "semantic-retrieval"], "capabilities": ["KnowledgeDiscovery", "SemanticArtifactRouting"], "representativeQueries": [ "What public knowledge and structured content are available from iNDX?", "Where can I retrieve iNDX semantic chunks and question-answer artifacts?", ], } ], } return json.dumps(payload, indent=2, ensure_ascii=False) + "\n" def skill_title_from_file(path: Path) -> str: if path.suffix == ".py": return path.name text = read_text(path) match = re.search(r"^# Skill:\s*(.+)$", text, re.MULTILINE) if match: return match.group(1).strip() return path.stem.replace("-", " ").title() def skill_summary_from_file(path: Path) -> str: known_summaries = { "ai-catalog-materialization-skill.md": "Create the public ARD ai-catalog.json capability manifest without duplicating the site's knowledge index.", "ai-index-discovery-materialization-skill.md": "Create the machine-readable ai-index.json discovery and routing layer from markdown, chunks.json, qa.json, and existing index structure.", "author-content-structuring-skill.md": "Add lightweight semantic structure, front matter, chunk markers, and stable identifiers to human-authored markdown content.", "cis-guided-semantic-chunk-generation-skill.md": "Create chunks.json semantic retrieval artifacts using the project-selected subset of the CIS envelope.", "discovery-files-materialization-skill.md": "Create the final public discovery files: robots.txt, sitemap.xml, llms.txt, agents.md, and skills.md.", "execute-content-structuring-process-overview-skill.md": "Guide the overall manual workflow for authoring, structuring, chunking, QA generation, HTML rendering, and discovery materialization.", "semantic-qa-materialization-skill.md": "Create qa.json semantic interaction artifacts from chunks.json and source markdown.", } if path.name in known_summaries: return known_summaries[path.name] if path.suffix == ".py": first = read_text(path).splitlines()[0:6] doc_line = " ".join(line.strip(' "\'') for line in first if line.strip().startswith('"""')) return doc_line.strip(' "') text = read_text(path) overview = re.search(r"(?ms)^# Overview\s*(.+?)(?:\n#|\n##|\Z)", text) if overview: for line in overview.group(1).splitlines(): stripped = line.strip() if stripped and not stripped.startswith("-"): return stripped[:220] contract = re.search(r"(?ms)^## Contract\s*(.+?)(?:\n##|\Z)", text) if contract: for line in contract.group(1).splitlines(): stripped = line.strip().lstrip("- ").strip() if stripped: return stripped[:220] for line in text.splitlines(): stripped = line.strip() if stripped.startswith("Human prompt"): continue if stripped and not stripped.startswith("#") and not stripped.startswith("---"): return stripped[:220] return "Project publishing workflow resource." def build_skills_md() -> str: skill_files = sorted(SKILLS_ROOT.glob("*-skill.md")) + sorted(SKILLS_ROOT.glob("*.py")) lines = [ "# iNDX Website Skills And Scripts", "", "This public inventory lists the project-specific skills and deterministic scripts used to build, validate, and publish the static website and AI-readable discovery layers.", "", "## Skills", ] for path in sorted(SKILLS_ROOT.glob("*-skill.md")): rel = path.relative_to(REPO_ROOT).as_posix() lines.append(f"- **{skill_title_from_file(path)}** (`/{rel}`): {skill_summary_from_file(path)}") lines.extend(["", "## Scripts"]) for path in sorted(SKILLS_ROOT.glob("*.py")): rel = path.relative_to(REPO_ROOT).as_posix() lines.append(f"- **{path.name}** (`/{rel}`): {skill_summary_from_file(path)}") lines.extend( [ "", "## Typical Build Order", "", "1. Structure source markdown content.", "2. Generate `chunks.json` and `qa.json` semantic artifacts.", "3. Run `sync_content_to_hugo.py`.", "4. Run Hugo from `hugo-html-builder/`.", "5. Run `build_ai_index.py`.", "6. Run `build_discovery_files.py`.", "", ] ) return "\n".join(lines) def validate_outputs() -> None: sitemap = PUBLIC_ROOT / "sitemap.xml" ET.parse(sitemap) sitemap_text = read_text(sitemap) if "" not in sitemap_text or "" not in sitemap_text: raise RuntimeError("sitemap.xml is missing changefreq or priority fields") if f"Sitemap: {SITE_URL}/sitemap.xml" not in read_text(PUBLIC_ROOT / "robots.txt"): raise RuntimeError("robots.txt does not reference sitemap.xml") for filename in ( "llms.txt", "agents.md", "skills.md", ".well-known/ai-catalog.json", ".well-known/security.txt", ".well-known/agent-card.json", ): path = PUBLIC_ROOT / filename if not path.exists() or path.stat().st_size == 0: raise RuntimeError(f"{filename} was not created") ai_catalog = json.loads(read_text(PUBLIC_ROOT / ".well-known" / "ai-catalog.json")) if ai_catalog.get("specVersion") != "1.0" or not ai_catalog.get("entries"): raise RuntimeError("ai-catalog.json is missing its supported specVersion or entries") for entry in ai_catalog["entries"]: required = {"identifier", "displayName", "type"} if not required.issubset(entry): raise RuntimeError("ai-catalog.json entry is missing required fields") if not entry["identifier"].startswith(f"urn:air:{SITE_DOMAIN}:"): raise RuntimeError("ai-catalog.json entry identifier is not anchored to the site domain") if ("url" in entry) == ("data" in entry): raise RuntimeError("ai-catalog.json entry must contain exactly one of url or data") queries = entry.get("representativeQueries", []) if not 2 <= len(queries) <= 5: raise RuntimeError("ai-catalog.json entry must contain 2-5 representativeQueries") for filename in SITEMAP_ROOT_HELPER_FILES: path = PUBLIC_ROOT / filename if path.exists() and f"{SITE_URL}/{filename}" not in sitemap_text: raise RuntimeError(f"sitemap.xml is missing root helper file: {filename}") def main() -> None: entries = collect_sitemap_entries() write_text(PUBLIC_ROOT / "robots.txt", build_robots()) write_text(PUBLIC_ROOT / "sitemap.xml", build_sitemap(entries)) write_text(PUBLIC_ROOT / "llms.txt", build_llms_txt(entries)) write_text(PUBLIC_ROOT / "agents.md", build_agents_md(entries)) write_text(PUBLIC_ROOT / "skills.md", build_skills_md()) write_text(PUBLIC_ROOT / ".well-known" / "ai-catalog.json", build_ai_catalog_json()) write_text(PUBLIC_ROOT / ".well-known" / "security.txt", build_security_txt()) write_text(PUBLIC_ROOT / ".well-known" / "agent-card.json", build_agent_card_json()) validate_outputs() print(f"Wrote discovery files in {PUBLIC_ROOT} for {len(entries)} sitemap URLs.") if __name__ == "__main__": main()