route.py

skills/design-pass/scripts/route.py184 lines, 7.0 KBView on GitHub
#!/usr/bin/env python3
"""Pick the primary and secondary design skill for a request.

Reads the routing and install tables from ../references/routing.md (the one
source of truth), matches the request text against each row's keywords, and
reports which picks are installed.

Scoring: keywords prefixed with `~` in routing.md are taste words (generic,
slop, polish...); the rest are surface words (dashboard, form, landing...).
The best row has the most surface hits; taste hits break ties; the earlier
row wins a remaining tie. A blank line inside a table is skipped.

Usage:
  route.py "make the landing page look less generic"
  route.py --json "polish the settings form"
  route.py --skills-dir ./fixture-skills "..."   # replaces the default dirs

Default skill dirs: ~/.claude/skills, ~/.agents/skills, ~/.cursor/skills,
~/.codex/skills. A skill counts as installed when <dir>/<name>/SKILL.md exists.
Stdlib only, Python 3.8+.
"""
import argparse
import json
import re
import sys
from pathlib import Path

DEFAULT_DIRS = ["~/.claude/skills", "~/.agents/skills", "~/.cursor/skills", "~/.codex/skills"]
ROUTING_MD = Path(__file__).resolve().parent.parent / "references" / "routing.md"
TICKED = re.compile(r"`([a-z0-9][a-z0-9-]*)`")


def _rows(lines, header_first_cell):
    """Yield cell lists for the markdown table whose header starts with header_first_cell."""
    inside = False
    for line in lines:
        s = line.strip()
        if not s:
            continue  # blank lines inside a table are tolerated
        if not s.startswith("|"):
            if inside:
                return
            continue
        cells = [c.strip() for c in s.strip("|").split("|")]
        if not inside:
            if cells and cells[0].lower() == header_first_cell.lower():
                inside = True
            continue
        if set("".join(cells)) <= set("-: "):
            continue  # separator row
        yield cells


def parse_routing(text):
    """Return (routes, installs) parsed from routing.md text."""
    lines = text.splitlines()
    routes = []
    for cells in _rows(lines, "Surface"):
        if len(cells) < 4:
            raise ValueError(f"routing row needs 4 cells: {cells}")
        surface, keywords, primary, secondary = cells[:4]
        routes.append({
            "surface": surface,
            "keywords": [k.strip().lstrip("~").strip().lower() for k in keywords.split(",") if k.strip()],
            "taste": {k.strip().lstrip("~").strip().lower() for k in keywords.split(",") if k.strip().startswith("~")},
            "primary": TICKED.findall(primary),
            "secondary": TICKED.findall(secondary),
        })
    installs = {}
    for cells in _rows(lines, "Skill"):
        if len(cells) < 2:
            continue
        names = TICKED.findall(cells[0])
        if not names:
            continue
        cmd = re.search(r"`(npx skills add [^`]+)`", cells[1])
        installs[names[0]] = cmd.group(1) if cmd else None
    if not routes:
        raise ValueError("no routing table found (header must start with 'Surface')")
    return routes, installs


def _contains(text, phrase):
    return re.search(r"(?<![a-z0-9])" + re.escape(phrase) + r"(?![a-z0-9])", text) is not None


def match(routes, request):
    """Return (best_route, matched_keywords) or (None, [])."""
    text = request.lower()
    best, best_hits, best_score = None, [], (0, 0)
    for route in routes:
        hits = [k for k in route["keywords"] if _contains(text, k)]
        taste = route.get("taste", set())
        surface = [k for k in hits if k not in taste]
        score = (len(surface), len(hits) - len(surface))
        if score > best_score:
            best, best_score = route, score
            best_hits = surface + [k for k in hits if k in taste]
    return best, best_hits


def named_skills(routes, installs, request):
    """Skill names the user typed, in table order."""
    text = request.lower()
    known = []
    for route in routes:
        for name in route["primary"] + route["secondary"]:
            if name not in known:
                known.append(name)
    for name in installs:
        if name not in known:
            known.append(name)
    return [n for n in known if _contains(text, n)]


def find_installed(name, dirs):
    for d in dirs:
        if (Path(d).expanduser() / name / "SKILL.md").is_file():
            return str(d)
    return None


def route(request, routing_text, dirs):
    routes, installs = parse_routing(routing_text)
    status = lambda n: {"name": n, "installed_in": find_installed(n, dirs), "install": installs.get(n)}
    result = {"request": request, "named": [status(n) for n in named_skills(routes, installs, request)]}
    best, hits = match(routes, request)
    if best is None:
        result.update(surface=None, matched=[], primary=None, chain=[], secondary=None)
        return result
    chain = [status(n) for n in best["primary"]]
    primary = next((c for c in chain if c["installed_in"]), None)
    secondary = next((status(n) for n in best["secondary"]
                      if not primary or n != primary["name"]), None)
    result.update(surface=best["surface"], matched=hits, primary=primary,
                  chain=chain, secondary=secondary)
    return result


def _line(s):
    where = f"installed ({s['installed_in']})" if s["installed_in"] else "not installed"
    tip = "" if s["installed_in"] else (f" -> {s['install']}" if s["install"] else " -> source unknown")
    return f"{s['name']}: {where}{tip}"


def render(r):
    out = []
    if r["named"]:
        out.append("named by user (use these, route only the remaining gap):")
        out += ["  " + _line(s) for s in r["named"]]
    if r["surface"] is None:
        out.append("surface: no keyword match; pick by hand from references/routing.md")
        return "\n".join(out)
    out.append(f"surface: {r['surface']} (matched: {', '.join(r['matched'])})")
    if r["primary"]:
        out.append("primary: " + _line(r["primary"]))
    else:
        out.append("primary: none installed; continue with the project's own design system")
    for s in r["chain"]:
        if s is not r["primary"]:
            out.append("  alt " + _line(s))
    out.append("secondary: " + (_line(r["secondary"]) if r["secondary"] else "none"))
    return "\n".join(out)


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("request", nargs="+", help="the user's request text or surface keywords")
    ap.add_argument("--skills-dir", action="append", help="skill dir to check (repeatable; replaces defaults)")
    ap.add_argument("--routing", default=str(ROUTING_MD), help="path to routing.md")
    ap.add_argument("--json", action="store_true", help="print JSON")
    a = ap.parse_args(argv)
    try:
        text = Path(a.routing).read_text(encoding="utf-8")
        r = route(" ".join(a.request), text, a.skills_dir or DEFAULT_DIRS)
    except (OSError, ValueError) as e:
        print(f"route.py: {e}", file=sys.stderr)
        return 2
    print(json.dumps(r, indent=2) if a.json else render(r))
    return 0


if __name__ == "__main__":
    sys.exit(main())