master
Colby Knox Publish 1.4.7 7d19532
#!/usr/bin/env python3
"""adom-context: what this Adom workspace is and what is live in it, in a few lines.

Claude Code's SessionStart hook runs `adom-context --hook` (wired by adom/hook), so a
fresh session starts knowing where it is instead of guessing from 250 skills. Safe to
run by hand any time; `--json` gives the same facts as data.

Every probe is optional and time-boxed, and they run in parallel: a missing CLI or a
down service reads as "unknown", never an error. Under --hook the exit code is always 0
and the whole run stays under ~3 s, because a SessionStart hook must never get in the
way of the session it is orienting.
"""
import json
import os
import socket
import subprocess
import sys
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

HOME = Path.home()
ADOM = HOME / ".adom"
PROBE_TIMEOUT = 2.5


def run_json(*cmd):
    try:
        p = subprocess.run(cmd, capture_output=True, text=True, timeout=PROBE_TIMEOUT)
        return json.loads(p.stdout) if p.stdout.strip() else None
    except Exception:
        return None


def hydrogen_url():
    # hd-control-url is the live one (rewritten on every Hydrogen start);
    # hydrogen-control-url is the older name some installs still carry.
    for name in ("hd-control-url", "hydrogen-control-url"):
        try:
            url = (ADOM / name).read_text().strip()
            if url:
                return url
        except OSError:
            pass
    return os.environ.get("ADOM_HD_CONTROL_URL") or None


def probe_hydrogen():
    url = hydrogen_url()
    if not url:
        return {"url": None, "up": False}
    try:
        with urllib.request.urlopen(url.rstrip("/") + "/health", timeout=PROBE_TIMEOUT) as r:
            return {"url": url, "up": r.status == 200}
    except Exception:
        return {"url": url, "up": False}


def probe_where(hydrogen):
    """hydrogen-local: the WSL2 distro Hydrogen runs on the user's own PC.
    container: anything else (an Adom cloud container, a service box)."""
    try:
        wsl = "microsoft" in Path("/proc/version").read_text().lower()
    except OSError:
        wsl = False
    local = wsl and (os.environ.get("ADOM_DESKTOP_MODE") == "local" or hydrogen["url"] is not None)
    return {
        "kind": "hydrogen-local" if local else "container",
        "host": socket.gethostname(),
        "windows_drive": "/mnt/c" if local and Path("/mnt/c").is_dir() else None,
    }


def probe_identity():
    d = run_json("adom-wiki", "whoami", "--json")
    user = ((d or {}).get("data") or {}).get("user") or {}
    if not user.get("username"):
        return None
    orgs = [o.get("name") for o in ((d.get("data") or {}).get("orgs") or []) if o.get("name")]
    return {"username": user["username"], "name": user.get("displayName"), "orgs": orgs}


def machine_state(t):
    """How one `adom-bridge targets` row reads to the AI. Only an explicit
    reachable:false is "offline". Older CLIs send no reachable field at all, and
    every row targets lists came from the relay's live connections, so a missing
    value falls back to connected, relayConnected and connectedAt, and is never
    printed as offline."""
    r = t.get("reachable")
    if r is True:
        return "reachable"
    if r is False:
        return "offline"
    if r == "mesh":
        return "mesh, dials on demand"
    if isinstance(r, str) and r:
        return r
    for key in ("connected", "relayConnected"):
        if t.get(key) is True:
            return "reachable"
    if t.get("connected") is False and t.get("relayConnected") is not True:
        return "offline"
    if t.get("connectedAt"):
        return "reachable"
    return f"status unknown, check with `adom-bridge --target {t.get('name') or '<name>'} status`"


def probe_targets():
    d = run_json("adom-bridge", "targets")
    if not d or d.get("status") != "ok":
        return None
    return {
        "primary": d.get("primaryMachine"),
        "machines": [
            {"name": t.get("name"), "os": t.get("os"), "reachable": machine_state(t),
             "primary": bool(t.get("primary"))}
            for t in d.get("targets") or []
        ],
    }


