"""project - a project received as a ledger of requirements, planned over shapes, written from parts, judged by what it does, and continued from wherever it stopped (12.0 C9, C10; the review: "receive a request as explicit outputs, constraints, dependencies and completion conditions"; the followup: "account for every requirement"). receive each turn's words join the project's clauses. A sentence is read into requirements: OUTCOMES someone can observe (a file written, rows kept in a database, a page served, lines printed), PROPERTIES of them (a timeout, an error counted as down, the time to answer, how many results are shown) and OPERATIONS on the rows (group, total, count, average, largest, smallest, keep only, sort, the first n, a value made from a column). Every word of a sentence must be owned: by a part's vocabulary, a column of the project's tables, a file, the project's own name or the words every sentence has. A word nobody owns is a HOLE (what does it mean?), never dropped: a requirement that is only kept as text is not a requirement. world the tables the request names (csv, json), read afresh at every plan: their columns, which holds urls, which holds names. A file not there yet is a hole until it is. parts declared contracts over shapes: table (file -> rows), probe (rows with urls -> results), compute (rows -> rows: the operations), keep (rows -> stored), latest (stored -> latest), export (rows -> a file), page (rows -> page), serve (page -> served), print (rows -> lines). A value made from a column is a part found in Oracle7's code store (the functions it composed and kept, lit on the Tree of Life spine by the words and the shape) or composed by the code composer from examples the next turn gives; either way it carries its sha. plan for each entry (named in the request as `python3 m.py sub ARGS`, or proposed when the request names none): backward from its outcomes to a source (the table, the servers probed, or what another entry kept), the operations its words ask for in between. Every requirement is tied to the links that supply it. write the parts' code in plan order, one module, entries dispatched by name. judge every requirement against what happened: each entry run as named, rows read back from its database, files read back and compared with the rows an independent reading of the request gives, the page fetched from it running, the lines printed. A project is done only when every requirement has passed its judge. continue a project that stops at a hole is kept as it is (in the conversation and in the project's .oracle7 folder): the next turn's example, file, explanation or "drop" fills the hole and the build goes on from there, after a restart too. No language model.""" import csv import hashlib import json import os import re import socket import sqlite3 import subprocess import sys import time from html import unescape as html_unescape import urllib.request from pathlib import Path import project_sources as PS import project_interactive as PI ENTRY = re.compile(r"`\s*(?:python3?\s+)?([\w./-]+\.py)\s+([a-z][\w-]*)((?:\s+[A-Z_]+)*)\s*`") URLV = re.compile(r"^https?://", re.I) DATA = re.compile(r"\b([\w./-]+\.(?:csv|jsonl|json))\b") BUILD = re.compile(r"(?i)\b(?:build|make|create|write|set up|put together|develop)\b") SINK_FILE = re.compile(r"(?i)\b(?:save|saves|saved|saving|write|writes|written|export|exports|exported|output|outputs|put|puts|" r"store|stores|dump|dumps)\b(?:(?!\.\s)[^;]){0,140}?\b(?:to|into|in|as)\s+(?:a\s+file\s+(?:called|named)\s+)?" r"`?([\w./-]+\.(csv|json|txt|html))\b") SINK_TO = re.compile(SINK_FILE.pattern.replace(r"(?:to|into|in|as)", r"(?:to|into|as)")) SINK_IN = re.compile(SINK_FILE.pattern.replace("{0,140}?", "{0,140}")) # greedy: the last 'in ' of the sentence # 12.0 C28: the written file as the verb's own object ("write top.csv with the rows ...", "save a summary.json of ...") SINK_OBJ = re.compile(r"(?i)\b(?:save|saves|write|writes|export|exports|output|outputs|produce|produces)\s+(?:a\s+|an\s+|the\s+)?" r"(?:file\s+)?`?([\w./-]+\.(csv|json|txt|html))\b") def sinks(s): """the files a sentence writes: 'to / into / as ' names where rows go; 'in ' does only when the sentence has no such target ('save the items in stock.csv ... to low.csv' reads stock.csv and writes low.csv); with neither, the file the verb writes as its own object ('write top.csv with ...')""" return list(SINK_TO.finditer(s)) or list(SINK_IN.finditer(s)) or list(SINK_OBJ.finditer(s)) STORED = re.compile(r"(?i)\b(?:database|sqlite|db)\b") REVISE = re.compile(r"(?i)\b(?:change|changed|update|revise|instead|rather|make it|now)\b") # the words just before an outcome that rule it out (up to three words between: "do not export the rows", "without a db") NEGATED = re.compile(r"\b(?:do\s+not|does\s+not|don'?t|doesn'?t|never|without|no|not)\s+(?:[a-z]+\s+){0,3}$") SERVED = re.compile(r"(?i)\b(?:browser|web ?page|webpage|website|serves?|served|on (?:a|the) page|(?:a|the) page)\b") PRINTED = re.compile(r"(?i)\b(?:prints?|printed|terminal|console)\b") # ---------------------------------------------------------------- the words every sentence has, and each part's own GENERAL = set("""a an the and or but of to in on at by for from with without into onto as is are was were be been being it its this that these those each every all any some my our your their his her them they we i me you he she one once two three four five six seven eight nine ten both other others another than then so such not no do does did done has have had will would should could can may might must shall also again just only very more most less much many same new old here there when where which who whom whose what why how up out over under after before while until about per via if else whether please want need like let able use using called named way ways get gets got go goes going thing things there's it's want wants make makes made build builds built create creates created write writes written set put together project program script tool app application run runs command commands file files folder data instead too still yet sure ok okay now first next last later always never ever own change changes changed update updates updated revise revised rather don't dont doesn't actually just really well oh hmm hey thanks thank""".split()) VOCAB = { "table": "table tables list lists listed listing row rows record records entry entries column columns sheet spreadsheet " "csv json inventory item items", "probe": "query queries queried check checks checked checking ping pings request requests fetch fetches fetched health " "url urls endpoint endpoints answer answers answered respond responds response reach reachable up down status " "statuses server servers service services site sites host hosts monitor monitors monitoring", "keep": "keep keeps kept store stores stored storing save saves saved record records recorded log logs logged database " "sqlite local timestamp timestamps timestamped time times losing lose lost result results history", "timeout": "within second seconds sec secs timeout slow silent", "error": "error errors fail fails failed failure failures", "ms": "millisecond milliseconds ms long took take takes latency", "latest": "current previous latest recent newest", "page": "page pages browser show shows shown showing display displays displayed view web html dashboard webpage website", "serve": "serve serves served port", "export": "export exports exported save write output outputs dump csv json file", "print": "print prints printed terminal console screen output", "ops": "group grouped groups grouping total totals sum sums summed add adds count counts counted number average averages " "averaged mean largest biggest highest most maximum max smallest lowest least minimum min sort sorted order " "ordered descending ascending top bottom where filter filtered over above under below greater than equal equals " "summary summaries summarize summarise report reports breakdown amount amounts across overall value values", "derive": "convert converted converts column columns", "design": "look looks feel feels style styled colour colours color colors font fonts typography palette theme dark light " "mode designed design editorial literary classic formal elegant luxurious quiet calm traditional scholarly warm " "friendly modern clean minimal technical precise scientific industrial neutral bold playful expressive dramatic " "accent accents", } PART_WORDS = {k: set(v.split()) for k, v in VOCAB.items()} ALL_PART_WORDS = set().union(*PART_WORDS.values()) def stem(w): w = w.lower() if w.endswith("'s"): w = w[:-2] for suf in ("ies",): if len(w) > 4 and w.endswith(suf): return w[:-3] + "y" for suf in ("ing", "ed"): if len(w) > 4 and w.endswith(suf): return w[: -len(suf)] # C12b: "es" is a plural ending only after s, x, z, ch, sh ("boxes", "churches"); after another letter the e is the # word's own ("cubes" -> cube, "tubes" -> tube, not cub, tub) if len(w) > 4 and w.endswith("es") and re.search(r"(?:s|x|z|ch|sh)es$", w): return w[:-2] if len(w) > 3 and w.endswith("s") and not w.endswith(("ss", "us", "is")): return w[:-1] return w def wmatch(a, b): a, b = stem(a), stem(b) return a == b or (len(a) >= 4 and len(b) >= 4 and (a.startswith(b) or b.startswith(a))) def _owned(w, owners): return any(wmatch(w, o) for o in owners) # ---------------------------------------------------------------- the world def read_table(root, name): """a table of the project: its columns, the rows' values, which column holds urls and which the names""" p = Path(root) / name if not p.is_file(): return {"file": name, "missing": True} try: if name.endswith(".jsonl"): rows = [json.loads(ln) for ln in p.read_text(encoding="utf-8").splitlines() if ln.strip()] elif name.endswith(".json"): rows = json.loads(p.read_text(encoding="utf-8")) if isinstance(rows, dict): rows = next((v for v in rows.values() if isinstance(v, list)), [rows]) else: rows = list(csv.DictReader(p.read_text(encoding="utf-8").splitlines())) except (ValueError, OSError) as e: return {"file": name, "unreadable": str(e)[:120]} rows = [r for r in rows if isinstance(r, dict)] cols = list(rows[0].keys()) if rows else [] url = next((c for c in cols if rows and all(URLV.match(str(r.get(c, ""))) for r in rows)), None) key = next((c for c in cols if c != url and rows and len({str(r[c]) for r in rows}) == len(rows) and not all(_isnum(r[c]) for r in rows)), None) or \ next((c for c in cols if c != url and rows and len({str(r[c]) for r in rows}) == len(rows)), None) numeric = [c for c in cols if rows and all(_isnum(r.get(c)) for r in rows)] return {"file": name, "cols": cols, "url": url, "key": key, "n": len(rows), "numeric": numeric, "hosts": sorted({re.sub(r"^https?://([^/:]+).*$", r"\1", str(r[url])) for r in rows}) if url else [], "sample": {c: rows[0].get(c) for c in cols} if rows else {}} def _isnum(v): if isinstance(v, bool): return False if isinstance(v, (int, float)): return True try: float(str(v).strip()) return True except (TypeError, ValueError): return False def num(v): if isinstance(v, (int, float)) and not isinstance(v, bool): return v s = str(v).strip() try: return int(s) except ValueError: try: return float(s) except ValueError: return v def load_rows(root, name): p = Path(root) / name if name.endswith(".jsonl"): return [json.loads(ln) for ln in p.read_text(encoding="utf-8").splitlines() if ln.strip()] if name.endswith(".json"): rows = json.loads(p.read_text(encoding="utf-8")) if isinstance(rows, dict): rows = next((v for v in rows.values() if isinstance(v, list)), [rows]) return [dict(r) for r in rows if isinstance(r, dict)] return list(csv.DictReader(p.read_text(encoding="utf-8").splitlines())) # ---------------------------------------------------------------- receiving: the clauses, the fills EXAMPLE = re.compile(r"(-?\d+(?:\.\d+)?|'[^']*'|\"[^\"]*\")\s*(?:->|=>|→|gives|becomes)\s*(-?\d+(?:\.\d+)?|'[^']*'|\"[^\"]*\")") DROP = re.compile(r"(?i)^\s*(?:please\s+)?(?:drop|ignore|forget|leave out|skip)\s+(?:requirement\s+|r)?(\d+)\b") DROP_WORD = re.compile(r"(?i)^\s*(?:please\s+)?(?:drop|ignore|forget|leave out|skip)\s+(?:the\s+(?:word\s+)?)?['\"`]?([a-z][\w-]*)['\"`]?\s*\.?$") MEANS = re.compile(r"(?i)['\"`]?([a-z][\w-]*)['\"`]?\s+(?:means|is|meant)\s+(?:the\s+)?([\w\s-]{2,60}?)\s*\.?$") CONTINUE = re.compile(r"(?i)^\s*(?:please\s+)?(?:continue|resume|go on|carry on|try again|retry|it'?s (?:there|in) now|" r"(?:i\s+)?added (?:it|the file)|use it|keep going|finish (?:it|the project))\b") def new_shape(): return {"v": 2, "entries": {}, "module": None, "proposed": False, "clauses": [], "dropped": [], "meanings": {}, "examples": {}, "derived": {}, "status": "new", "use": {}} def receive(text, root, kept=None): """the project's shape after this turn's words. kept: the shape the conversation (or the project's folder) holds""" shape = json.loads(json.dumps(kept)) if kept else new_shape() if shape.get("v") != 2: # a shape kept by the first version: its clauses are read again old = shape shape = new_shape() shape["clauses"] = list(old.get("clauses") or []) t = " ".join(text.split()) fill = False m = DROP.match(t) if m and kept: shape["dropped"].append("R%s" % m.group(1)) fill = True m = DROP_WORD.match(t) if not fill else None if m and kept: shape["meanings"][m.group(1).lower()] = "" fill = True if not fill and kept: exs = EXAMPLE.findall(t) open_derive = [h for h in shape.get("holes_kept") or [] if h.get("kind") == "derive"] source_entries = {h.get("entry", "*") for h in shape.get("holes_kept") or [] if h.get("kind") == "source"} scope_holes = [h for h in shape.get("holes_kept") or [] if h.get("kind") == "scope"] named_entry = next((n for n in shape["entries"] if re.fullmatch(r"(?i)(?:the\s+)?`?" + re.escape(n) + r"`?(?:\s+command)?[.!]?", t)), None) entry_match = ENTRY.fullmatch(t) if entry_match and entry_match.group(1) == shape.get("module"): named_entry = entry_match.group(2) if len(scope_holes) == 1 and named_entry in scope_holes[0].get("entries", []): shape.setdefault("scope_fills", {})[str(scope_holes[0]["clause"])] = named_entry fill = True elif len(source_entries) == 1 and re.match(r"(?i)^\s*(?:match(?:ing|ed)?\s+(?:on|by)\s+|on\s+)[a-z_]", t): shape.setdefault("source_fills", {})[next(iter(source_entries))] = t fill = True elif exs and open_derive: h = open_derive[0] shape["examples"][h["fn"]] = shape["examples"].get(h["fn"], []) + [[_lit(a), _lit(b)] for a, b in exs] shape["example_words"] = (shape.get("example_words", "") + " " + EXAMPLE.sub(" ", t)).strip() fill = True elif re.search(r"(?i)\buse\s+(?:it|that|the kept one|[a-z_]+)\b", t) and \ [h for h in shape.get("holes_kept") or [] if h.get("kind") == "derive" and h.get("offer")]: h = next(h for h in shape["holes_kept"] if h.get("kind") == "derive" and h.get("offer")) shape["use"][h["fn"]] = h["offer"]["sha256"] fill = True else: mm = MEANS.search(t) unread = {w for h in shape.get("holes_kept") or [] if h.get("kind") == "unread" for w in h.get("words", [])} if mm and mm.group(1).lower() in unread: shape["meanings"][mm.group(1).lower()] = mm.group(2).strip() fill = True elif CONTINUE.match(t): fill = True if not fill: shape["clauses"].append(t) hits = [(ci, m) for ci, c in enumerate(shape["clauses"]) for m in ENTRY.finditer(c)] for _ci, m in hits: shape["module"] = shape["module"] or m.group(1) shape["entries"].setdefault(m.group(2), {"args": m.group(3).split()}) return shape def _lit(s): s = s.strip() if s[:1] in "'\"": return s[1:-1] return num(s) # ---------------------------------------------------------------- reading the requirements def _sentences(clause): out, start = [], 0 for m in re.finditer(r"(?<=[.;!?])\s+", clause): out.append((start, clause[start:m.start()])) start = m.end() out.append((start, clause[start:])) return [(o, s) for o, s in out if s.strip()] def _segments(clause, hits): """the clause's sentences, each cut again where it names a command: every piece belongs to the command named at its start, or to the one named before it, or (before any command) to the whole project ("*"); None when the clause names none""" starts = [m.start() for m in hits] for off, s in _sentences(clause): cuts = [off] + [p for p in starts if off < p < off + len(s)] + [off + len(s)] for a, b in zip(cuts, cuts[1:]): piece = clause[a:b].strip(" ,;") if not piece: continue before = [m for m in hits if m.start() <= a] ent = before[-1].group(2) if before else ("*" if hits else None) yield a, piece, ent def _words(s): s = DATA.sub(" ", ENTRY.sub(" ", s)) s = re.sub(r"\b[\w./-]+\.(?:csv|jsonl|json|txt|html|py|db)\b", " ", s) return [w for w in re.findall(r"[a-z][a-z']*", s.lower().replace("-", " ")) if len(w) > 2] def project_noun(shape): """the words the project calls itself: 'build a service-health dashboard ...' -> service, health, dashboard""" for c in shape["clauses"]: m = re.search(r"(?i)\b(?:build|make|create|write|set up|put together|develop)\s+(?:me\s+|us\s+)?(?:(?:a|an|the|my|our)\s+)?" r"((?:[\w-]+\s+){0,3}?[\w-]+?)\s+(?:for|from|that|which|to|using|with|of|in|on|so|where|,|\.|`)", c + " .") if m: ws = [w for w in re.findall(r"[a-z]+", m.group(1).lower()) if w not in GENERAL] if ws: return ws[:4] return [] COLW = r"([a-z_]+)" def _col(word, cols, derived=()): for c in list(cols) + list(derived): if wmatch(word, c) or wmatch(word, c.replace("_", " ").split()[-1]): return c return None def read_ops(s, cols, numeric, derived_names, gcol_hint=None): """the operations a sentence asks of the rows. -> (ops, owned words, derive requests)""" low = " " + DATA.sub(" FILE ", s.lower()) + " " ops, own, derive = [], set(), [] # A reference supplies a second value, not a unary example-driven function. calculations = [] for m in re.finditer(r"\bmultiply\s+(?:each\s+|the\s+)?([a-z_]+)\s+by\s+(?:the\s+)?([a-z_]+)" r"\s+(?:as|into)\s+([a-z_]+)", low): left, right = _col(m.group(1), cols), _col(m.group(2), cols) if left is not None and right is not None: calculations.append((left, right, m.group(3), m.group(0))) for m in re.finditer(r"\bconvert(?:s|ed|ing)?\s+(?:each\s+|every\s+|the\s+|all\s+)?([a-z_]+)" r"(?:\s+from\s+FILE)?\s+(?:with|using)\s+(?:the\s+|its\s+|matching\s+)*([a-z_]+)", low): left, right = _col(m.group(1), cols), _col(m.group(2), cols) if left is not None and right is not None: calculations.append((left, right, "converted_" + left, m.group(0))) # C15: arithmetic between two columns in ordinary words ("cost as qty times price", "margin being price minus cost", # "total equal to a plus b", "share as part divided by whole"; "add/subtract/divide a to/from/by b as name") ARITH = {"times": "mul", "multiplied by": "mul", "x": "mul", "plus": "add", "added to": "add", "minus": "sub", "less": "sub", "take away": "sub", "divided by": "div", "over": "div", "per": "div"} arw = "|".join(sorted((re.escape(k) for k in ARITH), key=len, reverse=True)) for m in re.finditer(r"\b([a-z_]+)\s+(?:as|is|=|being|equal to|which is|worked out as|computed as)\s+(?:the\s+)?([a-z_]+)\s+" r"(%s)\s+(?:the\s+)?([a-z_]+)\b" % arw, low): left, right = _col(m.group(2), cols), _col(m.group(4), cols) if left is not None and right is not None and m.group(1) not in cols: # a new name: exact, not near calculations.append((left, right, m.group(1), m.group(0), ARITH[m.group(3)])) for m in re.finditer(r"\b(add|subtract|divide)\s+(?:each\s+|the\s+)?([a-z_]+)\s+(to|from|by)\s+(?:the\s+)?([a-z_]+)" r"\s+(?:as|into)\s+([a-z_]+)", low): a, b = _col(m.group(2), cols), _col(m.group(4), cols) if a is not None and b is not None: fn = {"add": "add", "subtract": "sub", "divide": "div"}[m.group(1)] left, right = (b, a) if fn == "sub" else (a, b) # subtract a from b: b - a calculations.append((left, right, m.group(5), m.group(0), fn)) calculations = [c if len(c) == 5 else c + ("mul",) for c in calculations] for left, right, name, phrase, fn in calculations: if not any(o.get("col") == name for o in ops): ops.append({"op": "calculate", "col": name, "left": left, "right": right, "fn": fn}) own |= set(re.findall(r"[a-z_]+", phrase)) | {name} for _l, _r, _n, phrase, _f in calculations: # C15: a phrase that defines a value is consumed by it - "both equal low = low.replace(phrase, " CALC ") # to price plus cost" is not also a filter "both == price" calculated_names = [o["col"] for o in ops] for m in re.finditer(r"\b([a-z_]+?)s?\s+in\s+([a-z]+)\b(?!\s*\.\w)", low): c = _col(m.group(1), cols) tgt = m.group(2) if c and tgt not in GENERAL and not _col(tgt, cols) and tgt not in ALL_PART_WORDS and tgt != "file": derive.append({"col": c, "name": tgt, "phrase": m.group(0).strip()}) own |= {m.group(1), tgt} for m in re.finditer(r"\bconvert(?:s|ed|ing)?\s+(?:each\s+|every\s+|the\s+|all\s+)?([a-z_]+?)s?\s+(?:to|into)\s+([a-z]+)\b", low): c = _col(m.group(1), cols) if c and not _col(m.group(2), cols): derive.append({"col": c, "name": m.group(2), "phrase": m.group(0).strip()}) own |= {m.group(1), m.group(2)} for m in re.finditer(r"\b([a-z]+)\s+(?:made|computed|worked out|derived|calculated|figured)\s+(?:out\s+)?from\s+" r"(?:the\s+|its\s+|their\s+|each\s+)?([a-z_]+?)s?\b", low): # C11: "its weight made from units" c = _col(m.group(2), cols) if c and not _col(m.group(1), cols) and m.group(1) not in GENERAL and not any(d["name"] == m.group(1) for d in derive): derive.append({"col": c, "name": m.group(1), "phrase": m.group(0).strip()}) own |= {m.group(1), m.group(2), "made", "computed", "worked", "out", "derived", "calculated", "figured", "from"} dmap = {d["col"]: d["name"] for d in derive} names = list(derived_names) + calculated_names + [d["name"] for d in derive] def col_of(w): c = _col(w, cols, names) return dmap.get(c, c) for m in re.finditer(r"\b(?:group(?:ed|s|ing)?\s+(?:[a-z_.]+\s+){0,3}?by|by|per|for each|for every)\s+(?:the\s+|their\s+|its\s+)?" + COLW, low): c = _col(m.group(1), cols) if c and c not in numeric: if not any(o["op"] == "group" for o in ops): ops.append({"op": "group", "col": c}) own.add(m.group(1)) break aggs = [(r"\b(?:total|totals|sum|sums|add up|adds up)\s+(?:of\s+|up\s+)?(?:the\s+|all\s+|their\s+|its\s+|each\s+)?" + COLW, "sum"), (r"\b(?:average|averages|mean)\s+(?:of\s+)?(?:the\s+|all\s+|their\s+)?" + COLW, "mean"), (r"\b(?:largest|biggest|highest|maximum|max)\s+(?:of\s+)?(?:the\s+)?" + COLW, "max"), (r"\b(?:smallest|lowest|minimum|min)\s+(?:of\s+)?(?:the\s+)?" + COLW, "min")] for rx, fn in aggs: for m in re.finditer(rx, low): c = col_of(m.group(1)) if c and (c in numeric or c in names): if not any(o["op"] == "agg" and o["fn"] == fn and o["col"] == c for o in ops): ops.append({"op": "agg", "fn": fn, "col": c}) own.add(m.group(1)) elif fn == "sum" and len([x for x in numeric if x != gcol_hint]) == 1 and re.match(r"\s*(?:by|per|for)\b", low[m.end(1) - len(m.group(1)):][len(m.group(1)):]): pass # a word that is both an operation and a column of the table is the column where the sentence uses it as one # ("whose count is below 3", "sorted by the total"): such a use does not ask for the operation low_ops = re.sub(r"\b(?:whose|where|with|its|their|by|the)\s+([a-z_]+)\b(?!\s+of\b)", lambda m: " COLUSE " if m.group(1) in ("count", "counts", "total", "totals", "sum", "number") and _col(m.group(1), cols) else m.group(0), low) if re.search(r"\btotals?\b", low_ops) and not any(o["op"] == "agg" and o["fn"] == "sum" for o in ops): cand = [c for c in numeric if c != gcol_hint] if len(cand) == 1: ops.append({"op": "agg", "fn": "sum", "col": dmap.get(cand[0], cand[0])}) if re.search(r"\b(?:count|counts|how many|number of)\b", low_ops): ops.append({"op": "agg", "fn": "count", "col": None}) CMPW = r"(?:over|above|more|greater|at|under|below|less|fewer)\b" for m in re.finditer(r"\b(?:where|whose|with)\s+(?:the\s+|its\s+|their\s+)?" + COLW + r"\s+(?:is|are|=|equals|equal to|of)\s+(?!" + CMPW + r")['\"`]?([\w.-]+)['\"`]?", low): c = col_of(m.group(1)) if c: ops.append({"op": "filter", "col": c, "cmp": "==", "val": num(m.group(2))}) own |= {m.group(1), m.group(2)} for m in re.finditer(COLW + r"\s+(?:is\s+|are\s+)?(over|above|more than|greater than|at least|under|below|less than|fewer than|at most)\s+(-?\d+(?:\.\d+)?)", low): c = col_of(m.group(1)) if c: cmp = {"over": ">", "above": ">", "more than": ">", "greater than": ">", "at least": ">=", "under": "<", "below": "<", "less than": "<", "fewer than": "<", "at most": "<="}[m.group(2)] ops.append({"op": "filter", "col": c, "cmp": cmp, "val": num(m.group(3))}) own.add(m.group(1)) m = re.search(r"\b(?:sort(?:ed|s)?|order(?:ed|s)?)\s+by\s+(?:the\s+|their\s+)?" + COLW + r"(\s+(?:descending|highest first|largest first|biggest first))?", low) if m and col_of(m.group(1)): ops.append({"op": "sort", "col": col_of(m.group(1)), "desc": bool(m.group(2))}) own.add(m.group(1)) elif re.search(r"\b(?:highest|largest|biggest|most)\s+first\b", low): ops.append({"op": "sort", "col": None, "desc": True}) elif re.search(r"\b(?:lowest|smallest|least)\s+first\b", low): ops.append({"op": "sort", "col": None, "desc": False}) m = re.search(r"\b(?:top|first)\s+(\d+)\b", low) if m: ops.append({"op": "top", "n": int(m.group(1))}) return ops, own, derive def _interaction_request(text): """Receive record actions and a separately named relationship source.""" visible = DATA.sub(lambda m: " " * len(m.group()), text) edits = list(re.finditer(r"(?i)\beditable\b|\b(?:edit|modify|update|change)\s+(?:(?:the|these|my|each)\s+)?(?:records?|rows?|values|data)\b|\bread[- ]only\b", visible)) edit = bool(edits and not NEGATED.search(visible[:edits[-1].start()].lower()) and not re.fullmatch(r"(?i)read[- ]only", edits[-1].group())) relations = list(re.finditer(r"(?i)\b(?:relationships?|connections?|edges|links)\b", visible)) relation = relations[-1] if relations and not NEGATED.search(visible[:relations[-1].start()].lower()) else None if not edits and not relations and not re.search(r"(?i)\binteractive\b", visible): return None edge, owned = None, set() owned.update("interactive selecting select selection click controls control".split()) if edits: owned.update("editable edit modify update change edits changes editing modifying updating persist persists persistent save saving form fields field values read only".split()) if relations: owned.update("relationship relationships connection connections edge edges link links linked connect connecting draw drawing drawn between endpoint endpoints source target create remove delete adding add".split()) if relation: tail = text[relation.end():] named = re.match(r"(?i)\s+(?:from|in|using|stored in)\s+`?([\w./-]+\.(?:csv|jsonl|json))\b", tail) edge = {"file": named.group(1) if named else ".oracle7/relationships.csv", "create": not bool(named)} suffix = tail[named.end():] if named else tail cols = re.search(r"(?i)\b(?:using\s+|with\s+)?([a-z_]\w*)\s+(?:and|to|->)\s+([a-z_]\w*)\s+(?:as\s+)?(?:columns|endpoints)\b", suffix) if cols: edge.update({"from": cols.group(1), "to": cols.group(2)}) owned.update(cols.groups()) return {"edit": edit, "edges": edge, "owned": sorted(owned)} def _source_contexts(shape, root): """Resolve sources in command scope; a named command never borrows another's columns.""" output_files = {m.group(1) for c in shape["clauses"] for m in sinks(c)} groups = {"*": []} for ci, clause in enumerate(shape["clauses"]): for _off, sentence, entry in _segments(clause, list(ENTRY.finditer(clause))): if entry in (None, "*"): entry = shape.get("scope_fills", {}).get(str(ci), entry) groups.setdefault(entry or "*", []).append(sentence) texts = {name: " ".join(pieces) for name, pieces in groups.items()} source_fills = shape.get("source_fills", {}) interactions = {name: _interaction_request(text) for name, text in texts.items()} auxiliary = {i["edges"]["file"] for i in interactions.values() if i and i.get("edges")} primary = lambda text: DATA.sub(lambda m: " " * len(m.group()) if m.group(1) in auxiliary else m.group(), text) default = PS.resolve(primary(texts["*"]), root, output_files=output_files, key_override=source_fills.get("*")) default["interaction"] = interactions.get("*") contexts = {} for name, text in texts.items(): if name != "*": contexts[name] = PS.resolve(primary(text), root, fallback=default["source"], output_files=output_files, key_override=source_fills.get(name)) contexts[name]["explicit"] = bool(PS.input_files(primary(text), output_files)) contexts[name]["interaction"] = interactions.get(name) or interactions.get("*") distinct = {json.dumps(c["source"], sort_keys=True): c for c in contexts.values() if c.get("source")} if not default["source"] and not default["holes"] and len(distinct) == 1: inherited = next(iter(distinct.values())) default = dict(inherited, explicit=False, ops_text=texts["*"]) default.setdefault("explicit", bool(PS.input_files(primary(texts["*"]), output_files))) contexts["*"] = default for name in shape["entries"]: if name not in contexts or (not contexts[name]["source"] and not contexts[name]["holes"]): named = [m for m in contexts if m not in (name, "*") and contexts[m].get("source") and re.search(r"(?i)\b(?:from|of|what)\s+`?" + re.escape(m) + r"`?\b", texts.get(name, ""))] contexts[name] = dict(contexts[named[0]] if len(named) == 1 else default, explicit=False) shape["sources"] = {n: c.get("source") for n, c in contexts.items()} shape["auxiliary_inputs"] = sorted(auxiliary) return contexts, output_files def _source_ops_text(text, source): """Matching keys select rows across tables; they are not a request to group the result.""" if not source or source.get("op") not in ("join", "lookup"): return text columns = {c for pair in source.get("keys", []) for c in pair} token = r"(?:[a-z_][\w]*\.)?(?:" + "|".join(re.escape(c) for c in sorted(columns)) + r")\b" return re.sub(r"\b(?:matching\s+(?:(?:on|by)\s+)?|matched\s+(?:(?:on|by)\s+)?|on\s+)" + token + r"(?:\s*(?:=|equals|to|with|,|and)\s*" + token + r")*", " ", text, flags=re.I) def requirements(shape, root): """the ledger: every requirement the clauses make, each with its kind, its entry, the words it came from; and the holes reading leaves (words nobody owns, tables not there)""" contexts, out_files = _source_contexts(shape, root) shape["source_contexts"] = contexts tables = {f: read_table(root, f) for c in shape["clauses"] for f in PS.input_files(c, out_files) if f not in shape.get("auxiliary_inputs", [])} world = contexts["*"].get("world") or next((c["world"] for c in contexts.values() if c.get("world")), None) or \ next(iter(tables.values()), None) if world: world = dict(world, hosts=sorted({h for w in tables.values() for h in w.get("hosts", [])})) cols = (world or {}).get("cols", []) numeric = (world or {}).get("numeric", []) stems = set() for f in list(tables): # C11: a table read names its rows ("each city in weather.csv"); a file written b = Path(f).stem.lower() # names nothing else in the sentence ("the lively products ... to lively.csv") stems |= {b} | set(re.findall(r"[a-z]+", b)) noun = project_noun(shape) entries = list(shape["entries"]) reqs, holes = [], [] derived_names = list((shape.get("derived") or {}).keys()) meanings = shape.get("meanings") or {} ids = shape.setdefault("ids", {}) # a requirement's id is kept by what it is: a drop or a fill never renumbers the rest def add(kind, text, ci, entry=None, **kw): key = (kind, kw.get("file"), kw.get("op_key"), entry if kind in ("served", "printed", "stored", "file", "op", "derive", "interaction") else None) for r in reqs: if r["key"] == list(key): if text not in r["from"]: r["from"].append(text) old = {k: r.get(k) for k in kw if r.get(k) != kw[k]} if old: # a later sentence's value replaces the earlier one ("5" -> "2") r.setdefault("superseded", []).append(old) r.update(kw) r["clause"] = ci return r o = kw.get("op") if kind == "op" and o and REVISE.search(shape["clauses"][ci]): # a revision ("change it so ...", "instead", "now") names an operation the project already has on the same # column: the new one replaces it, the old kept as superseded same = [r for r in reqs if r["kind"] == "op" and r["entry"] == entry and r["clause"] < ci and r["op"]["op"] == o["op"] and r["op"].get("col") == o.get("col") and r["op"].get("fn") == o.get("fn")] if same: r = same[-1] r.setdefault("superseded", []).append({k: v for k, v in r["op"].items() if o.get(k) != v}) r.update(kw) r["key"], r["clause"] = list(key), ci r["from"].append(text) return r kid = json.dumps(list(key)) old_key = json.dumps([kind, kw.get("file"), kw.get("op_key"), None]) if kid not in ids and kind in ("op", "derive") and old_key in ids and not any(r["id"] == ids[old_key] for r in reqs): ids[kid] = ids[old_key] # retain requirement identity when an older single-source project is continued if kid not in ids: ids[kid] = "R%d" % (max([int(v[1:]) for v in ids.values()] or [0]) + 1) r = {"id": ids[kid], "kind": kind, "entry": entry, "from": [text], "clause": ci, "key": list(key), "status": "open"} r.update(kw) reqs.append(r) return r for ci, clause in enumerate(shape["clauses"]): hits = list(ENTRY.finditer(clause)) for off, s, ent in _segments(clause, hits): if ent in (None, "*"): ent = shape.get("scope_fills", {}).get(str(ci), ent) context = contexts.get(ent or "*", contexts["*"]) # The original clauses remain the audit trail. An answered key hole # retires only its old binding phrase from this reading, so an old # misspelling cannot remain an unread requirement. Adjacent row # operations and outcomes are still read normally. for binding in context.get("retired_key_bindings", []): s = re.sub(r"(? 1 # a word given a meaning ("flags means the rows whose amount is over 100") is read as its meaning; a meaning # that names nothing to do (no outcome, no operation, no value) leaves the word a hole that says so unbound = [] for w, v in meanings.items(): if v and re.search(r"(?i)(?= 2: head_ops = read_ops(s[:at[1]], cols, numeric, derived_names)[0] for i in range(1, len(at)): piece_ops = read_ops(s[at[i]:at[i + 1] if i + 1 < len(at) else len(s)], cols, numeric, derived_names)[0] for o in ops: if o["op"] in ("agg", "group", "top") and o not in head_ops and o in piece_ops: scoped.setdefault(json.dumps(o, sort_keys=True), at[i]) excluded = [(k, {x: y for x, y in kw.items() if x != "_at"}) for k, kw in excluded] for k, kw in excluded: # an outcome the request rules out: judged as not done add("excluded", s, ci, ent, what=k, op_key="not " + k + (" " + kw["file"] if kw.get("file") else ""), **({"file": kw["file"]} if kw.get("file") else {})) if not kinds and not props and not ops and not derive and not excluded: if ci == 0 and (BUILD.search(s) or DATA.search(s)) and not unowned: add("context", s, ci, None) continue if not unowned: add("context", s, ci, None) continue out_at = {} for k, kw in kinds: tgt_entry = ent out_at[kw.get("_at", 0)] = add(k, s, ci, tgt_entry, **{x: y for x, y in kw.items() if x != "_at"})["id"] for k, kw in props: add(k, s, ci, None, **kw) if interaction and _interaction_request(s): add("interaction", s, ci, ent, op_key="record actions", actions=interaction) for o in ops: ok_ = json.dumps(o, sort_keys=True) if ok_ in scoped: add("op", s, ci, op_entry, op=o, op_key=ok_ + " @" + out_at[scoped[ok_]], out=out_at[scoped[ok_]]) else: add("op", s, ci, op_entry, op=o, op_key=ok_) for d in derive: fn = "%s_of_%s" % (re.sub(r"\W+", "_", d["name"]).strip("_"), d["col"]) add("derive", s, ci, ent, col=d["col"], name=d["name"], fn=fn, op_key=fn) if unowned: # its identity is the sentence it sits in, not which of its words are still unread: a word dropped or # explained leaves the rest of the hole under the same id r = add("unread", s, ci, ent, words=unowned, op_key="unread %d %d" % (ci, off)) r["status"] = "hole" for r in reqs: if r["id"] in shape.get("dropped", []): r["status"] = "dropped" reqs.sort(key=lambda r: int(r["id"][1:])) return reqs, world, tables # ---------------------------------------------------------------- planning: entries, sources, links, holes def _propose(shape, reqs): """entries for a request that names none: one that does the work (named by its verb) and one that serves the page""" outs = [r for r in reqs if r["kind"] in ("file", "stored", "printed", "served") and r["status"] != "dropped"] if not outs: return text = " ".join(shape["clauses"]).lower() if not shape.get("module"): noun = project_noun(shape) if not noun: # no name of its own: its table and what it makes tbl = next((f for c in shape["clauses"] for f in DATA.findall(c)), "project") noun = [re.sub(r"\W+", "_", Path(tbl).stem).strip("_") or "project", "page" if all(r["kind"] == "served" for r in outs) else "report"] shape["module"] = "_".join(noun[:3]) + ".py" batch = [r for r in outs if r["kind"] != "served"] served = [r for r in outs if r["kind"] == "served"] entries = {} if batch: verb = next((v for v in ("check", "report", "export", "update", "summarize", "collect", "refresh", "scan", "import", "sync", "build") if re.search(r"\b%s" % v, text)), "run") entries[verb] = {"args": [], "proposed": True} if served: entries["serve"] = {"args": ["PORT"], "proposed": True} shape["entries"] = entries shape["proposed"] = True bname = next((n for n in entries if n != "serve"), None) for r in outs: r["entry"] = "serve" if r["kind"] == "served" else bname def _store_offer(fn, name, col, sample): """a kept function of Oracle7's store for a value made from a column: lit on the spine by the words and the shape, its name saying both the value and the column, its own evidence still holding""" try: sys.path.insert(0, str(Path(__file__).resolve().parent)) import code_store as CS entries = CS.load() except Exception: # noqa: BLE001 return None, [] if not entries: return None, [] words = [stem(w) for w in re.findall(r"[a-z]+", name.lower())] + [stem(w) for w in re.findall(r"[a-z]+", col.lower())] shp = "'int'" if isinstance(sample, int) else "'float'" if isinstance(sample, float) else "'str'" try: lit = [e for _r, e in CS.CodeFlash(entries).light([shp], None, words)] except Exception: # noqa: BLE001 lit = entries by_sha = {e["sha256"]: e for e in entries} for e in lit: if len(e.get("params") or []) != 1: continue ew = [stem(w) for w in re.findall(r"[a-z]+", e["name"].lower())] if not all(any(wmatch(w, x) for x in ew) for w in words): continue if e.get("in_shapes") and e["in_shapes"][0] not in (shp, "'int'", "'float'") and shp != "'str'": continue why = CS.replay(e, by_sha) if why is None: deps = [] seen = set() def addd(x): for _n, sha in (x.get("deps") or {}).items(): d = by_sha.get(sha) if d is not None and sha not in seen: seen.add(sha) addd(d) deps.append(d) addd(e) return e, deps return None, [] def plan(shape, root): """-> (pipes, holes, reqs, world). pipes: entry -> {source, ops, derive, sinks, links}; every open requirement tied to the links that supply it, or a hole saying what would fill it""" reqs, world, tables = requirements(shape, root) if not shape["entries"]: _propose(shape, reqs) gone = {r["id"] for r in reqs if r["status"] == "dropped"} for r in reqs: # an operation of one outcome goes when that outcome is dropped if r.get("out") in gone and r["status"] != "dropped": r["status"], r["dropped_with"] = "dropped", r["out"] live = [r for r in reqs if r["status"] != "dropped"] holes = [] contexts = shape.get("source_contexts", {}) for name, context in contexts.items(): for hole in context.get("holes", []): h = dict(hole, entry=name) if not any(x.get("text") == h.get("text") for x in holes): holes.append(h) for r in live: if r["kind"] == "scope": holes.append({"kind": "scope", "req": r["id"], "clause": r["clause"], "entries": r["entries"], "text": "%s: which command does this correction belong to? Say its name: %s. The correction is kept." % (r["id"], ", ".join("`%s`" % n for n in r["entries"]))}) if r["kind"] == "unread": given = [(w, shape["meanings"][w]) for w in r["words"] if (shape.get("meanings") or {}).get(w)] if given: holes.append({"kind": "unread", "req": r["id"], "words": r["words"], "text": "%s: you said %s, but I can't read that as something to do: no file, page, database, " "printing or operation on the rows. Say it as one (\"%s means the rows whose ... is " "over ...\"), or \"drop %s\"." % (r["id"], "; ".join("'%s' means '%s'" % g for g in given), given[0][0], r["id"][1:])}) continue holes.append({"kind": "unread", "req": r["id"], "words": r["words"], "text": "%s: I don't know what %s means here (\"%s\"). Say what it means (\"%s means ...\"), or " "\"drop %s\"." % (r["id"], ", ".join("'%s'" % w for w in r["words"]), r["from"][0][:140], r["words"][0], r["id"][1:])}) for f, w in (tables or {}).items(): if w.get("missing"): holes.append({"kind": "world", "file": f, "text": "%s is not in the project yet. Add it and say \"continue\"." % f}) elif w.get("unreadable"): holes.append({"kind": "world", "file": f, "text": "%s could not be read as a table (%s)." % (f, w["unreadable"])}) if not world and any(r["kind"] in ("file", "stored", "served", "printed") for r in live): holes.append({"kind": "world", "text": "the request names no table of the project (a .csv or .json file) to work from."}) for r in live: if r["kind"] == "file" and any(Path(root, r.get("file", "")).resolve() == Path(root, f).resolve() for f in tables): holes.append({"kind": "outcome", "req": r["id"], "text": "%s: writing to %s would replace the table the project reads. Name another file to write " "(\"... to out.csv\"), or \"drop %s\"." % (r["id"], r["file"], r["id"][1:])}) entries = shape["entries"] names = list(entries) if not names: holes.append({"kind": "outcome", "text": "nothing in the request is an outcome I can observe (a file written, rows kept " "in a database, a page in the browser, lines printed)."}) return {}, holes, reqs, world serve_name = next((n for n in names if "PORT" in entries[n]["args"]), None) if serve_name is None and any(r["kind"] == "served" for r in live): # a page asked of a project whose commands all run and stop: a command that serves it is proposed beside them entries["serve"] = {"args": ["PORT"], "proposed": True} names.append("serve") serve_name = "serve" for r in live: if r["kind"] == "served": r["entry"] = None batch_names = [n for n in names if n != serve_name] or names[:1] for r in live: # an outcome named before any entry, or added later: its entry by kind if r["kind"] == "interaction" and (r["entry"] not in names or "PORT" not in entries[r["entry"]]["args"]): r["entry"] = serve_name or batch_names[0] if r["kind"] in ("file", "stored", "served", "printed") and (r["entry"] in (None, "*") or r["entry"] not in names): r["entry"] = serve_name if r["kind"] == "served" and serve_name else batch_names[0] if r["kind"] in ("op", "derive") and r["entry"] not in names: r["entry"] = "*" first = {} for r in live: # the same outcome asked again (a change saying "on the page"): one record if r["kind"] in ("file", "stored", "served", "printed"): k = (r["kind"], r.get("file"), r["entry"]) if k in first: first[k]["from"] += [x for x in r["from"] if x not in first[k]["from"]] r["status"] = "dropped" r["merged_into"] = first[k]["id"] else: first[k] = r live = [r for r in live if r["status"] != "dropped"] probe_words = PART_WORDS["probe"] - {"answer", "answers", "answered", "up", "down", "status", "server", "servers"} pipes = {} stores = {} for n in names: outs = [r for r in live if r["entry"] == n and r["kind"] in ("file", "stored", "served", "printed")] words = " ".join(x for r in live if r["entry"] in (n, "*") for x in r["from"]).lower() context = contexts.get(n, contexts.get("*", {})) pw = context.get("world") or {} probe = bool(pw.get("url") and any(re.search(r"\b%s\b" % w, words) for w in probe_words)) has_store = any(r["kind"] == "stored" for r in outs) stores[n] = (probe, has_store) pipes[n] = {"outs": [r["id"] for r in outs], "probe": probe, "input": context.get("source"), "world": pw, "explicit_source": context.get("explicit", False)} store_names = [n for n in names if stores[n][1]] for n in store_names: table_name = "results_" + re.sub(r"\W", "_", n) if sum(re.sub(r"\W", "_", m) == re.sub(r"\W", "_", n) for m in store_names) > 1: table_name += "_" + hashlib.sha256(n.encode()).hexdigest()[:8] pipes[n]["store_table"] = "results" if len(store_names) == 1 else table_name for n in names: p = pipes[n] pw = p["world"] outs = [r for r in live if r["id"] in p["outs"]] only_view = outs and all(r["kind"] in ("served", "printed") for r in outs) other_stores = [m for m in names if m != n and stores[m][1]] view_words = " ".join(x for r in outs for x in r["from"]) named_stores = [m for m in other_stores if re.search(r"(?i)\b(?:from|of|what)\s+`?" + re.escape(m) + r"`?\b", view_words)] other_store = named_stores[0] if len(named_stores) == 1 else other_stores[0] if len(other_stores) == 1 else None if only_view and not p["explicit_source"] and len(other_stores) > 1 and other_store is None: holes.append({"kind": "source", "entry": n, "text": "`%s` could read several stored results; name the command it reads from: %s." % (n, ", ".join(other_stores))}) if only_view and other_store and not p["explicit_source"]: src = "stored" # a view of what another command keeps reads it back elif p["probe"]: src = "probe" else: src = "table" p["source"] = src p["numeric"] = list(pw.get("numeric") or []) # a proposed view of a project that keeps nothing shows what the project's commands compute: their operations inherit = [m for m in names if m != n and pipes[m].get("input") == p.get("input")] if entries[n].get("proposed") and only_view and src == "table" else [] p["ops"] = [r["op"] for r in live if r["kind"] == "op" and r["entry"] in [n, "*"] + inherit and not r.get("out")] \ if src != "stored" else [] p["out_ops"] = {} # C11: the operations one outcome asks for itself for r in live: if r["kind"] == "op" and r.get("out") in p["outs"]: p["out_ops"].setdefault(r["out"], []).append(r["op"]) p["derive"] = [r for r in live if r["kind"] == "derive" and r["entry"] in [n, "*"] + inherit] if src == "table" else [] for operation in p["ops"] + [o for operations in p["out_ops"].values() for o in operations]: if operation["op"] == "calculate" and pw.get("n", 0) and any(c not in p["numeric"] for c in (operation["left"], operation["right"])): holes.append({"kind": "source", "entry": n, "text": "`%s` needs numeric values in both %s and %s to calculate %s. Correct those input values and continue." % (n, operation["left"], operation["right"], operation["col"])}) if src == "stored" and other_store: p["ops"] = [r["op"] for r in live if r["kind"] == "op" and r["entry"] == n and not r.get("out")] p["from"] = other_store p["store_probe"] = stores[other_store][0] p["store_table"] = pipes[other_store].get("store_table", "results") p["input"], p["world"] = pipes[other_store]["input"], pipes[other_store]["world"] pw = p["world"] p["numeric"] = list(pw.get("numeric") or []) if p["store_probe"] and (p["ops"] or p["out_ops"]): holes.append({"kind": "part", "entry": n, "text": "`%s` asks to transform stored probe results; say whether to use all history or only the latest result per server before that transformation." % n}) if src != "stored" and not p.get("input") and p["outs"]: holes.append({"kind": "source", "entry": n, "text": "`%s` needs an input table or an explicitly named combination of tables." % n}) links = [] if src == "probe": links += [{"part": "table", "why": "the servers are listed in %s" % pw["file"]}, {"part": "probe", "why": "each row's url is asked once"}] elif src == "table": graph = p.get("input") or {} relationship = graph.get("op", "read") why = "%s: %s" % (relationship, ", ".join(PS.files(graph)) or "the table") if graph.get("keys"): why += " matching " + ", ".join("%s = %s" % tuple(k) for k in graph["keys"]) links.append({"part": "table", "why": why}) else: links += [{"part": "db", "why": "the rows `%s` keeps" % other_store}] if stores[other_store][0]: links.append({"part": "latest", "why": "each row's most recent results are read back"}) for d in p["derive"]: links.append({"part": "derive", "why": "%s made from %s" % (d["name"], d["col"]), "req": d["id"]}) if p["ops"]: links.append({"part": "compute", "why": "; ".join(_op_text(o) for o in p["ops"])}) for r in outs: part = {"file": "export", "stored": "keep", "served": "page", "printed": "print"}[r["kind"]] if p["out_ops"].get(r["id"]): links.append({"part": "compute", "why": "for %s only: %s" % (r["id"], "; ".join( _op_text(o) for o in p["out_ops"][r["id"]])), "req": r["id"]}) links.append({"part": part, "why": {"file": "written to %s" % r.get("file"), "stored": "kept in the project's database", "served": "laid out as a page", "printed": "printed"}[r["kind"]], "req": r["id"]}) if part == "page": links.append({"part": "serve", "why": "served to a browser on PORT", "req": r["id"]}) p["links"] = links if src == "stored" and not stores[other_store][0]: p["record_fields"] = None if any(p["source"] == "probe" for p in pipes.values()): for n, p in pipes.items(): if p["ops"] and p["source"] == "probe": holes.append({"kind": "part", "text": "`%s %s`: %s of probe results is not a part I have yet." % ( shape["module"], n, _op_text(p["ops"][0]))}) pw = p.get("world", {}) if p["source"] == "probe" and not (pw.get("url") and pw.get("key")): holes.append({"kind": "world", "text": "%s has no column of urls and one of names (columns: %s)" % ( pw.get("file"), ", ".join(pw.get("cols", [])))}) # values made from a column: the store first, then the composer from examples derived = shape.setdefault("derived", {}) for r in live: if r["kind"] != "derive": continue fn = r["fn"] if fn in derived: continue sample = num((pipes.get(r["entry"], {}).get("world") or world or {}).get("sample", {}).get(r["col"])) e, deps = _store_offer(fn, r["name"], r["col"], sample) if e is not None and (e["sha256"] == (shape.get("use") or {}).get(fn) or _names_equal(e["name"], fn)): derived[fn] = {"name": r["name"], "col": r["col"], "fn": e["name"], "source": e["source"], "sha256": e["sha256"], "imports": e.get("imports") or [], "deps": [{"name": d["name"], "source": d["source"], "sha256": d["sha256"]} for d in deps], "from": "store", "project": e.get("project"), "id": e["id"]} continue exs = (shape.get("examples") or {}).get(fn) if not exs: # C11: examples given in the sentence that asked for the value got = [[_lit(a), _lit(b)] for t in r["from"] for a, b in EXAMPLE.findall(t)] if len(got) >= 3: exs = shape.setdefault("examples", {})[fn] = got if exs and len(exs) >= 3: holes.append({"kind": "compose", "req": r["id"], "fn": fn, "col": r["col"], "name": r["name"], "examples": exs, "text": "%s: %s made from %s - composing it from the %d examples given." % ( r["id"], r["name"], r["col"], len(exs))}) continue h = {"kind": "derive", "req": r["id"], "fn": fn, "col": r["col"], "name": r["name"], "text": "%s: no part I have makes %s from %s (\"%s\"). Give three examples of %s -> %s (like `%s -> ...`), " "and I compose it and keep it." % (r["id"], r["name"], r["col"], r["from"][0][:120], r["col"], r["name"], sample if sample is not None else "...")} if e is not None: h["offer"] = {"name": e["name"], "sha256": e["sha256"], "project": e.get("project")} h["text"] += " My store has %s (sha %s, kept from %s): say \"use it\" if that is what you mean." % ( e["name"], e["sha256"][:12], e.get("project") or "earlier work") holes.append(h) if any(r["kind"] == "served" for r in live): shape["design"] = design_for([r for r in live if r["kind"] == "look"]) for r in live: if r["kind"] != "interaction": continue p = pipes.get(r["entry"], {}) if not p.get("input"): continue try: if p.get("source") != "table": raise PI.InteractionError("name the source records to edit; a stored history or probe result is not its source record") actions = (contexts.get(r["entry"]) or contexts.get("*") or {}).get("interaction") or r["actions"] edges = dict(actions["edges"]) if actions.get("edges") else None if edges and not all(edges.get(k) for k in ("from", "to")): if edges.get("create"): edges.update({"from": "source", "to": "target", "label": "label"}) else: edge_columns, _edge_rows = PS.source_snapshot({"op": "read", "file": edges["file"]}, root) pairs = [(a, b) for a, b in (("source", "target"), ("from", "to"), ("source_id", "target_id"), ("from_id", "to_id"), ("parent", "child")) if a in edge_columns and b in edge_columns] if len(pairs) != 1: raise PI.InteractionError("name the relationship endpoints: relationships from %s using COLUMN and COLUMN as endpoints" % edges["file"]) edges.update({"from": pairs[0][0], "to": pairs[0][1]}) if "label" in edge_columns: edges["label"] = "label" if any(o["op"] in ("agg", "group") for o in p.get("ops", [])): raise PI.InteractionError("give the editor a view of individual source records; grouped totals have several owning records") shown = expected_rows(root, world, p, shape.get("derived") or {}) identity = next(iter(shown[0]), None) if shown else next(iter(p["world"].get("cols", [])), None) p["interaction"] = PI.plan_interaction(root, p["input"], shown, identity=identity, editable=None if actions["edit"] else [], edges=edges) r["binding"] = p["interaction"] p["links"].append({"part": "record actions", "why": "selection, source edits and relationships share the displayed record identities", "req": r["id"]}) except (ValueError, OSError, KeyError, TypeError, AttributeError) as error: holes.append({"kind": "interaction", "req": r["id"], "text": "%s: %s" % (r["id"], error)}) shape["status"] = "blocked" if holes else "planned" shape["holes_kept"] = holes return pipes, holes, reqs, world def _names_equal(a, b): wa = sorted(stem(w) for w in re.findall(r"[a-z]+", a.lower())) wb = sorted(stem(w) for w in re.findall(r"[a-z]+", b.lower())) return wa == wb def _op_text(o): if o["op"] == "calculate": return "%s made as %s %s %s" % (o["col"], o["left"], {"mul": "times", "add": "plus", "sub": "minus", "div": "divided by"}.get(o.get("fn"), "?"), o["right"]) if o["op"] == "group": return "grouped by %s" % o["col"] if o["op"] == "agg": return {"sum": "total", "mean": "average", "max": "largest", "min": "smallest", "count": "count"}[o["fn"]] + \ ("" if o["col"] is None else " of %s" % o["col"]) if o["op"] == "filter": return "only rows whose %s %s %s" % (o["col"], o["cmp"], o["val"]) if o["op"] == "sort": return "sorted by %s%s" % (o["col"] or "the summary", ", highest first" if o["desc"] else "") if o["op"] == "top": return "the first %d" % o["n"] return str(o) def sort_col(o, p, aggs): """what "highest first" sorts by when the request names no column: the summary it asks for, else the value it makes from a column, else the table's one column of numbers""" if o.get("col"): return o["col"] if aggs: return agg_name(aggs[0]) if p.get("derive"): return p["derive"][-1]["name"] nums = p.get("numeric") or [] return nums[0] if len(nums) == 1 else None def agg_name(o): if o["fn"] == "count": return "count" return {"sum": "total", "mean": "average", "max": "largest", "min": "smallest"}[o["fn"]] + "_" + o["col"] def settings(reqs): s = {"timeout": 10.0, "error_down": False, "ms": False, "timed": False, "keep_last": 1} for r in reqs: if r["status"] == "dropped": continue if r["kind"] == "timeout": s["timeout"] = r["seconds"] elif r["kind"] == "error_down": s["error_down"] = True elif r["kind"] == "ms": s["ms"] = True elif r["kind"] == "timestamp": s["timed"] = True elif r["kind"] == "keep_last": s["keep_last"] = max(s["keep_last"], r["n"]) return s # ---------------------------------------------------------------- writing: each part's code def write(shape, pipes, reqs, world): st = settings(reqs) mod = shape["module"] db = Path(mod).stem + ".db" probe = any(p["source"] == "probe" or p.get("store_probe") for p in pipes.values()) derived = shape.get("derived") or {} used_fns = [derived[d["fn"]] for p in pipes.values() for d in p.get("derive", []) if d["fn"] in derived] imports = sorted({"csv", "html", "http.server", "json", "sqlite3", "sys", "time"} | ({"urllib.error", "urllib.request"} if probe else set()) | {i for f in used_fns for i in f.get("imports") or []}) parts_used = sorted({l["part"] for p in pipes.values() for l in p["links"]}) L = ['"""%s - written by Oracle7 from the request (its parts: %s)."""' % (mod, ", ".join(parts_used))] L += ["import %s" % i for i in imports] + ["", ""] default_input = (world or {}).get("source") or {"op": "read", "file": world["file"]} L += PS.runtime_source().splitlines() + ["", ""] if any(p.get("interaction") for p in pipes.values()): L += PI.runtime_source().splitlines() + ["", ""] L += ["TABLE = %r" % world["file"], "DEFAULT_INPUT = %r" % default_input, "DB = %r" % db] if probe: fields = ["key", "url", "at", "status", "code", "error"] + (["ms"] if st["ms"] else []) probe_world = next((p.get("world") or world for p in pipes.values() if p["source"] == "probe"), world) L += ["KEY, URL = %r, %r" % (probe_world["key"], probe_world["url"]), "TIMEOUT = %r" % st["timeout"]] else: fields = None L += ["KEEP_LAST = %d" % st["keep_last"], "", ""] L += ["def table(source=None):", ' """the rows of a named source shape, read afresh"""', " return read_source(DEFAULT_INPUT if source is None else source)", "", "", "def num(v):", ' """a number written as text, read as a number; other values as they are"""', " if isinstance(v, (int, float)) and not isinstance(v, bool):", " return v", " s = str(v).strip()", " try:", " return int(s)", " except ValueError:", " pass", " try:", " return float(s)", " except ValueError:", " return v", "", ""] if probe: L += _emit_probe(st) for f in used_fns: for d in f.get("deps") or []: L += ["# kept function %s from Oracle7's store (sha %s)" % (d["name"], d["sha256"][:16])] + d["source"].splitlines() + ["", ""] L += ["# %s: %s made from %s - %s (sha %s)" % ( f["fn"], f["name"], f["col"], "kept function from Oracle7's store, from %s" % (f.get("project") or "earlier work") if f.get("from") == "store" else "composed by Oracle7's code composer from the examples given", f["sha256"][:16])] L += f["source"].splitlines() + ["", ""] for n, p in pipes.items(): if p["source"] in ("table", "stored"): provider = pipes.get(p.get("from"), p) stored_rows = "stored(%r)" % provider.get("store_table", p.get("store_table", "results")) if p["source"] == "stored" else None L += _emit_compute(n, p, derived, stored_rows) for rid in p.get("out_ops") or {}: L += _emit_compute(n, view(p, rid), derived, stored_rows, rid) rec_fields = {} store_tables = {} for n, p in pipes.items(): if any(r["kind"] == "stored" for r in reqs if r["id"] in p["outs"]): sr = next(r["id"] for r in reqs if r["id"] in p["outs"] and r["kind"] == "stored") rec_fields[n] = list(dict.fromkeys(fields if p["source"] == "probe" else out_columns(view(p, sr), p.get("world") or world, derived) + ["at"])) store_tables[p.get("store_table", "results")] = rec_fields[n] if not store_tables: store_tables["results"] = fields if probe else ["at"] L += ["STORE_FIELDS = %r" % store_tables, "FIELDS = %r" % (fields if probe else next(iter(rec_fields.values()), ["at"])), "", "", "def _qid(value):", " return chr(34) + str(value).replace(chr(34), chr(34) * 2) + chr(34)", "", "", "def connect(store='results'):", ' """one named result table per source command; previous rows stay"""', " fs = STORE_FIELDS[store]", " c = sqlite3.connect(DB)", " c.execute('create table if not exists %s (%s)' % (_qid(store), ', '.join(_qid(f) for f in fs)))", " have = [r[1] for r in c.execute('pragma table_info(%s)' % _qid(store))]", " for f in fs:", " if f not in have:", " c.execute('alter table %s add column %s' % (_qid(store), _qid(f)))", " return c", "", "", "def keep(rows, store='results'):", ' """every row kept in its command\'s table, with its time"""', " c = connect(store)", " fs = STORE_FIELDS[store]", " at = time.strftime('%Y-%m-%d %H:%M:%S')", " with c:", " for r in rows:", " r.setdefault('at', at)", " c.execute('insert into %s (%s) values (%s)' % (_qid(store), ', '.join(_qid(f) for f in fs), ', '.join('?' * len(fs))),", " [r.get(f) for f in fs])", " c.close()", " return len(rows)", "", "", "def stored(store='results'):", ' """every row in this command\'s table, oldest first"""', " c = connect(store)", " fs = STORE_FIELDS[store]", " rows = [dict(zip(fs, x)) for x in c.execute('select %s from %s order by rowid' % (', '.join(_qid(f) for f in fs), _qid(store)))]", " c.close()", " return rows", "", ""] head, why = design_head(shape.get("design")) L += ["DOC = %r" % '%s', "# the look: Oracle7's design family (palette, type, layout, motion): " + why, "HEAD = %r" % head, "STAGE = %r" % (tuple((shape.get("design") or {}).get("stage") or ()) or None,), "", ""] if probe: L += _emit_latest_page(st) L += ["def scene_records(rows):", ' """the records a scene is bound to (12.0 C12): each row\'s id (its first column) and value (the first column after', ' it whose values are all numbers), in the page\'s order"""', " cols = []", " for r in rows:", " for k in r:", " if k not in cols:", " cols.append(k)", " if not cols:", " return []", " vc = next((c for c in cols[1:] if c != 'at' and rows and all(isinstance(num(r.get(c)), (int, float)) for r in rows)), None)", " return [{'id': str(r.get(cols[0])), 'v': num(r.get(vc)) if vc else None} for r in rows]", "", ""] L += ["def page_rows(rows, title):", ' """the rows as a page: one line each, the columns side by side"""', " cols = []", " for r in rows:", " for k in r:", " if k not in cols:", " cols.append(k)", " head = ''.join('%s' % html.escape(str(c)) for c in cols)", " body = ''.join('%s' % (html.escape(str(r.get(cols[0]))), ''.join(", " '%s' % html.escape('' if r.get(c) is None else str(r.get(c))) for c in cols)) for r in rows)", " stage = (STAGE[1] + STAGE[2].replace('__ROWS__', json.dumps(scene_records(rows)).replace('

