Spaces:
Running
Running
github-actions[bot] commited on
Commit Β·
3a8aafc
1
Parent(s): 551e65a
Deploy 06ab4a6
Browse filesA gene placed at a coordinate no longer goes in on the plus strand (#423)
Source: https://github.com/WINTER4000/turingDNA/commit/06ab4a6e72d9b214d14cbdc74130f7395a805b4a
Files changed (2)
4034 unmodified lines403540364037403840394040340 unmodified lines43814382438343844385438642 unmodified lines4429443044314432443344344435443644374438443991 unmodified lines4531453245334534453545361890 unmodified lines64276428642964306431643264334034 unmodified lines# sizes and accessions. The capability is the same; the catalogue cost is a# few characters in one description rather than a whole second spec.def _tool_propose_edit(args: Dict[str, Any]) -> Dict[str, Any]:"""Propose an insert, delete or replace β and DO NOT make it.340 unmodified lines"`anchor` with the name of the feature to place it ""relative to, and `where` (before/after).")}out = _edits.span_edit(seq, op,start=int(args.get("start") or 0),42 unmodified linesstr((element_used or {}).get('name') or '')or str((((resolved_used or {}).get("labels")) or [""])[0])or 'the insert')warnings.append(f"{anchor_name} is on the minus strand, so "f"{flipped_name} was REVERSE-COMPLEMENTED and "f"annotated on the minus strand β it reads in the same direction "f"as {anchor_name}. Say that it was flipped.")elif anchor_strand < 0 and out["inserted"]:# Never silently reverse-complement someone's sequence. State the# orientation and let them decide: they may well have handed over the91 unmodified lines"unchanged" if frame["in_frame"] elsef"SHIFTED by {out['delta']:+d}"),"premature_stop": frame["premature_stop"],"features_affected": out["feature_notes"],**({"insert_resolved": resolved} if resolved else {}),"warnings": warnings,1890 unmodified lines"description": ("1-based. For insert, the base to go in AFTER ""(0 means before base 1). For delete/replace, the ""first base of the span."),},"end": {"type": "integer",4034 unmodified lines4035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083340 unmodified lines4424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450342 unmodified lines454645474548454945504551455245534554455545564557455845594560456191 unmodified lines465346544655465646574658465946604661466246634664466546661890 unmodified lines65576558655965606561656265636564656565666567656865696570657165726573657465754034 unmodified lines# sizes and accessions. The capability is the same; the catalogue cost is a# few characters in one description rather than a whole second spec.def _strand_context(feats: List[Dict[str, Any]], at: int) -> Dict[str, Any]:"""What a construct looks like around a coordinate: what spans it, whatflanks it, and which way those things read.An insertion point is not a bare number β it sits inside somebody'scassette, or between two genes that both transcribe leftward. The modelcannot see any of that; it is holding a number it worked out from a`read_construct` that may be several edits old. The tool has the livefeatures, so it is the one that can say."""named = [f for f in (feats or []) if str(f.get("name") or "").strip()]spanning, before, after = [], None, Nonefor f in named:fs, fe = int(f.get("start") or 0), int(f.get("end") or 0)if fs < at < fe:spanning.append(f)elif fe <= at and (before is None or fe > int(before.get("end") or 0)):before = felif fs >= at and (after is None or fs < int(after.get("start") or 0)):after = fdef _say(f):if not f:return Nonesign = "-" if int(f.get("strand") or 1) < 0 else "+"return (f"{f.get('name')} ({int(f.get('start') or 0) + 1}.."f"{int(f.get('end') or 0)} {sign})")neighbours = [f for f in (spanning + [before, after]) if f]minus = sum(1 for f in neighbours if int(f.get("strand") or 1) < 0)return {"has_annotations": bool(named),"inside": [_say(f) for f in spanning],"before": _say(before),"after": _say(after),# Only a hint, and only when the neighbourhood agrees with itself. A# point between a plus gene and a minus gene has no local strand and# saying it did would be the guess this exists to prevent."local_strand": (-1 if neighbours and minus == len(neighbours)else 1 if neighbours and minus == 0 else None),}def _tool_propose_edit(args: Dict[str, Any]) -> Dict[str, Any]:"""Propose an insert, delete or replace β and DO NOT make it.340 unmodified lines"`anchor` with the name of the feature to place it ""relative to, and `where` (before/after).")}# ββ A PART PLACED BY COORDINATE STILL HAS A STRAND βββββββββββββββββββ## THE BUG THIS CLOSES (seen in production 2026-12-01, with the map): a# four-gene autobioluminescence cassette on pCAMBIA1300. GFP, P2A, luz and# h3h all went in against named anchors and all came out correctly on the# minus strand. hisps was staged at coordinates 8,000..13,033 instead β# and so was never reverse-complemented, was annotated strand +1 by# default, and landed antisense to the CaMV 35S promoter driving it, six# kilobases away from the rest of the cassette. Drawn as a finished# construct. Would not transcribe.## Everything needed to prevent that was already here and on the OTHER# path: the anchor block above flips a library element or a fetched# record against a minus-strand anchor, and takes the anchor's strand for# the new feature. Below it, `anchor_strand` falls back to 1 β so a# coordinate does not merely skip the flip, it asserts the plus strand.## The asymmetry underneath is the real point. On every call the# orchestrator injects the live construct, so THIS FUNCTION always holds# current coordinates and current strands. The model holds a number it# derived from a read that may be several applied edits old, and each# applied insert renumbers everything downstream of it. The side that# knows was deferring to the side that was guessing.## So: bases the ENGINE supplied (the element library, or a sequence_ref# this run resolved) carry a declared orientation, which makes placing# them the engine's responsibility rather than the caller's. Refuse to# place one by bare coordinate on an annotated construct, and say what is# actually there. `strand` is the deliberate door for the case where a# coordinate really is meant. Pasted bases are untouched: a pasted string# has no declared orientation and may already have been flipped by hand,# which is why the anchor path leaves those alone too.# WHAT COUNTS AS NEEDING A STRAND, and why it is not simply "anything the# engine resolved". A GENE always does: it has a reading direction, it has# to agree with the promoter driving it, and `insert_ref` is the only way# one gets in β the element library is a harvest of vector BACKBONES and# holds no genes of interest, which this tool's own description says. A# backbone part dropped at a coordinate is ordinary by comparison, so# demanding a strand for every loxP and every marker would be the check# spreading past what it knows: it would refuse `insert="cat"` on a plain# plus-strand plasmid, which is a thing people do and a test here pins.# The one case where a backbone part is as dangerous as a gene is a# neighbourhood that reads minus β the T7-promoter-facing-the-wrong-way# failure the anchor path was written for β so that is included and# nothing else is.strand_arg = str(args.get("strand") or "").strip()ctx = _strand_context(feats, int(args.get("start") or 0))needs_strand = (resolved_used is not Noneor (element_used is not None and ctx["local_strand"] == -1))if (not anchor and op in ("insert", "replace")and needs_strand and not strand_arg and ctx["has_annotations"]):where_txt = ("inside " + ", ".join(ctx["inside"]) if ctx["inside"]else " between ".join(x for x in (ctx["before"], ctx["after"]) if x)or "in an unannotated stretch")return {"ok": False, "kind": "no_strand_for_a_placed_part", "error": (f"Base {args.get('start')} is {where_txt}. A gene or element this "f"engine resolved has a known orientation, so dropping it at a "f"coordinate would silently put it on the plus strand β which is "f"how a cassette ends up antisense to its own promoter. "f"Give `anchor` with the feature to place it against and `where` "f"(before/after), and the strand is handled for you. If you really "f"do mean this coordinate, pass `strand` (1 or -1) to say which way "f"it should read."),"placed_between": {k: ctx[k] for k in ("inside", "before", "after")},"local_strand": ctx["local_strand"]}# An explicit `strand` is honoured the same way the anchor path honours# the anchor's: flip the engine's bases, keep the annotation.if (not anchor and strand_arg in ("-1", "-") and args.get("insert")and (element_used is not None or resolved_used is not None)):args = dict(args, insert=_revcomp(str(args["insert"])))element_flipped = Trueanchor_strand = -1out = _edits.span_edit(seq, op,start=int(args.get("start") or 0),42 unmodified linesstr((element_used or {}).get('name') or '')or str((((resolved_used or {}).get("labels")) or [""])[0])or 'the insert')# anchor_name is empty when the caller gave `strand` with a bare# coordinate, so the sentence has to name what it can.because = (f"{anchor_name} is on the minus strand"if anchor_name else "you asked for the minus strand")reads_like = (f" β it reads in the same direction as {anchor_name}"if anchor_name else "")warnings.append(f"{because}, so {flipped_name} was REVERSE-COMPLEMENTED and "f"annotated on the minus strand{reads_like}. Say that it was "f"flipped.")elif anchor_strand < 0 and out["inserted"]:# Never silently reverse-complement someone's sequence. State the# orientation and let them decide: they may well have handed over the91 unmodified lines"unchanged" if frame["in_frame"] elsef"SHIFTED by {out['delta']:+d}"),"premature_stop": frame["premature_stop"],# WHERE IT LANDED, in features rather than in a number. The model has# no way to check a coordinate it worked out itself β this is the# construct telling it what is actually on either side, so a part in# the wrong neighbourhood is visible in the result instead of only on# the map. It also means the model does not have to track renumbering# across applied edits to know where it is."placed_between": {k: ctx[k] for k in ("inside", "before", "after")},"strand": anchor_strand,"features_affected": out["feature_notes"],**({"insert_resolved": resolved} if resolved else {}),"warnings": warnings,1890 unmodified lines"description": ("1-based. For insert, the base to go in AFTER ""(0 means before base 1). For delete/replace, the ""first base of the span. Last resort: an applied ""edit renumbers everything after it, so a ""coordinate from earlier in this run has probably ""moved. `anchor` cannot go stale."),},"strand": {"type": "integer","enum": [1, -1],"description": ("Which way a part placed by `start` must READ; -1 ""reverse-complements it. Required for a gene, ""which otherwise goes in on the plus strand and ""ends up antisense to its promoter."),},"end": {"type": "integer",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339"""A gene dropped at a coordinate went in on the plus strand, silently.
REPORTED 2026-12-01 from production, with the map. A four-gene fungalautobioluminescence cassette on pCAMBIA1300. GFP, P2A, luz and h3h were eachplaced against a named anchor and each came out correctly on the minusstrand, reading off the CaMV 35S promoter. hisps was staged at coordinates8,000..13,033 instead. In the agent's own words once the scientist pushedback:
"When hisps was staged at coordinates 8,000..13,033 (5,034 bp), it was inserted directly without being reverse-complemented. As a result, GFP, luz, h3h, and their P2A linkers all transcribe on the minus strand, while hisps is oriented on the plus strand (in reverse/antisense orientation relative to the CaMV 35S promoter)."
Drawn on the map as a finished construct. Would not transcribe. The BUILTcard said "frame intact", which was true and about the wrong thing.
WHERE IT CAME FROM. propose_edit has two ways to be told where an edit goes.The `anchor` path looks the feature up, takes its strand, andreverse-complements a library element or a fetched record to match β there isa long comment in agent_tools.py explaining exactly why, written after a T7promoter came out annotated -1 with plus-strand bases under the label. The`start` path ran none of it, and `anchor_strand` fell back to 1, so acoordinate did not merely skip the flip: it asserted the plus strand.
AND THE ASYMMETRY UNDERNEATH, which is the part worth keeping in mind. Theorchestrator injects the live construct on every call, so the TOOL alwaysholds current coordinates and current strands; the model holds a number itworked out from a read that may be several applied edits old, and everyapplied insert renumbers everything after it. The side that knew wasdeferring to the side that was guessing. That is also why hisps landed sixkilobases from the rest of the cassette, in the middle of the hygromycinmarker β same cause, and the refusal below would have said so at the door.
WHAT THIS FILE PINS. Bases the engine resolved cannot be placed by barecoordinate on an annotated construct; the refusal says what is actuallythere; `anchor` and an explicit `strand` both work and both flip; a pastedsequence is still never flipped behind the scientist's back; and every editreports the neighbours it landed between."""import jsonimport random
import pytest
from dee.core import orchestrator as Ofrom dee.core import run_integrity as RI
def _dna(n, seed): rnd = random.Random(seed) return "".join(rnd.choice("ACGT") for _ in range(n))
PLASMID = _dna(16974, 11)HISPS = "ATG" + _dna(5028, 44) + "TAA" # 5,034 nt, as in the reportPASTED = "ATG" + _dna(300, 7) + "TAA"
# The cassette as the map showed it: everything on the minus strand and# clustered high, with the hygromycin marker down at 7β8 kb where hisps went.FEATS = [ {"name": "CaMV35S", "type": "promoter", "start": 15949, "end": 16800, "strand": -1}, {"name": "GFP", "type": "CDS", "start": 15232, "end": 15949, "strand": -1}, {"name": "P2A", "type": "CDS", "start": 15166, "end": 15232, "strand": -1}, {"name": "luz", "type": "CDS", "start": 14365, "end": 15166, "strand": -1}, {"name": "hygromycin phosphotransferase", "type": "CDS", "start": 7000, "end": 8100, "strand": 1},]HISPS_RECORD = {"ok": True, "accession": "KX060001.1", "gene_symbol": "hisps", "molecule": "cds", "length": len(HISPS), "sequence": HISPS}
@pytest.fixture(autouse=True)def _no_persist(monkeypatch): monkeypatch.setattr(O, "_persist", lambda r: None) monkeypatch.setattr(O, "_CHAIN_EDITS", True)
def _run(features=FEATS): run = O.create_run(owner="u", anonymous=False) O.set_workspace(run, { "construct": "pCAMBIA1300", "route": "plasmid", "bench": {"plasmid": {"len": len(PLASMID), "topo": "circular"}}, "editor": {"name": "pCAMBIA1300", "sequence": PLASMID, "topology": "circular", "unsaved": False, "features": [dict(f) for f in features]}, }, "add hisps to the bioluminescence cassette") run.seen = [json.loads(RI.model_record(dict(HISPS_RECORD), run.molecules))] return run
def _edit_raw(monkeypatch, args, cid="e1", features=FEATS): """The tool's own return, including `_ui`.
`_ui` carries the previewed bases and is stripped before the model sees anything, which is right β but it is also the only place the test can check that a flip actually happened to the SEQUENCE rather than only to the label. Annotating minus over plus-strand bases is the exact shape of wrongness this whole file is about, so it has to be asserted against the bases. """ import dee.core.agent_tools as AT held = {} real = AT._TOOLS["propose_edit"]["fn"]
def spy(a): held["out"] = real(a) return held["out"]
monkeypatch.setitem(AT._TOOLS["propose_edit"], "fn", spy) _edit(args, cid, features) return held["out"]
def _edit(args, cid="e1", features=FEATS): run = _run(features) O._run_one_tool(run, "propose_edit", cid, dict(args)) msg = [m for m in run.history if m.get("tool_call_id") == cid] assert len(msg) == 1, f"expected one tool reply for {cid}" return json.loads(msg[0]["content"])
# ββ the reported failure ββββββββββββββββββββββββββββββββββββββββββββββββββββdef test_the_call_that_built_the_antisense_cassette_is_refused(): out = _edit({"op": "insert", "start": 8000, "insert_ref": "hisps", "label": "hisps", "feature_type": "CDS"})
assert out["ok"] is False, ( "this is the production call that produced an antisense gene and " "reported success") assert out["kind"] == "no_strand_for_a_placed_part"
def test_the_refusal_says_what_is_actually_at_that_coordinate(): """Naming the neighbour is most of the value. Base 8,000 is inside the hygromycin marker β the agent was about to put 5 kb through the construct's selection, and nothing in the old result would have said so.""" out = _edit({"op": "insert", "start": 8000, "insert_ref": "hisps"})
assert "hygromycin phosphotransferase" in out["error"] assert "8000" in out["error"] or "8,000" in out["error"] assert out["placed_between"]["inside"] == [ "hygromycin phosphotransferase (7001..8100 +)"] # and it has to name the way out, or the model just tries again assert "anchor" in out["error"] and "strand" in out["error"]
def test_the_anchored_call_the_other_four_genes_used_still_works(): """GFP, P2A, luz and h3h all went in this way and all came out right. The fix must not touch the path that was already correct.""" out = _edit({"anchor": "luz", "where": "after", "insert_ref": "hisps", "label": "hisps", "feature_type": "CDS"})
assert out["ok"] is True assert out["strand"] == -1 flip = [w for w in out["warnings"] if "REVERSE-COMPLEMENTED" in w] assert flip, "a gene placed against a minus-strand anchor must be flipped" assert "luz" in flip[0]
def test_a_coordinate_still_works_when_the_strand_is_declared(): """The door is deliberate: sometimes the coordinate really is meant. What is refused is leaving the strand to a default.""" out = _edit({"op": "insert", "start": 8000, "strand": -1, "insert_ref": "hisps", "label": "hisps", "feature_type": "CDS"})
assert out["ok"] is True assert out["strand"] == -1 flip = [w for w in out["warnings"] if "REVERSE-COMPLEMENTED" in w] assert flip, "strand=-1 has to flip the bases, not just label them" # The sentence cannot name an anchor here, because there isn't one. assert "minus strand" in flip[0]
def test_strand_plus_one_is_an_answer_too(): out = _edit({"op": "insert", "start": 8000, "strand": 1, "insert_ref": "hisps", "label": "hisps"})
assert out["ok"] is True assert not [w for w in out["warnings"] if "REVERSE-COMPLEMENTED" in w]
# ββ what must NOT change ββββββββββββββββββββββββββββββββββββββββββββββββββββdef test_a_pasted_sequence_is_never_flipped_behind_the_scientist_s_back(): """The engine owns the orientation of what the engine fetched. A pasted string has no declared orientation and may already have been flipped by hand, so it is placed as given β and so it needs no strand argument.""" out = _edit({"op": "insert", "start": 8000, "insert": PASTED, "label": "my insert"})
assert out["ok"] is True, out.get("error") assert not [w for w in out["warnings"] if "REVERSE-COMPLEMENTED" in w]
def test_an_unannotated_construct_still_takes_a_bare_coordinate(): """With no features there is no neighbourhood to be wrong about, and refusing would block the first insert into an empty backbone.""" out = _edit({"op": "insert", "start": 8000, "insert_ref": "hisps", "label": "hisps"}, features=[])
assert out["ok"] is True, out.get("error")
def test_a_delete_by_coordinate_is_not_caught_by_this(): """Deleting has no orientation to get wrong. Refusing it would be the check spreading past what it knows.""" out = _edit({"op": "delete", "start": 7100, "end": 7200})
assert out["ok"] is True, out.get("error")
# ββ the visibility half βββββββββββββββββββββββββββββββββββββββββββββββββββββdef test_every_edit_reports_the_neighbours_it_landed_between(): """The model cannot check a coordinate it worked out itself. This is the construct telling it what is on either side, so a part in the wrong neighbourhood shows up in the result and not only on the map β and so it does not have to track renumbering across applied edits to know where it is.""" out = _edit({"anchor": "luz", "where": "after", "insert_ref": "hisps", "label": "hisps"})
assert out["ok"] is True between = out["placed_between"] assert set(between) == {"inside", "before", "after"} assert between["after"] == "luz (14366..15166 -)" # the strand is spelled out in each name, which is the thing that was # impossible to see before assert "-" in between["after"]
def test_the_neighbourhood_report_marks_a_point_with_no_local_strand(): """Between a plus gene and a minus gene there is no local direction, and claiming one would be the guess this exists to prevent.""" from dee.core.agent_tools import _strand_context
mixed = _strand_context(FEATS, 11000) # HygR (+) behind, luz (-) ahead assert mixed["local_strand"] is None
agreed = _strand_context(FEATS, 15200) # inside the minus-strand cassette assert agreed["local_strand"] == -1
def test_the_schema_offers_strand_and_warns_that_coordinates_go_stale(): """The refusal only helps if the model can act on it, and it only avoids the coordinate path if the schema says why that path is worse.""" spec = [t["function"] for t in O.TOOL_SPECS if t["function"]["name"] == "propose_edit"][0] props = spec["parameters"]["properties"]
assert props["strand"]["enum"] == [1, -1] assert "antisense" in props["strand"]["description"] assert "renumbers" in props["start"]["description"], ( "the model has no other way to learn that a coordinate from earlier " "in the run has moved")
def test_strand_minus_one_flips_the_bases_and_not_just_the_label(monkeypatch): """The mutation this exists for: setting the feature's strand to -1 while leaving the bases on the plus strand. That passes every warning check β the flip message still prints β and produces precisely the construct the report described, annotated one way and reading the other.
Asserted against the previewed sequence, because the label agreeing with itself is not evidence. """ from dee.core.cloning import revcomp
out = _edit_raw(monkeypatch, {"op": "insert", "start": 8000, "strand": -1, "insert_ref": "hisps", "label": "hisps", "feature_type": "CDS"})
assert out["ok"] is True seq = out["_ui"]["sequence"] assert revcomp(HISPS) in seq, ( "strand=-1 annotated the feature on the minus strand but left the " "bases on the plus strand β the construct reads one way and is drawn " "the other") assert HISPS not in seq
hisps_feat = [f for f in out["_ui"]["features"] if f.get("name") == "hisps"] assert hisps_feat and hisps_feat[0]["strand"] == -1
def test_the_anchored_path_flips_the_bases_too(monkeypatch): """Same assertion against the path that was already correct, so the two cannot drift apart.""" from dee.core.cloning import revcomp
out = _edit_raw(monkeypatch, {"anchor": "luz", "where": "after", "insert_ref": "hisps", "label": "hisps", "feature_type": "CDS"})
assert out["ok"] is True assert revcomp(HISPS) in out["_ui"]["sequence"] assert HISPS not in out["_ui"]["sequence"]
# ββ how far the rule reaches ββββββββββββββββββββββββββββββββββββββββββββββββdef test_a_backbone_part_on_a_plus_strand_stretch_still_takes_a_coordinate(): """The rule is about genes, not about everything the engine can resolve.
The element library is a harvest of vector BACKBONES and holds no genes of interest β this tool's own description says so. Demanding a strand for every marker and every loxP would refuse `insert="cat"` on an ordinary plus-strand plasmid, which is a thing people do and which tests/test_edit_loop.py pins. Caught by that test when the first version of this guard was written too broadly. """ out = _edit({"op": "insert", "start": 8600, "insert": "cat", "label": "CmR"})
assert out["ok"] is True, out.get("error")
def test_a_backbone_part_dropped_into_a_minus_strand_stretch_is_not_exempt(): """The one case where a backbone part is as dangerous as a gene: a promoter or marker placed among features that all read minus. This is the failure the anchor path was written for β a T7 promoter annotated -1 with plus-strand bases under the label, drawn as working, that would not transcribe.""" out = _edit({"op": "insert", "start": 15200, "insert": "cat", "label": "CmR"})
assert out["ok"] is False assert out["kind"] == "no_strand_for_a_placed_part" assert out["local_strand"] == -1
def test_a_gene_is_not_exempt_anywhere(): """Unlike a backbone part, a gene needs its strand stated wherever it goes β its direction has to agree with the promoter driving it, and the neighbourhood at the insertion point does not settle that.""" for at in (8600, 15200): out = _edit({"op": "insert", "start": at, "insert_ref": "hisps", "label": "hisps"}, cid=f"g{at}") assert out["ok"] is False, f"a gene at {at} was placed without a strand" assert out["kind"] == "no_strand_for_a_placed_part"dee/core/agent_tools.py+147-5
tests/test_a_part_placed_by_coordinate_knows_its_strand.pyAdded+339