Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/interplane-forge/blob/main/server/tests/agentdoor.py # interplane-forge INTERPLANE Forge Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `interplane-forge / server / tests / agentdoor.py` 492 lines ยท 24296 bytes Raw Blame History 1 # ORACLE: host test harness (Python 3 standard library only), not product code. Checks of the agent 2 # door (docs/AGENT-DOOR.md) against a test forged built and fed by server/tests/agentdoor.sh. 3 # agentdoor.py social DIR FIXTURE.json write a hash-chained social.log + social.head (and record the 4 # seq of every line in FIXTURE.json under "social") 5 # agentdoor.py walk PORT BASE LIMIT OUT read the stream with after= from 0 to its end, LIMIT a page, 6 # write one canonical JSON line per event to OUT; checks paging 7 # agentdoor.py check PORT API_MD TSV FIXTURE.json every other check (both bases) 8 # Exit 0 only when every check passed. Each failure is one "FAIL ..." line. 9 import hashlib 10 import html 11 import json 12 import re 13 import sys 14 import urllib.error 15 import urllib.request 16 17 fails, passes = [], 0 18 19 20 def ok(msg): 21 global passes 22 passes += 1 23 print("PASS " + msg, flush=True) 24 25 26 def bad(msg): 27 fails.append(msg) 28 print("FAIL " + msg, flush=True) 29 30 31 def expect(cond, msg): 32 (ok if cond else bad)(msg) 33 return cond 34 35 36 class NoRedirect(urllib.request.HTTPRedirectHandler): 37 def redirect_request(self, *a, **k): 38 return None 39 40 41 OPENER = urllib.request.build_opener(NoRedirect) 42 43 44 def fetch(port, base, path, accept=None, headers=None): 45 req = urllib.request.Request("http://127.0.0.1:%d/%s" % (port, path)) 46 req.add_header("X-Forge-Base", base) 47 req.add_header("X-Real-IP", "10.9.9.8") 48 if accept: 49 req.add_header("Accept", accept) 50 for k, v in (headers or {}).items(): 51 req.add_header(k, v) 52 try: 53 r = OPENER.open(req, timeout=300) 54 return r.status, r.headers, r.read() 55 except urllib.error.HTTPError as e: 56 return e.code, e.headers, e.read() 57 58 59 def strip_hints(b): 60 s = b.decode("utf-8", "replace") 61 s = re.sub(r'([^<]*)', r"\1", s) 62 return s.replace(' translate="no"', "") 63 64 65 # ---- social log writer (the format of docs/social.md; the chain is sha256 of the previous line) 66 def social(d, fixture): 67 fx = json.load(open(fixture)) 68 d1, d2, own = fx["d1"], fx["d2"], "did:key:" + fx["nid"] 69 rfix, rpriv, rden = fx["rid_fix"], fx["rid_priv"], fx["rid_den"] 70 sess = "a" * 64 + "." + "b" * 32 71 rows = [ 72 ("account", d1, ""), ("name", d1, "fixdev"), ("session", d1, sess), 73 ("account", d2, ""), ("session", d2, sess.replace("a", "c")), 74 ("star", d1, "rad:" + rfix), ("fav", d1, "rad:" + rfix), ("fav", d2, "rad:" + rfix), 75 ("star", d2, "rad:" + rpriv), ("star", d2, "rad:" + rden), ("watch", d1, "rad:" + rfix), 76 ("follow", d2, d1), ("unstar", d1, "rad:" + rfix), ("star", d2, "rad:" + rfix), 77 ("logout", d1, "a" * 64), ("follow", d1, own), 78 ] 79 prev, lines, seqs = "0" * 64, [], [] 80 for i, (a, who, tgt) in enumerate(rows): 81 seq = i + 1 82 ln = '{"seq":%d,"ts":%d,"did":"%s","action":"%s","target":"%s","prev":"%s"}' % ( 83 seq, `1794600000` + 60 * i, who, a, tgt, prev) 84 lines.append(ln) 85 prev = hashlib.sha256(ln.encode()).hexdigest() 86 seqs.append({"seq": seq, "action": a, "did": who, "target": tgt}) 87 open(d + "/social.log", "w").write("\n".join(lines) + "\n") 88 open(d + "/social.head", "w").write("%d %s\n" % (len(lines), prev)) 89 fx["social"] = seqs 90 json.dump(fx, open(fixture, "w"), indent=1) 91 92 93 # ---- the stream 94 def getjson(port, base, path, accept=None): 95 st, hd, body = fetch(port, base, path, accept) 96 try: 97 return st, hd, json.loads(body.decode("utf-8")), body 98 except Exception: # noqa: BLE001 99 return st, hd, None, body 100 101 102 def walk(port, base, limit, out=None): 103 """follow next from after=0; returns the events. Checks: strictly increasing seq, no repeats, 104 next always moves forward until the end, every page at most limit long.""" 105 evs, seen, after, pages = [], set(), 0, 0 106 path = "events.json?after=0&limit=%d" % limit 107 while pages < 100000: 108 pages += 1 109 st, hd, doc, body = getjson(port, base, path) 110 if st != 200 or doc is None: 111 bad("walk %s%s: status %d %r" % (base, path, st, body[:200])) 112 return evs 113 page = doc.get("events", []) 114 if len(page) > limit: 115 bad("walk %s%s: %d events, limit %d" % (base, path, len(page), limit)) 116 if doc.get("count") != len(page): 117 bad("walk %s%s: count %r, %d events" % (base, path, doc.get("count"), len(page))) 118 for e in page: 119 s = e.get("seq") 120 if s in seen: 121 bad("walk %s: seq %r repeated" % (base, s)) 122 if evs and s <= evs[-1]["seq"]: 123 bad("walk %s: seq %r after %r (not increasing)" % (base, s, evs[-1]["seq"])) 124 if s <= after: 125 bad("walk %s: seq %r not after %d" % (base, s, after)) 126 seen.add(s) 127 evs.append(e) 128 nx = doc.get("next", "") 129 m = re.fullmatch(re.escape(base) + r"events\.json\?after=(\d+)&limit=(\d+)", nx) 130 if not m: 131 bad("walk %s%s: next %r" % (base, path, nx)) 132 return evs 133 na = int(m.group(1)) 134 if not page: 135 if na != after: 136 bad("walk %s: empty page moved next from %d to %d" % (base, after, na)) 137 if after != doc.get("head_seq"): 138 bad("walk %s: stopped at %d, head_seq %r" % (base, after, doc.get("head_seq"))) 139 break 140 if na <= after: 141 bad("walk %s: next %d does not move past %d" % (base, na, after)) 142 break 143 after = na 144 path = nx[len(base):] 145 if out: 146 with open(out, "w") as f: 147 for e in evs: 148 f.write(json.dumps(e, sort_keys=True) + "\n") 149 return evs 150 151 152 # ---- docs/API.md tables (the format server/tests/jsonpages.py parses, any schema name) 153 TYPES = ("string", "integer", "boolean", "object", "array") 154 155 156 def parse_api(path): 157 out, cur, sub = {}, None, None 158 for ln in open(path, encoding="utf-8").read().split("\n"): 159 m = re.match(r"^## `([a-z]+/[a-z-]+/\d+)`", ln) 160 if m: 161 cur, sub = m.group(1), "" 162 out[cur] = {"": {}} 163 continue 164 if ln.startswith("## "): 165 cur = None 166 continue 167 if cur is None: 168 continue 169 m = re.match(r"^### `([a-z_.]+)` (items|object)\s*$", ln) 170 if m: 171 sub = m.group(1) + " " + m.group(2) 172 out[cur][sub] = {} 173 continue 174 if ln.startswith("### "): 175 sub = None 176 continue 177 m = re.match(r"^\| `([a-z_0-9]+)` \| ([^|]+) \|", ln) 178 if m and sub is not None: 179 c = m.group(2).strip().lower() 180 w = c.split()[0] if c else "" 181 if w not in TYPES: 182 bad("API.md %s %s: key %s type %r outside the vocabulary" % (cur, sub, m.group(1), c)) 183 continue 184 out[cur][sub][m.group(1)] = (w, c.endswith("or null")) 185 return out 186 187 188 def keycheck(where, obj, table): 189 if not isinstance(obj, dict): 190 bad("%s: not an object" % where) 191 return 192 for k in table: 193 if k not in obj: 194 bad("%s: documented key %s missing" % (where, k)) 195 for k, v in obj.items(): 196 if k not in table: 197 bad("%s: key %s not documented" % (where, k)) 198 continue 199 w, nul = table[k] 200 if v is None: 201 if not nul: 202 bad("%s: %s is null, documented %s" % (where, k, w)) 203 continue 204 py = {"string": str, "integer": int, "boolean": bool, "object": dict, "array": list}[w] 205 if (w == "integer" and isinstance(v, bool)) or not isinstance(v, py): 206 bad("%s: %s is %s, documented %s" % (where, k, type(v).__name__, w)) 207 208 209 def validate(where, doc, schemas): 210 s = doc.get("schema") if isinstance(doc, dict) else None 211 if s not in schemas: 212 bad("%s: schema %r not documented" % (where, s)) 213 return 214 if list(doc)[0] != "schema": 215 bad("%s: first key is not schema" % where) 216 sc = schemas[s] 217 keycheck(where, doc, sc[""]) 218 for sub, table in sc.items(): 219 if not sub: 220 continue 221 dotted, kind = sub.rsplit(" ", 1) 222 nodes = [doc] 223 for p in dotted.split("."): 224 nxt = [] 225 for n in nodes: 226 for x in (n if isinstance(n, list) else [n]): 227 if isinstance(x, dict) and x.get(p) is not None: 228 nxt.append(x[p]) 229 nodes = nxt 230 for n in nodes: 231 if kind == "items": 232 for i, x in enumerate(n if isinstance(n, list) else []): 233 keycheck("%s %s[%d]" % (where, dotted, i), x, table) 234 else: 235 keycheck("%s %s" % (where, dotted), n, table) 236 ok("%s: valid %s" % (where, s)) 237 238 239 KINDS = ["patch_opened", "patch_revised", "patch_merged", "patch_archived", "review", "comment", 240 "issue_opened", "issue_closed", "release", "branch_moved", "star", "follow", "open_brought", 241 "open_withdrawn"] 242 ISO = re.compile(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ") 243 244 245 def stream_checks(port, base, fx, schemas): 246 st, hd, doc, body = getjson(port, base, "events.json?limit=200") 247 expect(st == 200 and hd.get("Content-Type") == "application/json; charset=utf-8", 248 "[%s] events.json 200 application/json (%d %s)" % (base, st, hd.get("Content-Type"))) 249 if doc is None: 250 bad("[%s] events.json is not JSON: %r" % (base, body[:300])) 251 return [] 252 validate("[%s] events.json" % base, doc, schemas) 253 evs = doc["events"] 254 expect(doc["head_seq"] == len(evs) == fx["expect_events"], 255 "[%s] head_seq %d, %d events, the fixture makes %d" % (base, doc["head_seq"], len(evs), fx["expect_events"])) 256 kinds = {e["kind"] for e in evs} 257 for k in KINDS: 258 expect(k in kinds, "[%s] kind %s present" % (base, k)) 259 text = body.decode("utf-8") 260 # exclusions: nothing from a private or refused repository, no favorite, account, name, session, 261 # logout, watch, unstar or star of a non-public repo; the refused open shelf RID never named 262 for r in (fx["rid_priv"], fx["rid_den"], fx["open_denied"]): 263 expect(r not in text, "[%s] %s never appears" % (base, r)) 264 for name in ("adpriv", "omega-pearl"): 265 expect('"name":"%s"' % name not in text, "[%s] repository %s never appears" % (base, name)) 266 srcs = {e["source"] for e in evs} 267 for s in fx["social"]: 268 src = "social.log:%d" % s["seq"] 269 should = (s["action"] == "star" and s["target"] == "rad:" + fx["rid_fix"]) or s["action"] == "follow" 270 expect((src in srcs) == should, "[%s] social line %d (%s %s) %s" % ( 271 base, s["seq"], s["action"], s["target"][:16], "is an event" if should else "is not an event")) 272 times_ok = all(ISO.fullmatch(e["time"]) for e in evs) 273 expect(times_ok, "[%s] every time is ISO-8601 UTC" % base) 274 links_ok = all(e[k] is None or e[k].startswith(base) for e in evs for k in ("path", "json")) 275 expect(links_ok, "[%s] every path and json starts with the base" % base) 276 for e in evs: 277 if e["repo"] is not None: 278 r = e["repo"] 279 if not (r["name"] == "adfix" and r["rid"] == fx["rid_fix"] and r["path"] == base + "drakestapleton/adfix" 280 and r["json"] == base + "drakestapleton/adfix.json" and r["owner"] == "drakestapleton"): 281 bad("[%s] seq %d repo %r" % (base, e["seq"], r)) 282 by = {} 283 for e in evs: 284 by.setdefault(e["kind"], []).append(e) 285 pat = fx["patch1"] 286 po = [e for e in by.get("patch_opened", []) if e["source"] == pat] 287 expect(len(po) == 1 and po[0]["subject"] == "fixture change one" and po[0]["path"] == base + "drakestapleton/adfix/patches/" + pat 288 and po[0]["actor"] == {"name": "fixdev", "did": fx["d1"], "path": base + "fixdev"}, 289 "[%s] patch_opened: source = COB id, title, path, actor fixdev with page" % base) 290 rv = by.get("review", []) 291 expect(len(rv) == 1 and rv[0]["verdict"] == "accept", "[%s] review with verdict accept" % base) 292 bm = by.get("branch_moved", []) 293 expect(len(bm) == 1 and bm[0]["from"] == fx["main0"] and bm[0]["source"] == fx["main1"] and bm[0]["commits"] == 2 294 and bm[0]["subject"] == "2 new commits on main" 295 and bm[0]["path"] == base + "drakestapleton/adfix/compare/%s...%s" % (fx["main0"], fx["main1"]), 296 "[%s] branch_moved main0 -> main1, 2 commits, compare link" % base) 297 rl = by.get("release", []) 298 expect(len(rl) == 1 and rl[0]["subject"] == "v1" and rl[0]["source"] == fx["tag_v1"] 299 and rl[0]["path"] == base + "drakestapleton/adfix/releases/tag/v1", "[%s] release v1 from the tag object" % base) 300 stv = by.get("star", []) 301 expect(len(stv) == 2 and all(e["repo"] and e["repo"]["name"] == "adfix" for e in stv), "[%s] two stars of adfix" % base) 302 fol = by.get("follow", []) 303 expect(len(fol) == 2 and any(e["target"] and e["target"]["name"] == "fixdev" and e["path"] == base + "fixdev" for e in fol) 304 and any(e["target"] and e["target"]["name"] == "drakestapleton" for e in fol), "[%s] follows name their target" % base) 305 ob = by.get("open_brought", []) 306 expect(len(ob) == 1 and ob[0]["path"] == base + "open/" + fx["open_held"] and ob[0]["subject"] == "shelf-a" 307 and ob[0]["time"] == "2026-11-10T00:00:00Z", "[%s] open_brought shelf-a at its list date" % base) 308 ow = by.get("open_withdrawn", []) 309 expect(len(ow) == 1 and ow[0]["subject"] == "shelf-b" and ow[0]["path"] == base + "open/", "[%s] open_withdrawn shelf-b" % base) 310 # the first pass is appended in time order (seq order equals time order inside one pass) 311 ts = [e["time"] for e in evs] 312 expect(ts == sorted(ts), "[%s] the fixture pass is in time order" % base) 313 return evs 314 315 316 def limits_etag(port, base, schemas): 317 st, hd, doc, _ = getjson(port, base, "events.json?limit=1000") 318 expect(st == 200 and doc and doc["limit"] == 200 and doc["limit_requested"] == 1000 and doc["limited"] is True, 319 "[%s] limit=1000 answers the maximum 200 and says so" % base) 320 st, hd, doc, _ = getjson(port, base, "events.json") 321 expect(st == 200 and doc and doc["limit"] == 50 and doc["limited"] is False, "[%s] default limit 50" % base) 322 for q in ("after=x", "after=-1", "limit=0", "limit=abc", "after=`1234567890123456789012`"): 323 st, hd, doc, body = getjson(port, base, "events.json?" + q) 324 expect(st == 400 and doc and doc.get("schema") == "forge/error/1" and doc.get("status") == 400, 325 "[%s] %s is 400 forge/error/1" % (base, q)) 326 st, hd, body = fetch(port, base, "events.json?after=2&limit=3") 327 et = hd.get("ETag") 328 expect(st == 200 and et and et.startswith('"ev'), "[%s] ETag %r" % (base, et)) 329 st2, hd2, body2 = fetch(port, base, "events.json?after=2&limit=3", headers={"If-None-Match": et or "x"}) 330 expect(st2 == 304 and body2 == b"" and hd2.get("ETag") == et, "[%s] If-None-Match -> 304, empty body" % base) 331 st3, _, _ = fetch(port, base, "events.json?after=2&limit=3", headers={"If-None-Match": '"ev0-0-0-0"'}) 332 expect(st3 == 200, "[%s] another ETag -> 200" % base) 333 a = fetch(port, base, "events.json?after=1&limit=4") 334 b = fetch(port, base, "events?after=1&limit=4", "application/json") 335 c = fetch(port, base, "feed?after=1&limit=4", "application/json") 336 expect(a[0] == b[0] == c[0] == 200 and a[2] == b[2] == c[2], "[%s] events and feed with Accept JSON = events.json" % base) 337 st, hd, _ = fetch(port, base, "events") 338 expect(st == 302 and hd.get("Location") == base + "feed", "[%s] events (HTML) -> 302 %sfeed" % (base, base)) 339 st, _, _ = fetch(port, base, "events.json", headers={}) 340 req = urllib.request.Request("http://127.0.0.1:%d/events.json" % port, method="POST", data=b"x=1") 341 req.add_header("X-Forge-Base", base) 342 try: 343 code = OPENER.open(req, timeout=60).status 344 except urllib.error.HTTPError as e: 345 code = e.code 346 expect(code in (403, 405), "[%s] POST events.json refused (%d)" % (base, code)) 347 348 349 def feed_checks(port, base, evs, fx): 350 st, hd, body = fetch(port, base, "feed") 351 h = strip_hints(body) 352 expect(st == 200 and hd.get("Content-Type", "").startswith("text/html"), "[%s] feed 200 HTML" % base) 353 expect('' % base in h, 354 "[%s] feed names %sevents.json as its JSON alternate" % (base, base)) 355 expect('Feed' % base in h, "[%s] forge row has the Feed entry" % base) 356 want = [ 357 'fixdev proposed a change to adfix: fixture change one' 358 % (base, base, base, fx["patch1"]), 359 'adfix: 2 new commits on main' 360 % (base, base, fx["main0"], fx["main1"]), 361 'fixdev starred adfix' % (base, base), 362 'starred adfix' % base, 363 'drakestapleton tagged v1 in' % (base, base), 364 ' reviewed fixture change one in adfix (accept)' 365 % (base, fx["patch1"], base), 366 ' followed fixdev' % base, 367 ' brought shelf-a to the open builds shelf' % (base, fx["open_held"]), 368 ] 369 for w in want: 370 expect(w in h, "[%s] feed sentence: %s" % (base, html.unescape(re.sub("<[^>]+>", "", w))[:70])) 371 expect("someone" in h, "[%s] an account without a display name is someone" % base) 372 expect(h.count("