interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / allen / catalog / catalog.py

600 lines · 26779 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Build Allen's public catalog: catalog.txt, catalog-detail.jsonl and areas.txt.
3
4Only unauthenticated sources are read, so a private repository cannot appear:
5 - https://api.github.com/orgs/aien-dev/repos?type=public (no Authorization header;
6 one API request per run, so hourly runs stay far below the 60/hour anonymous limit)
7 - git ls-remote / a shallow treeless git fetch of https://github.com/aien-dev/<repo>
8 with every credential source disabled (no helper, no global/system config, no
9 prompt, no SSH agent): head sha, HEAD commit date and subject, top-level names
10 - git ls-remote https://github.com/aien-dev/<repo>.wiki.git (wiki present or not)
11 - https://raw.githubusercontent.com/aien-dev/<repo>/<head sha>/README.md (STATUS.md)
12 - aienos.com om/site/pages.json, else crates/site-builder/src/seo.rs, at its head sha
13
14catalog.txt is the model's cached prompt prefix: only what the model reads, so a push
15does not change it. catalog-detail.jsonl holds per-repo detail and every head sha, for
16retrieval (retrieve.py) into the last user turn. Status, how-to and docs are copied
17from the repo's own text or omitted ("not stated"); nothing is reworded.
18
19Output is ASCII, LF, sorted, with no clock time. Any failed fetch exits nonzero and
20leaves the old files untouched; files are written through temporaries and renamed,
21and an unchanged file is not rewritten (its mtime is the gateway's cache key).
22
23Usage: catalog.py OUTDIR
24"""
25
26import concurrent.futures
27import datetime
28import hashlib
29import json
30import os
31import re
32import subprocess
33import sys
34import tempfile
35import unicodedata
36import urllib.error
37import urllib.request
38
39ORG = "aien-dev"
40API = "https://api.github.com/orgs/%s/repos?type=public&per_page=100" % ORG
41RAW = "https://raw.githubusercontent.com/%s/%s/%s/%s"
42SITE_REPO = "aienos.com"
43SEO_PATH = "crates/site-builder/src/seo.rs"
44REGISTRY_PATH = "om/site/pages.json" # the Omega site's page registry; preferred once present
45SITE = "https://www.aienos.com"
46UA = "aienos-allen-catalog/1"
47TIMEOUT = 30
48
49PURPOSE_MAX = 110 # characters of a repo's one-line purpose
50PAGE_MAX = 65 # characters of a page title plus its description
51NESTED_MAX = 200 # description of a nested page in catalog-detail.jsonl
52# Entry points Allen sends visitors and agents to keep more of their seo.rs text.
53ENTRY_PAGES = {"/agents/": 180, "/start/": 180}
54STATUS_MAX = 140 # a repo's own status/evidence statement
55HOWTO_MAX = 120 # first line of its install/usage section
56SUBJECT_MAX = 90 # HEAD commit subject
57PARSER = "p3" # bump when what at_sha() derives changes; names the cache entries
58CACHE = None # OUTDIR/.cache: per-commit derived data (immutable, so safe to reuse)
59
60# Drake's front door: listed first under "Start here" once it is public with a README.
61START = "sovereign-intelligence"
62START_MAX = 200
63# Described from their own README's first sentence rather than the GitHub description.
64FROM_README = (START, "AienOS-nv")
65
66# Fallback for /allen/ until its PageInfo reaches aienos.com main; the text is the
67# PageInfo on the feat/allen-chat branch, verbatim.
68ALLEN_PAGE = ("/allen/", "Talk to Allen",
69 "Chat with Allen, Drake's AI, on the live model on a DGX Spark: speed measured "
70 "from the stream, questions about Omega, and small HTML or Omega programs that "
71 "run sandboxed in your browser. Conversations are not stored.")
72
73OMEGA_BRIEF = (
74 "Omega in brief: Drake's language for verified programs written by AI, GPU to CPU (repo omega-mv; "
75 "Omegese is the program language, omc the compiler). The words and rules are above; full reference "
76 "docs/one_layer/OMEGESE.md in omega-mv; overview page /omega/; GPU half: CUDApp and /cudaplusplus/."
77)
78
79REACH = ("Reach Drake: X https://x.com/drakestapleton, email drake@aienos.com, "
80 "or talk to Allen at " + SITE + "/allen/.")
81
82PLURAL = re.compile(r"\b(we|our|ours|ourselves|us)\b", re.I)
83AIEN_WORD = re.compile(r"\bAIEN\b")
84
85
86def aien_case(s):
87 """Drake's spelling of the project name in descriptive text (2026-10-26): Aien, never AIEN.
88 Only descriptions pass through here; page titles, status lines and commit subjects stay verbatim."""
89 return AIEN_WORD.sub("Aien", s)
90
91
92class FetchError(Exception):
93 pass
94
95
96def get(url, allow_404=False):
97 """GET with no credentials. Returns (body bytes, headers) or (None, None) on an allowed 404."""
98 req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "*/*"})
99 try:
100 with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
101 return r.read(), r.headers
102 except urllib.error.HTTPError as e:
103 if allow_404 and e.code == 404:
104 return None, None
105 raise FetchError("%s: HTTP %d" % (url, e.code))
106 except (urllib.error.URLError, OSError) as e:
107 raise FetchError("%s: %s" % (url, e))
108
109
110def list_repos():
111 repos, url = [], API
112 while url:
113 body, headers = get(url)
114 try:
115 page = json.loads(body)
116 except ValueError:
117 raise FetchError("%s: not JSON" % url)
118 if not isinstance(page, list):
119 raise FetchError("%s: not a list" % url)
120 repos.extend(page)
121 url = None
122 for part in (headers.get("Link") or "").split(","):
123 m = re.match(r'\s*<(https://api\.github\.com/[^>]+)>;\s*rel="next"', part)
124 if m:
125 url = m.group(1)
126 if not repos:
127 raise FetchError("no public repositories listed")
128 for r in repos:
129 if r.get("private") or r.get("visibility", "public") != "public":
130 raise FetchError("non-public repository in an unauthenticated listing: refusing")
131 return repos
132
133
134def head_sha(name):
135 env = {k: v for k, v in os.environ.items() if not k.startswith(("GIT_", "SSH_"))}
136 env.update(GIT_TERMINAL_PROMPT="0", GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull,
137 GIT_ASKPASS="", SSH_ASKPASS="")
138 cmd = ["git", "-c", "credential.helper=", "ls-remote",
139 "https://github.com/%s/%s" % (ORG, name), "HEAD"]
140 try:
141 p = subprocess.run(cmd, env=env, stdin=subprocess.DEVNULL, capture_output=True,
142 text=True, timeout=TIMEOUT)
143 except (OSError, subprocess.TimeoutExpired) as e:
144 raise FetchError("ls-remote %s: %s" % (name, e))
145 out = p.stdout.strip()
146 if p.returncode == 0 and not out:
147 return None # an empty repository has no HEAD yet
148 m = re.match(r"([0-9a-f]{40})\tHEAD$", out)
149 if p.returncode != 0 or not m:
150 raise FetchError("ls-remote %s: exit %d" % (name, p.returncode))
151 return m.group(1)
152
153
154def ascii_text(s):
155 for a, b in (("\u2018", "'"), ("\u2019", "'"), ("\u201c", '"'), ("\u201d", '"'),
156 ("\u2013", "-"), ("\u2014", "-"), ("\u2026", "..."), ("\u00a0", " "),
157 ("\u2192", "->"), ("\u00d7", "x")):
158 s = s.replace(a, b)
159 s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode("ascii")
160 return re.sub(r"\s+", " ", s).strip()
161
162
163def clip(s, limit):
164 """Truncate (never reword): cut before any plural first person clause, then keep whole
165 sentences that fit, else cut at the last clause boundary, else at a word boundary."""
166 m = PLURAL.search(s)
167 if m:
168 head = s[:m.start()]
169 cut = max(head.rfind(", "), head.rfind("; "), head.rfind(": "), head.rfind(". "))
170 s = (head[:cut] if cut > 0 else "").rstrip(" ,;:") + "..."
171 if len(s) < 24:
172 return ""
173 if len(s) <= limit:
174 return s
175 end = s[:limit + 1].rfind(". ")
176 if end >= limit // 2:
177 return s[:end + 1]
178 head = s[:limit - 2]
179 cut = max(head.rfind(", "), head.rfind("; "), head.rfind(" ("))
180 if cut >= limit // 2:
181 return head[:cut].rstrip(" ,;:(.") + "..."
182 return s[:limit - 3].rsplit(" ", 1)[0].rstrip(" ,;:(.") + "..."
183
184
185def md_plain(line):
186 line = re.sub(r"!\[[^\]]*\]\([^)]*\)", "", line) # images
187 line = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", line) # links -> text
188 line = re.sub(r"\[([^\]]+)\]\[[^\]]*\]", r"\1", line) # reference links
189 line = re.sub(r"<[^>]+>", "", line) # html tags
190 line = re.sub(r"(\*\*|__|`)", "", line) # bold, code
191 line = re.sub(r"(?<!\w)[*_](\S[^*_]*\S|\S)[*_](?!\w)", r"\1", line) # italics
192 return line
193
194
195def first_sentence(readme):
196 """First prose sentence of a README, verbatim apart from markdown removal."""
197 text = readme.decode("utf-8", "replace")
198 para, fence = [], False
199 for raw in text.splitlines():
200 s = raw.strip()
201 if s.startswith(("```", "~~~")):
202 fence = not fence
203 continue
204 if fence:
205 continue
206 if not s:
207 if para:
208 break
209 continue
210 if para:
211 para.append(s)
212 continue
213 if s.startswith(("#", "<", "![", "[!", "[![", "|", ">", "-", "*", "+", "=", "---")) \
214 or re.match(r"\d+[.)] ", s) or re.match(r"\[[^\]]+\]:", s):
215 continue
216 plain = ascii_text(md_plain(s))
217 if len(plain) < 20 or not re.match(r"[A-Za-z0-9\"']", plain):
218 continue
219 para.append(s)
220 if not para:
221 return ""
222 body = ascii_text(md_plain(" ".join(para)))
223 m = re.search(r"(.+?[.!?])(\s+[A-Z(\"']|\s*$)", body)
224 return m.group(1) if m else body
225
226
227
228HOWTO_HEAD = re.compile(r"^#{1,4}\s*(install|installation|usage|quick ?start|getting started|how to use|"
229 r"use it|run it|running|build and run|try it)\b", re.I)
230STATUS_LINE = re.compile(r"^((?:status|evidence)\b[^:.]{0,40}):\s*(\S.*)$", re.I)
231STATUS_HEAD = re.compile(r"^#{1,4}\s*((?:status|evidence)\b.{0,40})$", re.I)
232BADGE = re.compile(r"!\[\s*((?:status|evidence)\b[^\]]{0,60})\]", re.I)
233
234
235def _lines(text):
236 """README lines with fence state: yields (line stripped, inside a code fence)."""
237 fence = False
238 for raw in text.splitlines():
239 s = raw.strip()
240 if s.startswith(("```", "~~~")):
241 fence = not fence
242 yield s, None
243 continue
244 yield s, fence
245
246
247def _sentence(s):
248 m = re.search(r"(.+?[.!?])(\s+[A-Z(\"']|\s*$)", s)
249 return m.group(1) if m else s
250
251
252def stated_status(text):
253 """The repo's own status/evidence statement, verbatim (first one found), else ""."""
254 lines = list(_lines(text))
255 for i, (s, fence) in enumerate(lines):
256 if fence is not False:
257 continue
258 m = STATUS_HEAD.match(s)
259 if m:
260 para = []
261 for t, f in lines[i + 1:]:
262 if f is not False or t.startswith(("#", "|")) or (not t and para):
263 break
264 if t:
265 para.append(t.lstrip("-*+ "))
266 if para:
267 label = ascii_text(md_plain(m.group(1)).strip())
268 body = _sentence(ascii_text(md_plain(" ".join(para))))
269 if not body.lower().startswith(label.split()[0].lower()):
270 body = label + ": " + body
271 return clip(body, STATUS_MAX)
272 continue
273 m = STATUS_LINE.match(ascii_text(md_plain(s)))
274 if m and not s.startswith(("|", ">")):
275 return clip(m.group(1).strip() + ": " + _sentence(m.group(2)), STATUS_MAX)
276 m = BADGE.search(text)
277 return clip(ascii_text(m.group(1)), STATUS_MAX) if m else ""
278
279
280def how_to(text):
281 """First line of the README's install/usage section: a command or a sentence, else ""."""
282 lines = list(_lines(text))
283 for i, (s, fence) in enumerate(lines):
284 if fence is not False or not HOWTO_HEAD.match(s):
285 continue
286 lead = ""
287 for t, f in lines[i + 1:]:
288 if f is False and t.startswith("#"):
289 break
290 if not t or f is None:
291 continue
292 if f:
293 if t.startswith("#"):
294 continue # a shell comment
295 return clip((lead + " " if lead else "run: ") + ascii_text(t), HOWTO_MAX)
296 if lead:
297 return clip(lead, HOWTO_MAX)
298 plain = ascii_text(md_plain(t.lstrip("-*+ ")))
299 if plain.endswith(":"):
300 lead = plain # an intro to the command below it
301 elif plain:
302 return clip(_sentence(plain), HOWTO_MAX)
303 return clip(lead, HOWTO_MAX)
304 return ""
305
306
307def git(args, cwd=None):
308 env = {k: v for k, v in os.environ.items() if not k.startswith(("GIT_", "SSH_"))}
309 env.update(GIT_TERMINAL_PROMPT="0", GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull,
310 GIT_ASKPASS="", SSH_ASKPASS="")
311 try:
312 return subprocess.run(["git", "-c", "credential.helper="] + args, cwd=cwd, env=env,
313 stdin=subprocess.DEVNULL, capture_output=True, text=True,
314 timeout=TIMEOUT * 4)
315 except (OSError, subprocess.TimeoutExpired) as e:
316 raise FetchError("git %s: %s" % (args[0], e))
317
318
319def wiki_exists(name):
320 """A public wiki answers ls-remote; a missing one asks for credentials (which are disabled)."""
321 p = git(["ls-remote", "https://github.com/%s/%s.wiki.git" % (ORG, name), "HEAD"])
322 if p.returncode == 0:
323 return bool(p.stdout.strip())
324 if "could not read Username" in p.stderr or "not found" in p.stderr.lower():
325 return False
326 raise FetchError("ls-remote %s.wiki: exit %d" % (name, p.returncode))
327
328
329def head_commit(name, sha):
330 """(commit time UTC date, subject, top-level names) of `sha`, by a shallow treeless fetch."""
331 with tempfile.TemporaryDirectory(prefix="catalog-git-") as d:
332 url = "https://github.com/%s/%s" % (ORG, name)
333 for args in (["init", "-q", "--bare", d], ["-C", d, "remote", "add", "origin", url],
334 ["-C", d, "config", "remote.origin.promisor", "true"],
335 ["-C", d, "config", "remote.origin.partialclonefilter", "tree:0"],
336 ["-C", d, "fetch", "-q", "--depth", "1", "--filter=tree:0", "origin", sha]):
337 p = git(args)
338 if p.returncode != 0:
339 raise FetchError("git %s for %s: exit %d" % (args[2] if args[0] == "-C" else args[0],
340 name, p.returncode))
341 log = git(["-C", d, "log", "-1", "--format=%ct%x00%s", sha])
342 tree = git(["-C", d, "ls-tree", "--name-only", sha])
343 if log.returncode != 0 or tree.returncode != 0 or "\x00" not in log.stdout:
344 raise FetchError("git log/ls-tree %s: failed" % name)
345 ts, subject = log.stdout.rstrip("\n").split("\x00", 1)
346 day = datetime.datetime.fromtimestamp(int(ts), datetime.timezone.utc).strftime("%Y-%m-%d")
347 return day, subject, sorted(tree.stdout.split())
348
349
350def at_sha(name, sha):
351 """Everything derived from one commit (immutable, so cached by sha and parser version)."""
352 path = os.path.join(CACHE, "%s-%s.json" % (PARSER, sha)) if CACHE else None
353 if path and os.path.exists(path):
354 with open(path, encoding="ascii") as f:
355 return json.load(f)
356 readme, _ = get(RAW % (ORG, name, sha, "README.md"), allow_404=True)
357 day, subject, top = head_commit(name, sha)
358 text = readme.decode("utf-8", "replace") if readme else ""
359 status = stated_status(text)
360 if not status and "STATUS.md" in top:
361 body, _ = get(RAW % (ORG, name, sha, "STATUS.md"), allow_404=True)
362 status = stated_status(body.decode("utf-8", "replace")) if body else ""
363 info = {"readme": hashlib.sha256(readme or b"").hexdigest() if readme else "",
364 "sentence": first_sentence(readme) if readme else "",
365 "status": status, "how_to": how_to(text),
366 "commit_date": day, "subject": clip(ascii_text(subject), SUBJECT_MAX),
367 "docs_dir": "docs" in top, "status_md": "STATUS.md" in top}
368 if path:
369 tmp = path + ".tmp"
370 with open(tmp, "w", encoding="ascii") as f:
371 json.dump(info, f, sort_keys=True)
372 os.replace(tmp, path)
373 return info
374
375
376def repo_record(r):
377 name = r["name"]
378 sha = head_sha(name)
379 info = at_sha(name, sha) if sha else {}
380 sentence = info.get("sentence", "")
381 desc = ascii_text(r.get("description") or "")
382 lic = (r.get("license") or {}).get("spdx_id") or "none"
383 if lic == "NOASSERTION":
384 lic = "other"
385 if name in FROM_README:
386 purpose = clip(sentence, START_MAX if name == START else PURPOSE_MAX) or clip(desc, PURPOSE_MAX)
387 else:
388 purpose = clip(desc or sentence, PURPOSE_MAX)
389 purpose = aien_case(purpose)
390 url = "https://github.com/%s/%s" % (ORG, name)
391 branch = r.get("default_branch") or "main"
392 docs = []
393 if info.get("readme"):
394 docs.append(url + "#readme")
395 if info.get("docs_dir"):
396 docs.append("%s/tree/%s/docs" % (url, branch))
397 if info.get("status_md"):
398 docs.append("%s/blob/%s/STATUS.md" % (url, branch))
399 if r.get("has_wiki") and wiki_exists(name):
400 docs.append(url + "/wiki")
401 detail = {"name": name, "url": url, "purpose": purpose, "license": lic,
402 "state": "archived" if r.get("archived") else "active",
403 "last_push": (r.get("pushed_at") or "")[:10], "head": sha or "empty",
404 "evidence": info.get("status") or "not stated", "docs": docs}
405 if info.get("how_to"):
406 detail["how_to"] = info["how_to"]
407 if sha:
408 detail["latest"] = {"date": info["commit_date"], "subject": info["subject"]}
409 return {"name": name, "sha": sha, "license": lic, "pushed": (r.get("pushed_at") or "")[:7],
410 "purpose": purpose, "from_readme": bool(sentence) and name in FROM_README,
411 "archived": bool(r.get("archived")), "detail": detail}
412
413
414def registry_pages(body):
415 """om/site/pages.json: [{path, title, description, area}, ...] (the Omega site's registry)."""
416 try:
417 entries = json.loads(body)
418 except ValueError:
419 raise FetchError("%s: not JSON" % REGISTRY_PATH)
420 if not isinstance(entries, list) or not entries:
421 raise FetchError("%s: not a non-empty array" % REGISTRY_PATH)
422 out = {}
423 for e in entries:
424 if not isinstance(e, dict) or not all(isinstance(e.get(k), str) for k in ("path", "title", "description")):
425 raise FetchError("%s: entry without string path, title and description" % REGISTRY_PATH)
426 if not re.match(r"^/([a-z0-9._-]+/)*$", e["path"]) or e["path"] in out:
427 raise FetchError("%s: bad or repeated path %r" % (REGISTRY_PATH, e["path"]))
428 out[e["path"]] = (e["title"], e["description"])
429 return out
430
431
432def seo_pages(body):
433 """crates/site-builder/src/seo.rs PAGES table (the Rust site builder)."""
434 src = body.decode("utf-8")
435 start = src.find("pub const PAGES: &[PageInfo] = &[")
436 end = src.find("\n];", start)
437 if start < 0 or end < 0:
438 raise FetchError("seo.rs: PAGES table not found")
439 block = src[start:end]
440 q = r'"((?:[^"\\]|\\.)*)"'
441 pages = re.findall(r"PageInfo \{ path: %s, name: %s, what: %s," % (q, q, q), block)
442 if not pages or len(pages) != block.count("PageInfo {"):
443 raise FetchError("seo.rs: %d PageInfo entries parsed, %d present"
444 % (len(pages), block.count("PageInfo {")))
445 unesc = lambda s: re.sub(r"\\(.)", r"\1", s)
446 return {unesc(p): (unesc(n), unesc(w)) for p, n, w in pages}
447
448
449def site_pages(sha):
450 """The page list at aienos.com `sha`: the Omega registry once it exists, else seo.rs.
451 Returns (pages, source label, digest of the file read)."""
452 body, _ = get(RAW % (ORG, SITE_REPO, sha, REGISTRY_PATH), allow_404=True)
453 if body is not None:
454 out, label = registry_pages(body), "pages.json"
455 else:
456 body, _ = get(RAW % (ORG, SITE_REPO, sha, SEO_PATH))
457 out, label = seo_pages(body), "seo.rs"
458 out.setdefault(ALLEN_PAGE[0], ALLEN_PAGE[1:])
459 return out, label, hashlib.sha256(body).hexdigest()
460
461
462def build():
463 repos = list_repos()
464 own = sorted((r for r in repos if not r.get("fork")), key=lambda r: r["name"].lower())
465 forks = sorted((r["name"] for r in repos if r.get("fork")), key=str.lower)
466 with concurrent.futures.ThreadPoolExecutor(8) as pool:
467 everything = list(pool.map(repo_record, own))
468 site_sha = pool.submit(head_sha, SITE_REPO).result()
469 if not site_sha:
470 raise FetchError("%s has no HEAD" % SITE_REPO)
471 pages, page_src, page_digest = site_pages(site_sha)
472 records = [rec for rec in everything if not rec["archived"]]
473 archived = [rec["name"] for rec in everything if rec["archived"]]
474
475 start = next((rec for rec in records if rec["name"] == START), None)
476 records = [rec for rec in records if rec["name"] != START]
477 if not (start and start["from_readme"]):
478 # not public, empty, or no README yet: nothing is said about it
479 print("catalog: %s %s; no Start here entry" % (START, "has no README yet" if start else "is not public"),
480 file=sys.stderr)
481 start = None
482
483 months = [rec["pushed"] for rec in records]
484 usual = max(sorted(set(months)), key=months.count) # most common last-push month, latest on a tie
485
486 # catalog.txt is the cached prompt prefix: it holds only what the model reads, so a push
487 # (new head sha) does not rewrite it. Heads and per-repo detail live in catalog-detail.jsonl.
488 L = []
489 L.append("Drake's public repos and site pages; nothing else of his is public. Name them and cite "
490 "only these URLs; if nothing fits, say Drake has nothing public for it.")
491 L.append("Sources: github.com/%s public repos and %s %s, read unauthenticated; heads in catalog-detail.jsonl."
492 % (ORG, SITE_REPO, page_src))
493 L.append("")
494 if start:
495 L.append("Start here:")
496 L.append("%s: %s (%s) https://github.com/%s/%s" % (start["name"], start["purpose"], start["license"],
497 ORG, start["name"]))
498 L.append("")
499 L.append("Active repos (URL: https://github.com/%s/ then the name; last push %s unless noted). "
500 "name: purpose (license):" % (ORG, usual))
501 for rec in records:
502 meta = [rec["license"]]
503 if rec["pushed"] != usual:
504 meta.append("last push " + rec["pushed"])
505 L.append("%s: %s (%s)" % (rec["name"], rec["purpose"] or "no description", ", ".join(meta)))
506 L.append("Archived: %s. Forks of outside projects: %s." % (", ".join(archived), ", ".join(forks)))
507 L.append("")
508 L.append("Pages on Drake's site (URL, title: what). These are pages, not repos:")
509 nested_pages = []
510 for path in sorted(pages):
511 name, what = pages[path]
512 name = ascii_text(name)
513 what = ascii_text(re.sub(r"\s*\([^)]*\)", "", what))
514 if path.count("/") > 2 and path not in ENTRY_PAGES:
515 # nested pages (/engineer/works/x/, /research/x/) go to retrieval: the prefix stays compact
516 # state/last_push/evidence/docs keep the repo-record shape, so a reader that predates
517 # page records (a gateway with an older retrieve.py loaded) cannot fail on them
518 nested_pages.append({"name": path, "kind": "page", "url": SITE + path, "title": name,
519 "purpose": aien_case(clip(what, NESTED_MAX)), "state": "page",
520 "last_push": "-", "evidence": "not stated", "docs": []})
521 continue
522 room = (ENTRY_PAGES.get(path) or PAGE_MAX) - len(name)
523 what = aien_case(clip(what, room)) if room >= 30 else ""
524 L.append("%s%s %s%s" % (SITE, path, name, ": " + what if what else ""))
525 parents = sorted({"/" + p["name"].split("/")[1] + "/" for p in nested_pages})
526 if parents:
527 L.append("More pages under %s are looked up per question; cite only URLs given to you."
528 % ", ".join(SITE + p for p in parents))
529 L.append("")
530 L.append(OMEGA_BRIEF)
531 L.append(REACH)
532 catalog = "\n".join(L) + "\n"
533 catalog.encode("ascii") # raises if anything non-ASCII slipped through
534 areas = "".join(rec["name"] + "\n" for rec in everything if not rec["archived"])
535
536 head = {"name": "_sources", "org": ORG, "site_repo": SITE_REPO, "site_head": site_sha,
537 "page_source": page_src, "page_source_sha256": page_digest, "forks": forks}
538 detail = "".join(json.dumps(d, sort_keys=True, ensure_ascii=True) + "\n"
539 for d in [head] + [rec["detail"] for rec in everything] + nested_pages)
540 return catalog, areas, detail
541
542
543def write_atomic(outdir, files):
544 tmps = []
545 try:
546 for name, text in files:
547 fd, tmp = tempfile.mkstemp(prefix="." + name + ".", dir=outdir)
548 tmps.append((tmp, name))
549 with os.fdopen(fd, "w", encoding="ascii", newline="\n") as f:
550 f.write(text)
551 f.flush()
552 os.fsync(f.fileno())
553 os.chmod(tmp, 0o644)
554 for tmp, name in tmps:
555 os.replace(tmp, os.path.join(outdir, name))
556 tmps = []
557 finally:
558 for tmp, _ in tmps:
559 try:
560 os.unlink(tmp)
561 except OSError:
562 pass
563
564
565def same(outdir, name, text):
566 try:
567 with open(os.path.join(outdir, name), "rb") as f:
568 return f.read() == text.encode("ascii")
569 except FileNotFoundError:
570 return False
571
572
573def main():
574 global CACHE
575 if len(sys.argv) != 2 or not os.path.isdir(sys.argv[1]):
576 sys.exit("usage: catalog.py OUTDIR")
577 outdir = sys.argv[1]
578 CACHE = os.path.join(outdir, ".cache")
579 os.makedirs(CACHE, mode=0o755, exist_ok=True)
580 try:
581 catalog, areas, detail = build()
582 except (FetchError, UnicodeError, KeyError, TypeError, ValueError) as e:
583 print("catalog: not written: %s" % e, file=sys.stderr)
584 sys.exit(1)
585 files = (("areas.txt", areas), ("catalog-detail.jsonl", detail), ("catalog.txt", catalog))
586 changed = [(n, t) for n, t in files if not same(outdir, n, t)]
587 if changed:
588 # an untouched file keeps its mtime, so the gateway keeps its warm prefix
589 write_atomic(outdir, changed)
590 heads = {json.loads(l).get("head") for l in detail.splitlines()}
591 for f in os.listdir(CACHE): # keep only the entries for current heads and parser
592 if not (f.startswith(PARSER + "-") and f[len(PARSER) + 1:-5] in heads):
593 os.unlink(os.path.join(CACHE, f))
594 print("catalog: %s; catalog.txt %d bytes, %d areas, %d detail records"
595 % ("wrote " + " ".join(n for n, _ in changed) if changed else "unchanged",
596 len(catalog), areas.count("\n"), detail.count("\n") - 1))
597
598
599if __name__ == "__main__":
600 main()