def probe_packages():
    # Same prefix order as check-updates.sh's self-heal.
    prefix = os.environ.get("ADOMPKG_PREFIX")
    for root in ([Path(prefix) / "adom_modules"] if prefix else []) + [
            HOME / "project" / "adom_modules", HOME / "adom_modules"]:
        if root.is_dir():
            break
    else:
        return []
    pkgs = []
    for manifest in sorted(root.glob("*/*/package.json")):
        try:
            m = json.loads(manifest.read_text())
        except Exception:
            continue
        org, slug = manifest.parent.parent.name, manifest.parent.name
        pkgs.append({"ref": f"{org}/{slug}", "version": m.get("version"), "type": m.get("type")})
    return pkgs


def probe_update():
    try:
        status = (ADOM / "last-update.status").read_text().strip()
    except OSError:
        return None
    return "ok" if status == "0" else status


def gather():
    with ThreadPoolExecutor(max_workers=5) as ex:
        hydrogen = ex.submit(probe_hydrogen)
        identity = ex.submit(probe_identity)
        targets = ex.submit(probe_targets)
        packages = ex.submit(probe_packages)
        update = ex.submit(probe_update)

        def result(f):
            try:
                return f.result(timeout=PROBE_TIMEOUT + 0.5)
            except Exception:
                return None

        h = result(hydrogen) or {"url": None, "up": False}
        return {
            "where": probe_where(h),
            "hydrogen": h,
            "identity": result(identity),
            "machines": result(targets),
            "packages": result(packages) or [],
            "last_update": result(update),
        }


def render(c):
    w, lines = c["where"], ["Adom context (adom-context; rerun it any time):"]
    if w["kind"] == "hydrogen-local":
        lines.append(f"- Where: the Hydrogen local workspace, a WSL2 distro on the user's own PC "
                     f"({w['host']}). {w['windows_drive'] or '/mnt/c'} is that PC's C: drive, so "
                     "Windows files are reachable directly here; skills that say you run in a "
                     "cloud container do not apply.")
    else:
        lines.append(f"- Where: a Linux container ({w['host']}), not the user's PC. Reach the "
                     "user's machines only through adom-bridge.")
    h = c["hydrogen"]
    if h["url"]:
        lines.append(f"- Hydrogen control API: {h['url']} ({'up' if h['up'] else 'not answering'}).")
    i = c["identity"]
    if i:
        orgs = f", orgs: {', '.join(i['orgs'])}" if i["orgs"] else ""
        lines.append(f"- Signed in to Adom as {i['username']} ({i['name']}){orgs}.")
    else:
        lines.append("- Adom sign-in: unknown (`adom-wiki whoami` gave nothing).")
    m = c["machines"]
    if m is None:
        lines.append("- Adom Bridge machines: none reachable (adom-bridge missing or no relay).")
    else:
        # In the local workspace the distro's hostname is its PC's name, so one target
        # is the very machine the user is sitting at.
        here = w["host"].lower() if w["kind"] == "hydrogen-local" else None
        names = "; ".join(
            f"{t['name']} ({t['os']}, {t['reachable']}"
            f"{', primary' if t['primary'] else ''}{', this PC' if (t['name'] or '').lower() == here else ''})"
            for t in m["machines"]) or "none"
        lines.append(f"- Adom Bridge machines: {names}.")
        if len(m["machines"]) > 1 and not m["primary"]:
            lines.append("  No primary machine is set: ask the user which one to use before "
                         "driving any of them, and pass --target <name>.")
    pkgs = c["packages"]
    if pkgs:
        lines.append(f"- Installed wiki packages ({len(pkgs)}): "
                     + ", ".join(p["ref"] for p in pkgs) + ".")
    if c["last_update"] not in (None, "ok"):
        lines.append(f"- Last auto-update: {c['last_update']} (see ~/.adom/last-update.log).")
    return "\n".join(lines)


def main(argv):
    if "-h" in argv or "--help" in argv:
        print(__doc__.strip())
        print("\nusage: adom-context [--json | --hook]")
        return 0
    try:
        c = gather()
        print(json.dumps(c, indent=2) if "--json" in argv else render(c))
    except Exception as e:
        if "--hook" not in argv:
            raise
        print(f"adom-context failed ({e}); run `adom-context` to retry.")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))