File size: 14,579 Bytes
d9b105f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | """resolve - a request in any wording read as one of the bench's operations, by Oracle7's own word meanings (12.0 Amendment 16).
The bench knows its operations by a few shapes of sentence. A request worded another way ("can you put back what you just
changed", "is anything broken", "pull up calc.py") is read here: its content words are compared, by the word meanings
Oracle7 derived from its own corpus with no training (converse/data/ladder/wordvec.npz), with the words that describe each
operation; the operation it reads is the one that clearly wins (a floor and a margin over the next). The things the request
names are bound from the open environment: a file or function of the project, a quoted text.
The field proposes, the law sanctions: an operation that only reads is done, and the reply says how the request was read; an
operation that changes or runs anything is offered, and done only on go. Nothing is read when no operation clearly wins: the
reply names the two nearest and asks. No language model."""
import os
import re
from pathlib import Path
WB = Path(__file__).resolve().parent
OPS = [ # name, the words that describe it, changes anything, the bench sentence it becomes ({file}, {text})
("status", "where status progress state standing going done finished overview summary update", False, "where are we"),
("log", "fail failed failure error errors wrong broke broken crash crashed log output traceback problem", False, "what failed"),
("diff", "change changed changes diff difference modified edits edited altered", False, "what changed"),
("read", "show read open view display see look contents print file", False, "read {file}"),
("grep", "find search locate grep where mentions occurrences usage used", False, "grep {text}"),
("ls", "list files folder directory contents inventory", False, "ls"),
("tasks", "tasks todo remaining left outstanding pending list", False, "tasks"),
("tests", "test tests testing suite verify verification check checks pass", True, "run the tests"),
("undo", "undo revert reverse rollback restore cancel back", True, "undo"),
("again", "again rerun repeat retry", True, "run it again"),
("audit", "audit security harden hardening vulnerabilities secure exposure", False, "audit the {text} config"),
]
STOP = set("""a an the it its this that these those i you we me my your our us please can could would will should shall
do does did is are was were be been to of in on for and or but with by from as at just now then so what how any all some
there here up out about into over once more yes no ok okay hey oracle oracle7 thing things stuff something
anything everything nothing anyone everyone someone noone anybody everybody somebody nobody""".split())
# the indefinite pronouns as a class (the list held "something" but not its siblings: Amendment 17)
_V = {}
def vectors():
if "V" not in _V:
import numpy as np
w = np.load(WB / "converse" / "data" / "ladder" / "wordvec.npz", allow_pickle=True)
V = w["vec"].astype("float32")
V /= (np.linalg.norm(V, axis=1, keepdims=True) + 1e-9)
_V["V"], _V["ix"] = V, {x: i for i, x in enumerate(w["words"])}
_V["np"] = np
return _V
def _ops_matrix():
if "O" not in _V:
D = vectors()
_V["O"] = [[D["V"][D["ix"][w]] for w in desc.split() if w in D["ix"]] for _n, desc, _c, _s in OPS]
return _V["O"]
def content(text):
"""the request's content words; a compound written apart whose joined form is a word of an operation ("to do" -> todo,
"roll back" -> rollback) is read joined (Amendment 19)"""
allw = set().union(*(set(d.split()) for _n, d, _c, _s in OPS))
raw, out, i = re.findall(r"[a-z]+", text.lower()), [], 0
while i < len(raw):
if i + 1 < len(raw) and raw[i] + raw[i + 1] in allw:
out.append(raw[i] + raw[i + 1])
i += 2
continue
out.append(raw[i])
i += 1
return [w for w in out if w not in STOP and len(w) > 1]
INFO = {"status", "log", "diff", "tasks"} # a question about the state of the work: only a question asks it
QUESTION = re.compile(r"(?i)^\s*(?:(?:so|and|ok(?:ay)?|hey|well)[\s,]+)*(?:whats|wheres|hows|whys|what|where|how|which|why|is|are|was|were|did|does|do|"
r"has|have|any|anything|show|tell|give|let me see|list)\b|\?\s*$")
def score(text, drop=()):
"""each operation's score: the request's strongest word for it (an exact word of the operation counts fully), with the
share of the request's words that fit it at all (coverage); the words that name things in the project are left out"""
D = vectors()
np = D["np"]
allw = set().union(*(set(d.split()) for _n, d, _c, _s in OPS))
ws = [w for w in content(text) if (w in D["ix"] or w in allw) and w not in drop] # an operation's own word counts
out = [] # even where no meaning is held for it
for (name, desc, changes, sent), M in zip(OPS, _ops_matrix()):
own = set(desc.split())
sims = []
for w in ws:
sims.append(1.0 if w in own else float(np.max(np.stack(M) @ D["V"][D["ix"][w]])) if (M and w in D["ix"]) else 0.0)
top = max(sims) if sims else 0.0
cover = (sum(1 for s in sims if s >= 0.45) / len(sims)) if sims else 0.0
out.append((top, name, changes, sent, cover))
out.sort(key=lambda x: -x[0])
return out
_TURN = {} # 12.5 step 9: the turn's own binding, read once (cleared each turn)
def new_turn():
"""called by the one exit's turn start: what a turn bound is never carried into the next"""
_TURN.clear()
def bind(text, env):
"""what the request names in the environment, read once per turn (12.5 step 9, design 4.C): the walk of the folder and
the reading of its functions are costly, and four readers of one turn asked for the same binding"""
key = (text, getattr(env, "kind", None), str(getattr(env, "root", "")), getattr(env, "host", None))
import time as _time
hit = _TURN.get(key)
if hit is None or _time.time() - hit[0] > 5.0: # outside a chat turn nothing clears it: an entry lives 5 s at most
hit = _TURN[key] = (_time.time(), _bind(text, env))
b = hit[1]
return {"file": b["file"], "function": b["function"], "quoted": b["quoted"]}
def _bind(text, env):
"""what the request names in the environment: a file (by name or stem), a function defined there, a quoted text"""
q = re.findall(r"[`\"']([^`\"']{1,120})[`\"']", text)
f, fn = None, None
if env is not None and env.kind == "folder":
names = {}
for p in env.walk(limit=20000):
names.setdefault(os.path.basename(p).lower(), p)
for tok in re.findall(r"[\w./-]+", text):
t = tok.lower().strip("./")
if t in names:
f = names[t]
break
for cand in (t + ".py", t + ".js", t + ".md", t + ".txt"):
if cand in names and t not in STOP:
f = names[cand]
break
if f:
break
defs = set()
for p in list(names.values())[:400]:
if p.endswith(".py"):
try:
defs |= set(re.findall(r"(?m)^\s*def\s+(\w+)", open(p, encoding="utf-8", errors="ignore").read()))
except Exception: # noqa: BLE001
pass
fn = next((w for w in re.findall(r"\w+", text) if w in defs), None)
return {"file": f, "function": fn, "quoted": q[0] if q else None}
def _wordings_path():
base = Path(os.environ.get("ORACLE7_BENCH_HOME") or (Path(os.environ.get("ORACLE7_STATE") or Path.home() / ".oracle7") / "bench"))
return base / "wordings.json"
def frame(text, drop=()):
"""a wording's frame: its content words, without the things it names, in order of first use ("pull up X" -> pull)"""
return [w for w in dict.fromkeys(content(text)) if w not in drop]
def learned(text, drop=()):
"""12.0 C29 (receive): the operation a wording with this frame was confirmed to mean, or None"""
f = frame(text, drop)
if not f:
return None
try:
import json
kept = json.loads(_wordings_path().read_text(encoding="utf-8"))
except Exception: # noqa: BLE001
return None
hit = kept.get(" ".join(f))
return hit.get("op") if isinstance(hit, dict) else None
def learn(text, op, env=None):
"""keep what an operator confirmed: this wording's frame means this operation (said once, sure after)"""
b = bind(text, env) if env is not None else {"file": None, "function": None, "quoted": None}
drop = set()
for x in (b.get("file"), b.get("function")):
if x:
stem = os.path.splitext(os.path.basename(x))[0].lower()
drop |= {stem} | set(re.findall(r"[a-z]+", stem))
if b.get("quoted"):
drop |= set(re.findall(r"[a-z]+", b["quoted"].lower()))
drop |= {"py", "js", "md", "txt"}
f = frame(text, drop)
if not f or len(f) > 4 or op not in {n for n, _d, _c, _s in OPS}:
return False # a long or empty frame is not a wording; only known operations
import json
p = _wordings_path()
try:
kept = json.loads(p.read_text(encoding="utf-8"))
except Exception: # noqa: BLE001
kept = {}
import time as _t
kept[" ".join(f)] = {"op": op, "from": text[:200], "t": _t.time()}
p.parent.mkdir(parents=True, exist_ok=True)
tmp = p.with_suffix(".tmp")
tmp.write_text(json.dumps(kept, indent=1), encoding="utf-8")
os.replace(tmp, p)
return True
FLOOR, MARGIN, COVER, NEAR = 0.6, 0.08, 0.5, 0.45
USES = 0.1 # a reading that uses what the request names (Amendment 17)
MAX_WORDS = 12 # a long turn is an instruction or a thought, not one operation
# 12.5 C34: polarity. "do not show poem.txt" read as "read poem.txt" because "do" is a stop word and "not" means no
# operation; the negator was dropped and the reading inverted. A told (not asked) turn whose clause carries a negator asks
# that the operation not be done: it is no reading to carry out. A negated question ("isn't anything broken?") still asks.
NEGATOR = re.compile(r"(?i)\b(?:not|never|don'?t|dont|doesn'?t|mustn'?t|shouldn'?t|won'?t|no\s+need\s+to)\b|n't\b")
def negated(text):
"""True when the turn tells, in a negated clause, rather than asks"""
if text.strip().endswith("?") or re.match(r"(?i)\s*(?:what|where|how|which|why|who|when|whats|wheres|is|are|was|were|"
r"did|does|has|have|isn'?t|aren'?t|wasn'?t|didn'?t|hasn'?t|haven'?t)\b", text):
return False # a question, even a negated one, asks
return any(NEGATOR.search(c) for c in re.split(r"[.;!?]|\bbut\b|\bthen\b", text) if c.strip())
def resolve(text, env, near_ok=False):
"""-> (bench sentence, operation, changes, sure) ; sure False means the nearest reading, to be offered, not done.
(None, None, None, the nearest two) when nothing is close enough."""
if len(re.findall(r"\w+", text)) > MAX_WORDS or negated(text):
return None, None, None, []
b = bind(text, env)
drop = set()
for x in (b["file"], b["function"]):
if x:
stem = os.path.splitext(os.path.basename(x))[0].lower()
drop |= {stem} | set(re.findall(r"[a-z]+", stem))
if b["quoted"]:
drop |= set(re.findall(r"[a-z]+", b["quoted"].lower()))
drop |= {"py", "js", "md", "txt"}
n_content = len([w for w in content(text) if w not in drop])
sc = [x for x in score(text, drop) if not (x[1] in INFO and not QUESTION.search(text))
and not (x[1] == "again" and (n_content > 3 or QUESTION.search(text)))] # "again" as an adverb asks no rerun
# what the request names binds its reading (Amendment 17): a reading whose sentence needs a thing the request does not
# name cannot be the reading; one that uses what the request names outranks one that leaves it unused, by USES
named_text = bool(b["quoted"] or b["function"])
def _fits(x):
sent_ = x[3]
if "{file}" in sent_ and not b["file"]:
return False
if "{text}" in sent_ and x[1] != "audit" and not named_text:
return False
return True
def _uses(x):
sent_ = x[3]
return ("{file}" in sent_ and b["file"]) or ("{text}" in sent_ and x[1] != "audit" and named_text)
sc = sorted(((x[0] + (USES if _uses(x) else 0.0),) + tuple(x[1:]) for x in sc if _fits(x)), key=lambda x: -x[0])
was = learned(text, drop) # C29: a wording the operator confirmed before is that reading, sure
if was:
for name_, _d, changes_, sent_ in OPS:
x = (2.0, name_, changes_, sent_, 1.0)
if name_ == was and _fits(x):
sc = [x] + [y for y in sc if y[1] != name_]
break
if (not sc or sc[0][0] < NEAR) and (b["file"] or b["function"]) and near_ok:
# Amendment 18: the words decide nothing, but the request names a thing that exists in the project; the reading falls
# to the operation that takes that thing, offered (never done) so the operator confirms or rewords
for name, _d, changes, sent in OPS:
if (b["file"] and "{file}" in sent) or (not b["file"] and b["function"] and "{text}" in sent and name != "audit"):
sent = sent.replace("{file}", env.rel(b["file"]) if b["file"] else "").replace("{text}", b["function"] or "")
return sent, name, changes, False
if not sc or sc[0][0] < NEAR:
return None, None, None, sc[:2]
s, name, changes, sent, cover = sc[0]
sure = s >= FLOOR and (len(sc) < 2 or s - sc[1][0] >= MARGIN) and cover >= COVER
if not sure and not near_ok:
return None, None, None, sc[:2]
if "{file}" in sent:
if not b["file"]:
return None, None, None, sc[:2]
sent = sent.replace("{file}", env.rel(b["file"]))
if "{text}" in sent:
t = b["quoted"] or b["function"]
if name == "audit":
t = next((w for w in ("ssh", "nginx", "ports", "logs") if w in text.lower()), None)
if not t:
return None, None, None, sc[:2]
sent = sent.replace("{text}", t)
return sent, name, changes, sure
|