interplane-forge
INTERPLANE Forge
Brought by drakestapleton
interplane-forge / server / tests / agentdoor.py
| 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'<span translate="no">([^<]*)</span>', 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('<link rel="alternate" type="application/json" href="%sevents.json">' % base in h, |
| 354 | "[%s] feed names %sevents.json as its JSON alternate" % (base, base)) |
| 355 | expect('<a href="%sfeed">Feed</a>' % base in h, "[%s] forge row has the Feed entry" % base) |
| 356 | want = [ |
| 357 | '<a href="%sfixdev">fixdev</a> proposed a change to <a href="%sdrakestapleton/adfix">adfix</a>: <a href="%sdrakestapleton/adfix/patches/%s">fixture change one</a>' |
| 358 | % (base, base, base, fx["patch1"]), |
| 359 | '<a href="%sdrakestapleton/adfix">adfix</a>: <a href="%sdrakestapleton/adfix/compare/%s...%s">2 new commits on main</a>' |
| 360 | % (base, base, fx["main0"], fx["main1"]), |
| 361 | '<a href="%sfixdev">fixdev</a> starred <a href="%sdrakestapleton/adfix">adfix</a>' % (base, base), |
| 362 | 'starred <a href="%sdrakestapleton/adfix">adfix</a>' % base, |
| 363 | '<a href="%sdrakestapleton">drakestapleton</a> tagged <a href="%sdrakestapleton/adfix/releases/tag/v1">v1</a> in' % (base, base), |
| 364 | ' reviewed <a href="%sdrakestapleton/adfix/patches/%s">fixture change one</a> in <a href="%sdrakestapleton/adfix">adfix</a> (accept)' |
| 365 | % (base, fx["patch1"], base), |
| 366 | ' followed <a href="%sfixdev">fixdev</a>' % base, |
| 367 | ' brought <a href="%sopen/%s">shelf-a</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("<li>") == min(50, len(evs)), "[%s] feed lists %d items (%d)" % (base, min(50, len(evs)), h.count("<li>"))) |
| 373 | # newest first and paged with before= |
| 374 | seqs_html = [int(m) for m in re.findall(r'feed\?before=(\d+)', h)] |
| 375 | if len(evs) > 50: |
| 376 | expect(len(seqs_html) == 1, "[%s] Older link present" % base) |
| 377 | mid = evs[len(evs) // 2]["seq"] |
| 378 | st, _, b2 = fetch(port, base, "feed?before=%d" % mid) |
| 379 | h2 = strip_hints(b2) |
| 380 | older = [e for e in evs if e["seq"] < mid][-50:] |
| 381 | expect(st == 200 and h2.count("<li>") == len(older) and '<a href="%sfeed">Newest</a>' % base in h2, |
| 382 | "[%s] feed?before=%d lists the %d older events and links Newest" % (base, mid, len(older))) |
| 383 | for q in ("before=0", "before=x"): |
| 384 | st, _, _ = fetch(port, base, "feed?" + q) |
| 385 | expect(st == 400, "[%s] feed?%s is 400" % (base, q)) |
| 386 | st, hd, tb = fetch(port, base, "feed?format=text") |
| 387 | t = tb.decode("utf-8", "replace") |
| 388 | expect(st == 200 and hd.get("Content-Type", "").startswith("text/plain") and "proposed a change to" in t and "fixdev" in t, |
| 389 | "[%s] feed?format=text is the plain-text form" % base) |
| 390 | |
| 391 | |
| 392 | def fill(tmpl, fx): |
| 393 | v = {"owner": "drakestapleton", "repo": "adfix", "ref": "main", "path": "a.txt", "sha": fx["main1"], |
| 394 | "a": fx["main0"], "b": fx["main1"], "tag": "v1", "user": "drakestapleton", "q": "hi", |
| 395 | "order": "trending", "project": fx["open_held"], "slug": "fixture-work", "seq": "0", "n": "5"} |
| 396 | out = tmpl |
| 397 | for k, x in v.items(): |
| 398 | out = out.replace("{%s}" % k, x) |
| 399 | if "/patches/{id}" in tmpl: |
| 400 | out = out.replace("{id}", fx["patch1"]) |
| 401 | if "/issues/{id}" in tmpl: |
| 402 | out = out.replace("{id}", fx["issue1"]) |
| 403 | return out |
| 404 | |
| 405 | |
| 406 | def agents_checks(port, base, apimd, tsv, fx, schemas): |
| 407 | st, hd, doc, body = getjson(port, base, "agents.json") |
| 408 | expect(st == 200 and doc is not None, "[%s] agents.json 200 JSON" % base) |
| 409 | if doc is None: |
| 410 | return |
| 411 | validate("[%s] agents.json" % base, doc, schemas) |
| 412 | # tsv is the table this build compiled in (.build/agents.tsv, made by run.sh agentsgen from |
| 413 | # server/agents.tsv: rows of parts the build does not compose are already "none" rows) |
| 414 | rows = [ln.split("\t") for ln in open(tsv).read().split("\n") if ln and not ln.startswith("#")] |
| 415 | hdr, rows = rows[0], rows[1:] |
| 416 | expect(hdr == ["method", "path", "json", "schema", "auth", "doc", "purpose"], "agents.tsv header") |
| 417 | expect(all(len(r) == 7 for r in rows), "agents.tsv: every row has 7 fields") |
| 418 | routes = [r for r in rows if r[0] != "none"] |
| 419 | na = [r for r in rows if r[0] == "none"] |
| 420 | # the document is the table: same rows, same order (the build compiled the table in) |
| 421 | expect([(x["method"], x["path"], x["json"], x["schema"] or "-") for x in doc["routes"]] |
| 422 | == [(r[0], base + r[1], r[2], r[3]) for r in routes], "[%s] agents.json routes are the table's rows" % base) |
| 423 | expect([x["what"] for x in doc["not_available"]] == [r[1] for r in na], "[%s] not_available is the table's none rows" % base) |
| 424 | whats = " | ".join(x["what"] for x in doc["not_available"]) |
| 425 | expect("writes over HTTP without a browser session" in whats and "MCP server" in whats, |
| 426 | "[%s] not_available names writes without a browser session and the MCP server" % base) |
| 427 | # every listed address answers its listed schema (templates filled from the fixture) |
| 428 | for x in doc["routes"]: |
| 429 | path = fill(x["path"][len(base):], fx) |
| 430 | acc = "application/json" if x["json"] == "accept" else None |
| 431 | st, hd, d, b = getjson(port, base, path, acc) |
| 432 | if "(base / only)" in x["purpose"] and base != "/": |
| 433 | expect(st == 404, "[%s] %s (base / only) is 404 under %s" % (base, path, base)) |
| 434 | continue |
| 435 | if x["auth"] == "session": |
| 436 | expect(st == 303 and (hd.get("Location") or "").endswith("login"), "[%s] %s (session) signed out -> 303 login" % (base, path)) |
| 437 | continue |
| 438 | if x["schema"] is None: |
| 439 | expect(st == 200 and d is not None, "[%s] %s answers JSON (no schema key)" % (base, path)) |
| 440 | continue |
| 441 | got = d.get("schema") if isinstance(d, dict) else None |
| 442 | expect(st == 200 and got == x["schema"], "[%s] %s answers %s (%d %s)" % (base, path, x["schema"], st, got)) |
| 443 | # both directions: every schema heading of docs/API.md is a row, every row's schema is documented |
| 444 | # in the file its doc column names |
| 445 | # the source table (every build's rows, first column the part) lists every documented schema |
| 446 | src = [ln.split("\t") for ln in open("server/agents.tsv").read().split("\n") if ln and not ln.startswith("#")] |
| 447 | listed = {r[4] for r in src[1:] if len(r) == 8 and r[4] != "-"} |
| 448 | for s in schemas: |
| 449 | expect(s in listed or s in ("forge/error/1",), "docs/API.md schema %s is listed in server/agents.tsv" % s) |
| 450 | for r in routes: |
| 451 | if r[3] == "-": |
| 452 | continue |
| 453 | try: |
| 454 | txt = open(r[5]).read() |
| 455 | except OSError: |
| 456 | bad("agents.tsv row %s: doc %s cannot be read" % (r[1], r[5])) |
| 457 | continue |
| 458 | expect(r[3] in txt, "agents.tsv row %s: %s is documented in %s" % (r[1], r[3], r[5])) |
| 459 | |
| 460 | |
| 461 | def check(port, apimd, tsv, fixture): |
| 462 | fx = json.load(open(fixture)) |
| 463 | schemas = parse_api(apimd) |
| 464 | for s in ("interplane/events/1", "interplane/agents/1"): |
| 465 | expect(s in schemas, "docs/API.md documents %s" % s) |
| 466 | for base in ("/", "/forge/"): |
| 467 | evs = stream_checks(port, base, fx, schemas) |
| 468 | limits_etag(port, base, schemas) |
| 469 | feed_checks(port, base, evs, fx) |
| 470 | agents_checks(port, base, apimd, tsv, fx, schemas) |
| 471 | |
| 472 | |
| 473 | def main(): |
| 474 | cmd = sys.argv[1] |
| 475 | if cmd == "social": |
| 476 | social(sys.argv[2], sys.argv[3]) |
| 477 | return |
| 478 | if cmd == "walk": |
| 479 | walk(int(sys.argv[2]), sys.argv[3], int(sys.argv[4]), sys.argv[5]) |
| 480 | elif cmd == "check": |
| 481 | check(int(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5]) |
| 482 | elif cmd == "agents": |
| 483 | # agents.json alone, both bases (the store-reading build: store/tests/agentdoor-store.sh) |
| 484 | fx = json.load(open(sys.argv[5])) |
| 485 | schemas = parse_api(sys.argv[3]) |
| 486 | for base in ("/", "/forge/"): |
| 487 | agents_checks(int(sys.argv[2]), base, sys.argv[3], sys.argv[4], fx, schemas) |
| 488 | print("agentdoor.py %s: %d passed, %d failed" % (cmd, passes, len(fails))) |
| 489 | sys.exit(1 if fails else 0) |
| 490 | |
| 491 | |
| 492 | main() |