#!/usr/bin/env python3 """resolve-helper.py HELPER.md [--json OUT] — open every pointer in a helper's answer BEFORE it may enter the table. A helper (a read-only subagent) writes pointers in three shapes: a full one (`CT/internal/stacks/delete.go:624`), a bare file name (`delete.go:756`) and a short one (`:1025`, "same file as the last one"). This tool 1. resolves each to a full `PREFIX/path:line[-line]`, 2. says DEAD when the file or the line does not exist, UNRESOLVED when a bare name fits no file or more than one, 3. checks the NAME the helper put in front of the pointer (a backticked identifier within 90 characters, with no other pointer between): it must stand within 3 lines of the cited range. IDENT-OK / IDENT-MISS / NO-IDENT. It does not judge the claim. A claim that carries a mark in TABLE.md is read by the main session (check-pointers.py prints the lines). Read-only: it opens files in the git clones on DooPlex and prints. """ import json, os, re, sys HERE = os.path.dirname(os.path.abspath(__file__)) REPO = os.path.abspath(os.path.join(HERE, "..", "..", "..", "..")) WS = os.path.dirname(REPO) PREFIX = {"AG": os.path.join(WS, "felhom-agent"), "CT": os.path.join(WS, "felhom-controller", "controller"), "CAT": os.path.join(WS, "app-catalog-felhom.eu"), "HUB": os.path.join(REPO, "hub", "internal"), "E": REPO, "AR": os.path.join(REPO, "documentation", "architecture"), "RB": os.path.join(REPO, "documentation", "runbooks")} RANGES = r"~?:?(\d+(?:-\d+)?(?:\s?,\s?:?\d+(?:-\d+)?)*)" PTR = re.compile(r"(?P(?:%s)/[\w./@+-]+\.\w+)(?::(?P\d+(?:-\d+)?(?:,\s?:?\d+(?:-\d+)?)*))?" r"|(?[\w.-]+\.(?:go|sh|py|md|yml|yaml|html|json|service|timer))(?::(?P
\d+(?:-\d+)?(?:,\s?:?\d+(?:-\d+)?)*))" r"|(?\d+(?:-\d+)?)(?![\d:])" % "|".join(PREFIX)) IDENT = re.compile(r"`([^`]{2,80})`") _cache, _walk = {}, {} def lines_of(path): if path not in _cache: try: _cache[path] = open(path, encoding="utf-8", errors="replace").read().split("\n") except OSError: _cache[path] = None return _cache[path] def find_base(pre, base): if pre not in _walk: idx = {} for d, dn, fn in os.walk(PREFIX[pre]): dn[:] = [x for x in dn if x not in (".git", "node_modules", "vendor", "evidence")] for f in fn: idx.setdefault(f, []).append(os.path.relpath(os.path.join(d, f), PREFIX[pre])) _walk[pre] = idx return _walk[pre].get(base, []) def check(full, rng, text, pos): pre, rest = full.split("/", 1) ls = lines_of(os.path.join(PREFIX[pre], rest)) if ls is None: return "DEAD", "NO-IDENT" if not rng: return "OK", "NO-IDENT" a, _, b = rng.partition("-") a, b = int(a), int(b or a) if b > len(ls): return "DEAD", "NO-IDENT" back = text[max(0, pos - 90):pos] cut = max(back.rfind(":"), back.rfind(";"), back.rfind(",")) # a pointer or a clause break in between: do not reach over it ids = [m for m in IDENT.finditer(back) if m.start() > cut - 1 or cut < 0] ids = ids or list(IDENT.finditer(back))[-1:] if not ids: return "OK", "NO-IDENT" name = re.sub(r"[()…]|\.\.\.", "", ids[-1].group(1)).strip().split(" ")[0].split("(")[0] name = name.split(".")[-1] if re.fullmatch(r"[\w.]+", name) else name win = "\n".join(ls[max(0, a - 4):b + 3]) return "OK", ("IDENT-OK" if name and name in win else f"IDENT-MISS({name})") def resolve(text, known, default_pre): """Returns (text with every pointer rewritten as a backticked full token, [records]).""" out, recs, last, i = [], [], None, 0 for m in PTR.finditer(text): out.append(text[i:m.start()]) i = m.end() if m.group("full"): full, rngs = m.group("full"), m.group("fr") elif m.group("bare"): base, rngs = m.group("bare"), m.group("br") full = known.get(base) if not full: c = find_base(default_pre, base) full = f"{default_pre}/{c[0]}" if len(c) == 1 else None if not full: recs.append({"ptr": m.group(0), "file": "UNRESOLVED", "ident": "NO-IDENT"}) out.append(m.group(0)) continue else: full, rngs = last, m.group("sr") if not full: out.append(m.group(0)) continue last = full known.setdefault(os.path.basename(full), full) toks = [] for r in re.split(r"\s?,\s?:?", rngs) if rngs else [None]: st, idn = check(full, r, text, m.start()) tok = f"{full}:{r}" if r else full recs.append({"ptr": tok, "file": st, "ident": idn}) toks.append(f"`{tok}`") out.append(" ".join(toks)) out.append(text[i:]) return "".join(out), recs def main(): src = sys.argv[1] text = open(src, encoding="utf-8").read() default_pre = "CT" if "controller" in src else "AG" if "agent" in src else "HUB" if "hub" in src else "AR" known = {} for m in re.finditer(r"((?:%s)/[\w./@+-]+\.\w+)" % "|".join(PREFIX), text): # first pass: every full path the helper named known.setdefault(os.path.basename(m.group(1)), m.group(1)) endings, cur, allrecs, lastq = [], None, [], None for line in text.split("\n"): h = re.match(r"^### (.+)$", line) if h: cur = {"title": h.group(1).strip(), "answers": {}, "extra": []} endings.append(cur) lastq = None continue if cur is None: continue a = re.match(r"^([1-8])\. (.*)$", line) body = a.group(2) if a else line new, recs = resolve(re.sub(r"`((?:%s)/[^`]+)`" % "|".join(PREFIX), r"\1", body), known, default_pre) for r in recs: r["ending"] = cur["title"] r["q"] = a.group(1) if a else (lastq or "-") allrecs += recs if a: cur["answers"][a.group(1)] = new lastq = a.group(1) elif line.strip() and lastq and not line.startswith(("#", "---")): cur["answers"][lastq] += " · " + new.strip().lstrip("-* ") # a continuation line belongs to the answer above it elif line.strip(): cur["extra"].append(new) n = len(allrecs) dead = [r for r in allrecs if r["file"] != "OK"] miss = [r for r in allrecs if r["ident"].startswith("IDENT-MISS")] ok = sum(1 for r in allrecs if r["ident"] == "IDENT-OK") print(f"{os.path.basename(src)}: endings {len(endings)} · pointers {n} · dead/unresolved {len(dead)} · " f"name found at the line {ok} · name NOT at the line {len(miss)} · no name to check {n - ok - len(miss) - len(dead)}") for r in dead: print(f" {r['file']:<10} {r['ptr']} [{r['ending'][:50]} q{r['q']}]") for r in miss: print(f" {r['ident']:<28} {r['ptr']} [{r['ending'][:50]} q{r['q']}]") if "--json" in sys.argv: json.dump({"endings": endings, "pointers": allrecs}, open(sys.argv[sys.argv.index("--json") + 1], "w"), indent=1) return 0 if __name__ == "__main__": sys.exit(main())