%s

' % html.escape(title) + stage +", " '%s%s
' % (head, body, record_json))", "", "", "def serve(port, render):", ' """the page, served on loopback; made afresh on every visit"""', " class H(http.server.BaseHTTPRequestHandler):", " def do_GET(self):", " b = render().encode()", " self.send_response(200)", " self.send_header('Content-Type', 'text/html; charset=utf-8')", " self.end_headers()", " self.wfile.write(b)", "", " def log_message(self, *a):", " pass", "", " http.server.ThreadingHTTPServer(('127.0.0.1', port), H).serve_forever()", "", "", "def export(rows, path, columns=()):", ' """the rows written to a file; an empty CSV still declares its columns"""', " cols = []", " for r in rows:", " for k in r:", " if k not in cols:", " cols.append(k)", " if not cols:", " cols = list(columns)", " if path.endswith('.json'):", " json.dump(rows, open(path, 'w'), indent=1, default=str)", " return len(rows)", " with open(path, 'w', newline='') as f:", " w = csv.DictWriter(f, fieldnames=cols)", " w.writeheader()", " for r in rows:", " w.writerow(r)", " return len(rows)", "", ""] own_name = [w for w in project_noun(shape) if w not in ("page", "site", "website", "tool", "project", "app", "view") and w not in PART_WORDS["design"]] # the look's words describe the page, they do not name it title = " ".join(w.capitalize() for w in (own_name or re.findall(r"[a-z]+", Path(world["file"]).stem.lower()) or [Path(mod).stem])).replace("_", " ") # a generic noun names nothing: the table L += ["TITLE = %r" % title, "", "", "def main(argv):"] for n, p in pipes.items(): outs = [r for r in reqs if r["id"] in p["outs"]] provider = pipes.get(p.get("from"), p) store_table = provider.get("store_table", "results") if p["source"] == "stored" else p.get("store_table", "results") input_shape = p.get("input") or default_input L.append(" if argv[:1] == [%r]:" % n) if p["source"] == "probe": pw = p.get("world") or world L.append(" rows = probe(table(%r), key=%r, url=%r)" % (input_shape, pw["key"], pw["url"])) elif p["source"] in ("table", "stored"): L.append(" rows = compute_%s()" % _compute_ident(n)) else: L.append(" rows = stored(%r)" % store_table) for r in outs: if r["kind"] == "stored": L.append(" print('%%d rows kept in %%s' %% (keep(%s, %r), DB))" % (_rows_for(n, p, r["id"]), p.get("store_table", "results"))) for r in outs: if r["kind"] == "file": src = "stored(%r)" % store_table if (r.get("every") and any(x["kind"] == "stored" for x in outs)) else _rows_for(n, p, r["id"]) cols = (store_tables[store_table] if r.get("every") and any(x["kind"] == "stored" for x in outs) else fields if p["source"] == "probe" or p.get("store_probe") else out_columns(view(p, r["id"]), p.get("world") or world, derived)) L.append(" print('%%d rows written to %%s' %% (export(%s, %r, %r), %r))" % (src, r["file"], cols, r["file"])) for r in outs: if r["kind"] == "printed": L.append(" for r in %s:" % _rows_for(n, p, r["id"])) L.append(" print(' '.join('%s %s' % (k, v) for k, v in r.items() if k != 'at'))") served = [r for r in outs if r["kind"] == "served"] if served: if p.get("interaction"): compute = "compute_%s" % _compute_ident(n, served[0]["id"] if (p.get("out_ops") or {}).get(served[0]["id"]) else None) L.append(" return serve_interactive(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_rows(%s(), TITLE), %r, %s)" % (compute, p["interaction"], compute)) elif (p["source"] == "stored" and p.get("store_probe") and not p.get("ops") and not p.get("derive") and not (p.get("out_ops") or {}).get(served[0]["id"])): pw = provider.get("world") or world L.append(" return serve(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_latest(%r, %r, %r))" % ( provider.get("input") or default_input, pw["key"], store_table)) elif p["source"] in ("table", "stored"): L.append(" return serve(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_rows(compute_%s(), TITLE))" % _compute_ident(n, served[0]["id"] if (p.get("out_ops") or {}).get(served[0]["id"]) else None)) else: L.append(" return serve(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_rows(rows, TITLE))") L.append(" return 0") usage = " | ".join("%s %s%s" % (mod, n, "".join(" " + a for a in e["args"])) for n, e in shape["entries"].items()) L += [" print(%r)" % ("usage: " + usage), " return 2", "", "", "if __name__ == '__main__':", " sys.exit(main(sys.argv[1:]))", ""] return "\n".join(L) def _ident(n): # Separate namespaces keep e.g. `report-a` distinct from `report_a`, even # when an ordinary command happens to contain an encoded-looking suffix. return "w_" + n if re.fullmatch(r"\w+", n) else "e_" + n.encode("utf-8").hex() def _compute_ident(name, outcome=None): if outcome is None: return "entry_" + _ident(name) # Encoding each component makes a command named `report__r1` different # from the outcome r1 of report, with no separator ambiguity. return "outcome_" + name.encode("utf-8").hex() + "_" + outcome.encode("utf-8").hex() def view(p, rid): """the pipe as one outcome sees it: the command's operations, then the ones that outcome asked for itself (C11)""" own = (p.get("out_ops") or {}).get(rid) if p else None return dict(p, ops=list(p["ops"]) + list(own)) if own else p def _rows_for(n, p, rid): return "compute_%s()" % _compute_ident(n, rid) if (p.get("out_ops") or {}).get(rid) else "rows" def out_columns(p, world, derived): ops = p.get("ops") or [] g = next((o["col"] for o in ops if o["op"] == "group"), None) aggs = [o for o in ops if o["op"] == "agg"] if aggs: return ([g] if g else []) + [agg_name(o) for o in aggs] world = p.get("world") or world return list(dict.fromkeys(list((world or {}).get("cols", [])) + [d["name"] for d in p.get("derive", []) if d["fn"] in derived] + [o["col"] for o in ops if o["op"] == "calculate"])) def _emit_compute(n, p, derived, rows_expr=None, outcome=None): """the operations, in the order a reader would do them: values made, rows kept, grouped and summed, sorted, cut""" if rows_expr is None: rows_expr = "table(%r)" % p["input"] if p.get("input") else "table()" L = ["def compute_%s():" % _compute_ident(n, outcome), ' """%s"""' % ("; ".join(_op_text(o) for o in p["ops"]) or "the rows as they are"), " rows = " + rows_expr] for d in p.get("derive", []): f = derived.get(d["fn"]) if f: L += [" for r in rows:", " r[%r] = %s(num(r[%r]))" % (d["name"], f["fn"], d["col"])] for o in p["ops"]: if o["op"] == "calculate": if o.get("fn") not in ("mul", "add", "sub", "div"): raise ValueError("calculation part %r is not represented" % o.get("fn")) L += [" for r in rows:", " factors = [num(r[%r]), num(r[%r])]" % (o["left"], o["right"]), " if any(isinstance(v, bool) or not isinstance(v, (int, float)) or (isinstance(v, float) and not _source_math.isfinite(v)) for v in factors):", " raise ValueError(%r)" % ("%s requires finite numeric values in %s and %s" % (o["col"], o["left"], o["right"])), " if %r == 'div' and factors[1] == 0:" % o.get("fn"), " raise ValueError(%r)" % ("%s divides by a zero %s" % (o["col"], o["right"])), " value = %s" % {"mul": "factors[0] * factors[1]", "add": "factors[0] + factors[1]", "sub": "factors[0] - factors[1]", "div": "factors[0] / factors[1]"}[o.get("fn", "mul")], " if isinstance(value, float) and not _source_math.isfinite(value):", " raise ValueError(%r)" % ("%s exceeds the finite numeric range" % o["col"]), " r[%r] = value" % o["col"]] for o in p["ops"]: if o["op"] == "filter": L.append(" rows = [r for r in rows if _cmp(num(r[%r]), %r, %r)]" % (o["col"], o["cmp"], o["val"])) g = next((o["col"] for o in p["ops"] if o["op"] == "group"), None) aggs = [o for o in p["ops"] if o["op"] == "agg"] if aggs: L += [" groups = {}", " for r in rows:", " groups.setdefault(%s, []).append(r)" % ("r[%r]" % g if g else "None"), " out = []", " for k, rs in groups.items():", " o = {%s}" % ("%r: k" % g if g else "")] for o in aggs: nm = agg_name(o) if o["fn"] == "count": L.append(" o[%r] = len(rs)" % nm) else: vals = "[num(r[%r]) for r in rs]" % o["col"] L.append(" o[%r] = %s" % (nm, {"sum": "round(sum(%s), 10)" % vals, "mean": "round(sum(%s) / len(rs), 10)" % vals, "max": "max(%s)" % vals, "min": "min(%s)" % vals}[o["fn"]])) L += [" out.append(o)", " rows = out"] for o in p["ops"]: if o["op"] == "sort": col = sort_col(o, p, aggs) if col: L.append(" rows.sort(key=lambda r: num(r[%r]), reverse=%r)" % (col, o["desc"])) for o in p["ops"]: if o["op"] == "top": L.append(" rows = rows[:%d]" % o["n"]) L += [" return rows", "", "", "def _cmp(a, op, b):", " if isinstance(a, str) or isinstance(b, str):", " a, b = str(a).lower(), str(b).lower()", " return {'==': a == b, '>': a > b, '<': a < b, '>=': a >= b, '<=': a <= b}[op]", "", ""] return L def _emit_probe(st): L = ["def probe(rows, key=KEY, url=URL):", ' """each url asked once; no answer within TIMEOUT s%s is down, and the others go on"""' % ( ", or an error status," if st["error_down"] else ""), " out = []", " for r in rows:", " t0 = time.time()", " res = {'key': r[key], 'url': r[url], 'at': time.strftime('%Y-%m-%d %H:%M:%S'),", " 'status': 'down', 'code': None, 'error': None}", " try:", " with urllib.request.urlopen(r[url], timeout=TIMEOUT) as a:", " res['code'] = a.status", " res['status'] = 'up'", " except urllib.error.HTTPError as e:", " res['code'] = e.code", " res['error'] = 'HTTP %d' % e.code" if st["error_down"] else " res['status'], res['error'] = 'up', 'HTTP %d' % e.code", " except Exception as e: # noqa: BLE001 (no answer in time, refused, unreachable)", " res['error'] = type(e).__name__ + ': ' + str(e)[:120]"] if st["ms"]: L += [" if res['status'] == 'up':", " res['ms'] = round((time.time() - t0) * 1000)", " else:", " res['ms'] = None"] L += [" out.append(res)", " return out", "", ""] return L def _emit_latest_page(st): shown = ["status", "at"] + (["ms"] if st["ms"] else []) + ["code", "error"] heads = ["current", "previous"] if st["keep_last"] == 2 else ["result %d" % (i + 1) for i in range(st["keep_last"])] return ["def latest(source=None, key=KEY, store='results'):", ' """each server\'s last KEEP_LAST results, newest first, in its source\'s order"""', " c = connect(store)", " fs = STORE_FIELDS[store]", " out = []", " for r in table(source):", " rows = c.execute('select %s from %s where key = ? order by rowid desc limit ?' % (', '.join(_qid(f) for f in fs), _qid(store)),", " (r[key], KEEP_LAST)).fetchall()", " out.append((r[key], [dict(zip(fs, x)) for x in rows]))", " c.close()", " return out", "", "", "SHOWN = %r" % shown, "HEADS = %r" % heads, "", "", "def page_latest(source=None, key=KEY, store='results'):", ' """the page: one row per server, its results side by side"""', " def cell(x):", " if x is None:", " return '-'", " return '' % html.escape(str(x['status'])) + '
'.join(", " html.escape('%s: %s' % (f, '' if x.get(f) is None else x.get(f))) for f in SHOWN) + ''", " body = ''.join('%s%s' % (html.escape(str(k)), ''.join(cell(rs[i] if i < len(rs) else None)", " for i in range(len(HEADS)))) for k, rs in latest(source, key, store))", " return (DOC % 'Service health' + HEAD + '

