Spaces:
Running
Running
github-actions[bot] commited on
Commit ·
f8413f1
1
Parent(s): 57de896
Deploy 18b4593
Browse filesMerge pull request #249 from WINTER4000/fix/orchestrator-conversation-recovery
Source: https://github.com/WINTER4000/turingDNA/commit/18b4593875209cdc9fbbbdaabf237de5f1c36e40
Files changed (7)
1067 unmodified lines1068106910701071107210731067 unmodified lines"model": current_model(),"host": host,"wt_length_aa": len(protein),# Scoring is always full-length (context matters); the pool may be# windowed. Reporting both stops the agent from describing a targeted# library as if it had searched the whole protein.1067 unmodified lines10681069107010711072107310741067 unmodified lines"model": current_model(),"host": host,"wt_length_aa": len(protein),"wt_protein": protein, # immutable model reference retained for downstream interaction analysis# Scoring is always full-length (context matters); the pool may be# windowed. Reporting both stops the agent from describing a targeted# library as if it had searched the whole protein.
342 unmodified lines343344345346347348342 unmodified lines"the list' — the catalogue is small and deliberately conservative."),}if paste.get("header"):result["header_claim"] = {"text": paste["header"],342 unmodified lines343344345346347348349350351352353354355342 unmodified lines"the list' — the catalogue is small and deliberately conservative."),}if molecule == "dna" and detail.get("is_clean_cds") and not detail.get("ambiguity_codes"):result["protein"] = _edits.translate(residues).rstrip("*")result["translation"] = {"source": "input CDS", "genetic_code": "standard (table 1)","note": "Deterministic translation, not gene identity or experimental validation. Confirm the genetic code for this organism.",}if paste.get("header"):result["header_claim"] = {"text": paste["header"],
328 unmodified lines329330331332333334372 unmodified lines7077087097107117122 unmodified lines71571671771871972072152 unmodified lines77477577677777877978014 unmodified lines79579679779879980080118 unmodified lines8208218228238248258268278283 unmodified lines8328338348358368374 unmodified lines842843844845846847259 unmodified lines110711081109111011111112127 unmodified lines1240124112421243124412451246101 unmodified lines1348134913501351135213531354160 unmodified lines151515161517151815191520303 unmodified lines182418251826182718281829135 unmodified lines19651966196719681969197056 unmodified lines202720282029203020312032203320342035203620372038203920402041204215 unmodified lines20582059206020612062206320642065206620672068206943 unmodified lines21132114211521162117211829 unmodified lines214821492150215121522153136 unmodified lines229022912292229322942295229624 unmodified lines232123222323232423252326232712 unmodified lines2340234123422343234423452346234723482349235023519 unmodified lines23612362236323642365236623672368236923702371222 unmodified lines2594259525962597259825992600105 unmodified lines270627072708270927102711271210 unmodified lines2723272427252726272727282729273027312732273327342735160 unmodified lines28962897289828992900290121 unmodified lines292329242925292629272928529 unmodified lines34583459346034613462346314 unmodified lines347834793480348134823483119 unmodified lines360336043605360636073608439 unmodified lines404840494050405140524053405440554056405740584059406013 unmodified lines40744075407640774078407940804081159 unmodified lines42414242424342444245424642472 unmodified lines4250425142524253425442554256425742584259767 unmodified lines502750285029503050315032328 unmodified linesreturn f"Runs {_tool_verb(name)} — this one changes your saved work."def _sourced_pool(run: Run) -> set:"""Every sequence this run has legitimately seen.372 unmodified linesreturn text[:limit]def _outcome_brief(run: "Run", completion: str) -> Optional[Dict[str, Any]]:"""Build a bounded, sequence-free briefing from events already shown.2 unmodified linesintegrity record for that result. This makes the card safe to persist andreplay as the briefing when the scientist returns to the run."""results = [e for e in run.events if e.get("kind") == "tool_result"]worked = [e for e in results if e.get("ok") and e.get("summary")]if not worked:return None52 unmodified linespartial = completion == "partial" or bool(missing)return {"status": "partial" if partial else "complete","objective": _brief_text(run.goal or run.title or "Scientific workflow", 400),"findings": findings,"failures": failures,"evidence": {14 unmodified linesand how many integrity checks actually ran. A bounded correction step in``_drive`` gives Turing one chance to repair the work before handoff."""results = [e for e in run.events if e.get("kind") == "tool_result"]if not results and not run.evidence:return {"status": "not_applicable", "checks": [], "unresolved": []}18 unmodified lineslatest_evidence: Dict[Tuple[str, str], Dict[str, Any]] = {}for item in run.evidence:key = (str(item.get("tool") or ""), str(item.get("input_ref") or ""))latest_evidence[key] = itempassed = 0for item in latest_evidence.values():call_index, event = by_call.get(str(item.get("call_id") or ""), (-1, {}))missing = [str(value)[:300] for value in (item.get("missing") or []) if value]3 unmodified linesor call_index > last_success)if blocks:unresolved.extend(missing)elif item.get("status") == "produced":passed += len(item.get("checks") or []) or 1if passed:4 unmodified lines"status": "attention" if unresolved else "verified","checks": checks[:6],"unresolved": unresolved,}259 unmodified lines# the configured primary); once a fallback succeeds it stays pinned so an# outage does not cost three primary retries on every later step.serving_model: str = ""# request_key → {count, name, summary} for every tool call this run has# EXECUTED. Feeds two things: the refusal of a call already made# MAX_IDENTICAL_TOOL_CALLS times, and the distinct-work test in127 unmodified lines"extensions", "step_base", "step_allowance", "cost_checkpoint_ack","tools_run", "tools_at_checkpoint", "inbox","continuity", "memories", "instructions", "cost_limit_usd", "budget_spent","library_seen", "serving_model")})latest_outcome = next((e for e in reversed(run.events)if e.get("kind") == "outcome"), None)outcome_meta = None101 unmodified lines"extensions", "step_base", "step_allowance", "cost_checkpoint_ack","tools_run", "tools_at_checkpoint", "inbox","continuity", "memories", "instructions", "cost_limit_usd", "budget_spent","library_seen", "serving_model"):if key in execution:setattr(run, key, copy.deepcopy(execution[key]))run.persistence_revision = int(_meta.get("revision") or 0)160 unmodified lines"gene_symbol": str(result.get("gene_symbol") or "")[:32],"organism": str(args.get("organism") or "")[:48],"kind": str(result.get("kind") or "")[:24],"source": str(result.get("source") or "")[:24],"length": int(result.get("length") or len(seq)),"sequence": seq,303 unmodified linesargs = json.loads(fn.get("arguments") or "{}")except (TypeError, ValueError):continue # the loop will report the bad JSONif _guard_tool_args(run, args):continue # about to be refused — do not computeeligible.append((call_id, name, args))135 unmodified linesreturn Nonedropped = run.history[:cut]note = _digest_dropped(dropped, _tool_summaries(run))head: List[Dict[str, Any]] = []# Re-pin the original goal. Everything else about a run is recoverable56 unmodified lines# show prose as it is written instead of after the whole step lands. OFF by# default: it changes the hot path of every run, so it ships dark and is enabled# with TURINGDNA_STREAM=1 once smoke-tested on the Space. Any streaming-layer# failure falls back to the trusted non-streaming call, so turning it on can# only affect time-to-first-token, never correctness._STREAM = os.environ.get("TURINGDNA_STREAM", "0") == "1"def _call_model(run: "Run", config: "_llm.OpenRouterConfig",body: Dict[str, Any]) -> Tuple[Dict[str, Any], float, int, int, str]:"""One model call for the loop. Streams into run.live_text when enabled,falling back to the non-streaming path on any streaming failure so a streambug degrades to today's behaviour instead of breaking the run."""primary = run.serving_model or config.modelmodels = [primary]if primary == config.model:15 unmodified lineslambda frag: setattr(run, "live_text", run.live_text + frag))except _llm.AgentError:raiseexcept Exception: # noqa: BLE001 — streaming plumbing onlylogger.warning("streaming failed; falling back to non-streaming",exc_info=True)run.live_text = ""result = _llm.call(selected, payload)finally:run.streaming = Falseexcept _llm.AgentError as exc:43 unmodified lines# the life of the drive. See llm.bind_abort_hook._llm.bind_abort_hook(lambda: run.stop_requested)try:while True:# ── Out of steps? Buy more, if this is still work. ────────────# The step budget used to end the stretch and make the user type29 unmodified linessteers = run.inbox[:]run.inbox.clear()for msg in steers:run.history.append({"role": "user", "content": msg})_emit(run, "steer", {"text": msg})136 unmodified linesif not tool_calls:completion = "complete"provenance_seen = bool(withheld) or any(event.get("kind") == "provenance" for event in run.events)unfinished = [p.get("step", "") for p in run.planif p.get("status") in ("pending", "active")]if (unfinished and run.plan_updated_this_stretch24 unmodified lines"[TuringDNA pre-handoff verification] Do not finish yet. ""The execution record has unresolved work:\n- "+ "\n- ".join(audit["unresolved"][:8])+ "\nUse the available tools to repair what is recoverable. ""If it cannot be repaired, state the limitation ""plainly and do not describe the objective as complete.")})12 unmodified linestext = (text + "\n\n" + notice) if text else noticeif audit["unresolved"]:completion = "partial"# We cannot prove that the model's prose acknowledged the# gap. Replace it rather than appending a warning beneath a# potentially unsafe "ready to order" claim.text = ("Work remains incomplete. Pre-handoff verification ""found: " + "; ".join(audit["unresolved"][:4]) + ".")if run.evidence or audit["status"] != "not_applicable":latest = {(e["tool"], e.get("request_key", e.get("input_ref"))): efor e in run.evidence}report = {"items": copy.deepcopy(list(latest.values())),9 unmodified linesif provenance_seen:text += " An unsourced sequence was withheld."decision = run.decisions.get("cases", {}).get(run.decisions.get("active"))if decision and decision["recommendation"]["status"] == "needs_review":notice = "The recorded scientific recommendation needs review because its supporting argument changed."text = (text + "\n\n" + notice) if completion == "partial" else noticecompletion = "partial"if decision.get("follow_up"):text += "\nProposed next action: " + decision["follow_up"]["action"]if text:_emit(run, "text", {"text": text})222 unmodified linestry:args = _integrity.bind_reference(run.molecules, name, args)field = _integrity.REFERENCE_INPUTS.get(name)if field and args.get(field) and not input_ref:input_ref = _integrity.register_molecule(run.molecules, args[field])except (ValueError, TypeError) as exc:failure = {"ok": False, "kind": "invalid_reference", "error": str(exc)}105 unmodified lines# Only pass a real id — an anonymous run must never resolve to a row.run.tools_run += 1_note_tool_call(run, name, args)if precomputed is not None:result = precomputedelse:def progress(state):10 unmodified lines# call: a tool that spends the rest of the allowance must stop the run at# the tool, not one LLM round-trip later._meter_compute(run)model_result = _strip_ui(result)# Bind BEFORE the event is emitted, so the very next system prompt — the# one the model plans with — already knows what this run is about._bind_target(run, name, args, result)if run.target.get("sequence"):run.target["sequence_ref"] = _integrity.register_molecule(run.molecules, run.target["sequence"], kind=run.target.get("kind", ""),features=run.target.get("features"), topology=run.target.get("topology", ""))encoded_result = _integrity.model_record(model_result, run.molecules)with _RUNS_LOCK:160 unmodified linesit — the same reasoning as the fabrication refusal, which names the tool toreach for instead of simply saying no."""try:seen = run.tool_call_counts.get(_call_key(run, name, args))except Exception: # noqa: BLE001 — unhashable/unserialisable args21 unmodified linesdef _note_tool_call(run: Run, name: str, args: Dict[str, Any]) -> None:"""Record that this exact call executed. Called once per real execution."""try:key = _call_key(run, name, args)except Exception: # noqa: BLE001529 unmodified lineswould be a cross-account leak, not merely a bug."""set_workspace(run, workspace, message)if carry_from is not None:if not run.owner or carry_from.owner != run.owner or carry_from.anonymous:raise ValueError("carry_from must be a run the same owner started")14 unmodified linesif pending:_apply_handover(run, pending, str(pending.get("run_id") or ""),inherit=False)# The opening ask names the run in the history list. Set once, so a long# conversation keeps the title it started with rather than renaming# itself to whatever was asked last.119 unmodified lines# instant before the claim), not run.status, for exactly that reason.if prev_status in ("done", "error", "stopped"):run.evidence = []set_workspace(run, workspace, message)if not run.title:run.title = _title_for(message)439 unmodified linesspecs = copy.deepcopy(TOOL_SPECS)for spec in specs:fn = spec.get("function") or {}field = _integrity.REFERENCE_INPUTS.get(fn.get("name"))if field:params = fn["parameters"]params.setdefault("properties", {})["sequence_ref"] = {"type": "string", "description": "Exact molecular reference from a tool result or bound target. Prefer this over copying sequence letters."}params["required"] = [k for k in params.get("required", []) if k != field]params["anyOf"] = [{"required": [field]}, {"required": ["sequence_ref"]}]out = []for spec in specs:name = (spec.get("function") or {}).get("name", "")13 unmodified linesSYSTEM_PROMPT = ("You are Turing, the orchestrator of TuringDNA — a directed-evolution ""workbench. You do not describe work; you DO it, by calling tools, and ""the scientist watches each step land in their workspace as you go.\n\n""SCIENTIFIC DECISIONS\n""For competing explanations, interpretation of assay results, or deciding what experiment to run next, "159 unmodified lines"which domain, ask.\n"" - check_interactions before anyone commits a MULTI-mutant to ""synthesis. Good single mutations do not reliably stack, and this is the ""only way to see a clash before the bench does.\n"" - check_prior_art before a big commitment of bench time, so they don't ""spend a quarter re-deriving a published result. Report it as context to ""review; it is NOT a freedom-to-operate opinion and an empty result "2 unmodified lines"POINT AT WHAT YOU ARE TALKING ABOUT\n""The scientist is looking at a bench, not just a chat rail. When you name ""a specific thing — a variant, a residue, a guide, a feature on their map ""— call focus_on with it in the same turn, so the canvas scrolls there ""and highlights it while they read your sentence. \"The clash is at 1099\" ""lands very differently when 1099 is on screen.\n""It costs nothing and changes nothing, so use it freely for the thing ""that matters — but pointing at everything is the same as pointing at ""nothing. One target per point you are making. And it is a request, not ""a guarantee: if the thing isn't rendered, nothing moves, so never write "767 unmodified lines+ _instructions_note(instructions or {})+ _workspace_note(workspace or {})+ capability_state+ _target_note(target or {})+ ("\nExact input reference: " + str(target["sequence_ref"])+ ". Pass sequence_ref to design tools instead of copying sequences.\n"328 unmodified lines329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410372 unmodified lines7837847857867877887897907917927932 unmodified lines79679779879980080180252 unmodified lines85585685785885986086114 unmodified lines87687787887988088188218 unmodified lines9019029039049059069079089099103 unmodified lines9149159169179189199204 unmodified lines925926927928929930931259 unmodified lines119111921193119411951196119711981199120012011202127 unmodified lines13301331133213331334133513361337101 unmodified lines14391440144114421443144414451446160 unmodified lines1607160816091610161116121613303 unmodified lines1917191819191920192119221923192419251926192719281929135 unmodified lines20652066206720682069207020712072207356 unmodified lines2130213121322133213421352136213721382139214021412142214315 unmodified lines21592160216121622163216421652166216721682169217043 unmodified lines22142215221622172218221922202221222229 unmodified lines22522253225422552256225722582259136 unmodified lines239623972398239924002401240224 unmodified lines242724282429243024312432243312 unmodified lines2446244724482449245024512452245324542455245624579 unmodified lines24672468246924702471247224732474247524762477247824792480248124822483248424852486222 unmodified lines27092710271127122713271427152716105 unmodified lines282228232824282528262827282828292830283110 unmodified lines2842284328442845284628472848284928502851285228532854285528562857285828592860286128622863160 unmodified lines3024302530263027302830293030303121 unmodified lines30533054305530563057305830593060529 unmodified lines359035913592359335943595359614 unmodified lines3611361236133614361536163617119 unmodified lines3737373837393740374137423743374437453746439 unmodified lines418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421013 unmodified lines4224422542264227422842294230423142324233423442354236423742384239159 unmodified lines43994400440144024403440444052 unmodified lines4408440944104411441244134414441544164417767 unmodified lines51855186518751885189519051915192519351945195328 unmodified linesreturn f"Runs {_tool_verb(name)} — this one changes your saved work."def _resolution_key(args: Dict[str, Any]) -> str:return json.dumps([str(args.get("text") or "").strip().casefold(),str(args.get("organism") or "").strip().casefold()])def _resolved_sequence(run: "Run", name: str, args: Dict[str, Any]):"""Reuse only an exact, successful lookup in THIS owned conversation."""if name != "fetch_sequence":return Nonerecord = run.resolved_sequences.get(_resolution_key(args))if not record:# Older saved conversations predate the per-run lookup index. Recover# only a successful tool reply paired with the exact original request.calls = {}for message in run.history:if message.get("role") == "assistant":for call in message.get("tool_calls") or []:fn = call.get("function") or {}if fn.get("name") == "fetch_sequence":try:request = json.loads(fn.get("arguments") or "{}")if isinstance(request, dict):calls[call.get("id")] = _resolution_key(request)except (TypeError, ValueError):passelif (message.get("role") == "tool"and calls.get(message.get("tool_call_id")) == _resolution_key(args)):try:result = json.loads(message.get("content") or "{}")if isinstance(result, dict) and result.get("ok"):ref = result.get("sequence_ref")if not ref and result.get("sequence"):ref = _integrity.register_molecule(run.molecules, result["sequence"], kind=result.get("molecule") or "")if ref in run.molecules:record = {k: v for k, v in result.items() if k not in {"sequence", "_ui"}}record["sequence_ref"] = refexcept (TypeError, ValueError):passif not record:return Nonerun.resolved_sequences[_resolution_key(args)] = recordmolecule = run.molecules.get(record.get("sequence_ref"))if not molecule:return Nonereturn dict(record, sequence=molecule["sequence"], reused_from_run=True)def _remember_pasted_sequences(run: "Run", message: str) -> None:"""Keep the scientist's actual inputs when old chat text is compacted.Space-wrapped DNA is common in pasted records. Never join ordinary words,infer an organism, bind a target, or send these records to a shared cache."""dna = [re.sub(r"\s+", "", m.group()).upper() for m in re.finditer(r"(?<![A-Za-z])(?:[ACGTUNacgtun]{30,}\s*)+(?![A-Za-z])", message)]candidates = [(v, "dna") for v in dna]for _, sequence, kind in _prov.extract_sequences(message):if not any(sequence in v for v in dna):candidates.append((sequence, "dna" if kind == "nt" else "protein"))for sequence, kind in candidates:ident = _integrity.register_molecule(run.molecules, sequence, kind=kind)run.molecules[ident].setdefault("label", "User-provided sequence")def _molecular_inventory(run: "Run") -> str:entries = [{"sequence_ref": ref, "kind": mol.get("kind"),"length": len(mol["sequence"]), "label": mol.get("label", "Tool-derived molecule")}for ref, mol in list(run.molecules.items())[-16:]]if not entries:return ""return ("\nAVAILABLE MOLECULES (exact stored inputs; use references, never retype):\n"+ json.dumps(entries) + "\nUse compare_sequences with sequence_a_ref/sequence_b_ref ""to compare a paste against a retrieved reference. A gene name alone does not establish identity. ""identify_sequence supplies a translated protein for a clean complete CDS.\n")def _sourced_pool(run: Run) -> set:"""Every sequence this run has legitimately seen.372 unmodified linesreturn text[:limit]def _turn_results(run: "Run") -> List[Dict[str, Any]]:return [e for e in run.events[run.turn_event_start:]if e.get("kind") == "tool_result" and e.get("name") != "focus_on"]def _outcome_brief(run: "Run", completion: str) -> Optional[Dict[str, Any]]:"""Build a bounded, sequence-free briefing from events already shown.2 unmodified linesintegrity record for that result. This makes the card safe to persist andreplay as the briefing when the scientist returns to the run."""results = _turn_results(run)worked = [e for e in results if e.get("ok") and e.get("summary")]if not worked:return None52 unmodified linespartial = completion == "partial" or bool(missing)return {"status": "partial" if partial else "complete","objective": _brief_text(run.turn_request or run.goal or run.title or "Scientific workflow", 400),"findings": findings,"failures": failures,"evidence": {14 unmodified linesand how many integrity checks actually ran. A bounded correction step in``_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": []}18 unmodified lineslatest_evidence: Dict[Tuple[str, str], Dict[str, Any]] = {}for item in run.evidence:key = (str(item.get("tool") or ""), str(item.get("request_key") or item.get("input_ref") or ""))latest_evidence[key] = itempassed = 0invalid_output = Falsefor item in latest_evidence.values():call_index, event = by_call.get(str(item.get("call_id") or ""), (-1, {}))missing = [str(value)[:300] for value in (item.get("missing") or []) if value]3 unmodified linesor call_index > last_success)if blocks:unresolved.extend(missing)invalid_output |= not event or bool(event.get("ok"))elif item.get("status") == "produced":passed += len(item.get("checks") or []) or 1if passed:4 unmodified lines"status": "attention" if unresolved else "verified","checks": checks[:6],"unresolved": unresolved,"invalid_output": invalid_output,}259 unmodified lines# the configured primary); once a fallback succeeds it stays pinned so an# outage does not cost three primary retries on every later step.serving_model: str = ""# A conversation contains several independent requests. Receipts and# verification cover the current request, while molecular work is durable.turn_event_start: int = 0turn_request: str = ""resolved_sequences: Dict[str, Any] = field(default_factory=dict)decision_notices: Dict[str, int] = field(default_factory=dict)# request_key → {count, name, summary} for every tool call this run has# EXECUTED. Feeds two things: the refusal of a call already made# MAX_IDENTICAL_TOOL_CALLS times, and the distinct-work test in127 unmodified lines"extensions", "step_base", "step_allowance", "cost_checkpoint_ack","tools_run", "tools_at_checkpoint", "inbox","continuity", "memories", "instructions", "cost_limit_usd", "budget_spent","library_seen", "serving_model", "turn_event_start", "turn_request","resolved_sequences", "decision_notices")})latest_outcome = next((e for e in reversed(run.events)if e.get("kind") == "outcome"), None)outcome_meta = None101 unmodified lines"extensions", "step_base", "step_allowance", "cost_checkpoint_ack","tools_run", "tools_at_checkpoint", "inbox","continuity", "memories", "instructions", "cost_limit_usd", "budget_spent","library_seen", "serving_model", "turn_event_start", "turn_request","resolved_sequences", "decision_notices"):if key in execution:setattr(run, key, copy.deepcopy(execution[key]))run.persistence_revision = int(_meta.get("revision") or 0)160 unmodified lines"gene_symbol": str(result.get("gene_symbol") or "")[:32],"organism": str(args.get("organism") or "")[:48],"kind": str(result.get("kind") or "")[:24],"molecule": str(result.get("molecule") or "")[:24],"source": str(result.get("source") or "")[:24],"length": int(result.get("length") or len(seq)),"sequence": seq,303 unmodified linesargs = json.loads(fn.get("arguments") or "{}")except (TypeError, ValueError):continue # the loop will report the bad JSONif (_repeat_refusal(run, name, args) is not Noneor _resolved_sequence(run, name, args) is not None):continuetry:args = _integrity.bind_reference(run.molecules, name, args)except (ValueError, TypeError):continueif _guard_tool_args(run, args):continue # about to be refused — do not computeeligible.append((call_id, name, args))135 unmodified linesreturn Nonedropped = run.history[:cut]for message in dropped:if message.get("role") == "user":_remember_pasted_sequences(run, str(message.get("content") or ""))note = _digest_dropped(dropped, _tool_summaries(run))head: List[Dict[str, Any]] = []# Re-pin the original goal. Everything else about a run is recoverable56 unmodified lines# show prose as it is written instead of after the whole step lands. OFF by# default: it changes the hot path of every run, so it ships dark and is enabled# with TURINGDNA_STREAM=1 once smoke-tested on the Space. Any streaming-layer# failure parks the run without resubmitting a potentially billed request._STREAM = os.environ.get("TURINGDNA_STREAM", "0") == "1"def _call_model(run: "Run", config: "_llm.OpenRouterConfig",body: Dict[str, Any]) -> Tuple[Dict[str, Any], float, int, int, str]:"""One model call. Retry only definitively rejected requests; a brokenresponse may already be billed and must never be silently purchased twice."""primary = run.serving_model or config.modelmodels = [primary]if primary == config.model:15 unmodified lineslambda frag: setattr(run, "live_text", run.live_text + frag))except _llm.AgentError:raiseexcept Exception as exc: # noqa: BLE001 — may already be billedlogger.warning("streaming response interrupted", exc_info=True)run.live_text = ""raise _llm.AgentError("The model response was interrupted. Your work is saved; resume to continue.",kind="stream_interrupted", fallback_safe=False) from excfinally:run.streaming = Falseexcept _llm.AgentError as exc:43 unmodified lines# the life of the drive. See llm.bind_abort_hook._llm.bind_abort_hook(lambda: run.stop_requested)try:for message in run.history:if message.get("role") == "user":_remember_pasted_sequences(run, str(message.get("content") or ""))while True:# ── Out of steps? Buy more, if this is still work. ────────────# The step budget used to end the stretch and make the user type29 unmodified linessteers = run.inbox[:]run.inbox.clear()for msg in steers:_remember_pasted_sequences(run, msg)run.turn_request = msg.strip()[:400]run.history.append({"role": "user", "content": msg})_emit(run, "steer", {"text": msg})136 unmodified linesif not tool_calls:completion = "complete"provenance_seen = bool(withheld) or any(event.get("kind") == "provenance" for event in run.events[run.turn_event_start:])unfinished = [p.get("step", "") for p in run.planif p.get("status") in ("pending", "active")]if (unfinished and run.plan_updated_this_stretch24 unmodified lines"[TuringDNA pre-handoff verification] Do not finish yet. ""The execution record has unresolved work:\n- "+ "\n- ".join(audit["unresolved"][:8])+ "\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.")})12 unmodified linestext = (text + "\n\n" + notice) if text else noticeif audit["unresolved"]:completion = "partial"notice = ("Open checks: " + "; ".join(audit["unresolved"][:4]) + ".")# An invalid scientific artifact must not be called ready.# A failed lookup, however, must not erase an explanation# or the evidence already available in this conversation.text = notice if audit.get("invalid_output") else ((text + "\n\n" + notice) if text else notice)if run.evidence or audit["unresolved"]:latest = {(e["tool"], e.get("request_key", e.get("input_ref"))): efor e in run.evidence}report = {"items": copy.deepcopy(list(latest.values())),9 unmodified linesif provenance_seen:text += " An unsourced sequence was withheld."decision = run.decisions.get("cases", {}).get(run.decisions.get("active"))decision_current = bool(decision) and (run.turn_event_start == 0 or any(e.get("kind") == "scientific_decision" and (e.get("decision") or {}).get("id") == decision["id"]for e in run.events[run.turn_event_start:]))if (decision and decision["recommendation"]["status"] == "needs_review"and (decision_current or run.decision_notices.get(decision["id"]) != decision["revision"])):run.decision_notices[decision["id"]] = decision["revision"]notice = "The recorded scientific recommendation needs review because its supporting argument changed."# An unresolved decision from THIS request must not be# presented as validated. Older decisions are background;# their reminder cannot erase an unrelated answer.text = notice if decision_current else ((text + "\n\n" + notice) if text else notice)if decision_current:completion = "partial"if decision_current and decision.get("follow_up"):text += "\nProposed next action: " + decision["follow_up"]["action"]if text:_emit(run, "text", {"text": text})222 unmodified linestry:args = _integrity.bind_reference(run.molecules, name, args)field = _integrity.REFERENCE_INPUTS.get(name)if (field and args.get(field) and not input_refand re.fullmatch(r"[A-Za-z*\s]+", str(args[field]))):input_ref = _integrity.register_molecule(run.molecules, args[field])except (ValueError, TypeError) as exc:failure = {"ok": False, "kind": "invalid_reference", "error": str(exc)}105 unmodified lines# Only pass a real id — an anonymous run must never resolve to a row.run.tools_run += 1_note_tool_call(run, name, args)cached_resolution = _resolved_sequence(run, name, args)if cached_resolution is not None:result = cached_resolutionelif precomputed is not None:result = precomputedelse:def progress(state):10 unmodified lines# call: a tool that spends the rest of the allowance must stop the run at# the tool, not one LLM round-trip later._meter_compute(run)if name == "fetch_sequence" and result.get("ok") and result.get("sequence"):key = _resolution_key(args)ident = _integrity.register_molecule(run.molecules, result["sequence"],kind=result.get("molecule") or "unspecified")run.molecules[ident].setdefault("label", str(result.get("label") or args.get("text") or "Resolved sequence")[:160])run.resolved_sequences[key] = dict({k: v for k, v in result.items() if k not in {"sequence", "_ui"}}, sequence_ref=ident)while len(run.resolved_sequences) > 16:del run.resolved_sequences[next(iter(run.resolved_sequences))]model_result = _strip_ui(result)# Bind BEFORE the event is emitted, so the very next system prompt — the# one the model plans with — already knows what this run is about._bind_target(run, name, args, result)if run.target.get("sequence"):run.target["sequence_ref"] = _integrity.register_molecule(run.molecules, run.target["sequence"], kind=run.target.get("molecule") or run.target.get("kind", ""),features=run.target.get("features"), topology=run.target.get("topology", ""))encoded_result = _integrity.model_record(model_result, run.molecules)with _RUNS_LOCK:160 unmodified linesit — the same reasoning as the fabrication refusal, which names the tool toreach for instead of simply saying no."""if name == "focus_on" or _resolved_sequence(run, name, args) is not None:return Nonetry:seen = run.tool_call_counts.get(_call_key(run, name, args))except Exception: # noqa: BLE001 — unhashable/unserialisable args21 unmodified linesdef _note_tool_call(run: Run, name: str, args: Dict[str, Any]) -> None:"""Record that this exact call executed. Called once per real execution."""if name == "focus_on":return # navigation must not earn another autonomous compute windowtry:key = _call_key(run, name, args)except Exception: # noqa: BLE001529 unmodified lineswould be a cross-account leak, not merely a bug."""set_workspace(run, workspace, message)run.turn_request = message.strip()[:400]if carry_from is not None:if not run.owner or carry_from.owner != run.owner or carry_from.anonymous:raise ValueError("carry_from must be a run the same owner started")14 unmodified linesif pending:_apply_handover(run, pending, str(pending.get("run_id") or ""),inherit=False)_remember_pasted_sequences(run, message)# The opening ask names the run in the history list. Set once, so a long# conversation keeps the title it started with rather than renaming# itself to whatever was asked last.119 unmodified lines# instant before the claim), not run.status, for exactly that reason.if prev_status in ("done", "error", "stopped"):run.evidence = []run.turn_event_start = len(run.events)run.turn_request = message.strip()[:400]run.provenance_retried = False_remember_pasted_sequences(run, message)set_workspace(run, workspace, message)if not run.title:run.title = _title_for(message)439 unmodified linesspecs = copy.deepcopy(TOOL_SPECS)for spec in specs:fn = spec.get("function") or {}fields = _integrity.reference_fields(fn.get("name"))if fields:params = fn["parameters"]alternatives = []for ref, field in fields.items():params.setdefault("properties", {})[ref] = {"type": "string", "description": f"Exact stored molecular reference for {field}; prefer over copying sequence letters."}if field in params.get("required", []):params["required"].remove(field)alternatives.append({"anyOf": [{"required": [field]}, {"required": [ref]}]})if alternatives:# Use the same anyOf shape already accepted by the provider;# paired inputs need all four literal/reference combinations.combinations = [list(branch.get("required", []))for branch in params.get("anyOf", [{}])]for choice in alternatives:combinations = [prior + branch["required"] for prior in combinationsfor branch in choice["anyOf"]]params["anyOf"] = [{"required": required} for required in combinations]out = []for spec in specs:name = (spec.get("function") or {}).get("name", "")13 unmodified linesSYSTEM_PROMPT = ("You are Turing, the orchestrator of TuringDNA — a directed-evolution ""workbench. Execute requested work with tools, and answer questions directly ""from the evidence already available. A follow-up explanation is not a new workflow.\n\n""SCOPE THE CURRENT REQUEST\n""Use the fewest relevant operations needed to answer or complete the current request. ""Do not run folding, interaction analysis, library lookup, annotation, or decision framing ""just because those capabilities exist. Check stored results before retrieving the same input again. ""When asked whether a pasted sequence is a named gene/CDS, distinguish a valid reading frame ""from identity: compare the supplied molecule with a sourced reference or interpret a completed BLAST. ""A gene lookup alone does not identify the user's paste. If a service is unavailable, ""explain what the existing evidence establishes and what remains unverified.\n\n""SCIENTIFIC DECISIONS\n""For competing explanations, interpretation of assay results, or deciding what experiment to run next, "159 unmodified lines"which domain, ask.\n"" - check_interactions before anyone commits a MULTI-mutant to ""synthesis. Good single mutations do not reliably stack, and this is the ""available model-based screen for possible epistasis, not proof of experimental compatibility.\n"" - check_prior_art before a big commitment of bench time, so they don't ""spend a quarter re-deriving a published result. Report it as context to ""review; it is NOT a freedom-to-operate opinion and an empty result "2 unmodified lines"POINT AT WHAT YOU ARE TALKING ABOUT\n""The scientist is looking at a bench, not just a chat rail. When you name ""a specific thing — a variant, a residue, a guide, a feature on their map ""— use focus_on when navigation would help, so the canvas scrolls there ""and highlights it while they read your sentence. \"The clash is at 1099\" ""lands very differently when 1099 is on screen.\n""Navigation is optional; never repeat an unchanged focus or use it as evidence. Use it for the thing ""that matters — but pointing at everything is the same as pointing at ""nothing. One target per point you are making. And it is a request, not ""a guarantee: if the thing isn't rendered, nothing moves, so never write "767 unmodified lines+ _instructions_note(instructions or {})+ _workspace_note(workspace or {})+ capability_state+ (_molecular_inventory(run) if run else "")+ (("\nCURRENT USER REQUEST: " + run.turn_request +"\nAnswer this request directly. Previous objectives and review notices are background. ""Reuse recorded results; do not restart completed workflows for a follow-up question.\n")if run and run.turn_request else "")+ _target_note(target or {})+ ("\nExact input reference: " + str(target["sequence_ref"])+ ". Pass sequence_ref to design tools instead of copying sequences.\n"
10 unmodified lines1112131415162 unmodified lines192021222324252627282918 unmodified lines484950515253545556575859606162636465666768697012 unmodified lines8384858687888910 unmodified lines"design_variant_library": "sequence","design_crispr_guides": "sequence","design_primers": "template",}ANALYSIS_TYPES = {"assess_stability": ("heuristic", "Structural risk factors, not a measured or calibrated stability change."),2 unmodified lines"map_domains": ("database annotation", "Annotations describe the referenced record; confirm applicability to edited sequences."),"check_conservation": ("sequence comparison", "Conservation is not direct experimental evidence for the requested property."),}EVIDENCE_TOOLS = frozenset(set(REFERENCE_INPUTS) | set(ANALYSIS_TYPES) | {"fold_structure", "simulate_assembly", "design_integration","edit_sequence", "check_synthesis", "check_overhangs",})SEQUENCE_KEYS = {"sequence", "protein", "dna", "template", "reference"}def request_key(name, args, model):18 unmodified linesdef bind_reference(objects, name, args):"""Resolve only objects owned by this run; never silently use another target."""args = dict(args)ident = args.pop("sequence_ref", None)if ident is None:return argsfield = REFERENCE_INPUTS.get(name)if not field or ident not in objects:raise ValueError("Unknown molecular reference for this tool. Resolve the input first.")molecule = objects[ident]if args.get(field) and re.sub(r"\s+", "", str(args[field])).upper() != molecule["sequence"]:raise ValueError("The supplied sequence disagrees with its molecular reference.")if name in {"design_primers", "design_crispr_guides"} and (molecule["kind"] in {"protein", "aa"} ornot re.fullmatch(r"[ACGTN]+", molecule["sequence"])):raise ValueError("This tool requires a DNA reference, not a protein.")args[field] = molecule["sequence"]return argsdef model_record(result, objects, limit=8000):"""Replace sequence payloads with immutable references, then bound by fields.12 unmodified linesif key == "_ui":continueif key in SEQUENCE_KEYS and isinstance(item, str) and len(item) >= 20 and re.fullmatch(r"[A-Za-z*\s]+", item):kind = "protein" if key == "protein" else ("dna" if key in {"dna", "template"} else "")ident = register_molecule(objects, item, kind=kind)out[key + "_ref"] = identout[key + "_length"] = len(objects[ident]["sequence"])10 unmodified lines11121314151617181920212223242526272 unmodified lines303132333435363738394018 unmodified lines596061626364656667686970717273747576777879808182838485868788899091929394959697989910012 unmodified lines11311411511611711811910 unmodified lines"design_variant_library": "sequence","design_crispr_guides": "sequence","design_primers": "template","identify_sequence": "sequence","blast_sequence": "sequence","map_plasmid": "sequence","find_cut_sites": "sequence","check_synthesis": "sequence","assess_expression": "dna","design_mutagenesis_primers": "cds","check_interactions": "wt_protein","propose_round2": "wt_protein","assess_stability": "sequence","assess_solubility": "protein",}ANALYSIS_TYPES = {"assess_stability": ("heuristic", "Structural risk factors, not a measured or calibrated stability change."),2 unmodified lines"map_domains": ("database annotation", "Annotations describe the referenced record; confirm applicability to edited sequences."),"check_conservation": ("sequence comparison", "Conservation is not direct experimental evidence for the requested property."),}EVIDENCE_TOOLS = frozenset({"design_variant_library", "design_crispr_guides", "design_primers"} | set(ANALYSIS_TYPES) | {"fold_structure", "simulate_assembly", "design_integration","edit_sequence", "check_synthesis", "check_overhangs",})SEQUENCE_KEYS = {"sequence", "protein", "dna", "template", "reference", "wt_protein"}def request_key(name, args, model):18 unmodified linesdef bind_reference(objects, name, args):"""Resolve only objects owned by this run; never silently use another target."""args = dict(args)fields = reference_fields(name)for ref, field in fields.items():ident = args.pop(ref, None)if ident is None:continueif not isinstance(ident, str) or ident not in objects:raise ValueError("Unknown molecular reference for this tool. Resolve the input first.")molecule = objects[ident]sequence = molecule["sequence"]if args.get(field) and re.sub(r"\s+", "", str(args[field])).upper() != sequence:raise ValueError("The supplied sequence disagrees with its molecular reference.")dna_tools = {"design_primers", "design_crispr_guides", "map_plasmid","find_cut_sites", "check_synthesis", "assess_expression","design_mutagenesis_primers"}protein_tools = {"check_interactions", "propose_round2", "assess_stability", "assess_solubility"}kind = molecule.get("kind")if name in dna_tools and (kind in {"protein", "aa"} or not re.fullmatch(r"[ACGTN]+", sequence)):raise ValueError("This tool requires a DNA reference, not a protein.")if name in protein_tools and (kind in {"dna", "nt", "rna", "gene"} or(kind not in {"protein", "aa"} and re.fullmatch(r"[ACGTUN]+", sequence))):raise ValueError("This tool requires a protein reference. Use identify_sequence to translate a clean complete CDS first.")args[field] = sequenceif any(k.endswith("_ref") and k in {"sequence_ref", "sequence_a_ref", "sequence_b_ref", "wild_type_ref", "mutant_ref"} for k in args):raise ValueError("Unknown molecular reference for this tool. Resolve the input first.")return argsdef reference_fields(name):fields = {"sequence_ref": REFERENCE_INPUTS[name]} if name in REFERENCE_INPUTS else {}if name == "compare_sequences":fields.update(sequence_a_ref="sequence_a", sequence_b_ref="sequence_b")elif name == "assess_solubility":fields.update(wild_type_ref="wild_type", mutant_ref="mutant")return fieldsdef model_record(result, objects, limit=8000):"""Replace sequence payloads with immutable references, then bound by fields.12 unmodified linesif key == "_ui":continueif key in SEQUENCE_KEYS and isinstance(item, str) and len(item) >= 20 and re.fullmatch(r"[A-Za-z*\s]+", item):kind = "protein" if key in {"protein", "wt_protein"} else ("dna" if key in {"dna", "template"} else value.get("molecule", ""))ident = register_molecule(objects, item, kind=kind)out[key + "_ref"] = identout[key + "_length"] = len(objects[ident]["sequence"])
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302"""Incident regressions: a scientific follow-up must not restart the whole run.
Local tools run for real; model and database calls are scripted so these testsexercise runtime guarantees, not claim to measure model reasoning quality."""import copyimport jsonimport threading
import pytest
from dee.core import orchestrator as Ofrom dee.core import run_integrity as Ifrom dee.core import agent_tools as T
DNA = "ATG" + "GCT" * 39 + "TAA"PROTEIN = "M" + "A" * 39
def cfg(): return O._llm.OpenRouterConfig(api_key="test", model="test", max_steps=8, max_cost_usd=1)
def tc(name, args, ident="c1"): return {"id": ident, "function": {"name": name, "arguments": json.dumps(args)}}
def script(monkeypatch, messages): pending = iter(messages) calls = [] def respond(config, body): calls.append(copy.deepcopy(body)) return next(pending), 0, 10, 0 monkeypatch.setattr(O._llm, "call", respond) monkeypatch.setattr(O, "_STREAM", False) return calls
def text_events(run): return "\n".join(e.get("text", "") for e in run.events if e["kind"] == "text")
def test_followup_is_not_blocked_by_old_failures_or_reported_as_29_calls(monkeypatch): run = O.Run("followup", "", True) run.status = "done" run.goal = "Design an expression library" run.plan = [{"step": "Old unfinished work", "status": "active"}] run.events = [{"kind": "tool_result", "name": "fetch_sequence", "id": str(i), "ok": False, "error": "Database unavailable"} for i in range(29)] run.evidence = [I.evidence("design_variant_library", {"ok": True, "variants": []})] run.provenance_retried = True calls = script(monkeypatch, [{"content": "A clean CDS does not establish gene identity.", "tool_calls": []}]) monkeypatch.setattr(O, "_spawn", lambda r: O._drive(r, cfg())) assert O.reply(run, "Does being a CDS identify the gene?") assert len(calls) == 1 assert run.status == "done" assert "does not establish" in text_events(run) assert not [e for e in run.events[29:] if e["kind"] in {"evidence", "outcome"}] assert "CURRENT USER REQUEST: Does being a CDS" in str(calls[0]) assert not run.provenance_retried
def test_failed_lookup_keeps_useful_answer_and_honest_limit(monkeypatch): run = O.Run("lookup-down", "", True) run.events.append({"kind": "tool_result", "name": "fetch_sequence", "id": "c1", "ok": False, "error": "Database unavailable"}) reply = {"content": "Your paste has a valid reading frame, but its gene identity remains unverified.", "tool_calls": []} calls = script(monkeypatch, [reply, reply]) O._drive(run, cfg()) assert len(calls) == 2 # bounded repair only assert "valid reading frame" in text_events(run) assert "Database unavailable" in text_events(run) assert run.events[-1]["reason"] == "partial"
def test_navigation_cannot_mask_failure_or_become_scientific_evidence(): run = O.Run("nav", "", True) run.events = [{"kind": "tool_result", "name": "fetch_sequence", "id": "1", "ok": False, "error": "offline"}, {"kind": "tool_result", "name": "focus_on", "id": "2", "ok": True, "summary": "library"}] assert O._completion_audit(run)["status"] == "attention" assert O._outcome_brief(run, "partial") is None for _ in range(4): O._note_tool_call(run, "focus_on", {"view": "library"}) assert O._repeat_refusal(run, "focus_on", {"view": "library"}) is None assert not run.tool_call_counts
def test_space_wrapped_paste_survives_compaction_and_provenance(monkeypatch): run = O.Run("paste", "", True) paste = " ".join(DNA[i:i + 41] for i in range(0, len(DNA), 41)) + " identify it" run.history = [{"role": "user", "content": paste}] + [ {"role": "assistant", "content": "later discussion"} for _ in range(30)] monkeypatch.setattr(O, "MAX_HISTORY_MESSAGES", 10) assert O._trim_history(run) ref = next(k for k, v in run.molecules.items() if v["sequence"] == DNA) assert O._guard_tool_args(run, {"sequence": DNA}) == [] assert O._guard_provenance(run, DNA)[1] == [] assert ref in O._molecular_inventory(run) assert DNA not in O._molecular_inventory(run) assert not run.target # preserving inputs must never silently switch target
def test_resolved_reference_reused_after_provider_goes_down(monkeypatch): run = O.Run("reuse", "", True) seen = [] def execute(name, args, anonymous, **kw): seen.append(args) assert len(seen) == 1, "a known molecule was fetched again" return {"ok": True, "kind": "gene", "molecule": "dna", "sequence": DNA, "label": "Synthetic reference", "source": "fixture"} monkeypatch.setattr(T, "execute_tool", execute) request = {"text": "SYNTHETIC", "organism": "test"} O._run_one_tool(run, "fetch_sequence", "1", request) O._run_one_tool(run, "fetch_sequence", "2", request) assert len(seen) == 1 assert json.loads(run.history[-1]["content"])["reused_from_run"] assert run.target["sequence"] == DNA assert O._resolved_sequence(run, "fetch_sequence", dict(request, organism="other")) is None assert O._resolved_sequence(O.Run("other", "", True), "fetch_sequence", request) is None calls = [tc("fetch_sequence", request), tc("map_domains", {"accession": "P00000"}, "2")] monkeypatch.setattr(T, "execute_tool", lambda name, args, anon, **kw: {"ok": True}) assert "c1" not in O._prefetch_readonly(run, calls)
def test_old_saved_tool_reply_can_rebuild_lookup_index(): run = O.Run("old", "", True) ref = I.register_molecule(run.molecules, DNA, kind="dna") request = {"text": "SYNTHETIC", "organism": "test"} run.history = [{"role": "assistant", "tool_calls": [tc("fetch_sequence", request)]}, {"role": "tool", "tool_call_id": "c1", "content": json.dumps({"ok": True, "sequence_ref": ref, "molecule": "dna"})}] assert O._resolved_sequence(run, "fetch_sequence", request)["sequence"] == DNA assert not O._resolved_sequence(run, "fetch_sequence", dict(request, text="different"))
@pytest.mark.parametrize("name", ["check_interactions", "propose_round2", "assess_solubility", "assess_stability"])def test_dna_is_not_a_protein_even_when_every_letter_is_an_amino_acid(name): objects = {} ref = I.register_molecule(objects, DNA, kind="dna") with pytest.raises(ValueError, match="protein reference"): I.bind_reference(objects, name, {"sequence_ref": ref})
def test_identify_translation_supplies_exact_protein_reference_without_claiming_identity(): result = T._tool_identify_sequence({"sequence": DNA}) assert result["protein"] == PROTEIN assert result["identified"] is False assert result["translation"]["genetic_code"] == "standard (table 1)" objects = {} record = json.loads(I.model_record(result, objects)) assert "protein" not in record args = I.bind_reference(objects, "check_interactions", {"sequence_ref": record["protein_ref"], "variants": ["A2G,A3V"]}) assert args["wt_protein"] == PROTEIN for invalid in (DNA[:-3], DNA[:30] + "TAG" + DNA[33:], "GTG" + DNA[3:]): assert "protein" not in T._tool_identify_sequence({"sequence": invalid})
def test_library_wildtype_remains_accessible_for_downstream_analysis(): objects = {} result = {"ok": True, "wt_protein": PROTEIN, "variants": [{"protein": "M" + "G" + "A" * 38}]} record = json.loads(I.model_record(result, objects)) args = I.bind_reference(objects, "check_interactions", {"sequence_ref": record["wt_protein_ref"]}) assert args["wt_protein"] == PROTEIN assert args["wt_protein"] != objects[record["variants"][0]["protein_ref"]]["sequence"]
def test_comparison_of_paste_and_database_result_uses_two_distinct_references(): objects = {} a = I.register_molecule(objects, DNA, kind="dna") b = I.register_molecule(objects, DNA[:30] + "GGT" + DNA[33:], kind="dna") args = I.bind_reference(objects, "compare_sequences", {"sequence_a_ref": a, "sequence_b_ref": b}) result = T._tool_compare_sequences(args) assert result["ok"] assert args["sequence_a"] != args["sequence_b"] with pytest.raises(ValueError, match="Unknown"): I.bind_reference({}, "compare_sequences", {"sequence_a_ref": a, "sequence_b_ref": b}) with pytest.raises(ValueError, match="disagrees"): I.bind_reference(objects, "compare_sequences", {"sequence_a_ref": a, "sequence_a": "CCCC"})
def test_comparison_schema_requires_both_inputs_but_accepts_references(): spec = next(s["function"] for s in O.active_tool_specs() if s["function"]["name"] == "compare_sequences") params = spec["parameters"] assert "sequence_a" not in params["required"] assert "sequence_b" not in params["required"] assert params["anyOf"] == [ {"required": ["sequence_a", "sequence_b"]}, {"required": ["sequence_a", "sequence_b_ref"]}, {"required": ["sequence_a_ref", "sequence_b"]}, {"required": ["sequence_a_ref", "sequence_b_ref"]}, ] assert not T._tool_compare_sequences({"sequence_a": DNA})["ok"]
def test_reference_based_blast_still_requires_explicit_consent(monkeypatch): run = O.Run("blast", "", True) ref = I.register_molecule(run.molecules, DNA, kind="dna") monkeypatch.setattr(T, "execute_tool", lambda *a, **kw: pytest.fail("Unapproved external sequence submission")) assert O._run_one_tool(run, "blast_sequence", "1", {"sequence_ref": ref}) assert run.status == "awaiting_input" assert run.pending_confirm["args"]["sequence"] == DNA
def test_broken_stream_is_not_automatically_purchased_again(monkeypatch): run = O.Run("stream", "", True) monkeypatch.setattr(O, "_STREAM", True) def broken(*a): raise ValueError("broken response") monkeypatch.setattr(O._llm, "stream_call", broken) monkeypatch.setattr(O._llm, "call", lambda *a: pytest.fail("duplicate provider request")) with pytest.raises(O._llm.AgentError) as exc: O._call_model(run, cfg(), {}) assert exc.value.kind == "stream_interrupted" assert not exc.value.fallback_safe assert not run.streaming
def test_request_boundaries_and_lookup_index_survive_save_restore(monkeypatch): from dee import auth run = O.Run("restore-conversation-fixes", "owner", False) run.status = "done" run.turn_event_start = 1 run.turn_request = "Compare my paste" run.events = [{"kind": "user", "seq": 1, "text": "First request"}] ref = I.register_molecule(run.molecules, DNA, kind="dna") request = {"text": "SYNTHETIC", "organism": "test"} run.resolved_sequences[O._resolution_key(request)] = {"ok": True, "sequence_ref": ref, "molecule": "dna"} run.decision_notices = {"decision": 2} saved, done = {}, threading.Event() def save(owner, **row): saved.update(copy.deepcopy(row)); done.set() return {"ok": True} monkeypatch.setattr(auth, "save_agent_run", save) monkeypatch.setattr(auth, "record_run_credits", lambda *a, **kw: None) monkeypatch.setattr(auth, "get_agent_run", lambda *a: saved) O._persist(run) assert done.wait(3) restored = O.rehydrate(run.run_id, run.owner) assert restored.turn_event_start == 1 assert restored.turn_request == "Compare my paste" assert restored.decision_notices == run.decision_notices assert O._resolved_sequence(restored, "fetch_sequence", request)["sequence"] == DNA
def test_old_decision_notice_never_replaces_answer_and_is_not_repeated(monkeypatch): run = O.Run("decision-reply", "", True) case = O._decisions.execute(run.decisions, "frame_decision", { "question": "Which explanation fits the assay?", "context": "Expression is unknown", "hypotheses": [{"id": "a", "statement": "Activity changed", "assumption": "Equal abundance"}, {"id": "b", "statement": "Expression changed", "assumption": "Signal tracks abundance"}], "recommendation": {"action": "Check abundance", "rationale": "Resolve confounding", "depends_on": ["a"]}, "next_observation": {"question": "Is abundance equal?", "why": "Resolve confounding", "outcomes": [ {"id": "yes", "label": "Equal", "supports": ["a"], "next_action": "Test activity"}, {"id": "no", "label": "Unequal", "supports": ["b"], "next_action": "Normalize"}]}}, {}) run.decisions["cases"][case["id"]]["recommendation"]["status"] = "needs_review" answer = {"content": "The stored reference and your paste are distinct inputs.", "tool_calls": []} script(monkeypatch, [answer, answer]) O._emit(run, "user", {"text": "Earlier assay work"}) run.status = "done" monkeypatch.setattr(O, "_spawn", lambda r: O._drive(r, cfg())) O.reply(run, "How does my paste compare to the reference?") assert "distinct inputs" in text_events(run) assert text_events(run).count("supporting argument changed") == 1 monkeypatch.setattr(O, "_spawn", lambda r: O._drive(r, cfg())) O.reply(run, "Explain the difference again") assert text_events(run).count("distinct inputs") == 2 assert text_events(run).count("supporting argument changed") == 1 assert run.events[-1]["reason"] == "complete"
def test_different_constraints_do_not_erase_failed_deliverable(): run = O.Run("two-designs", "", True) bad = I.evidence("design_crispr_guides", {"ok": True, "guides": []}, "same-input") bad.update(call_id="1", request_key="constraint-a") good = I.evidence("design_crispr_guides", {"ok": True, "guides": [{"spacer": "ACGT", "pam": "NGG"}]}, "same-input") good.update(call_id="2", request_key="constraint-b") run.evidence = [bad, good] run.events = [{"kind": "tool_result", "name": "design_crispr_guides", "id": n, "ok": True} for n in ("1", "2")] assert O._completion_audit(run)["status"] == "attention" good["request_key"] = "constraint-a" # an actual repair supersedes its failed attempt assert O._completion_audit(run)["status"] == "verified"
def test_followup_compares_stored_inputs_without_restarting_work(monkeypatch): run = O.Run("conversation", "", True) run.status = "done" run.goal = "Design a library" pasted = I.register_molecule(run.molecules, DNA, kind="dna") reference = I.register_molecule(run.molecules, DNA[:30] + "GGT" + DNA[33:], kind="dna") run.events = [{"kind": "tool_result", "name": "check_interactions", "id": "old", "ok": False, "error": "old failure"}] calls = script(monkeypatch, [ {"content": "I will compare your paste with the stored reference.", "tool_calls": [tc("compare_sequences", {"sequence_a_ref": pasted, "sequence_b_ref": reference})]}, {"content": "Your sequence differs from the reference. A clean CDS alone does not prove gene identity.", "tool_calls": []}]) monkeypatch.setattr(O, "_spawn", lambda r: O._drive(r, cfg())) assert O.reply(run, "Is my pasted sequence identical to the reference?") assert len(calls) == 2 assert run.status == "done" results = O._turn_results(run) assert [r["name"] for r in results] == ["compare_sequences"] assert results[0]["ok"] assert "differs" in text_events(run) outcome = next(e for e in run.events if e["kind"] == "outcome") assert outcome["objective"] == "Is my pasted sequence identical to the reference?" assert not outcome["failures"]1966 unmodified lines19671968196919701971197219731974197519761966 unmodified linesreturn {"id": call_id, "function": {"name": name, "arguments": _j.dumps(args)}}class _PrefetchRun:"""The little of Run that _prefetch_readonly touches."""def __init__(self, anonymous=False):self.run_id = "r1"self.owner = "u1"self.anonymous = anonymousself.model = "small"1966 unmodified lines19671968196919701971197219731974197519761966 unmodified linesreturn {"id": call_id, "function": {"name": name, "arguments": _j.dumps(args)}}class _PrefetchRun(orch.Run):"""The little of Run that _prefetch_readonly touches."""def __init__(self, anonymous=False):super().__init__("r1", "u1", anonymous)self.owner = "u1"self.anonymous = anonymousself.model = "small"
120 unmodified lines121122123124125126127128129120 unmodified linesif name not in specs: # another factual gate may still applycontinueparams = specs[name]["parameters"]assert {"required": ["sequence_ref"]} in params["anyOf"]args = integrity.bind_reference(run.molecules, name, {"sequence_ref": ident})assert args[field] == "ATGGCC" * 20def test_the_gate_is_monotonic():120 unmodified lines121122123124125126127128129130131132133134135136120 unmodified linesif name not in specs: # another factual gate may still applycontinueparams = specs[name]["parameters"]original = next(s["function"]["parameters"] for s in orch.TOOL_SPECS if s["function"]["name"] == name)if field in original.get("required", []):assert {"required": ["sequence_ref"]} in params["anyOf"]else:assert "anyOf" not in params, "optional sequences must remain optional"protein = name in {"check_interactions", "propose_round2", "assess_stability", "assess_solubility"}seq = "MKWVTFISLLFLFSSAYS" * 10 if protein else "ATGGCC" * 20ref = integrity.register_molecule(run.molecules, seq, kind="protein" if protein else "dna")args = integrity.bind_reference(run.molecules, name, {"sequence_ref": ref})assert args[field] == seqdef test_the_gate_is_monotonic():
dee/core/agent_tools.py+1
dee/core/identify.py+7
dee/core/orchestrator.py+205-42
dee/core/run_integrity.py+46-16
tests/test_conversation_recovery.pyAdded+302
tests/test_orchestrator.py+2-2
tests/test_tool_surface.py+10-3