#!/usr/bin/env python3 """ link_briefs.py — verlinkt jedes Phase-/Screen-Ticket mit seinem Designer-Brief. Stellt den Designer-Brief (`.planning/designer-briefs/PXX-*.md`) als ERSTEN Doku-Link in die Ticket-Beschreibung (vor die bestehenden ROADMAP-/Spec-Links). Idempotent (Working-ID-Match; setzt nichts doppelt). Default = DRY-RUN, --apply = scharf. Mapping: Working-ID → Phasen-Nr. - R-Pxx / AK-Pxx / VR-Pxx / VA-Pxx → P{xx} (automatisch) - D-* / VD-* → manuelles Mapping (siehe DMAP) - mehrdeutige D-*/VD-* (mehrere Phasen) → übersprungen + gemeldet """ import json, os, re, sys, glob, time, urllib.request, urllib.error APPLY = "--apply" in sys.argv TOK = {} for line in open(os.path.expanduser("~/.cli-tokens/plane")): line = line.strip() if "=" in line and not line.startswith("#"): k, v = line.split("=", 1); TOK[k.strip()] = v.strip() BASE = TOK["PLANE_BASE_URL"].rstrip("/"); WS = TOK["PLANE_WORKSPACE"]; KEY = TOK["PLANE_API_KEY"] PID = "35d0d968-8ab3-40cc-97b8-b81d917dc5df" API = f"{BASE}/api/v1/workspaces/{WS}/projects/{PID}" GITEA = "https://git.tool-ctrl.de/toolctrl-labs/HiveGrid-Cloud/src/branch/main" BRIEFDIR = ".planning/designer-briefs" def req(method, path, body=None): url = path if path.startswith("http") else API + path st, d = 0, {} for _ in range(8): r = urllib.request.Request(url, data=(json.dumps(body).encode() if body is not None else None), method=method) r.add_header("X-API-Key", KEY); r.add_header("Content-Type", "application/json") try: with urllib.request.urlopen(r, timeout=30) as resp: raw = resp.read().decode(); st, d = resp.status, (json.loads(raw) if raw else {}) except urllib.error.HTTPError as e: st, d = e.code, {"_error": e.read().decode()[:300]} if st == 429: time.sleep(25); continue if APPLY and method != "GET": time.sleep(0.4) return st, d return st, d def get_all(path): out, c = [], None while True: st, d = req("GET", path + (("?per_page=100&cursor=" + c) if c else "?per_page=100")) if st >= 400: break if isinstance(d, list): out += d; break out += d.get("results", []) if d.get("next_page_results") and d.get("next_cursor"): c = d["next_cursor"] else: break return out # P-Nr -> Brief-Dateiname (aus dem Verzeichnis) PBRIEF = {} for p in glob.glob(f"{BRIEFDIR}/P*.md"): m = re.match(r"P(\d{2})-", os.path.basename(p)) if m: PBRIEF[int(m.group(1))] = os.path.basename(p) # D-*/VD-* manuelles Mapping (nur EINDEUTIGE; mehrdeutige bewusst weggelassen) DMAP = { "D-D0a": 1, "D-D0b": 1, "D-CRM": 6, "D-KANBAN": 8, "D-FORM": 16, "D-KAMP": 14, "D-HR": 17, "D-ADMIN": 19, "D-PLAN": 9, "D-ABN": 9, "D-CHAT": 15, "D-DASH": 11, "D-BOOK": 16, "D-FLOW": 12, "VD-2": 26, "VD-3": 27, "VD-4": 29, } # bewusst übersprungen (mehrere Phasen): D-WEB, D-REST, D-POLISH, VD-1, VD-5, VD-6 SKIP_AMBIG = {"D-WEB", "D-REST", "D-POLISH", "VD-1", "VD-5", "VD-6"} def phase_of(wid): if wid in DMAP: return DMAP[wid] m = re.match(r"(?:R|AK|VR|VA)-P(\d+)", wid) if m: return int(m.group(1)) return None print(f"=== link_briefs.py — {'APPLY' if APPLY else 'DRY-RUN'} ===") print(f"Briefe gefunden: {len(PBRIEF)} (P{min(PBRIEF)}–P{max(PBRIEF)})\n") issues = get_all("/issues/") linked = skipped_nobrief = skipped_ambig = already = nodoku = 0 ambig_list = [] for i in sorted(issues, key=lambda x: x["sequence_id"]): if " · " not in i["name"]: continue wid = i["name"].split(" · ")[0] if wid in SKIP_AMBIG: skipped_ambig += 1; ambig_list.append(wid); continue ph = phase_of(wid) if ph is None: continue # Externals/Vertrieb/Website/Noah brief = PBRIEF.get(ph) if not brief: skipped_nobrief += 1 print(f" ?? {wid}: kein Brief für P{ph} (v2-deferred Phase wie P10/P18?)") continue html = i.get("description_html") or "" if f"designer-briefs/{brief}" in html: already += 1; continue url = f"{GITEA}/{BRIEFDIR}/{brief}" linkhtml = (f'🎨 Designer-Brief P{ph:02d}') # Marker matcht ... (sync-Skript-Format) UND ... (Plane-Editor-normalisiert) m = re.search(r'📚 Doku', html) if m: br = "
" if "
" in m.group(0) else "
" pos = m.end() new = html[:pos] + linkhtml + br + html[pos:] else: nodoku += 1 print(f" ⚠ {wid}: kein '📚 Doku'-Block — übersprungen") continue print(f" + {wid:9} → {brief}") linked += 1 if APPLY: st, d = req("PATCH", f"/issues/{i['id']}/", {"description_html": new}) if st >= 400: print(" PATCH FAIL:", st, d) print(f"\n=== {'verlinkt' if APPLY else 'würde verlinken'}: {linked} · bereits: {already} · " f"mehrdeutig übersprungen: {skipped_ambig} {sorted(set(ambig_list))} · " f"kein Brief: {skipped_nobrief} · kein Doku-Block: {nodoku} ===") if not APPLY: print("Dry-Run — nichts geschrieben. Mit --apply scharf schalten.")