Service health

%s%s'", " '
server
' % (''.join('%s' % h for h in HEADS), body))", "", ""] # ---------------------------------------------------------------- the rows the request asks for, read independently def expected_rows(root, world, p, derived, initial_rows=None): """what a reader of the request would compute from the table: the judge's own reading, not the written code's""" from judge.project_sources_judge import expected_source_rows if initial_rows is None: source = p.get("input") or {"op": "read", "file": (p.get("world") or world)["file"]} rows = expected_source_rows(root, source) else: rows = [dict(row) for row in initial_rows] for d in p.get("derive", []): f = derived.get(d["fn"]) ns = {} for i in f.get("imports") or []: ns[i.split(".")[0]] = __import__(i) for dep in f.get("deps") or []: exec(compile(dep["source"], "judge:" + dep["name"], "exec"), ns) exec(compile(f["source"], "judge:" + f["fn"], "exec"), ns) for r in rows: r[d["name"]] = ns[f["fn"]](num(r[d["col"]])) for o in p["ops"]: if o["op"] == "calculate": if o.get("fn") not in ("mul", "add", "sub", "div"): raise ValueError("the judge does not know calculation %s" % o.get("fn")) for r in rows: # the judge's own arithmetic, read from the operation's name a, b = num(r[o["left"]]), num(r[o["right"]]) if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): raise ValueError("%s requires numeric %s and %s" % (o["col"], o["left"], o["right"])) if o["fn"] == "div" and b == 0: raise ValueError("%s divides by a zero %s" % (o["col"], o["right"])) r[o["col"]] = {"mul": lambda: a * b, "add": lambda: a + b, "sub": lambda: a - b, "div": lambda: a / b}[o["fn"]]() for o in p["ops"]: if o["op"] == "filter": def ok(r, o=o): a, b = num(r[o["col"]]), o["val"] if isinstance(a, str) or isinstance(b, str): a, b = str(a).lower(), str(b).lower() return {"==": a == b, ">": a > b, "<": a < b, ">=": a >= b, "<=": a <= b}[o["cmp"]] rows = [r for r in rows if ok(r)] g = next((o["col"] for o in p["ops"] if o["op"] == "group"), None) aggs = [o for o in p["ops"] if o["op"] == "agg"] if aggs: keys = [] for r in rows: k = r[g] if g else None if k not in keys: keys.append(k) out = [] for k in keys: rs = [r for r in rows if (r[g] if g else None) == k] o = {g: k} if g else {} for a in aggs: vals = [num(r[a["col"]]) for r in rs] if a["col"] else [] o[agg_name(a)] = {"count": len(rs), "sum": sum(vals) if vals else 0, "mean": (sum(vals) / len(vals)) if vals else 0, "max": max(vals) if vals else None, "min": min(vals) if vals else None}[a["fn"]] out.append(o) rows = out for o in p["ops"]: if o["op"] == "sort": col = sort_col(o, p, aggs) if col: rows = sorted(rows, key=lambda r: num(r[col]), reverse=o["desc"]) for o in p["ops"]: if o["op"] == "top": rows = rows[:o["n"]] return rows def _scene_records(rows): """the judge's own reading of which record each scene object should be (the contract the page's scene_records keeps)""" cols = [] for r in rows: for k in r: if k not in cols: cols.append(k) if not cols: return [] vc = next((c for c in cols[1:] if c != "at" and rows and all(isinstance(num(r.get(c)), (int, float)) for r in rows)), None) return [{"id": str(r.get(cols[0])), "v": num(r.get(vc)) if vc else None} for r in rows] def _same(a, b): a, b = num(a), num(b) if isinstance(a, (int, float)) and isinstance(b, (int, float)): return abs(a - b) <= 1e-6 * max(1.0, abs(a), abs(b)) return str(a) == str(b) def rows_match(got, want): """the rows read back give the rows asked for: same number, and each asked row's values among the row read back""" if len(got) != len(want): return False, "%d rows, want %d" % (len(got), len(want)) for i, (g, w) in enumerate(zip(got, want)): for k, v in w.items(): if k not in g: return False, "row %d has no column %s" % (i + 1, k) # A source's textual identifiers retain their spelling: 001 is not 1. same = str(g[k]) == v if isinstance(v, str) else (g[k] in (None, "") if v is None else _same(g[k], v)) if not same: return False, "row %d: %s is %s, want %s" % (i + 1, k, g[k], v) return True, "%d rows, every value as asked" % len(want) def _page_rows_match(page, want): """Read visible table cells together; a city somewhere on a page cannot prove its order's city.""" candidates = [] for table in re.findall(r"]*>(.*?)", page, re.I | re.S): columns, rows = [], [] for line in re.findall(r"]*>(.*?)", table, re.I | re.S): heads = re.findall(r"]*>(.*?)", line, re.I | re.S) cells = re.findall(r"]*>(.*?)", line, re.I | re.S) clean = lambda value: html_unescape(re.sub(r"<[^>]+>", "", value)) if heads and not cells: columns = [clean(value) for value in heads] elif cells: if len(cells) != len(columns): return False, "the page has a row with different columns from its header" rows.append(dict(zip(columns, [clean(value) for value in cells]))) if not want or all(column in columns for column in want[0]): candidates.append(rows_match(rows, want)) return next((result for result in candidates if result[0]), candidates[0] if candidates else (False, "the page has no table with the requested columns")) # ---------------------------------------------------------------- judges: every requirement against what happened def _free_port(): s = socket.socket() s.bind(("127.0.0.1", 0)) p = s.getsockname()[1] s.close() return p def _db_rows(db, table="results"): if not db.exists(): return [] try: c = sqlite3.connect(str(db)) try: quoted = '"' + table.replace('"', '""') + '"' cols = [r[1] for r in c.execute("pragma table_info(%s)" % quoted)] return [dict(zip(cols, x)) for x in c.execute("select * from %s order by rowid" % quoted)] finally: c.close() except sqlite3.Error: return [] def _db_has_table(db, table="results"): if not db.is_file(): return False try: c = sqlite3.connect(str(db)) try: return c.execute("select 1 from sqlite_master where type='table' and name=?", (table,)).fetchone() is not None finally: c.close() except sqlite3.Error: return False def _read_file(path): if not path.is_file(): return None try: if path.suffix == ".json": v = json.loads(path.read_text(encoding="utf-8")) return v if isinstance(v, list) else [v] if path.suffix == ".csv": return list(csv.DictReader(path.read_text(encoding="utf-8").splitlines())) return [{"text": ln} for ln in path.read_text(encoding="utf-8").splitlines()] except (ValueError, OSError): return None def _judge_order(pipes, serve_names): """Run each command once, after the stored command it reads, with servers otherwise last.""" ordered, visiting, done = [], [], set() def visit(name): if name in done: return if name in visiting: cycle = visiting[visiting.index(name):] + [name] raise ValueError("stored command dependency cycle: " + " -> ".join(cycle)) if name not in pipes: raise ValueError("stored command dependency names an unknown provider: %s" % name) visiting.append(name) provider = pipes[name].get("from") if provider: visit(provider) visiting.pop() done.add(name) ordered.append(name) for name in [n for n in pipes if n not in serve_names] + list(serve_names): visit(name) return ordered def judge(root, shape, pipes, reqs, world, runenv=None): """each entry run as the request names it (batch entries first), every outcome read back, every requirement given its verdict. -> (passed, lines, holes); reqs carry their status and evidence""" root = Path(root) if runenv is None: # round-3 R2: the project's entries run in the run jail import runjail runenv = runjail.env(root=root) mod = shape["module"] st = settings(reqs) derived = shape.get("derived") or {} db = root / (Path(mod).stem + ".db") live = {r["id"]: r for r in reqs if r["status"] != "dropped"} seen = {} lines = [] names = list(pipes) excl_before = {r["file"]: ((root / r["file"]).stat().st_mtime if (root / r["file"]).is_file() else None) for r in live.values() if r["kind"] == "excluded" and r.get("file") and r["file"] != "*"} files_at_start = {p.name: p.stat().st_mtime for p in root.iterdir() if p.is_file()} db_before = db.is_file() serve_names = [n for n in names if "PORT" in shape["entries"][n]["args"]] try: run_names = _judge_order(pipes, serve_names) except ValueError as exc: message = str(exc) for requirement in live.values(): requirement["status"] = "failed" requirement["evidence"] = message return False, lines, [message] for n in run_names: p = pipes[n] pw = p.get("world") or world or {} if n in serve_names: port = _free_port() sp = subprocess.Popen([sys.executable, mod, n, str(port)], cwd=str(root), stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, env=runenv) page = None last_error = "" for _ in range(40): try: with urllib.request.urlopen("http://127.0.0.1:%d/" % port, timeout=5) as response: page = response.read().decode("utf-8", "replace") break except Exception as exc: # noqa: BLE001 last_error = str(exc) if sp.poll() is not None: break time.sleep(0.3) err = "" sp.terminate() try: _o, err = sp.communicate(timeout=5) except subprocess.TimeoutExpired: sp.kill() _o, err = sp.communicate(timeout=5) if page is None and not err: err = last_error seen[n] = {"page": page, "err": (err or "")[-300:]} lines.append("`python3 %s %s PORT` %s" % (mod, n, "served a page on loopback" if page is not None else "served no page: " + (err or "")[-160:])) continue table = p.get("store_table") or pipes.get(p.get("from"), {}).get("store_table") or "results" before = _db_rows(db, table) files_before = {r["file"]: (root / r["file"]).stat().st_mtime if (root / r["file"]).is_file() else None for r in live.values() if r["kind"] == "file" and r["entry"] == n} t0 = time.time() try: r = subprocess.run([sys.executable, mod, n], cwd=str(root), capture_output=True, text=True, env=runenv, timeout=60 + st["timeout"] * max(1, pw.get("n", 1))) rc, out = r.returncode, (r.stdout + r.stderr) except subprocess.TimeoutExpired: rc, out = None, "ran past its time" took = time.time() - t0 after = _db_rows(db, table) seen[n] = {"rc": rc, "out": out, "took": took, "before": before, "added": after[len(before):], "all": after, "table": table, "table_exists": _db_has_table(db, table), "files_before": files_before} lines.append("`python3 %s %s` ran in %.1f s, exit %s" % (mod, n, took, rc)) # each requirement for rid, r in live.items(): k = r["kind"] ev, ok = "", None p = pipes.get(r["entry"]) if r.get("entry") in pipes else None pw = (p.get("world") if p else None) or world or {} want_rows = None if k in ("stored", "file", "served", "printed") and p: try: if p["source"] == "table": want_rows = expected_rows(root, pw, view(p, rid), derived) elif p["source"] == "stored" and p.get("from") in pipes: producer = pipes[p["from"]] if producer["source"] == "table": stored_rid = next((item["id"] for item in live.values() if item["entry"] == p["from"] and item["kind"] == "stored"), None) stored_rows = list((seen.get(p["from"]) or {}).get("before", [])) + expected_rows( root, producer.get("world") or world, view(producer, stored_rid), derived) want_rows = expected_rows(root, pw, view(p, rid), derived, initial_rows=stored_rows) elif view(p, rid).get("ops"): want_rows = expected_rows(root, pw, view(p, rid), derived, initial_rows=(seen.get(p["from"]) or {}).get("all", [])) except (ValueError, KeyError, TypeError, OSError) as exc: r["status"], r["evidence"] = "failed", "the independent source judge could not resolve the input: %s" % exc continue if k == "context": ok, ev = True, "read" elif k in ("unread",): ok, ev = False, "not read" elif k == "excluded": # what the request rules out was not done w = r.get("what") if w == "file" and r["file"] == "*": # no file at all: nothing new or rewritten beside the program made = sorted(p.name for p in root.iterdir() if p.is_file() and p.name != mod and files_at_start.get(p.name) != p.stat().st_mtime) ok = not made ev = "no file written, as asked" if ok else "files written though the request ruled it out: %s" % \ ", ".join(made[:5]) elif w == "file": f = root / r["file"] now = f.stat().st_mtime if f.is_file() else None ok = now == excl_before.get(r["file"]) ev = "%s %s" % (r["file"], "not written, as asked" if ok else "was written, though the request ruled it out") elif w == "stored": ok = db_before or not db.is_file() ev = "no database made, as asked" if ok else "%s was made, though the request ruled out a database" % db.name elif w == "served": ok = not serve_names ev = "no page served, as asked" if ok else "a page is served, though the request ruled it out" else: outs = [x.get("out", "") for x in seen.values() if "out" in x] ok = not any((o or "").strip() for o in outs) ev = "nothing printed, as asked" if ok else "lines were printed, though the request ruled it out" elif k == "stored": s = seen.get(r["entry"]) or {} got = len(s.get("added", [])) if want_rows is not None: match, details = rows_match(s.get("all", []), s.get("before", []) + want_rows) ok = s.get("rc") == 0 and s.get("table_exists", False) and match ev = "%s, table %s: %s; %d new rows" % (db.name, s.get("table", "results"), details, got) else: want = pw.get("n", 0) if p and p["source"] == "probe" else None ok = s.get("rc") == 0 and got > 0 and (want is None or got == want) ev = "%d rows kept in %s by one run (want %s)" % (got, db.name, want) elif k == "file": s = seen.get(r["entry"]) or {} path = root / r["file"] rows = _read_file(path) fresh = path.is_file() and path.stat().st_mtime != (s.get("files_before") or {}).get(r["file"]) if rows is None or not fresh or s.get("rc") != 0: ok, ev = False, "%s was not written by `%s`" % (r["file"], r["entry"]) elif want_rows is not None: expected = s.get("before", []) + want_rows if r.get("every") and any( item["kind"] == "stored" and item["entry"] == r["entry"] for item in live.values()) else want_rows ok, ev = rows_match(rows, expected) ev = "%s: %s" % (r["file"], ev) elif r.get("every"): ok = len(rows) == len(s.get("all", [])) and len(rows) > 0 ev = "%s holds %d rows; the database holds %d" % (r["file"], len(rows), len(s.get("all", []))) else: want = pw.get("n", 0) ok = len(rows) == want ev = "%s holds %d rows (want %d)" % (r["file"], len(rows), want) elif k == "served": s = seen.get(r["entry"]) or {} page = s.get("page") if page is None: ok, ev = False, "no page: %s" % s.get("err", "") elif not judge_look(page, {})[0]: ok, ev = False, "the page is not made from the design family's tokens: " + judge_look(page, {})[1] elif want_rows is not None: want = want_rows ok, ev = _page_rows_match(page, want) ev = "the page: " + ev mR = re.search(r"const R = (\[.*?\]), N = R\.length", page, re.S) if mR: # C12: the scene's objects are the records asked, with their values try: got_r = json.loads(mR.group(1).replace("<\\/", "= 400 and x.get("status") != "down"] return bool(added) and not bad, "%d rows; an error status recorded as down for every one (%d not)" % (len(added), len(bad)) if k == "ms": nums = [x.get("ms") for x in added if x.get("status") == "up"] kept = bool(nums) and all(isinstance(v, (int, float)) for v in nums) shown = not pages or all(any(str(v) in pg for v in nums) for pg in pages) return kept and shown, "milliseconds kept for %d up rows: %s; shown on the page: %s" % (len(nums), kept, shown) if k == "timestamp": rows = added or [x for s in seen.values() for x in s.get("added", [])] return bool(rows) and all(x.get("at") for x in rows), "every kept row has its time: %s" % bool(rows) if k == "keep_last": ok = all(("previous" in pg or "result 2" in pg) for pg in pages) if pages else True return ok, "the page has a column for each of the last %d results: %s" % (r["n"], ok) return None, "" # ---------------------------------------------------------------- the ledger, kept with the project def ledger_lines(reqs): out = [] for r in reqs: if r["kind"] == "context": continue if r.get("merged_into"): out.append("%s the same outcome as %s (\"%s\")" % (r["id"], r["merged_into"], r["from"][0][:80])) continue what = {"file": "writes %s" % r.get("file"), "stored": "keeps rows in a database", "served": "a page in the browser", "printed": "prints the rows", "op": _op_text(r["op"]) if r.get("op") else "", "derive": "%s made from %s" % ( r.get("name"), r.get("col")), "timeout": "no answer within %g s is down" % r.get("seconds", 0), "error_down": "an error status is down", "ms": "time to answer in milliseconds", "timestamp": "each row with its time", "keep_last": "the last %d results shown" % r.get("n", 1), "unread": "words not read: %s" % ", ".join(r.get("words", [])), "interaction": "record edits and relationships through the page", "look": "the look asked: %s" % ", ".join(r.get("words", [])), "excluded": "not done, as asked: %s" % {"file": ("no file written" if r.get("file") == "*" else "no %s written" % r.get("file")), "stored": "no database", "served": "no page", "printed": "nothing printed"}.get( r.get("what"), r.get("what"))}.get(r["kind"], r["kind"]) if r.get("superseded"): what += " (was %s)" % ", ".join("%s %s" % (k, v) for old in r["superseded"] for k, v in old.items()) if r.get("out"): what += " (for %s only)" % r["out"] if r.get("dropped_with"): what += " (went with %s)" % r["dropped_with"] out.append("%s %s%s - %s%s" % (r["id"], what, (" (`%s`)" % r["entry"]) if r.get("entry") not in (None, "*") else "", r["status"], (": " + r["evidence"]) if r.get("evidence") else "")) return out # ---------------------------------------------------------------- the look: Oracle7's design family (workbench/design) _DESIGN = {} def _design(): if not _DESIGN: import importlib.util d = Path(__file__).resolve().parent / "design" for n in ("palette", "type", "layout", "motion", "scene"): spec = importlib.util.spec_from_file_location("o7design_" + n, str(d / ("organ_%s.py" % n))) m = importlib.util.module_from_spec(spec) spec.loader.exec_module(m) _DESIGN[n] = m return _DESIGN def read_look(sentence): """the look a sentence asks of its page: a colour (a W3C colour name or a hex), tone words, dark. None when it asks none""" D = _design() low = sentence.lower() words = re.findall(r"[a-z]+", DATA.sub(" ", low)) seed = next((w for w in words if w in D["palette"].NAMES and w not in ("white", "black")), None) m = re.search(r"#[0-9a-f]{6}\b", low) if m: seed = m.group(0) tones = [w for w in words if w in D["type"].TONES] dark = bool(re.search(r"\bdark\b", low)) scene = None if re.search(r"\b3-?d\b|\bthree[- ]?d(?:imensional)?\b|\bthree\.?js\b|\bin three dimensions\b|\bscene\b", low): sw_ = getattr(D["scene"], "SHAPE_WORDS", {g: (g,) for g in D["scene"].GEOM}) hit = next(((g, w) for w in words for g, names in sw_.items() if any(wmatch(w, n) for n in names)), None) shape, shape_word = hit if hit else ("box", None) scene = {"shape": shape, "camera": "static" if re.search(r"\bstill\b|\bstatic\b", low) else "orbit", "light": next((w for w in words if w in D["scene"].RIGS), "daylight")} if not (seed or tones or dark or scene): return None sw = ([w for w in words if w in ("scene", "three", "dimensions", "dimensional", "camera", "orbit", "orbiting", "still", "static", scene["light"]) or wmatch(w, scene["shape"]) or (shape_word and wmatch(w, shape_word))] + (["3d"] if re.search(r"\b3-?d\b", low) else []) if scene else []) return {"seed": seed, "tone": tones, "dark": dark, "scene": scene, "words": [w for w in [seed] + tones + (["dark"] if dark else []) if w] + sw} def design_for(looks): """the design family's answer for a project's pages: palette, type, layout and motion, each from its specialist""" D = _design() seed = next((l["seed"] for l in looks if l.get("seed")), None) or "slategray" tones = [t for l in looks for t in l.get("tone", [])] or ["clean"] dark = any(l.get("dark") for l in looks) pal = D["palette"].ask({"seed": seed, "modes": ["dark"] if dark else ["light", "dark"], "series": 0}) typ = D["type"].ask({"tone": tones, "use": "site"}) if typ.get("status") != "answered": typ = D["type"].ask({"tone": ["clean"], "use": "site"}) lay = D["layout"].ask({"sections": ["table"], "widths": [375, 768, 1440], "body_size": typ.get("body_size", 18)}) mot = D["motion"].ask({"changes": ["enter", "hover"], "tone": "calm" if "calm" in tones or "quiet" in tones else ""}) cat = D["type"].catalogue() gen = lambda fam: "serif" if (cat.get(fam) or {}).get("category") in ("Serif", "Display") else "sans-serif" sc = next((l["scene"] for l in looks if l.get("scene")), None) stage = None if sc: # the scene specialist: one object per row, on the palette's colours lp = D["palette"].ask({"seed": seed, "modes": ["light"], "series": 2})["modes"]["light"] stage = D["scene"].stage(sc["shape"], sc["light"], sc["camera"], lp) return {"seed": seed, "tone": tones, "dark_only": dark, "palette": pal, "type": typ, "layout": lay, "motion": mot, "generic": {"display": gen(typ.get("display")), "body": gen(typ.get("body"))}, "scene": sc, "stage": list(stage) if stage else None} def design_head(dz): """the and ", "not asked" modes = dz["palette"]["modes"] t, lay, mot = dz["type"], dz["layout"], dz["motion"] def vars_(m): return ";".join("--%s:%s" % (k, m[k]) for k in ("background", "foreground", "muted", "border", "primary", "accent")) first = modes.get("light") or modes.get("dark") css = [":root{%s;--font-display:'%s',%s;--font-body:'%s',%s}" % (vars_(first), t["display"], dz["generic"]["display"], t["body"], dz["generic"]["body"])] if "light" in modes and "dark" in modes: css.append("@media (prefers-color-scheme: dark){:root{%s}}" % vars_(modes["dark"])) sz = t["sizes"] g = lay["grids"] wide = g[max(g, key=int)] css += ["*{box-sizing:border-box}", "body{margin:0;background:var(--background);color:var(--foreground);font:400 %dpx/%s var(--font-body)}" % ( t["body_size"], t["line_height"]), "main{max-width:%dpx;margin:0 auto;padding:%dpx %dpx}" % (lay["max_width"], g["375"]["margin"] * 2, g["375"]["margin"]), "@media (min-width:600px){main{padding:%dpx %dpx}}" % (g["768"]["margin"] * 2, g["768"]["margin"]), "@media (min-width:1024px){main{padding:%dpx %dpx}}" % (wide["margin"] and 64, 32), "h1{font:%d %dpx/%s var(--font-display);margin:0 0 %dpx;color:var(--foreground)}" % ( t["weights"]["display"][0], sz[min(4, len(sz) - 1)], t["display_line_height"], sz[1]), "table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}", "th{text-align:left;color:var(--muted);font-weight:%d;border-bottom:2px solid var(--border);padding:12px 16px}" % ( t["weights"]["body"][-1]), "td{border-bottom:1px solid var(--border);padding:12px 16px;vertical-align:top}", "a{color:var(--primary)}", ".up{box-shadow:inset 4px 0 0 var(--primary)}.down{box-shadow:inset 4px 0 0 var(--accent)}", "td{transition:filter %dms %s}tr:hover td{filter:brightness(0.96)}" % ( mot["kinds"]["hover"]["duration_ms"], mot["kinds"]["hover"]["easing"]), "main{animation:o7in %dms %s both}@keyframes o7in{from{opacity:0;transform:translateY(8px)}to{opacity:1;" "transform:none}}" % (mot["kinds"]["enter"]["duration_ms"], mot["kinds"]["enter"]["easing"]), mot["reduced_motion"]["css"]] fam = lambda f, ws: "family=%s:wght@%s" % (f.replace(" ", "+"), ";".join(str(w) for w in sorted(set(ws)))) link = ('' % (fam(t["display"], t["weights"]["display"]), fam(t["body"], t["weights"]["body"]))) why = "palette from %s (%s), type %s / %s at %d px on a %s scale, %d px content, motion %d/%d ms with reduced motion" % ( dz["seed"], "dark" if dz["dark_only"] else "light and dark", t["display"], t["body"], t["body_size"], t["ratio"], lay["max_width"], mot["kinds"]["enter"]["duration_ms"], mot["kinds"]["hover"]["duration_ms"]) if dz.get("stage"): css.append(dz["stage"][0]) why += "; a three.js scene of one %s per row (%s light, %s camera)" % (dz["scene"]["shape"], dz["scene"]["light"], dz["scene"]["camera"]) return link + "", why def _lum(h): def lin(c): c = c / 255.0 return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 r, g, b = [lin(int(h[i:i + 2], 16)) for i in (1, 3, 5)] return 0.2126 * r + 0.7152 * g + 0.0722 * b def judge_look(page, req): """the page's own tokens read back: text on its background at 7:1 or more in every mode it declares, its fonts named, a phone's margin, the reduced-motion rule; and what the request asked of the look (its colour's hue, dark)""" if not page: return False, "no page" blocks = re.findall(r"--background:(#[0-9a-f]{6});--foreground:(#[0-9a-f]{6})", page) if not blocks: return False, "no colour tokens" cs = [(max(_lum(f), _lum(b)) + 0.05) / (min(_lum(f), _lum(b)) + 0.05) for b, f in blocks] why = ["text contrast %s" % ", ".join("%.1f" % c for c in cs)] ok = all(c >= 7 for c in cs) fonts = re.findall(r"--font-(?:display|body):'([^']+)'", page) ok &= len(fonts) == 2 why.append("fonts %s" % " / ".join(fonts)) ok &= "prefers-reduced-motion" in page m = re.search(r"main\{max-width:\d+px;margin:0 auto;padding:\d+px (\d+)px\}", page) ok &= bool(m) and int(m.group(1)) >= 16 why.append("phone margin %s px" % (m.group(1) if m else "?")) if req.get("seed"): D = _design() prim = re.search(r"--primary:(#[0-9a-f]{6})", page) seedhex = D["palette"].NAMES.get(req["seed"], req["seed"]) if not req["seed"].startswith("#") else req["seed"] _L, C, H = D["palette"].lch_of(seedhex) if prim and C > 0.02: ph = D["palette"].lch_of(prim.group(1))[2] d = min(abs(ph - H) % 360, 360 - abs(ph - H) % 360) ok &= d <= 20 why.append("primary %s, %.0f degrees from %s" % (prim.group(1), d, req["seed"])) if req.get("scene"): # C12: the scene is bound to the page's records - the record payload's ids are the table rows' ids, in order mR = re.search(r"const R = (\[.*?\]), N = R\.length", page, re.S) try: recs = json.loads(mR.group(1).replace("<\\/", "', page)] rows = len(tr_ids) n = re.match(r"(\d+)", str(len(recs))) if recs is not None else None three = re.search(r"three@\d+\.\d+\.\d+", page) bound = recs is not None and [str(x.get("id")) for x in recs] == tr_ids okc = bool(recs is not None and three and 'id="stage"' in page and len(recs) == rows and bound) # the shape asked is the geometry drawn (spheres asked: SphereGeometry in the stage), not only a stage want_geo = re.search(r"new THREE\.(\w+Geometry)", _design()["scene"].GEOM.get(req["scene"].get("shape"), "") or "") geo_ok = bool(want_geo) and ("new THREE.%s(" % want_geo.group(1)) in page okc &= geo_ok # the stage's script is run through a JavaScript engine where the box has one (node --check: it parses); # where none is installed the evidence says the script was not run - it is not counted as checked js = "\n".join(re.findall(r"", page, re.S)) ran = _js_parses(js) if js else None if ran is False: okc = False ok &= okc why.append("a three.js scene of %s objects for %d rows%s%s; %s drawn (%s asked)%s; script %s" % ( n.group(1) if n else "no", rows, "" if three else ", three.js not pinned", ", each bound to its row's id" if bound else ", objects NOT bound to the table's rows", want_geo.group(1) if geo_ok else "not the shape", req["scene"].get("shape"), "", {True: "parses (node --check)", False: "does not parse (node --check)", None: "not run: no JavaScript engine on this box"}[ran])) if req.get("dark"): Lb = _design()["palette"].lch_of(blocks[0][0])[0] ok &= Lb < 0.3 why.append("dark background L %.2f" % Lb) return bool(ok), "; ".join(why) def _js_parses(js): """True / False when a JavaScript engine (node) is on this box and the module script parses or not; None without one""" import shutil import tempfile node = shutil.which("node") or shutil.which("nodejs") if not node: return None with tempfile.NamedTemporaryFile("w", suffix=".mjs", delete=False, encoding="utf-8") as f: f.write(js) path = f.name try: return subprocess.run([node, "--check", path], capture_output=True, timeout=30).returncode == 0 except Exception: # noqa: BLE001 return None finally: os.unlink(path) def save_project(root, shape): d = Path(root) / ".oracle7" d.mkdir(exist_ok=True) (d / "project.json").write_text(json.dumps(shape, indent=1, default=str), encoding="utf-8") def load_project(root): p = Path(root) / ".oracle7" / "project.json" if p.is_file(): try: return json.loads(p.read_text(encoding="utf-8")) except ValueError: return None return None def derive_goal(h, shape): """a value made from a column, as a goal for the code composer: its examples from the turn that gave them""" exs = [((a,), b, None) for a, b in h["examples"]] return {"name": h["fn"], "params": [h["col"]], "module": Path(shape["module"] or "project.py").stem, "examples": exs, "module_text": ""} def sha_of(name, src): return hashlib.sha256((name + "\n" + src).encode()).hexdigest() def compose_holes(root, shape, holes, net_scope=()): """the values made from a column that now have examples: each composed by Oracle7's code composer (its search over typed moves, its read-back in a separate interpreter), the result going back into the plan under its sha. -> lines""" todo = [h for h in holes if h["kind"] == "compose"] if not todo: return [] sys.path.insert(0, str(Path(__file__).resolve().parent)) import compose_code as CC out = [] for h in todo: goal = derive_goal(h, shape) words = " ".join([shape.get("example_words", ""), h["name"], h["col"]] + [c for c in shape["clauses"]]) res = CC.run_job(str(root), [goal], words=words, net_scope=list(net_scope)) if res.get("stopped") and sys.modules.get("continuation") is not None: raise sys.modules["continuation"].Stopped("composing (%s)" % res["error"]) # C14: the examples stay kept r = (res.get("results") or [{}])[0] if "error" not in res else {"status": "error", "gap": res.get("error")} if r.get("status") == "composed": deps = [] for s in r.get("support") or []: m = re.search(r"(?m)^def (\w+)\(", s) if m: deps.append({"name": m.group(1), "source": s, "sha256": sha_of(m.group(1), s)}) shape.setdefault("derived", {})[h["fn"]] = { "name": h["name"], "col": h["col"], "fn": h["fn"], "source": r["source"], "sha256": sha_of(h["fn"], r["source"]), "imports": sorted(set(r.get("imports") or []) | set(r.get("support_imports") or [])), "deps": deps, "from": "composed", "r": r, "goal": {"name": goal["name"], "params": goal["params"], "examples": [[list(a), o] for a, o, _t in goal["examples"]]}} out.append("%s made from %s: composed from your %d examples - `%s` (read back by a separate interpreter: %s)" % ( h["name"], h["col"], len(h["examples"]), r["source"].strip().splitlines()[-1].strip(), r.get("read_back"))) else: shape["examples"].pop(h["fn"], None) # the next examples start afresh out.append("%s made from %s: not composed - %s" % (h["name"], h["col"], (r.get("gap") or "")[:300])) return out def keep_derived(root, shape): """the values composed for this project, kept in Oracle7's store once the project's judges passed with them (the law decides, not the composer): -> the kept records""" sys.path.insert(0, str(Path(__file__).resolve().parent)) import code_store as CS added = [] for fn, d in (shape.get("derived") or {}).items(): if d.get("from") != "composed" or d.get("kept"): continue g = dict(d["goal"]) e = CS.entry_for(d["r"], g, "%s (%s)" % (shape.get("module"), Path(root).name), []) got = CS.keep([e]) if e else [] if e: d["kept"] = e["id"] added += got or [e] return added def is_project(text, kept, root=None): """a project request: a build verb, and an entry command, a table of the project or an outcome someone can see; not a request about tests or one function. Or a turn that continues or changes the project kept""" t = text.strip() other = re.search(r"(?i)\btests?\b|\bfunction\b|\bclass\b|\bdef\b|\bfix\b|\brepair\b|\bbug\b|\.py\b", t) and not ENTRY.search(t) if re.search(r"(?i)\b(?:in)?to\s+(?:yourself|oracle7)\b|^\s*(?:please\s+)?(?:build|add|make|give)\s+(?:yourself|oracle7)\s*[:,-]", t): return False # a feature of Oracle7 itself: selfdev's project route (C10) if re.match(r"(?i)^\s*make\s+[\w-]+\s*:", t): return False # the make command's own form: `make name: steps` if kept and not other: if _interaction_request(t): return True if re.match(r"(?i)^\s*(?:also|and also|now also|change it so|make it also|add|plus|then also)\b", t): return True if DROP.match(t) or DROP_WORD.match(t) or CONTINUE.match(t): return True if REVISE.search(t) or re.match(r"(?i)^\s*(?:(?:actually|wait|rather)\b|no\s*,)", t): return True # a revision of the project kept ("actually, make it above 25") if kept.get("status") == "blocked": if any(h.get("kind") == "scope" for h in kept.get("holes_kept", [])) and ( ENTRY.fullmatch(t) or any(re.fullmatch(r"(?i)(?:the\s+)?`?" + re.escape(n) + r"`?(?:\s+command)?[.!]?", t) for n in kept.get("entries", {}))): return True if EXAMPLE.search(t) or MEANS.search(t) or re.search(r"(?i)\buse\s+(?:it|that)\b", t): return True if any(h.get("kind") == "source" for h in kept.get("holes_kept", [])) and \ re.match(r"(?i)^\s*(?:match(?:ing|ed)?\s+(?:on|by)\s+|on\s+)[a-z_]", t): return True if other: return False if not BUILD.search(t): return False if ENTRY.search(t): return True has_table = bool(DATA.search(t)) outcome = bool(_interaction_request(t) or SINK_FILE.search(t) or SINK_OBJ.search(t) or STORED.search(t) or re.search(r"(?i)\b(?:browser|web ?page|website|dashboard)\b", t) or PRINTED.search(t)) return has_table and outcome