Spaces:
Running
Running
github-actions[bot] commited on
Commit Β·
a656c82
1
Parent(s): 6541060
Deploy a5aede1
Browse filesMerge pull request #330 from WINTER4000/claude/structures-complexes
Source: https://github.com/WINTER4000/turingDNA/commit/a5aede159341d54e6c0cd02f26d9864a2927ccbb
Files changed (9)
- dee/core/agent_tools.py+145-3
- dee/core/analysis.pyAdded+242
- dee/core/capabilities.py+7-1
- dee/core/orchestrator.py+386-6
- tests/test_analysis.pyAdded+255
- tests/test_claim_audit.pyAdded+197
- tests/test_collect_job.pyAdded+189
- tests/test_confirm_gate.py+8
- tests/test_tool_catalog_cost.pyAdded+125
2003 unmodified lines20042005200620072008200920102011201217 unmodified lines2030203120322033203420351472 unmodified lines350835093510351135123513153 unmodified lines3667366836693670367136722003 unmodified lines"error": (f"NCBI BLAST is still running after "f"{job.elapsed():.0f}s β its queue is shared and can "f"take several minutes."),"next": ("Tell the user it is still running and carry on with ""something else, or ask them to try again shortly. ""Never invent hits while waiting.")}hits = job.hitsif not hits:17 unmodified lines}def _tool_simulate_assembly(args: Dict[str, Any]) -> Dict[str, Any]:"""Actually assemble the fragments β Gibson, Golden Gate or restriction.1472 unmodified lines# someone's unpublished construct to NCBI on their behalf."blast_sequence": {"fn": _tool_blast_sequence, "requires_signin": False,"requires_confirm": True},# The only tool that changes the construct. Three flags, each earning its# place: signed-in because it writes; confirm because the user must agree# to their own DNA being altered; needs_target because the sequence comes153 unmodified lines},},},{"type": "function","function": {2003 unmodified lines2004200520062007200820092010201120122013201417 unmodified lines2032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921301472 unmodified lines3603360436053606360736083609361036113612153 unmodified lines37663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338142003 unmodified lines"error": (f"NCBI BLAST is still running after "f"{job.elapsed():.0f}s β its queue is shared and can "f"take several minutes."),"next": ("Tell the user it is still running and carry on ""with something else. Come back for it with ""collect_job using this job_id β do NOT call ""blast_sequence again, and do not re-send the ""sequence. Never invent hits while waiting.")}hits = job.hitsif not hits:17 unmodified lines}# βββ Collecting work that outlived the turn βββββββββββββββββββββββββββββ## blast_sequence waits AGENT_WAIT_SECONDS and then returns honestly:# "still running, here is the job_id, carry on with something else." The# job keeps going on its own thread and nothing ever goes back for it.## Re-calling blast_sequence looks like the answer, and _blast.submit does# reuse a cached job for the same sequence β but that is a path THROUGH the# sequence, and the sequence is exactly what the agent may no longer have.# A long conversation compacts; the letters are evicted; this project's# standing rule is that an agent must never retype a sequence from memory.# At that point the job is unreachable: the work finished, the answer is# sitting in memory, and the only handle to it was a parameter the agent# can no longer supply.## The job_id is that handle. It is small enough to survive in a summary# line, and it refers to the work rather than to its input.## WHAT THIS DOES NOT DO: wake a run that has already ended. That wants a# watcher thread outliving the run, and this deploys to a Space that sleeps# when idle β a watcher there would fire sometimes, which is worse than one# that fires when asked. So collection is explicit: the agent (or the# scientist's next message) comes back for it.# kind β how to look one up. A registry rather than an if-chain so a second# slow service joins by adding a row, and so the tool's error can list what# kinds exist rather than guessing.def _collect_blast(job_id: str, wait_seconds: float) -> Dict[str, Any]:from dee.core import blast as _blastjob = _blast.get(job_id)if job is None:return {"ok": False, "kind": "unknown_job","error": (f"No BLAST job {job_id!r} is in memory on this "f"server."),"next": ("It may have been lost to a restart. Re-run ""blast_sequence if you still have the sequence, or ""say the search was lost β do not describe hits ""from memory.")}if wait_seconds > 0 and not job.done():_blast.wait(job, timeout=wait_seconds)if not job.done():return {"ok": False, "kind": "still_running", "job_id": job.job_id,"elapsed_seconds": job.elapsed(),"error": (f"Still running after {job.elapsed():.0f}s β "f"NCBI's queue is shared."),"next": ("Collect it again later with this same job_id. ""Never invent hits while waiting.")}if job.status == "error":return {"ok": False, "kind": "blast_failed", "job_id": job.job_id,"error": job.error,"next": "Report that NCBI did not answer."}hits = job.hitsif not hits:return {"ok": True, "job_id": job.job_id, "hit_count": 0, "hits": [],"search": job.kind, "summary": "no significant hits","next": ("No hit above threshold is a real finding β it may ""be a novel or synthetic sequence.")}return {"ok": True, "job_id": job.job_id, "search": job.kind,"hit_count": len(hits), "hits": hits, "top": hits[0],"elapsed_seconds": job.elapsed(),"summary": f"{hits[0]['title'][:60]} Β· {hits[0]['identity_pct']}% id","note": ("Identity and coverage are BLAST's own numbers, reported ""verbatim. A high-identity hit names what this sequence ""most resembles β it is not proof they are the same ""molecule.")}_JOB_COLLECTORS = {"blast": _collect_blast}# Long enough to be worth a step, short enough that the run does not look# hung. The drive thread is held for this, the same trade the Modal path# already makes deliberately β a parked thread, not a blocked user._COLLECT_WAIT_MAX = 120.0def _tool_collect_job(args: Dict[str, Any]) -> Dict[str, Any]:job_id = str(args.get("job_id") or "").strip()if not job_id:return {"ok": False, "error": "Pass the job_id the earlier tool gave you."}kind = str(args.get("kind") or "blast").strip().lower()collector = _JOB_COLLECTORS.get(kind)if collector is None:return {"ok": False, "error": (f"No collector for {kind!r}. Known kinds: "f"{', '.join(sorted(_JOB_COLLECTORS))}.")}try:wait = float(args.get("wait_seconds") or 0)except (TypeError, ValueError):wait = 0.0wait = max(0.0, min(wait, _COLLECT_WAIT_MAX))return collector(job_id, wait)def _tool_simulate_assembly(args: Dict[str, Any]) -> Dict[str, Any]:"""Actually assemble the fragments β Gibson, Golden Gate or restriction.1472 unmodified lines# someone's unpublished construct to NCBI on their behalf."blast_sequence": {"fn": _tool_blast_sequence, "requires_signin": False,"requires_confirm": True},# No confirm: blast_sequence already took the consent to send this# sequence to NCBI, and this sends nothing β it reads back a job that# consent already started."collect_job": {"fn": _tool_collect_job, "requires_signin": False},# The only tool that changes the construct. Three flags, each earning its# place: signed-in because it writes; confirm because the user must agree# to their own DNA being altered; needs_target because the sequence comes153 unmodified lines},},},{"type": "function","function": {"name": "collect_job","description": ("Go back for a slow job that was still running when the tool ""that started it had to answer. blast_sequence returns ""'still running' with a job_id after about a minute; the ""search keeps going and this is how you get its result. Use ""the job_id, NOT the sequence: in a long conversation the ""sequence may no longer be in your context, and you must ""never retype one from memory β the job_id is small enough ""to survive and refers to the work itself. Call it when you ""next have a reason to, or when the scientist asks what came ""of the search. Never describe hits from a search you have ""not collected."),"parameters": {"type": "object","properties": {"job_id": {"type": "string","description": "The job_id the earlier tool returned.",},"kind": {"type": "string","enum": ["blast"],"description": "Which service. Defaults to blast.",},"wait_seconds": {"type": "number","minimum": 0,"maximum": 120,"description": ("Wait up to this long for it to finish before ""answering. 0 checks and returns at once."),},},"required": ["job_id"],},},},{"type": "function","function": {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242"""Arithmetic the agent does not have to do in its head.
THE GAP. Turing can only compute what a tool computes. "What is the meanon-target score of the top five guides", "how many of these variants clear0.8", "what fraction of the construct is coding" β none of those is atool, so the model does them mentally, over a table it can now read, andwrites the answer down as a finding. Mental arithmetic over twenty rows iswrong often enough to matter, and it is wrong *silently*: the sentencereads exactly like the version that was computed.
That is the whole motivation. Not autonomy, not a wider action surface βone specific class of confident error, removed by letting the agentactually evaluate the thing.
WHY THIS IS NOT A SHELL, AND WILL NOT BECOME ONE. The audit that asked forthis said plainly that Turing should not be given a shell: a bioinformaticsagent with arbitrary execution on the server is a different product with adifferent threat model, and the value here was never "run anything". It is"do this sum correctly". So the surface is deliberately the smallest thingthat closes the gap:
Β· ONE expression. No statements, no assignment, no loops, no def, no lambda, no imports. Β· NO attribute access at all. Every published sandbox escape in this shape goes through an attribute β `().__class__.__bases__`, `x.__globals__`, `"".join.__self__`. Without the Attribute node the route does not exist, rather than being blocked by a denylist that has to stay ahead of the next idea. Β· NO builtins. `__builtins__` is emptied and the only callables are the dozen bound below by name. Β· NO way to make a big iterable. There is no `range`, no `**`, and the only data in scope is what this run's own tools returned β which is bounded by what they produced. An expression therefore cannot allocate its way out; it is bounded by the data, not by a timeout we would have to enforce by killing a thread we cannot kill. Β· A node budget, so a pathological nest of comprehensions over real data is refused before it runs rather than while it runs.
WHAT IS IN SCOPE. This run's own artifacts, by the name the table alreadyhas β `guides`, `variants`, `primers` β and nothing else. No filesystem,no network, no other user's work, no state that outlives the call. Itreads the same rows read_result reads, which is why that came first: theagent can look at the table, then compute over the same object it lookedat, and the two can never disagree."""from __future__ import annotations
import astimport statisticsfrom typing import Any, Dict, List, Tuple
# Every node kind an expression may contain. An allow-list, so a Python# upgrade that adds a node kind fails closed._ALLOWED_NODES = ( ast.Expression, ast.Constant, ast.Name, ast.Load, ast.Store, ast.List, ast.Tuple, ast.Set, ast.Dict, ast.Subscript, ast.Slice, ast.BinOp, ast.UnaryOp, ast.BoolOp, ast.Compare, ast.IfExp, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp, ast.comprehension, ast.Call, ast.keyword, ast.Starred, # operators ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod, ast.UAdd, ast.USub, ast.Not, ast.And, ast.Or, ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE, ast.In, ast.NotIn, ast.Is, ast.IsNot,)
# Deliberately absent and individually load-bearing:# Attribute β the route every escape of this shape takes.# Pow β 10**10**10 is the one cheap way to hang the process.# Lambda β `sorted(key=...)` is nice; a callable the caller defines# is not worth it when `sorted_by` below does the same job.# JoinedStr β formatting is not arithmetic.# NamedExpr β an expression that binds a name is a statement wearing a# disguise.
def _mean(xs): xs = [x for x in xs if isinstance(x, (int, float)) and not isinstance(x, bool)] return statistics.fmean(xs) if xs else None
def _median(xs): xs = [x for x in xs if isinstance(x, (int, float)) and not isinstance(x, bool)] return statistics.median(xs) if xs else None
def _stdev(xs): xs = [x for x in xs if isinstance(x, (int, float)) and not isinstance(x, bool)] return statistics.stdev(xs) if len(xs) > 1 else None
def _sorted_by(rows, key, reverse=False): """sorted(), by a dict key, without needing a lambda.
The one thing a lambda was actually wanted for. Rows missing the key sort last rather than raising, because a column absent from one row of a heterogeneous table is a data fact, not a user error. """ rows = list(rows) missing = [r for r in rows if not (isinstance(r, dict) and key in r)] have = [r for r in rows if isinstance(r, dict) and key in r] have.sort(key=lambda r: (r[key] is None, r[key]), reverse=reverse) return have + missing
def _pct(part, whole): try: return round(100.0 * float(part) / float(whole), 2) if whole else None except (TypeError, ValueError, ZeroDivisionError): return None
_FUNCTIONS: Dict[str, Any] = { "len": len, "sum": sum, "min": min, "max": max, "abs": abs, "round": round, "sorted": sorted, "any": any, "all": all, "set": set, "list": list, "dict": dict, "tuple": tuple, "int": int, "float": float, "str": str, "bool": bool, "mean": _mean, "median": _median, "stdev": _stdev, "sorted_by": _sorted_by, "pct": _pct,}
# Bigger than any expression a person would write, small enough that a# generated nest of comprehensions is refused before it is evaluated.MAX_NODES = 400MAX_SOURCE = 1200# What comes back. An expression returning the whole table is a mistake,# not an analysis β read_result is how you read rows.MAX_RESULT_ITEMS = 50MAX_RESULT_CHARS = 2000
class AnalysisError(Exception): """A refusal the agent can read and act on."""
def _comprehension_targets(tree: ast.AST) -> set: """Names a comprehension binds, e.g. the `g` in [g['x'] for g in rows].
These are the only names an expression may introduce. Collected up front because the walk below rejects every Name it does not know, and a comprehension's own variable is obviously not in the caller's scope β the first version refused every comprehension ever written, which is the form almost every useful expression here takes. """ bound = set() for node in ast.walk(tree): if not isinstance(node, ast.comprehension): continue for sub in ast.walk(node.target): if isinstance(sub, ast.Name): bound.add(sub.id) return bound
def _check(tree: ast.AST, names: Dict[str, Any]) -> None: allowed_names = set(names) | _comprehension_targets(tree) count = 0 for node in ast.walk(tree): count += 1 if count > MAX_NODES: raise AnalysisError( f"expression is too complex ({MAX_NODES}-node limit). Break " f"it into separate calls.") if isinstance(node, ast.Attribute): # Named separately from the generic refusal because it is the # one people hit honestly, reaching for .sort() or .keys(). raise AnalysisError( "attribute access is not available here (no '.'). Use the " "functions instead: sorted_by(rows, 'key'), mean(...), " "len(...), or subscript a row with ['key'].") if not isinstance(node, _ALLOWED_NODES): raise AnalysisError( f"{type(node).__name__} is not allowed here. This evaluates " f"one arithmetic expression over your own results β no " f"statements, assignment, imports, lambdas or '**'.") if isinstance(node, ast.Name) and node.id not in allowed_names: raise AnalysisError( f"unknown name {node.id!r}. In scope: " f"{', '.join(sorted(names))}.")
def _shrink(value: Any) -> Any: """Bound what comes back, and say so when it was cut.""" if isinstance(value, (list, tuple, set)): items = list(value) out = [_shrink(v) for v in items[:MAX_RESULT_ITEMS]] if len(items) > MAX_RESULT_ITEMS: out.append(f"... {len(items) - MAX_RESULT_ITEMS} more") return out if isinstance(value, dict): return {str(k)[:40]: _shrink(v) for k, v in list(value.items())[:MAX_RESULT_ITEMS]} if isinstance(value, (int, float, bool)) or value is None: return value return str(value)[:MAX_RESULT_CHARS]
def evaluate(expression: str, scope: Dict[str, Any]) -> Tuple[Any, List[str]]: """Evaluate one expression against `scope`. Returns (value, names).
Raises AnalysisError with a message written for the agent β the useful answer to "that is not allowed" is which thing to reach for instead. """ source = str(expression or "").strip() if not source: raise AnalysisError("no expression given.") if len(source) > MAX_SOURCE: raise AnalysisError(f"expression is longer than {MAX_SOURCE} characters.") if "\n" in source: raise AnalysisError("one expression, on one line β no statements.")
names: Dict[str, Any] = dict(_FUNCTIONS) names.update(scope)
try: tree = ast.parse(source, mode="eval") except SyntaxError as exc: raise AnalysisError(f"could not parse that: {exc.msg}.") from exc _check(tree, names)
try: value = eval( # noqa: S307 compile(tree, "<analysis>", "eval"), {"__builtins__": {}}, dict(names)) except AnalysisError: raise except ZeroDivisionError: raise AnalysisError("division by zero β check for an empty group.") except (KeyError, IndexError) as exc: raise AnalysisError( f"no such key or row: {exc}. Read the table with read_result to " f"see the columns it actually has.") from exc except (TypeError, ValueError) as exc: raise AnalysisError(f"{exc}") from exc except RecursionError as exc: # pragma: no cover raise AnalysisError("expression nested too deeply.") from exc return _shrink(value), sorted(scope)49 unmodified lines5051525354555649 unmodified lines# result this run already produced, so it belongs# beside the other tools that manage the work# rather than under any phase of the loop."read_result"},}49 unmodified lines5051525354555657585960616249 unmodified lines# result this run already produced, so it belongs# beside the other tools that manage the work# rather than under any phase of the loop."read_result",# Also orchestration: it starts nothing and sends# nothing, it goes back for work already running."collect_job",# Arithmetic over work already done. No provider,# no new measurement, nothing added to the bench."analyze"},}
53 unmodified lines54555657585960104 unmodified lines165166167168169170716 unmodified lines8878888898908918928933 unmodified lines89789889990090190290390435 unmodified lines9409419429439449459469479489499509511749 unmodified lines27012702270327042705270627078 unmodified lines271627172718271927202721288 unmodified lines301030113012301330143015188 unmodified lines3204320532063207320832091316 unmodified lines452645274528452945304531128 unmodified lines46604661466246634664466556 unmodified lines4722472347244725472647274728287 unmodified lines50165017501850195020502153 unmodified linesimport osimport copyfrom dataclasses import dataclass, field, replacefrom typing import Any, Dict, List, Optional, Tuplefrom dee.core import scientific_decisions as _decisionsfrom dee.core import run_integrity as _integrity104 unmodified lines# No view: the tab is already open on these very rows. See the# read_result branch in _execute_tool_call."read_result": {"view": None, "verb": "Re-reading its own result"},"fold_structure": {"view": "structure", "verb": "Folding structure"},"find_complex_structure": {"view": "structure", "verb": "Finding the experimental complex"},# The result paints the Structure tab (TDInteraction) and now says so:716 unmodified lines}def _completion_audit(run: "Run") -> Dict[str, Any]:"""Deterministic pre-handoff check over work the runtime actually saw.This is deliberately not a second LLM judging the first. It checks facts3 unmodified lines``_drive`` gives Turing one chance to repair the work before handoff."""results = _turn_results(run)if not results and not run.evidence:return {"status": "not_applicable", "checks": [], "unresolved": []}by_call = {str(event.get("id") or ""): (i, event)for i, event in enumerate(results)}35 unmodified linesif passed:checks.append(f"{passed} deliverable integrity check(s) passed")unresolved = list(dict.fromkeys(value for value in unresolved if value))[:8]return {"status": "attention" if unresolved else "verified","checks": checks[:6],"unresolved": unresolved,"invalid_output": invalid_output,}1749 unmodified lines"the objective is complete while an active or pending item remains.")})continueaudit = _completion_audit(run)if (audit["unresolved"] and not run.verification_guard_used):run.verification_guard_used = Truerun.boost_next_step = True8 unmodified lines+ "\nUse existing results or an appropriate alternative to repair what is recoverable; do not blindly repeat a failed lookup. ""If it cannot be repaired, state the limitation ""plainly and do not describe the objective as complete.")})if withheld and not run.provenance_retried:# The verification retry is also the one bounded chance288 unmodified lines})return False# ββ a real tool ββββββββββββββββββββββββββββββββββββββββββββββββββββββinput_ref = args.get("sequence_ref") if isinstance(args, dict) else Noneif not isinstance(input_ref, str):188 unmodified lines"name": name,"ok": bool(result.get("ok")),"result_kind": result.get("kind"),"error": result.get("error") if not result.get("ok") else None,# A declining tool often carries the sentence that makes the refusal# make sense β assess_expression's "this is a missing data file, not1316 unmodified linesreturn outdef _readable_results(run: Run) -> List[Dict[str, Any]]:"""Every result of this run that can be re-opened, oldest first."""with _RUNS_LOCK:128 unmodified linesreturn f"re-read its own {tool} result"_READ_RESULT_SPEC: Dict[str, Any] = {"type": "function","function": {56 unmodified linesTOOL_SPECS: List[Dict[str, Any]] = (list(_tools.TOOL_SPECS)+ [_ASK_USER_SPEC, _UPDATE_PLAN_SPEC, _READ_RESULT_SPEC]+ _decisions.TOOL_SPECS)# Tools that only exist when a backend is actually wired up. Offering one287 unmodified lines# step 1 could only produce an empty shelf and a wasted step.if name == "read_result" and run is not None and not _readable_results(run):continueif not _CONDITIONAL_TOOLS.get(name, _always)():continueout.append(spec)53 unmodified lines54555657585960104 unmodified lines165166167168169170171172716 unmodified lines8898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610773 unmodified lines108110821083108410851086108710881089109010911092109335 unmodified lines11291130113111321133113411351136113711381139114011411142114311441145114611471749 unmodified lines28972898289929002901290229038 unmodified lines2912291329142915291629172918291929202921292229232924292529262927288 unmodified lines3216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243188 unmodified lines3432343334343435343634373438343934403441344234431316 unmodified lines476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786128 unmodified lines4915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503656 unmodified lines50935094509550965097509850995100287 unmodified lines5388538953905391539253935394539553965397539853995400540153 unmodified linesimport osimport copyfrom dataclasses import dataclass, field, replacefrom typing import Any, Dict, Iterable, List, Optional, Tuplefrom dee.core import scientific_decisions as _decisionsfrom dee.core import run_integrity as _integrity104 unmodified lines# No view: the tab is already open on these very rows. See the# read_result branch in _execute_tool_call."read_result": {"view": None, "verb": "Re-reading its own result"},"analyze": {"view": None, "verb": "Working it out"},"collect_job": {"view": None, "verb": "Collecting a running job"},"fold_structure": {"view": "structure", "verb": "Folding structure"},"find_complex_structure": {"view": "structure", "verb": "Finding the experimental complex"},# The result paints the Structure tab (TDInteraction) and now says so:716 unmodified lines}# βββ Holding the answer to the work βββββββββββββββββββββββββββββββββββββ## _completion_audit below checks the ARTIFACTS: did a tool fail, is a# deliverable structurally incomplete, how many integrity checks ran.# Nothing checked the ANSWER. A run can pass every one of those and still# hand over a sentence about guide 23 of a set of 20, or an off-target# claim about a column the model was never sent β and the scientist has no# way to tell, because the prose reads exactly like the true version.## This is the same shape as the provenance guard, applied to figures rather# than to letters, and it is ONE-SIDED for the same reason that guard is.# "8 of the 20 guides" is a shortlist and is how people write; a smaller# number is almost never an error. A number LARGER than what the run# produced cannot be anything but invented, and that asymmetry is what# makes this checkable without drowning the model in false corrections.## Deterministic, no second model call, and it reads the same event log# read_result reads β which is the point of having built that first.# Table key β the words that table's rows are called in prose. Derived# nouns ("guide" from "guides") plus the irregular ones a scientist# actually writes._ROW_NOUNS: Dict[str, Tuple[str, ...]] = {"guides": ("guide", "guides", "grna", "grnas", "sgrna", "sgrnas"),"variants": ("variant", "variants", "mutant", "mutants"),"pairs": ("primer pair", "primer pairs", "pair", "pairs"),"primers": ("primer", "primers", "oligo", "oligos"),"fragments": ("fragment", "fragments"),"sites": ("site", "sites", "cut site", "cut sites"),"poses": ("pose", "poses"),"features": ("feature", "features"),"hits": ("hit", "hits"),"candidates": ("candidate", "candidates"),}# Parts of a field name that say nothing about WHICH property it is, and# common domain words that appear in ordinary prose regardless. A token has# to survive both lists, and be long enough not to collide by accident,# before its presence in a sentence means anything._FIELD_NOISE = frozenset({"max", "min", "avg", "mean", "sum", "pct", "percent", "count", "score","label", "top", "total", "value", "values", "id", "idx", "index", "num","flag", "flags", "is", "has", "the", "of", "per",# Domain words a correct answer uses constantly; matching them would# fire on almost every reply."target", "targets", "sequence", "sequences", "protein", "gene", "genes","region", "position", "strand", "context", "primer", "primers", "guide","guides", "variant", "variants", "result", "results", "data", "notes","note", "reasoning", "summary", "detail", "details", "name", "type","start", "end", "length", "predicted", "prediction", "enzyme", "site",})_FIELD_TOKEN_MIN = 5def _artifact_tables(run: "Run") -> Dict[str, Dict[str, Any]]:"""What this run actually produced, per tool: the table and its size.Reads the same successful tool_result events read_result reads, so theanswer is checked against the very rows the scientist's tab was paintedfrom rather than against a second, possibly different, computation."""out: Dict[str, Dict[str, Any]] = {}for ev in _readable_results(run):name = str(ev.get("name") or "")panel = (ev.get("ui") or {}).get("panel")if not isinstance(panel, dict) or not panel:continuetable, rows = _panel_table(panel)if not table or not rows:continueprior = out.get(name, {}).get("n_rows", 0)# The LARGEST run of a tool bounds what may be claimed. Two# designs in one conversation and the agent quoting a row from the# bigger one is legitimate; a row beyond both is not.if len(rows) >= prior:out[name] = {"table": table, "n_rows": len(rows), "rows": rows}return outdef _unseen_fields(run: "Run") -> Dict[str, List[str]]:"""Per tool, the columns in the panel that the model was never sent._strip_ui is why these exist: the panel carries ~48 keys per CRISPRguide and the model's copy carries nine. Everything in the differenceis a property the agent cannot know anything about unless it callsread_result β so a confident sentence about one, with no read, is aguess wearing the costume of a finding."""out: Dict[str, List[str]] = {}for ev in _readable_results(run):name = str(ev.get("name") or "")ui = ev.get("ui") or {}panel, payload = ui.get("panel"), ui.get("payload")if not isinstance(panel, dict) or not isinstance(payload, dict):continue_, prows = _panel_table(panel)_, mrows = _panel_table(payload)if not prows:continueshown = set(mrows[0]) if mrows else set()hidden = [k for k in prows[0] if k not in shown]if hidden:out.setdefault(name, []).extend(hidden)return outdef _field_tokens(fields: Iterable[str]) -> Dict[str, str]:"""token β the field it came from, for tokens specific enough to meansomething when they turn up in a sentence."""out: Dict[str, str] = {}for field in fields:for part in re.split(r"[^a-z0-9]+", str(field).lower()):if len(part) >= _FIELD_TOKEN_MIN and part not in _FIELD_NOISE:out.setdefault(part, str(field))return outdef _read_back_tools(run: "Run") -> set:"""Tools whose rows this run actually re-opened."""with _RUNS_LOCK:events = list(run.events)seen = set()for ev in events:if ev.get("kind") != "tool_call" or ev.get("name") != "read_result":continuewant = str((ev.get("args") or {}).get("tool") or "").strip()if want:seen.add(want)return seendef _claim_audit(run: "Run", text: str) -> List[str]:"""Where the answer claims more than the run produced.Returns findings in the same shape _completion_audit's `unresolved`uses, so they ride the existing one-bounded-retry machinery ratherthan adding a second correction loop."""prose = str(text or "").strip()if not prose:return []# Hyphens folded so "off-target" and "offtarget" are one word, and the# whole thing lowered once rather than per pattern.flat = re.sub(r"[-β-β]", "", prose.lower())found: List[str] = []tables = _artifact_tables(run)for name, info in tables.items():n = info["n_rows"]for noun in _ROW_NOUNS.get(info["table"], ()):# "23 guides" / "top 30 guides" β a total larger than exists.for m in re.finditer(r"\b(?:top\s+)?(\d{1,4})\s+" + re.escape(noun)+ r"\b", flat):claimed = int(m.group(1))if claimed > n:found.append(f"the answer says '{m.group(0)}' but "f"{name} returned {n}")# "guide 23" / "guide #23" β a row that does not exist.for m in re.finditer(re.escape(noun) + r"\s*#?\s*(\d{1,4})\b", flat):claimed = int(m.group(1))if claimed > n:found.append(f"the answer refers to '{m.group(0)}' but "f"{name} returned only {n} {info['table']}")# A property the model was never sent, asserted without reading it.read_back = _read_back_tools(run)for name, hidden in _unseen_fields(run).items():if name in read_back:continuefor token, field in _field_tokens(hidden).items():if re.search(r"\b" + re.escape(token) + r"\b", flat):found.append(f"the answer discusses {token} but {name}'s "f"{field} was never sent to you and you did not call "f"read_result on it")break # one finding per tool is enoughreturn list(dict.fromkeys(found))[:6]def _completion_audit(run: "Run", text: str = "") -> Dict[str, Any]:"""Deterministic pre-handoff check over work the runtime actually saw.This is deliberately not a second LLM judging the first. It checks facts3 unmodified lines``_drive`` gives Turing one chance to repair the work before handoff."""results = _turn_results(run)# `text` is the draft answer, when there is one. Checking it here rather# than in a second guard means a run gets ONE bounded correction for# everything the runtime can see is wrong, not one per category.claims = _claim_audit(run, text) if text else []if not results and not run.evidence:return {"status": "attention" if claims else "not_applicable","checks": [], "unresolved": claims}by_call = {str(event.get("id") or ""): (i, event)for i, event in enumerate(results)}35 unmodified linesif passed:checks.append(f"{passed} deliverable integrity check(s) passed")# Claims last: an execution failure is the more useful thing to read# first, and the retry prompt shows the leading items.unresolved = list(dict.fromkeys(value for value in (unresolved + claims) if value))[:8]return {"status": "attention" if unresolved else "verified","checks": checks[:6],"unresolved": unresolved,"invalid_output": invalid_output,# Which of the above are about the ANSWER rather than the work. The# remedy differs: a failed lookup is repaired by running something,# an overstated claim by reading what was already produced."claims": [c for c in claims if c in unresolved],}1749 unmodified lines"the objective is complete while an active or pending item remains.")})continueaudit = _completion_audit(run, text)if (audit["unresolved"] and not run.verification_guard_used):run.verification_guard_used = Truerun.boost_next_step = True8 unmodified lines+ "\nUse existing results or an appropriate alternative to repair what is recoverable; do not blindly repeat a failed lookup. ""If it cannot be repaired, state the limitation ""plainly and do not describe the objective as complete."# Only when the draft itself overstated something.# A run whose findings are all execution failures is# told exactly what it was told before.+ ("\nThe items above about your ANSWER are not ""failed work: the tools succeeded and your ""sentence went past what they returned. Call ""read_result on that tool and rewrite the claim ""from the rows you read, or drop it. Do not ""re-run the tool β it already answered."if audit.get("claims") else ""))})if withheld and not run.provenance_retried:# The verification retry is also the one bounded chance288 unmodified lines})return False# ββ analyze: one expression over this run's own tables βββββββββββββββ# Above `tools_run` for the same reason read_result is: it spends# nothing and reaches no provider. It also must not satisfy the# distinct-work test, or a run with nothing left to do could extend# itself by computing arithmetic nobody asked for.if name == "analyze":_emit(run, "tool_call", {"id": call_id, "name": name,"verb": _tool_verb(name), "args": dict(args)})payload = _analyze(run, args)_emit(run, "tool_result", {"id": call_id, "name": name,"ok": bool(payload.get("ok")),"error": payload.get("error") if not payload.get("ok") else None,"summary": _analyze_summary(payload),"ui": None,})run.history.append({"role": "tool", "tool_call_id": call_id,"content": json.dumps(payload, default=str)[:8000],})return False# ββ a real tool ββββββββββββββββββββββββββββββββββββββββββββββββββββββinput_ref = args.get("sequence_ref") if isinstance(args, dict) else Noneif not isinstance(input_ref, str):188 unmodified lines"name": name,"ok": bool(result.get("ok")),"result_kind": result.get("kind"),# The handle to work that outlived this call. Without it on the# EVENT, a job a tool left running is reachable only through the# model's own history β which compaction evicts, and which is the# one place a job_id must not live if it is to stay collectable.**({"job_id": str(result.get("job_id"))[:64]}if result.get("job_id") else {}),"error": result.get("error") if not result.get("ok") else None,# A declining tool often carries the sentence that makes the refusal# make sense β assess_expression's "this is a missing data file, not1316 unmodified linesreturn outdef _pending_jobs(run: Run) -> List[str]:"""Job ids this run started and never got an answer for.Read off the event log rather than tracked on the Run, for the reason_tool_summaries is: the event was written when the tool answered, so itis exact, and a rehydrated run restores its events."""with _RUNS_LOCK:events = list(run.events)out: List[str] = []for ev in events:if ev.get("kind") != "tool_result" or ev.get("ok"):continueif ev.get("result_kind") != "still_running":continuejid = str(ev.get("job_id") or "")if jid and jid not in out:out.append(jid)return outdef _readable_results(run: Run) -> List[Dict[str, Any]]:"""Every result of this run that can be re-opened, oldest first."""with _RUNS_LOCK:128 unmodified linesreturn f"re-read its own {tool} result"# βββ Arithmetic it does not have to do in its head ββββββββββββββββββββββ## read_result let the agent SEE its twenty guides. It still could not# average them. "The mean on-target score of the top five is 0.81" is not# a tool call anywhere in this system, so the model computes it mentally# and writes it down as a finding β and mental arithmetic over twenty rows# is wrong often enough to matter, silently, in a sentence that reads# exactly like the version that was computed.## dee.core.analysis is the evaluator and holds the whole security argument;# this is only the binding. What it binds is the point: the names in scope# are THIS RUN'S OWN TABLES, by the name the table already has, read from# the same events read_result reads. So the agent looks at the rows and# computes over the very same object, and the two cannot disagree.def _analysis_scope(run: Run) -> Dict[str, Any]:"""The names an expression may use: this run's tables, and nothing else.Bound under BOTH the table's own name ("guides") and the tool's("design_crispr_guides"), because the agent has seen both and eitheris a reasonable thing to type. Two tools sharing a table name isresolved by the one with more rows, the same rule _artifact_tablesuses for what may be claimed."""scope: Dict[str, Any] = {}for name, info in _artifact_tables(run).items():rows = info["rows"]scope[name] = rowstable = info["table"]if len(rows) >= len(scope.get(table) or []):scope[table] = rowsreturn scopedef _analyze(run: Run, args: Dict[str, Any]) -> Dict[str, Any]:from dee.core import analysis as _anscope = _analysis_scope(run)if not scope:return {"ok": False, "kind": "nothing_to_analyze","error": "This conversation has no result table yet.","next": "Run the tool that produces the data first."}expression = str(args.get("expression") or "")try:value, names = _an.evaluate(expression, scope)except _an.AnalysisError as exc:return {"ok": False, "kind": "bad_expression", "error": str(exc),"in_scope": sorted(scope)}out: Dict[str, Any] = {"ok": True, "expression": expression[:400],"value": value, "in_scope": names}label = str(args.get("label") or "").strip()if label:out["label"] = label[:120]return outdef _analyze_summary(payload: Dict[str, Any]) -> str:"""The line the SCIENTIST reads. Shows the answer, because an activityentry saying only "computed something" is noise in a transcript."""if not payload.get("ok"):return str(payload.get("error") or "could not evaluate that")[:160]value = payload.get("value")shown = json.dumps(value, default=str)if len(shown) > 90:shown = shown[:87] + "..."label = payload.get("label")return f"{label}: {shown}" if label else f"computed {shown}"_ANALYZE_SPEC: Dict[str, Any] = {"type": "function","function": {"name": "analyze","description": ("Evaluate one arithmetic expression over the result tables this ""conversation has already produced, instead of doing the sum in ""your head. Use it for any number you would otherwise work out ""mentally β a mean, a count of rows passing a threshold, a ""fraction, a spread, a ranking. A mental average over twenty ""rows is wrong often enough to matter, and it is wrong ""invisibly: nobody can tell a computed number from a guessed ""one by reading it. Call read_result first if you need to see ""which columns a table actually has. This evaluates ONE ""expression β no statements, no assignment, no imports, no ""attribute access ('.'), no '**'. Use ['key'] to read a column, ""and the provided functions: len, sum, min, max, abs, round, ""sorted, sorted_by(rows,'key'), any, all, mean, median, stdev, ""pct(part,whole), set, list, int, float, str."),"parameters": {"type": "object","properties": {"expression": {"type": "string","description": ("The expression, e.g. ""\"mean([g['on_target_score'] for g in guides[:5]])\" ""or \"len([g for g in guides if g['gc_pct'] > 60])\". ""Call with an obviously wrong name to be told what ""is in scope."),},"label": {"type": "string","description": ("Optional short name for what this number is, shown ""to the scientist beside the answer."),},},"required": ["expression"],},},}_READ_RESULT_SPEC: Dict[str, Any] = {"type": "function","function": {56 unmodified linesTOOL_SPECS: List[Dict[str, Any]] = (list(_tools.TOOL_SPECS)+ [_ASK_USER_SPEC, _UPDATE_PLAN_SPEC, _READ_RESULT_SPEC,_ANALYZE_SPEC]+ _decisions.TOOL_SPECS)# Tools that only exist when a backend is actually wired up. Offering one287 unmodified lines# step 1 could only produce an empty shelf and a wasted step.if name == "read_result" and run is not None and not _readable_results(run):continue# Nothing is pending, so there is nothing to collect. Same# monotonic contract: it opens at the step after a tool first# says "still running".if name == "collect_job" and run is not None and not _pending_jobs(run):continue# Same again: an expression needs a table to be about.if name == "analyze" and run is not None and not _analysis_scope(run):continueif not _CONDITIONAL_TOOLS.get(name, _always)():continueout.append(spec)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""Arithmetic the agent does not have to do in its head, and the fence.
THE GAP. read_result let Turing SEE its twenty guides. It still could notaverage them β no tool computes a mean, a threshold count or a spread. Sothe model does it mentally and writes the answer down as a finding, andmental arithmetic over twenty rows is wrong often enough to matter. It iswrong *invisibly*: a guessed number and a computed one read identically.
WHY THIS IS NOT A SHELL. The audit that asked for this said plainly thatTuring should not be given one β a bioinformatics agent with arbitraryexecution on the server is a different product with a different threatmodel, and the value here was never "run anything", it was "do this sumcorrectly". So the fence is structural rather than a denylist:
Β· no Attribute node at all. Every published escape of this shape goes through an attribute (`().__class__.__bases__`, `x.__globals__`, `"".join.__self__`). Removing the node removes the route, instead of blocking today's spellings of it. Β· no builtins, and only the dozen callables bound by name. Β· nothing that can MAKE a large iterable: no range, no `**`. The only data in scope is what this run's own tools returned, so an expression is bounded by the data rather than by a timeout we would have to enforce by killing a thread we cannot kill. Β· a node budget, so a pathological nest is refused before it runs.
The escape suite at the bottom is the real test of all that."""import pytest
from dee.core import analysis as A, orchestrator as O
GUIDES = [{"rank": i + 1, "on_target_score": round(0.95 - i * 0.04, 3), "gc_pct": 45 + i * 2, "notes": ""} for i in range(20)]SCOPE = {"guides": GUIDES}
def _val(expr, scope=None): return A.evaluate(expr, scope if scope is not None else SCOPE)[0]
# ββ the arithmetic it was built for βββββββββββββββββββββββββββββββββββ
def test_the_mean_it_used_to_do_in_its_head(): assert _val("round(mean([g['on_target_score'] for g in guides[:5]]), 3)") == 0.87
def test_counting_rows_past_a_threshold(): assert _val("len([g for g in guides if g['gc_pct'] > 60])") == 12
def test_a_percentage_without_a_division_mistake(): assert _val("pct(len([g for g in guides if g['on_target_score'] > 0.8]), " "len(guides))") == 20.0
def test_spread_and_extremes(): assert _val("max(g['gc_pct'] for g in guides) - " "min(g['gc_pct'] for g in guides)") == 38 assert _val("round(stdev([g['gc_pct'] for g in guides]), 2)") == 11.83
def test_ranking_without_a_lambda(): """sorted_by exists so the evaluator never has to allow Lambda.""" assert _val("[g['rank'] for g in sorted_by(guides, 'gc_pct', True)[:3]]") \ == [20, 19, 18]
def test_a_missing_column_sorts_last_rather_than_raising(): """A heterogeneous table is a data fact, not a user error.""" rows = [{"a": 2}, {"b": 1}, {"a": 1}] assert _val("[r['a'] for r in sorted_by(rows, 'a')[:2]]", {"rows": rows}) == [1, 2]
def test_empty_input_gives_nothing_rather_than_a_crash(): assert _val("mean([])", {"rows": []}) is None assert _val("stdev([1])", {"rows": []}) is None assert _val("pct(1, 0)", {"rows": []}) is None
# ββ what comes back is bounded ββββββββββββββββββββββββββββββββββββββββ
def test_a_huge_result_is_cut_and_says_so(): """An expression returning the whole table is a mistake, not an analysis β read_result is how you read rows.""" rows = [{"i": i} for i in range(500)] out = _val("[r['i'] for r in rows]", {"rows": rows}) assert len(out) == A.MAX_RESULT_ITEMS + 1 assert "more" in str(out[-1])
def test_the_scope_is_reported_back(): _, names = A.evaluate("len(guides)", SCOPE) assert names == ["guides"], "the agent is not told what it may refer to"
# ββ refusals a model can act on βββββββββββββββββββββββββββββββββββββββ
def test_an_unknown_name_lists_what_is_in_scope(): """The same shelf philosophy read_result uses: the useful answer to 'no such name' is the list of real ones.""" with pytest.raises(A.AnalysisError) as exc: A.evaluate("len(primers)", SCOPE) assert "guides" in str(exc.value) and "mean" in str(exc.value)
def test_attribute_access_names_the_alternative(): with pytest.raises(A.AnalysisError) as exc: A.evaluate("guides.sort()", SCOPE) assert "sorted_by" in str(exc.value)
def test_a_bad_column_points_at_read_result(): with pytest.raises(A.AnalysisError) as exc: A.evaluate("[g['nope'] for g in guides]", SCOPE) assert "read_result" in str(exc.value)
def test_statements_are_refused(): for bad in ("x = 1", "import os", "for g in guides: pass"): with pytest.raises(A.AnalysisError): A.evaluate(bad, SCOPE)
def test_an_empty_or_oversized_expression_is_refused(): with pytest.raises(A.AnalysisError): A.evaluate(" ", SCOPE) with pytest.raises(A.AnalysisError): A.evaluate("len(guides) + " * 2000 + "1", SCOPE)
def test_a_pathological_nest_is_refused_before_it_runs(): expr = "len(" * 150 + "guides" + ")" * 150 with pytest.raises(A.AnalysisError) as exc: A.evaluate(expr, SCOPE) assert "complex" in str(exc.value) or "node" in str(exc.value).lower()
# ββ the fence βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ESCAPES = [ "().__class__.__bases__[0].__subclasses__()", "[].__class__.__mro__[1].__subclasses__()", "().__getattribute__('__class__')", "guides.__class__", "getattr(guides, '__class__')", "__import__('os').system('id')", "open('/etc/passwd').read()", "eval('1+1')", "exec('x=1')", "compile('1','x','eval')", "globals()", "locals()", "vars()", "dir()", "breakpoint()", "(lambda: 1)()", "f'{guides}'", "(y := 5)",]
@pytest.mark.parametrize("attack", ESCAPES)def test_it_does_not_escape(attack): """Each of these is refused with a message, not a traceback: a raw exception leaking out is itself a finding about what ran.""" with pytest.raises(A.AnalysisError): A.evaluate(attack, SCOPE)
RESOURCE = ["10**10**10", "[0]*10**9", "'a'*10**9", "[x for x in range(10**9)]", "2**2**30"]
@pytest.mark.parametrize("attack", RESOURCE)def test_it_cannot_allocate_its_way_out(attack): """There is no range and no '**', and the only iterables in scope are the run's own tables β so the bound is the data, not a timeout.""" with pytest.raises(A.AnalysisError): A.evaluate(attack, SCOPE)
def test_the_node_allowlist_fails_closed(): """An allow-list, so a Python release that adds a node kind refuses it rather than quietly permitting it.""" assert A.ast.Attribute not in A._ALLOWED_NODES assert A.ast.Pow not in A._ALLOWED_NODES assert A.ast.Lambda not in A._ALLOWED_NODES assert A.ast.Import not in A._ALLOWED_NODES
# ββ wired into the run ββββββββββββββββββββββββββββββββββββββββββββββββ
def _run(): run = O.Run(run_id="r", owner="u", anonymous=False) run.events.append({"kind": "tool_result", "id": "c1", "name": "design_crispr_guides", "ok": True, "ui": {"panel": {"guides": GUIDES}, "payload": {"guides": GUIDES}}}) return run
def test_the_scope_is_this_runs_own_tables_under_both_names(): scope = O._analysis_scope(_run()) assert scope["guides"] == GUIDES assert scope["design_crispr_guides"] == GUIDES, ( "the agent has seen the tool name too and either is reasonable to type" )
def test_it_computes_over_the_very_rows_read_result_shows(): """Not a second computation that could disagree with the screen.""" run = _run() assert O._analyze(run, {"expression": "len(guides)"})["value"] == 20 assert O._read_result(run, {"tool": "design_crispr_guides"})["n_rows"] == 20
def test_a_refusal_comes_back_as_a_readable_result_not_an_exception(): out = O._analyze(_run(), {"expression": "guides.__class__"}) assert not out["ok"] and "attribute" in out["error"].lower() assert out["in_scope"]
def test_the_tool_is_offered_only_once_there_is_a_table(): empty = O.Run(run_id="e", owner="u", anonymous=False) names = lambda r: [s["function"]["name"] for s in O.active_tool_specs(r)] assert "analyze" not in names(empty) assert "analyze" in names(_run())
def test_the_activity_line_shows_the_answer(): """"Computed something" is noise in a transcript; the number is the whole point of the step.""" run = _run() O._run_one_tool(run, "analyze", "call_a", {"expression": "len(guides)", "label": "guides designed"}) ev = [e for e in run.events if e.get("id") == "call_a" and e["kind"] == "tool_result"][0] assert ev["summary"] == "guides designed: 20" assert ev["ui"] is None
def test_re_computing_is_not_metered_as_work(): run = _run() before = run.tools_run O._run_one_tool(run, "analyze", "call_a", {"expression": "len(guides)"}) assert run.tools_run == before
def test_it_is_registered_and_categorised(): from dee.core import capabilities assert "analyze" in [s["function"]["name"] for s in O.TOOL_SPECS] assert capabilities.uncategorised(O.TOOL_SPECS) == []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197"""Holding the answer to the work, not just the work to itself.
WHAT WAS ALREADY CHECKED. _completion_audit is a good guard and it checksthe ARTIFACTS: did the last attempted operation fail, is a successfuldeliverable missing a required part, how many integrity checks ran. A runcan pass every one of those and still hand the scientist a sentence aboutguide 23 of a set of 20, or a confident off-target comparison drawn from acolumn the model was never sent. Nothing read the ANSWER.
WHY ONE-SIDED. "8 of the 20 guides I would order" is a shortlist and is howpeople write; firing on every count that disagrees with the table wouldbury the model in corrections it should ignore, and a guard that is usuallywrong is a guard that gets ignored when it is right. A number LARGER thanwhat the run produced cannot be a shortlist. That asymmetry β the same onethe provenance guard uses for sequences β is what makes this checkable atall.
THE SECOND CHECK IS THE REASON read_result WAS BUILT FIRST. _strip_ui sendsthe model nine of a CRISPR guide's forty-eight columns. Everything in thedifference is a property the agent cannot know anything about: an answerranking guides by off-target risk, with no read_result call behind it, isa guess wearing the costume of a finding. The fix is not to send more; itis to notice, and to say which tool to re-open.
Deterministic, no second model call, and it reads the same event logread_result reads."""from dee.core import orchestrator as O
# 48 columns in the panel, 9 in the model's copy β the real proportions.PANEL_KEYS = ("rank", "spacer", "pam", "on_target_score", "gc_pct", "cfd_max_offtarget", "offtarget_count", "ko_efficacy", "ko_reasoning", "frameshift_pct", "top_indel_label")MODEL_KEYS = ("rank", "spacer", "pam", "on_target_score", "gc_pct")
def _run(n=20, name="design_crispr_guides", key="guides"): run = O.Run(run_id="r1", owner="u1", anonymous=False) panel_rows = [{k: (i + 1 if k == "rank" else 0.5) for k in PANEL_KEYS} for i in range(n)] model_rows = [{k: (i + 1 if k == "rank" else 0.5) for k in MODEL_KEYS} for i in range(n)] run.events.append({ "kind": "tool_result", "id": "c1", "name": name, "ok": True, "summary": f"{n} {key}", "ui": {"panel": {key: panel_rows}, "payload": {key: model_rows}}, }) return run
def _read(run, tool="design_crispr_guides"): run.events.append({"kind": "tool_call", "id": "rr", "name": "read_result", "args": {"tool": tool}}) return run
# ββ a claim larger than the work ββββββββββββββββββββββββββββββββββββββ
def test_a_row_that_does_not_exist_is_caught(): """The expensive version of this error: the scientist orders guide 23.""" found = O._claim_audit(_run(20), "Guide 23 has the best on-target score.") assert found and "guide 23" in found[0] assert "only 20" in found[0]
def test_a_total_larger_than_the_table_is_caught(): found = O._claim_audit(_run(20), "I found 30 guides for this target.") assert found and "30 guides" in found[0] and "returned 20" in found[0]
def test_a_shortlist_is_not_an_error(): """THE REASON THIS GUARD IS ONE-SIDED. Reporting fewer than were produced is normal, correct writing and must never be corrected.""" run = _run(20) for honest in ("Here are 8 of the 20 guides I would order.", "The top 5 guides all sit in exon 2.", "I designed 20 guides; guide 1 is the strongest.", "Only 3 guides cleared the GC filter."): assert O._claim_audit(run, honest) == [], honest
def test_numbers_that_are_not_row_counts_are_left_alone(): """A sequence pane is full of integers. Matching bare numbers rather than numbers attached to a row noun would fire on every reply.""" run = _run(20) assert O._claim_audit( run, "The spacer is 20 bp at position 412 of the 5,386 bp construct, " "GC 51%, cut 3 bp upstream of the PAM.") == []
def test_the_largest_run_of_a_tool_sets_the_bound(): """Designing twice and quoting a row from the bigger set is legitimate; a row beyond both is not.""" run = _run(8) big = [{k: (i + 1 if k == "rank" else 0.5) for k in PANEL_KEYS} for i in range(20)] run.events.append({"kind": "tool_result", "id": "c2", "name": "design_crispr_guides", "ok": True, "ui": {"panel": {"guides": big}, "payload": {"guides": big}}}) assert O._claim_audit(run, "Guide 17 is the one to order.") == [] assert O._claim_audit(run, "Guide 21 is the one to order.") != []
# ββ a claim about a column the model never had ββββββββββββββββββββββββ
def test_a_property_that_was_never_sent_is_flagged(): """The agent has rank, spacer, PAM, on-target and GC. It has never seen an off-target number, so it cannot rank by one.""" found = O._claim_audit(_run(20), "Guide 2 has the lowest off-target risk.") assert found and "offtarget" in found[0] assert "read_result" in found[0]
def test_the_hyphen_does_not_hide_the_word(): run = _run(20) assert O._claim_audit(run, "guide 2 has the lowest offtarget count") assert O._claim_audit(run, "guide 2 has the lowest off-target count")
def test_reading_the_table_back_settles_it(): """The whole point. The claim is fine once it rests on the rows.""" run = _run(20) claim = "Guide 2 has the lowest off-target risk." assert O._claim_audit(run, claim) assert O._claim_audit(_read(run), claim) == []
def test_a_column_the_model_did_get_is_never_flagged(): run = _run(20) assert O._claim_audit( run, "Guide 1 has the highest on-target score and 55% GC.") == []
def test_ordinary_words_in_a_field_name_do_not_fire(): """'target', 'sequence', 'position', 'notes' and 'reasoning' appear in almost every correct answer. A token list that matched them would make this guard fire constantly and therefore be switched off.""" run = _run(20) for innocent in ("The target gene is MSTN and the sequence is sourced.", "My reasoning: position 412 sits inside the CDS.", "See the notes column for details on each guide."): assert O._claim_audit(run, innocent) == [], innocent
# ββ shape, cost, and that it is actually reached ββββββββββββββββββββββ
def test_an_empty_answer_is_not_audited(): assert O._claim_audit(_run(20), "") == [] assert O._claim_audit(_run(20), " ") == []
def test_findings_are_bounded(): run = _run(5) noisy = " ".join(f"guide {i}" for i in range(6, 60)) assert len(O._claim_audit(run, noisy)) <= 6
def test_one_finding_per_tool_for_unseen_columns(): """Four hidden columns in one sentence is one problem, not four.""" found = O._claim_audit( _run(20), "Off-target, frameshift, indel and efficacy all favour guide 1.") unseen = [f for f in found if "never sent" in f] assert len(unseen) == 1
def test_the_completion_audit_carries_it(): """A sanitiser nothing calls is the dead-gate bug again. The claim findings have to ride the EXISTING one-bounded-retry machinery rather than adding a second correction loop.""" run = _run(20) audit = O._completion_audit(run, "Guide 23 is best.") assert audit["status"] == "attention" assert audit["unresolved"] and audit["claims"] # Without a draft answer the audit means exactly what it used to. assert O._completion_audit(run)["status"] == "verified"
def test_an_execution_only_run_is_told_what_it_was_always_told(): """The extra sentence about read_result must not appear on a run whose findings are all failed work β the remedy there is to run something.""" run = _run(20) assert O._completion_audit(run, "Guide 1 is best.")["claims"] == []
def test_the_retry_prompt_names_the_right_remedy(): src = (O.__file__.replace(".pyc", ".py")) body = open(src, encoding="utf-8").read() i = body.index("pre-handoff verification") window = body[i:i + 2400] assert 'audit.get("claims")' in window, ( "the claim findings get the generic 'repair the work' prompt, which " "tells the agent to re-run a tool that already answered correctly" ) # Split across a source line break, so match the unwrapped half. assert "re-run the tool" in window123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189"""Going back for work that outlived the turn.
THE GAP. blast_sequence waits AGENT_WAIT_SECONDS and then answershonestly: "still running, here is the job_id, carry on with somethingelse." The search keeps going on its own thread. Nothing ever went backfor it, so the answer arrived in memory and was never read by anybody.
WHY RE-CALLING blast_sequence IS NOT THE FIX. _blast.submit does reuse acached job for the same sequence, so a second call is not a second NCBIsubmission β but that path goes THROUGH the sequence, and the sequence isexactly what the agent may no longer have. A long conversation compacts,the letters are evicted, and this project's standing rule is that an agentnever retypes a sequence from memory. At that point the finished search isunreachable: the only handle to it was a parameter that no longer exists.
The job_id is a handle to the WORK rather than to its input, and it issmall enough to survive a summary line. That is the whole design.
WHAT THIS DELIBERATELY DOES NOT DO: wake a run that has already ended.That needs a watcher outliving the run, and this deploys to a Space thatsleeps when idle β a watcher there fires sometimes, which is worse thanone that fires when asked. Collection is explicit."""import threadingimport time
import pytest
from dee.core import agent_tools as T, blast as B, orchestrator as O
@pytest.fixturedef job(): j = B.BlastJob(job_id="testjob01", seq_hash="h", kind="protein") with B._LOCK: B._BY_ID[j.job_id] = j yield j with B._LOCK: B._BY_ID.pop(j.job_id, None)
def _finish(j, hits=None, delay=0.2): def go(): time.sleep(delay) j.hits = hits if hits is not None else [ {"title": "myostatin [Homo sapiens]", "identity_pct": 99.4, "accession": "NP_005250"}] j.status = "done" j.finished_at = time.time() threading.Thread(target=go, daemon=True).start()
# ββ the answer is reachable without the sequence ββββββββββββββββββββββ
def test_a_finished_job_is_collected_by_its_id_alone(job): """No sequence argument anywhere. That is the point.""" _finish(job, delay=0) time.sleep(0.1) out = T._tool_collect_job({"job_id": "testjob01"}) assert out["ok"] and out["hit_count"] == 1 assert out["top"]["identity_pct"] == 99.4
def test_it_can_wait_for_one_that_is_nearly_done(job): _finish(job, delay=0.3) out = T._tool_collect_job({"job_id": "testjob01", "wait_seconds": 10}) assert out["ok"] and out["hit_count"] == 1
def test_a_job_still_running_says_so_and_keeps_the_handle(job): out = T._tool_collect_job({"job_id": "testjob01"}) assert not out["ok"] and out["kind"] == "still_running" assert out["job_id"] == "testjob01", ( "the handle is gone, so there is no way back to this search at all" ) assert "invent" in out["next"].lower()
def test_no_hits_is_reported_as_a_finding_not_a_failure(job): _finish(job, hits=[], delay=0) time.sleep(0.1) out = T._tool_collect_job({"job_id": "testjob01"}) assert out["ok"] and out["hit_count"] == 0 assert "novel or synthetic" in out["next"]
def test_a_failed_search_never_becomes_hits(job): job.status = "error" job.error = "NCBI returned 502" out = T._tool_collect_job({"job_id": "testjob01"}) assert not out["ok"] and out["error"] == "NCBI returned 502" assert "Do not describe" in out["next"] or "did not answer" in out["next"]
# ββ honest failure ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def test_a_job_this_server_never_had_says_what_to_do(): """Lost to a restart is the normal reason. Saying only 'not found' invites the agent to fill the gap from memory, which is the one thing it must not do with BLAST hits.""" out = T._tool_collect_job({"job_id": "doesnotexist"}) assert not out["ok"] and out["kind"] == "unknown_job" assert "do not describe hits from memory" in out["next"].lower()
def test_an_unknown_service_lists_the_ones_that_exist(): out = T._tool_collect_job({"job_id": "x", "kind": "alphafold"}) assert not out["ok"] and "blast" in out["error"]
def test_a_missing_id_is_refused(): assert not T._tool_collect_job({})["ok"]
def test_the_wait_is_bounded(job, monkeypatch): """The drive thread is held for this. Unbounded, a hung NCBI would hold it until the run's own timeout. The ceiling is lowered here rather than waited out β a test that really sleeps two minutes to prove a clamp is a test people delete.""" monkeypatch.setattr(T, "_COLLECT_WAIT_MAX", 0.5) started = time.time() out = T._tool_collect_job({"job_id": "testjob01", "wait_seconds": 10_000}) assert time.time() - started < 5, "the requested wait was not clamped" assert out["kind"] == "still_running"
def test_a_nonsense_wait_does_not_crash_the_collection(job): assert T._tool_collect_job({"job_id": "testjob01", "wait_seconds": "nonsense"})["kind"] == "still_running"
# ββ it is reachable, and only when there is something to reach ββββββββ
def test_the_handle_survives_on_the_event_not_only_in_history(): """Compaction evicts the model's copy of the result. If the job_id lives only there, the job becomes uncollectable at exactly the moment collecting it matters.""" run = O.Run(run_id="r", owner="u", anonymous=False) run.events.append({"kind": "tool_result", "id": "c1", "name": "blast_sequence", "ok": False, "result_kind": "still_running", "job_id": "abc123", "ui": None}) assert O._pending_jobs(run) == ["abc123"]
def test_a_finished_search_is_not_pending(): run = O.Run(run_id="r", owner="u", anonymous=False) run.events.append({"kind": "tool_result", "id": "c1", "name": "blast_sequence", "ok": True, "result_kind": None, "ui": {"panel": {}}}) assert O._pending_jobs(run) == []
def test_the_tool_is_offered_only_once_something_is_pending(): run = O.Run(run_id="r", owner="u", anonymous=False) names = lambda r: [s["function"]["name"] for s in O.active_tool_specs(r)] assert "collect_job" not in names(run) run.events.append({"kind": "tool_result", "id": "c1", "name": "blast_sequence", "ok": False, "result_kind": "still_running", "job_id": "abc123", "ui": None}) assert "collect_job" in names(run)
def test_the_runtime_puts_the_job_id_on_the_event(): src = open(O.__file__.replace(".pyc", ".py"), encoding="utf-8").read() # The REAL tool path's emit, not read_result's own (which has no job). i = src.index('"result_kind": result.get("kind")') assert 'result.get("job_id")' in src[i:i + 600], ( "the tool_result event no longer carries job_id, so _pending_jobs " "finds nothing and collect_job is never offered" )
def test_blast_points_at_the_collector_rather_than_at_itself(): """'Try again shortly' reads as 'call me again', which needs the sequence the agent may not have.""" src = open(T.__file__.replace(".pyc", ".py"), encoding="utf-8").read() i = src.index('"kind": "still_running", "job_id": job.job_id') window = src[i:i + 700] assert "collect_job" in window assert "do not re-send the" in window.lower()
def test_it_is_registered_and_categorised(): from dee.core import capabilities names = [s["function"]["name"] for s in O.TOOL_SPECS] assert "collect_job" in names assert capabilities.uncategorised(O.TOOL_SPECS) == []378 unmodified lines379380381382383384378 unmodified lines# Physical chemistry and codon arithmetic on sequences the caller already# holds. Nothing transmitted, nothing stored."assess_solubility", "assess_expression",}378 unmodified lines379380381382383384385386387388389390391392378 unmodified lines# Physical chemistry and codon arithmetic on sequences the caller already# holds. Nothing transmitted, nothing stored."assess_solubility", "assess_expression",# Reads back a BLAST this run already started. blast_sequence is gated# precisely because it is the one tool that sends the user's residues# off-Space, and it took that consent when it submitted; collecting the# answer transmits nothing new and cannot start a search β there is no# sequence parameter, only a job_id that must already exist in memory.# Gating it would make the agent ask twice for one transmission, which# trains people to click through the prompt that matters."collect_job",}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""What the tool catalog costs, and why it is not loaded lazily.
THE CATALOG IS IN THE CACHED PREFIX. dee/core/llm.py puts one Anthropiccache breakpoint on the system message, and because Anthropic renderstools before the system prompt, that one breakpoint caches the tool specsand the system prompt together β the ~14.5k tokens re-sent on every step.Everything below follows from that: the catalog is paid in full on a cacheMISS and at roughly a tenth of that on a hit.
THE CASE FOR LAZY LOADING, AND WHY IT LOSES. Forty-seven tools is a lot tochoose from, especially for the small model this orchestrates with, andhalving the surface would halve the prefix. But the saving is in cachedreads, which are the cheap ones, while the cost is in extra misses, whichare the expensive ones β and a lazy catalog is not monotonic, so it missesevery time the offered set changes. Measured against the real specs, at$0.75/M input with the standard ~10x hit/miss ratio:
10-step run, current (14.5k prefix, 2 misses) $0.0360 10-step run, lazy (7k prefix, 5 misses) $0.0355 10-step run, lazy (7k prefix, 9 misses) $0.0597
A wash at moderate churn and worse at high churn β for a product where"which tool do I need next" changes step to step. And the cents are noteven the binding constraint: a find_tool call burns a STEP, and the budgetis MAX_STEPS 24. Four lookups is four steps not spent on science, out oftwenty-four.
WHAT THE GATE ALREADY DOES, monotonically and for one miss: 47 specs downto 22 on a cold run, which is 53% off at step 1 β exactly the moment themodel has least to go on and the surface matters most.
SO THIS FILE IS NOT A LAZY CATALOG. It is the measurement that made thedecision, kept runnable, plus a ceiling: a tool added with a 5k-characterschema is a tax on every step of every run by every user, and that shouldfail a test rather than be discovered on a bill. Revisit the decision whenthere is a task-level eval that can measure tool-selection accuracy β whichis the only claimed benefit still unmeasured, and the same gap theTOOL_GATE comment already admits to."""import json
from dee.core import orchestrator as O
def _chars(specs): return len(json.dumps(specs))
def _cold_run(): return O.Run(run_id="cold", owner="u", anonymous=False)
def _warm_run(): run = O.Run(run_id="warm", owner="u", anonymous=False) run.sequence_seen = True run.library_seen = True run.target = {"sequence": "ATGC" * 50} return run
# ββ the ceiling βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ~4 chars per token. The whole catalog, before any gating.MAX_CATALOG_CHARS = 72_000# What a cold run actually sends β the number that matters most, because# step 1 is a cache miss for everybody.MAX_COLD_CHARS = 34_000# No single tool may dominate the prefix.MAX_ONE_SPEC_CHARS = 3_500
def test_the_whole_catalog_stays_under_its_ceiling(): total = _chars(O.TOOL_SPECS) assert total < MAX_CATALOG_CHARS, ( f"the tool catalog is {total:,} chars (~{total // 4:,} tokens) and is " f"re-sent on every step of every run. Trim a description or justify " f"raising the ceiling here." )
def test_a_cold_run_sends_about_half_the_catalog(): """The gate's whole purpose. If this converges on the full catalog the gate has stopped working, and step 1 β the cache miss everybody pays β doubles.""" cold = _chars(O.active_tool_specs(_cold_run())) assert cold < MAX_COLD_CHARS, f"cold run sends {cold:,} chars" assert cold < _chars(O.TOOL_SPECS) * 0.70, ( "the sequence/library/target gates are barely removing anything; " "either a new tool declares no sequence argument when it needs one, " "or the gate is no longer reached" )
def test_no_single_tool_dominates_the_prefix(): worst = max(O.TOOL_SPECS, key=lambda s: len(json.dumps(s))) size = len(json.dumps(worst)) assert size < MAX_ONE_SPEC_CHARS, ( f"{worst['function']['name']} is {size:,} chars of every prompt. " f"Move the detail into the tool's RESULT, which is paid once, " f"instead of its description, which is paid every step." )
def test_the_gate_only_ever_opens(): """The economics above depend on monotonicity: a set that opens once costs one extra miss, a set that changes costs one per change. If a gate ever CLOSED mid-run this file's conclusion would flip.""" cold = {s["function"]["name"] for s in O.active_tool_specs(_cold_run())} warm = {s["function"]["name"] for s in O.active_tool_specs(_warm_run())} assert cold <= warm, ( f"these tools vanish once the run warms up: {sorted(cold - warm)}. " f"A shrinking surface costs a cache miss and can strand the agent " f"mid-plan." )
def test_the_read_back_tools_cost_what_the_audit_said(): """read_result, analyze and collect_job are all gated shut until there is something to act on, so none of them is on the cold path.""" cold = {s["function"]["name"] for s in O.active_tool_specs(_cold_run())} for late in ("read_result", "analyze", "collect_job"): assert late not in cold, ( f"{late} is offered before it can possibly succeed, which costs " f"its schema on the one request nobody can cache" )dee/core/agent_tools.py+145-3
dee/core/analysis.pyAdded+242
dee/core/capabilities.py+7-1
dee/core/orchestrator.py+386-6
tests/test_analysis.pyAdded+255
tests/test_claim_audit.pyAdded+197
tests/test_collect_job.pyAdded+189
tests/test_confirm_gate.py+8
tests/test_tool_catalog_cost.pyAdded+125