#!/usr/bin/env python3 """Ranks indexed projects against a need profile and explains the fit. Usage: python3 -I match.py index.json need.json [--top 5] need.json (same vocabulary as the HANDOVER header): { "goal": "free text: what I want to build", "kind": ["game", "game-map"], # acceptable kinds "stack": ["unity", "c#"], # preferred stack "tags": ["hacker", "3d", "city"], # wanted topics/features "must": ["3d"], # core requirements: each missing one halves the score, cap 39 "avoid": ["php"], # deal-breakers "max_remaining_hours": 40 } # optional Score 0–100: kind 20, stack 30, tags+goal keywords 35, readiness 15 (scaled by topic fit); avoid terms and missing must-haves cut the score. publish_check BLOCK does not change relevance but is always listed as a conflict. This is the cheap, explainable first pass. An agent should read the HANDOVER.md of the top hits for the real verdict. """ import json import re import sys STOP = set("a an the and or for with of to in on my i want build make app tool project simple small some that this " "is it be can should like based using use from".split()) ALIASES = {"js": "javascript", "ts": "typescript", "csharp": "c#", "cs": "c#", "py": "python", "node": "node.js", "nodejs": "node.js", "postgres": "postgresql", "esp-32": "esp32", "rpi": "raspberry-pi", "springboot": "spring-boot", "spring": "spring-boot"} def norm(term): t = str(term).lower().strip() t = re.sub(r"\(.*?\)", "", t) t = re.sub(r"\s+v?\d+(\.\d+)*\b", "", t).strip() # "Svelte 5" -> "svelte" t = t.replace(" ", "-") return ALIASES.get(t, t) def words(text): return {w for w in re.findall(r"[a-z0-9#+.-]{3,}", (text or "").lower()) if w not in STOP} def same(w, h): """Exact match, or one is a prefix of the other and both are at least 5 chars (inventory ~ inventories).""" if w == h: return True return len(w) >= 5 and len(h) >= 5 and (w.startswith(h) or h.startswith(w)) def overlap(want, have, empty=0.5): if not want: return empty, [], [] hit = [w for w in want if any(same(w, h) for h in have)] miss = [w for w in want if w not in hit] return len(hit) / len(want), hit, miss def score(p, need): reasons, missing, conflicts = [], [], [] kinds = {norm(k) for k in (need.get("kind") or [])} pk = norm(p.get("kind") or "") s_kind = 1.0 if not kinds or pk in kinds else 0.0 (reasons if s_kind else conflicts).append(f"kind {pk or 'unknown'}") stack = {norm(x) for x in (p.get("stack") or [])} tags = {norm(x) for x in (p.get("tags") or [])} text = words(" ".join([p.get("title") or "", p.get("summary") or "", p.get("abstract") or ""])) parts = {x for t in stack | tags for x in re.split(r"[-_/]", t) if len(x) > 1} have = stack | tags | parts | text s_stack, hit, miss = overlap([norm(x) for x in need.get("stack") or []], stack | parts | text) reasons += [f"stack {h}" for h in hit] missing += [f"stack {m}" for m in miss] wanted = [norm(x) for x in need.get("tags") or []] + sorted(words(need.get("goal")) - {norm(x) for x in need.get("tags") or []}) s_topic, hit, miss = overlap(wanted, have) reasons += [f"topic {h}" for h in hit] missing += [f"topic {m}" for m in miss if m in {norm(x) for x in need.get("tags") or []}] comp = p.get("completion_percent") rem = p.get("remaining_effort_hours") s_ready = (comp or 30) / 100 * s_topic # readiness only counts if the topic fits if rem is None: missing.append("effort estimate (remaining_effort_hours unknown)") elif need.get("max_remaining_hours") and rem > need["max_remaining_hours"]: s_ready *= 0.3 conflicts.append(f"remaining effort {rem} h > {need['max_remaining_hours']} h") total = 20 * s_kind + 30 * s_stack + 35 * s_topic + 15 * s_ready musts = [norm(x) for x in need.get("must") or []] _, _, must_miss = overlap(musts, have) if must_miss: conflicts.append("missing must-have: " + ", ".join(must_miss)) total = min(total * 0.5 ** len(must_miss), 39) if "publish_check" not in p: conflicts.append("no publish_check (old handover format) - scan before use") for a in need.get("avoid") or []: a = norm(a) if a in stack or a in tags or a in text: total *= 0.4 conflicts.append(f"contains avoided '{a}'") if (p.get("publish_check") or "").upper() == "BLOCK": # relevance stays, but the agent must warn: secrets/private data not removed yet conflicts.append("publish_check BLOCK: secrets/private data not cleaned up - do not use before the owner fixes it") return round(total), reasons, missing, conflicts def main(): if len(sys.argv) < 3: print(__doc__) return 2 index = json.load(open(sys.argv[1], encoding="utf-8")) need = json.load(open(sys.argv[2], encoding="utf-8")) top = int(sys.argv[sys.argv.index("--top") + 1]) if "--top" in sys.argv else 5 ranked = sorted(((score(p, need), p) for p in index["projects"]), key=lambda x: -x[0][0]) best = ranked[0][0][0] if ranked else 0 if best >= 70: print("VERDICT: strong match - read the HANDOVER.md of the top hit.") elif best >= 40: print("VERDICT: partial match - check the HANDOVER.md; it may only save part of the work.") else: print("VERDICT: weak - probably nothing fits; say so honestly and consider starting fresh.") for (sc, reasons, missing, conflicts), p in ranked[:top]: print(f"{sc:3d} {p['id']} ({p.get('kind')}, {p.get('completion_percent')}% done) – {p.get('summary')}") print(f" fits: {', '.join(reasons) or '-'}") print(f" missing: {', '.join(missing) or '-'}") print(f" conflicts: {', '.join(conflicts) or '-'}") return 0 if __name__ == "__main__": sys.exit(main())