646 lines
27 KiB
Python
646 lines
27 KiB
Python
"""What a worker project is — read off its conversations' transcripts.
|
|
|
|
A lab project's card comes from its folder (``catalog.py``: ``package.json``,
|
|
the README, ``index.html``…). A worker's disk isn't the hub's, and Gabriel
|
|
chose (form ``project-metadata-on-guests-computers_2l6bxi``, 2026-11-06) not
|
|
to read it — no call to the computer, no AI summary: what the card says is
|
|
what the project's own conversations saw. A Claude Code transcript carries a
|
|
lot of it:
|
|
|
|
* **key files** — ``package.json``, ``README.md``, ``CLAUDE.md``,
|
|
``index.html``, as of the last time a session read one whole (a Read's
|
|
``toolUseResult.file``), wrote it (a Write's ``content``), edited it (the
|
|
Edit's ``originalFile`` with the edit applied) or ``cat``-ed a
|
|
``package.json`` in a shell command;
|
|
* **the stack** — the packages the source files it touched import, the
|
|
``package.json`` dependencies, the file kinds it worked on (``.vue``,
|
|
``.ts``, ``.rs``…) and marker files (``tsconfig.json``, ``vite.config.*``);
|
|
* **the site** — the deployed URL its sessions printed or opened: a host
|
|
whose first label (``<user>.github.io/<repo>``: the repo) holds every word
|
|
of the project's name, seen at least twice, the shortest such name winning —
|
|
a Vercel preview (``music-generator-oofabqftc-akkibi11``) is longer than the
|
|
production alias (``music-generator-eta``).
|
|
|
|
``Scanner`` follows every worker transcript by byte offset (transcripts only
|
|
grow; a shrink starts over) from a background thread, so a request never reads
|
|
a transcript. A ``Scan`` is per transcript and knows nothing about projects;
|
|
``project_meta`` folds the scans of a project's conversations onto its root
|
|
(worktrees folded in by the worker's ``WorkerIndex.rewrite``) — latest file
|
|
wins across conversations.
|
|
|
|
Measured on 2026-11-06: Akira's 208 MB of transcripts scan in ~0.6 s; the
|
|
Orus MacBook's ~1 GB in a few seconds, once per hub start.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import os
|
|
import posixpath as pp
|
|
import re
|
|
import threading
|
|
from collections import Counter
|
|
|
|
from projects import catalog as catalog_mod
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
MAX_TEXT = catalog_mod.MAX_TEXT
|
|
README_NAMES = ("README.md", "README", "readme.md", "Readme.md")
|
|
KEY_NAMES = frozenset(README_NAMES + ("package.json", "CLAUDE.md", "index.html"))
|
|
# Root-level files whose presence alone says something (catalog.stack_tags).
|
|
MARKERS = frozenset({"tsconfig.json", "Cargo.toml", "go.mod", "pyproject.toml",
|
|
"requirements.txt", "Dockerfile"})
|
|
# Config files that stand for a dependency.
|
|
_CONFIG_DEP = (("vite.config.", "vite"), ("tailwind.config.", "tailwindcss"),
|
|
("svelte.config.", "svelte"), ("astro.config.", "astro"))
|
|
_SRC_EXTS = frozenset({".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs",
|
|
".vue", ".svelte", ".astro"})
|
|
# File kinds that stand for a dependency or a marker, once a project's
|
|
# conversations touched at least EXT_MIN of them.
|
|
_EXT_DEP = {".ts": "typescript", ".tsx": "typescript", ".mts": "typescript",
|
|
".vue": "vue", ".svelte": "svelte", ".astro": "astro"}
|
|
_EXT_MARKER = {".rs": "Cargo.toml", ".go": "go.mod", ".py": "pyproject.toml"}
|
|
EXT_MIN = 3
|
|
# Where an index.html may sit when the root has none.
|
|
_INDEX_DIRS = ("", "public", "landing", "web", "app", "frontend", "client", "site")
|
|
# Per-transcript caps — a runaway session can't grow the hub's memory.
|
|
_CAP_FILES = 40
|
|
_CAP_DIRS = 1000
|
|
_CAP_URLS = 500
|
|
# Maximum number of transcript scans retained in memory (LRU-evicted).
|
|
# Must comfortably exceed active worker transcript count (~1,100+) so the
|
|
# 20 s ScanThread never thrashes by evicting and re-reading the same files.
|
|
_MAX_SCANS = 4096
|
|
_MAX_META_CACHE = 256
|
|
|
|
_URL_RE = re.compile(r"https?://([a-z0-9][a-z0-9.-]*\.[a-z]{2,})(?::\d+)?(/[a-z0-9._~-]*)?", re.I)
|
|
_IMPORT_RE = re.compile(
|
|
r"""(?:\bfrom\s+|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"]([^'"\s]+)['"]""")
|
|
_PKG_RE = re.compile(r"^(?:@[a-z0-9._-]+/)?[a-z0-9._-]+$")
|
|
_CAT_RE = re.compile(r"""\bcat\s+(?:"([^"]*?)/?package\.json"|'([^']*?)/?package\.json'|(\S*?)/?package\.json)(?=[\s;&|)]|$)""")
|
|
_CD_RE = re.compile(r"""^\s*cd\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))""")
|
|
_JSON_START = re.compile(r"(?m)^\{")
|
|
# Hosts that are never a project's site.
|
|
# Code hosts, CDNs, the lab's own hosts, and the SaaS whose tenant subdomain
|
|
# carries a company's name (``orus.sentry.io``, ``orus-insurance.slack.com``).
|
|
_NOT_A_SITE = ("github.com", "gitlab.com", "bitbucket.org", "npmjs.com", "npmjs.org",
|
|
"jsdelivr.net", "unpkg.com", "githubusercontent.com", "vercel.com",
|
|
"netlify.com", "lab.gabvdl.xyz", "test.gabvdl.xyz", "localhost",
|
|
"anthropic.com", "claude.ai", "claude.com", "googleapis.com",
|
|
"google.com", "slack.com", "sentry.io", "atlassian.net", "notion.so",
|
|
"notion.site", "linear.app", "figma.com", "zendesk.com", "hubspot.com",
|
|
"datadoghq.com", "datadoghq.eu", "grafana.net", "posthog.com",
|
|
"intercom.io", "stripe.com", "auth0.com", "okta.com", "retool.com",
|
|
"amplitude.com", "mixpanel.com", "segment.com", "lysta.fr",
|
|
"cloudflareaccess.com", "amazonaws.com", "cloudfront.net")
|
|
_REPO_PAGES = (".github.io", ".gitlab.io")
|
|
_IP_RE = re.compile(r"^\d+(\.\d+){3}$")
|
|
_TOKEN_SPLIT = re.compile(r"[^a-z0-9]+")
|
|
|
|
|
|
# ── one transcript ───────────────────────────────────────────────────────────
|
|
class Scan:
|
|
"""What one transcript says about the files it touched, up to ``offset``."""
|
|
|
|
__slots__ = ("offset", "files", "dirs", "markers", "imports", "urls", "bash")
|
|
|
|
def __init__(self):
|
|
self.offset = 0
|
|
self.files: dict[str, tuple[str, str]] = {} # abs path → (ts, content)
|
|
self.dirs: dict[str, dict[str, int]] = {} # dir → {ext: n}
|
|
self.markers: set[str] = set() # abs paths
|
|
self.imports: dict[str, set[str]] = {} # dir → package names
|
|
self.urls: Counter = Counter() # site URL → mentions
|
|
self.bash: dict[str, str] = {} # tool_use id → package.json path
|
|
|
|
def copy(self) -> "Scan":
|
|
"""A copy the scanner can feed while readers hold the original."""
|
|
c = Scan()
|
|
c.offset = self.offset
|
|
c.files = dict(self.files)
|
|
c.dirs = {d: dict(e) for d, e in self.dirs.items()}
|
|
c.markers = set(self.markers)
|
|
c.imports = {d: set(p) for d, p in self.imports.items()}
|
|
c.urls = Counter(self.urls)
|
|
c.bash = dict(self.bash)
|
|
return c
|
|
|
|
# ── feeding ────────────────────────────────────────────────────────────
|
|
def feed(self, line: str) -> None:
|
|
if "://" in line:
|
|
self._urls(line)
|
|
if '"toolUseResult"' in line:
|
|
e = _loads(line)
|
|
if e is not None:
|
|
self._result(e)
|
|
elif "package.json" in line and '"Bash"' in line and '"tool_use"' in line:
|
|
e = _loads(line)
|
|
if e is not None:
|
|
self._bash_call(e)
|
|
|
|
def _urls(self, line: str) -> None:
|
|
for m in _URL_RE.finditer(line):
|
|
host = m.group(1).lower().rstrip(".")
|
|
if host.startswith("www."):
|
|
host = host[4:]
|
|
seg = (m.group(2) or "").strip("/").split("/", 1)[0]
|
|
url = f"https://{host}" + (f"/{seg}" if seg and host.endswith(_REPO_PAGES) else "")
|
|
if url in self.urls or len(self.urls) < _CAP_URLS:
|
|
self.urls[url] += 1
|
|
|
|
def _result(self, e: dict) -> None:
|
|
r = e.get("toolUseResult")
|
|
if not isinstance(r, dict):
|
|
return
|
|
ts = e.get("timestamp") or ""
|
|
f = r.get("file")
|
|
if isinstance(f, dict) and isinstance(f.get("content"), str) and f.get("filePath"):
|
|
whole = (f.get("startLine") or 1) <= 1 and \
|
|
(f.get("numLines") or 0) >= (f.get("totalLines") or 0)
|
|
self._saw(f["filePath"], ts, f["content"], whole)
|
|
return
|
|
fp = r.get("filePath")
|
|
if isinstance(fp, str) and fp:
|
|
if r.get("type") in ("create", "update") and isinstance(r.get("content"), str):
|
|
self._saw(fp, ts, r["content"], True)
|
|
elif "oldString" in r or isinstance(r.get("edits"), list):
|
|
new = _edited(r, (self.files.get(fp) or (None, None))[1])
|
|
if new is not None:
|
|
self._saw(fp, ts, new, True)
|
|
else:
|
|
self._touch(fp)
|
|
return
|
|
if "stdout" in r and self.bash:
|
|
tid = _tool_use_id(e)
|
|
path = self.bash.pop(tid, None) if tid else None
|
|
text = _package_json_in(r.get("stdout") or "") if path else None
|
|
if text:
|
|
self._saw(path, ts, text, True)
|
|
|
|
def _bash_call(self, e: dict) -> None:
|
|
content = (e.get("message") or {}).get("content")
|
|
if not isinstance(content, list):
|
|
return
|
|
for b in content:
|
|
if not (isinstance(b, dict) and b.get("type") == "tool_use" and b.get("name") == "Bash"):
|
|
continue
|
|
path = cat_target((b.get("input") or {}).get("command") or "", e.get("cwd"))
|
|
if path and b.get("id"):
|
|
if len(self.bash) > 50:
|
|
self.bash.clear()
|
|
self.bash[b["id"]] = path
|
|
|
|
def _touch(self, fp: str) -> None:
|
|
d, base = pp.split(fp)
|
|
ext = pp.splitext(base)[1].lower()
|
|
exts = self.dirs.get(d)
|
|
if exts is None:
|
|
if len(self.dirs) >= _CAP_DIRS:
|
|
return
|
|
exts = self.dirs[d] = {}
|
|
exts[ext] = exts.get(ext, 0) + 1
|
|
if base in MARKERS or base.startswith(tuple(p for p, _ in _CONFIG_DEP)):
|
|
self.markers.add(fp)
|
|
|
|
def _saw(self, fp: str, ts: str, content: str, whole: bool) -> None:
|
|
self._touch(fp)
|
|
base = pp.basename(fp)
|
|
if whole and base in KEY_NAMES and (fp in self.files or len(self.files) < _CAP_FILES):
|
|
self.files[fp] = (ts, content[:MAX_TEXT])
|
|
if pp.splitext(base)[1].lower() in _SRC_EXTS:
|
|
pkgs = imports_in(content)
|
|
if pkgs:
|
|
self.imports.setdefault(pp.dirname(fp), set()).update(pkgs)
|
|
|
|
|
|
def _loads(line: str) -> dict | None:
|
|
try:
|
|
e = json.loads(line)
|
|
except ValueError:
|
|
return None
|
|
return e if isinstance(e, dict) else None
|
|
|
|
|
|
def _tool_use_id(e: dict) -> str | None:
|
|
content = (e.get("message") or {}).get("content")
|
|
if isinstance(content, list):
|
|
for b in content:
|
|
if isinstance(b, dict) and b.get("tool_use_id"):
|
|
return b["tool_use_id"]
|
|
return None
|
|
|
|
|
|
def _edited(r: dict, known: str | None) -> str | None:
|
|
"""The file after an Edit (or a MultiEdit), from its ``originalFile`` —
|
|
else from the content this transcript last saw."""
|
|
orig = r.get("originalFile")
|
|
if not isinstance(orig, str):
|
|
orig = known
|
|
if orig is None:
|
|
return None
|
|
edits = r.get("edits") if isinstance(r.get("edits"), list) else [r]
|
|
for ed in edits:
|
|
old, new = ed.get("oldString", ed.get("old_string")), ed.get("newString", ed.get("new_string"))
|
|
if not isinstance(old, str) or not isinstance(new, str):
|
|
return None
|
|
if old == "": # an Edit that creates the file
|
|
if orig != "":
|
|
return None
|
|
orig = new
|
|
continue
|
|
if old not in orig:
|
|
return None
|
|
all_ = ed.get("replaceAll", ed.get("replace_all"))
|
|
orig = orig.replace(old, new) if all_ else orig.replace(old, new, 1)
|
|
return orig
|
|
|
|
|
|
def imports_in(text: str) -> set[str]:
|
|
"""The npm packages a source file imports (``@scope/pkg``, ``pkg``)."""
|
|
out: set[str] = set()
|
|
for m in _IMPORT_RE.finditer(text):
|
|
spec = m.group(1)
|
|
if spec.startswith((".", "/", "~", "#", "@/", "node:", "bun:", "virtual:", "http")):
|
|
continue
|
|
parts = spec.split("/")
|
|
name = "/".join(parts[:2]) if spec.startswith("@") else parts[0]
|
|
if _PKG_RE.match(name):
|
|
out.add(name)
|
|
return out
|
|
|
|
|
|
def cat_target(cmd: str, cwd: str | None) -> str | None:
|
|
"""The ``package.json`` a shell command prints with ``cat`` (one only):
|
|
an absolute path, else relative to the command's leading ``cd``, else to
|
|
the session's cwd."""
|
|
hits = list(_CAT_RE.finditer(cmd))
|
|
if len(hits) != 1 or cmd.count("package.json") != 1:
|
|
return None
|
|
m = hits[0]
|
|
rel = next((g for g in m.groups() if g is not None), "")
|
|
home = _home(cwd)
|
|
base = cwd
|
|
cd = _CD_RE.match(cmd)
|
|
if cd:
|
|
base = _expand(next(g for g in cd.groups() if g is not None), home, cwd)
|
|
path = _expand(rel, home, base) if rel else base
|
|
if not path or not path.startswith("/"):
|
|
return None
|
|
return pp.normpath(pp.join(path, "package.json"))
|
|
|
|
|
|
def _home(cwd: str | None) -> str | None:
|
|
m = re.match(r"^(/Users/[^/]+|/home/[^/]+|/root)(?=/|$)", cwd or "")
|
|
return m.group(1) if m else None
|
|
|
|
|
|
def _expand(p: str, home: str | None, base: str | None) -> str | None:
|
|
if p == "~" or p.startswith("~/"):
|
|
return (home + p[1:]) if home else None
|
|
if p.startswith("$HOME"):
|
|
return (home + p[5:]) if home else None
|
|
if p.startswith("/"):
|
|
return p
|
|
return pp.join(base, p) if base else None
|
|
|
|
|
|
def _package_json_in(text: str) -> str | None:
|
|
"""The first JSON object in a command's output that looks like a
|
|
``package.json`` (``cat`` prints it from column 0)."""
|
|
dec = json.JSONDecoder()
|
|
for m in _JSON_START.finditer(text):
|
|
try:
|
|
obj, end = dec.raw_decode(text, m.start())
|
|
except ValueError:
|
|
continue
|
|
if isinstance(obj, dict) and ("name" in obj or "dependencies" in obj or "scripts" in obj):
|
|
return text[m.start():end]
|
|
return None
|
|
|
|
|
|
def scan_lines(lines, scan: Scan | None = None) -> Scan:
|
|
"""Feed text lines (tests and one-offs)."""
|
|
s = scan or Scan()
|
|
for line in lines:
|
|
s.feed(line)
|
|
return s
|
|
|
|
|
|
# ── every worker transcript ──────────────────────────────────────────────────
|
|
class Scanner:
|
|
"""A ``Scan`` per transcript, kept current by ``refresh`` (one thread).
|
|
Readers get whole ``Scan`` objects that are never mutated after they're
|
|
published — a refresh feeds a copy and swaps it in."""
|
|
|
|
def __init__(self):
|
|
self._scans: dict[str, Scan] = {}
|
|
self._stat: dict[str, tuple[int, int]] = {} # path → (size, mtime_ns)
|
|
self._lock = threading.Lock() # one refresh at a time
|
|
self.version = 0
|
|
|
|
def get(self, path: str) -> Scan | None:
|
|
return self._scans.get(path)
|
|
|
|
def refresh(self, paths) -> int:
|
|
"""Read what each transcript grew by since the last call; returns how
|
|
many changed."""
|
|
changed = 0
|
|
with self._lock:
|
|
for path in paths:
|
|
try:
|
|
st = os.stat(path)
|
|
except OSError:
|
|
continue
|
|
key = (st.st_size, st.st_mtime_ns)
|
|
if self._stat.get(path) == key:
|
|
continue
|
|
old = self._scans.get(path)
|
|
scan = Scan() if old is None or st.st_size < old.offset else old.copy()
|
|
try:
|
|
_tail(path, scan)
|
|
except OSError:
|
|
continue
|
|
self._scans.pop(path, None)
|
|
self._scans[path] = scan
|
|
self._stat[path] = key
|
|
while len(self._scans) > _MAX_SCANS:
|
|
evicted = next(iter(self._scans))
|
|
self._scans.pop(evicted, None)
|
|
# Keep self._stat[evicted] so unchanged old transcripts are
|
|
# never re-read from disk in an eviction loop.
|
|
changed += 1
|
|
if changed:
|
|
self.version += 1
|
|
return changed
|
|
|
|
|
|
def _tail(path: str, scan: Scan) -> None:
|
|
"""Feed the complete lines past ``scan.offset``."""
|
|
with open(path, "rb") as fh:
|
|
fh.seek(scan.offset)
|
|
for raw in fh:
|
|
if not raw.endswith(b"\n"):
|
|
break # a line still being written
|
|
scan.offset += len(raw)
|
|
scan.feed(raw.decode("utf-8", errors="replace"))
|
|
|
|
|
|
SCANNER = Scanner()
|
|
|
|
|
|
class ScanThread(threading.Thread):
|
|
"""Keeps ``SCANNER`` current on every worker transcript the registry
|
|
knows; the first pass reads them all (a few seconds), later ones only
|
|
what grew."""
|
|
|
|
def __init__(self, deps, interval: float = 20.0):
|
|
super().__init__(daemon=True, name="worker-meta")
|
|
self.deps = deps
|
|
self.interval = interval
|
|
self._wake = threading.Event()
|
|
|
|
def poke(self) -> None:
|
|
self._wake.set()
|
|
|
|
def pass_once(self) -> int:
|
|
from projects import worker_projects as wp
|
|
reg = wp.registry(self.deps)
|
|
return SCANNER.refresh(p for ps in reg.paths.values() for p in ps)
|
|
|
|
def run(self) -> None:
|
|
while True:
|
|
try:
|
|
self.pass_once()
|
|
except Exception: # noqa: BLE001 — keep the thread alive
|
|
log.exception("worker meta scan failed")
|
|
self._wake.wait(self.interval)
|
|
self._wake.clear()
|
|
|
|
|
|
# ── one project ──────────────────────────────────────────────────────────────
|
|
def _rel(p: str, root: str) -> str | None:
|
|
if p == root:
|
|
return ""
|
|
return p[len(root) + 1:] if p.startswith(root + "/") else None
|
|
|
|
|
|
def project_meta(root: str, name: str, scans, rewrite=lambda p: p) -> dict:
|
|
"""A worker project's card fields, from the scans of its conversations.
|
|
|
|
``rewrite`` folds a worktree path into its main checkout (the worker's
|
|
``WorkerIndex.rewrite``). The name stays the folder's — a template's
|
|
``package.json`` name (``vite-project``) would rename it."""
|
|
files: dict[str, tuple[str, str]] = {}
|
|
exts: Counter = Counter()
|
|
markers: set[str] = set()
|
|
deps: set[str] = set()
|
|
urls: Counter = Counter()
|
|
for sc in scans:
|
|
for fp, (ts, content) in sc.files.items():
|
|
rel = _rel(rewrite(fp), root)
|
|
if rel and (rel not in files or ts >= files[rel][0]):
|
|
files[rel] = (ts, content)
|
|
for d, counts in sc.dirs.items():
|
|
if _rel(rewrite(d), root) is not None:
|
|
exts.update(counts)
|
|
for fp in sc.markers:
|
|
rel = _rel(rewrite(fp), root)
|
|
if rel:
|
|
markers.add(rel)
|
|
for d, pkgs in sc.imports.items():
|
|
if _rel(rewrite(d), root) is not None:
|
|
deps |= pkgs
|
|
urls.update(sc.urls)
|
|
|
|
def text(rel: str) -> str | None:
|
|
hit = files.get(rel)
|
|
return hit[1] if hit else None
|
|
|
|
seen: dict[str, str] = {}
|
|
pkg = None
|
|
if "package.json" in files:
|
|
try:
|
|
pkg = json.loads(files["package.json"][1])
|
|
seen["package.json"] = files["package.json"][0]
|
|
except ValueError:
|
|
pkg = None
|
|
if not isinstance(pkg, dict):
|
|
pkg = None
|
|
for rel, (_ts, content) in files.items():
|
|
if pp.basename(rel) == "package.json" and "node_modules" not in rel:
|
|
try:
|
|
p = json.loads(content)
|
|
except ValueError:
|
|
continue
|
|
if isinstance(p, dict):
|
|
for k in ("dependencies", "devDependencies", "peerDependencies"):
|
|
if isinstance(p.get(k), dict):
|
|
deps |= set(p[k])
|
|
|
|
readme_rel = next((r for r in README_NAMES if r in files), None)
|
|
readme = text(readme_rel) if readme_rel else None
|
|
if readme_rel:
|
|
seen["README.md"] = files[readme_rel][0]
|
|
claude_md = text("CLAUDE.md")
|
|
if claude_md is not None:
|
|
seen["CLAUDE.md"] = files["CLAUDE.md"][0]
|
|
index_rel = next((r for r in (pp.join(d, "index.html") for d in _INDEX_DIRS)
|
|
if r in files), None)
|
|
index_meta = catalog_mod.parse_index_meta(text(index_rel)) if index_rel else None
|
|
if index_rel:
|
|
seen["index.html"] = files[index_rel][0]
|
|
|
|
# The stack: imports + dependencies, the file kinds, the markers.
|
|
root_names = {r for r in markers | set(files) if "/" not in r}
|
|
for ext, dep in _EXT_DEP.items():
|
|
if exts.get(ext, 0) >= EXT_MIN:
|
|
deps.add(dep)
|
|
for ext, marker in _EXT_MARKER.items():
|
|
if exts.get(ext, 0) >= EXT_MIN:
|
|
root_names.add(marker)
|
|
for rel in markers:
|
|
base = pp.basename(rel)
|
|
for prefix, dep in _CONFIG_DEP:
|
|
if base.startswith(prefix):
|
|
deps.add(dep)
|
|
stack = catalog_mod.stack_tags(deps, lambda n: n in root_names)
|
|
|
|
description = catalog_mod._description(pkg, readme) or _claude_md_description(claude_md) \
|
|
or catalog_mod._clean((index_meta or {}).get("description") or "")
|
|
names = [name] + ([pkg["name"].split("/")[-1]] if pkg and isinstance(pkg.get("name"), str) else [])
|
|
url = _homepage(pkg) or site_url(urls, names) or _og_url(index_meta)
|
|
version = pkg.get("version") if pkg else None
|
|
keywords = pkg.get("keywords") if pkg and isinstance(pkg.get("keywords"), list) else []
|
|
scripts = list(pkg.get("scripts") or {}) if pkg and isinstance(pkg.get("scripts"), dict) else []
|
|
return {
|
|
"description": description,
|
|
"version": version if isinstance(version, str) else None,
|
|
"url": url,
|
|
"stack": stack,
|
|
"keywords": [k for k in keywords if isinstance(k, str)][:6],
|
|
"hasPackageJson": pkg is not None,
|
|
"readme": readme,
|
|
"claudeMd": claude_md,
|
|
"indexMeta": index_meta,
|
|
"ogImage": _og_image(index_meta, url),
|
|
"scripts": [s for s in scripts if isinstance(s, str)][:24],
|
|
"seenAt": seen or None,
|
|
}
|
|
|
|
|
|
def _claude_md_description(text: str | None) -> str:
|
|
"""The first prose line of a CLAUDE.md that isn't its boilerplate."""
|
|
if not text:
|
|
return ""
|
|
for line in text.splitlines():
|
|
cleaned = catalog_mod._clean(line.strip())
|
|
if not cleaned or cleaned.startswith(("#", "!", "<", "---", "```", "http", "-", "|", ">")):
|
|
continue
|
|
if "Claude Code" in cleaned or "guidance to Claude" in cleaned:
|
|
continue
|
|
return cleaned
|
|
return ""
|
|
|
|
|
|
def _homepage(pkg: dict | None) -> str | None:
|
|
hp = (pkg or {}).get("homepage")
|
|
if isinstance(hp, str) and hp.startswith("http") and not _blocked(_host(hp)):
|
|
return catalog_mod._norm_url(hp.strip())
|
|
return None
|
|
|
|
|
|
def _og_url(meta: dict | None) -> str | None:
|
|
u = (meta or {}).get("ogUrl") or ""
|
|
if u.startswith("http") and not _blocked(_host(u)) and "@@" not in u:
|
|
return catalog_mod._norm_url(u)
|
|
return None
|
|
|
|
|
|
def _og_image(meta: dict | None, url: str | None) -> dict | None:
|
|
"""An ``og:image`` the browser can load: absolute, or relative to the
|
|
project's site."""
|
|
ref = ((meta or {}).get("ogImage") or "").strip()
|
|
if not ref or "@@" in ref:
|
|
return None
|
|
if ref.startswith("http"):
|
|
return {"kind": "url", "src": ref}
|
|
if url and not ref.startswith(("data:", "//")):
|
|
return {"kind": "url", "src": url.rstrip("/") + "/" + ref.lstrip("./").lstrip("/")}
|
|
return None
|
|
|
|
|
|
def _host(url: str) -> str:
|
|
return url.split("//", 1)[-1].split("/", 1)[0].split(":", 1)[0].lower()
|
|
|
|
|
|
def _blocked(host: str) -> bool:
|
|
if not host or _IP_RE.match(host) or ".localhost." in f".{host}.":
|
|
return True
|
|
return any(host == b or host.endswith("." + b) for b in _NOT_A_SITE)
|
|
|
|
|
|
def _tokens(name: str) -> list[str]:
|
|
toks = [t for t in _TOKEN_SPLIT.split(name.lower()) if len(t) >= 3]
|
|
return toks or [t for t in [_TOKEN_SPLIT.sub("", name.lower())] if t]
|
|
|
|
|
|
def site_url(urls: Counter, names) -> str | None:
|
|
"""The project's deployed site among the URLs its conversations
|
|
mentioned: every word of its name in the host's first label (or, on
|
|
``*.github.io``, the repo segment), seen twice or more. A domain of its
|
|
own (``orus.eu``) beats a subdomain of someone else's (``orus.sentry.io``);
|
|
then the shortest label wins (a preview deployment carries a hash and a
|
|
team), then the most mentioned."""
|
|
token_sets = [t for t in (_tokens(n) for n in names if n) if t]
|
|
best = None
|
|
for url, n in urls.items():
|
|
if n < 2:
|
|
continue
|
|
host = _host(url)
|
|
if _blocked(host):
|
|
continue
|
|
seg = url.split("//", 1)[-1].split("/", 1)[1] if url.count("/") > 2 else ""
|
|
target = seg if host.endswith(_REPO_PAGES) else host.split(".", 1)[0]
|
|
if not target or not any(all(t in target for t in ts) for ts in token_sets):
|
|
continue
|
|
apex = not host.endswith(_REPO_PAGES) and host.count(".") == 1
|
|
key = (not apex, len(target), -n, len(url))
|
|
if best is None or key < best[0]:
|
|
best = (key, url)
|
|
return best[1] if best else None
|
|
|
|
|
|
# ── the hub side ─────────────────────────────────────────────────────────────
|
|
_meta_cache: dict[str, tuple[tuple, dict]] = {}
|
|
|
|
|
|
def meta_for(deps, p: dict) -> dict:
|
|
"""``project_meta`` for one registry project, cached until a transcript
|
|
of its conversations grows. Reads only what the scanner has — never a
|
|
transcript."""
|
|
from projects import worker_projects as wp
|
|
reg = wp.registry(deps)
|
|
paths = sorted({x for sid in p["sessions"] for x in reg.paths.get(sid, ())})
|
|
scans = [(x, SCANNER.get(x)) for x in paths]
|
|
key = (p["path"], tuple((x, s.offset) for x, s in scans if s is not None))
|
|
hit = _meta_cache.get(p["slug"])
|
|
if hit and hit[0] == key:
|
|
return hit[1]
|
|
idx = reg.indexes.get(p["worker"])
|
|
rewrite = idx.rewrite if idx is not None else (lambda q: q)
|
|
meta = project_meta(p["path"], p["name"], [s for _x, s in scans if s is not None], rewrite)
|
|
_meta_cache.pop(p["slug"], None)
|
|
_meta_cache[p["slug"]] = (key, meta)
|
|
while len(_meta_cache) > _MAX_META_CACHE:
|
|
_meta_cache.pop(next(iter(_meta_cache)))
|
|
return meta
|
|
|
|
|
|
def summary_fields(meta: dict) -> dict:
|
|
"""The ``ProjectSummary`` part of a ``project_meta``."""
|
|
return {k: meta[k] for k in ("description", "version", "url", "stack", "keywords",
|
|
"hasPackageJson")}
|
|
|