Spaces:
Running
Running
github-actions[bot] commited on
Commit Β·
ba6aefc
1
Parent(s): 68d228b
Deploy ea8b113
Browse filesMerge pull request #379 from WINTER4000/fix/vector-accession-leak
Source: https://github.com/WINTER4000/turingDNA/commit/ea8b1136f8bb18abb75b9f55c8d55d1be2c377da
Files changed (6)
169 unmodified lines17017117217317417513 unmodified lines1891901911921931942884 unmodified lines307930803081308230833084193 unmodified lines32783279328032813282328312 unmodified lines32963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372169 unmodified linesreturn outdef _tool_fetch_sequence(args: Dict[str, Any], user_id: Optional[str] = None) -> Dict[str, Any]:"""Resolve a gene symbol / accession / raw paste to an actual DNAsequence β the same dee.core.resolve.resolve_target() that backs the13 unmodified linesif len(text) > 1_000_000:return {"ok": False, "error": "Input too long. Cap is 1 Mbp."}# Pass the organism through as given. The old allow-list silently BLANKED# anything outside {ecoli, human, mouse}, so a user who answered "yeast"# got asked "which species is GAL1?" β the question they had just2884 unmodified lines}def _tool_lookup_vector(args: Dict[str, Any]) -> Dict[str, Any]:"""What the catalogue says about a cloning backbone β and nothing else.193 unmodified lines# against a product sheet, while an INSDC record carries whatever its# depositor annotated. Both beat recall; conflating them would let a# design rest on the weaker one.near = _vec.search(name, limit=6)idx_rows: List[Dict[str, Any]] = []try:12 unmodified linesexact = next((r for r in idx_rowsif _vec._norm(str(r.get("name") or "")) == _vec._norm(name)), None)if exact:map_ui = {}rec = Nonetry:from dee.core import vector_sequence as _vsrec = _vs.accession_record(str(exact.get("accession") or ""),expect_bp=exact.get("length_bp"))except Exception: # noqa: BLE001logger.exception("INSDC record load failed for %s",exact.get("accession"))if rec:map_ui = {"_ui": {# The index's name, not the record's: an EMBL ID line carries# the accession ("AB014641"), while the index carries what the# depositor called it ("pGEX-PUC-3T"), which is what the user# typed and what they should see on the tab."name": exact.get("name") or rec.get("name") or name,"sequence": rec.get("sequence"),"length": rec.get("length"),"topology": rec.get("topology"),"gc": rec.get("gc"),"features": rec.get("features") or [],"source": "vector_index","accession": rec.get("accession"),}}acc = exact.get("accession")ena_url = f"https://www.ebi.ac.uk/ena/browser/view/{acc}" if acc else Noneif map_ui:next_action = (f"The Map tab is now open on {exact.get('name') or name} β "f"INSDC record {acc}, {map_ui['_ui']['length']:,} bp "f"{map_ui['_ui'].get('topology') or 'circular'}, "f"{len(map_ui['_ui'].get('features') or [])} feature(s) as ""annotated by whoever deposited it. Say so in one line, and ""say that this is a depositor's record rather than a ""hand-verified catalogue entry. Describe the backbone ONLY ""from the features in the record; call find_cut_sites or ""scan_construct for sites and coordinates. Do NOT state an ""MCS order, a selection marker or a tag that the record does ""not annotate.")else:next_action = (f"The index has {exact.get('name') or name} as INSDC "f"accession {acc}, but the record itself could not be ""fetched or did not verify. Give the user the ENA link and ""ask them to paste the file into the Map tab, then call ""map_plasmid. Do NOT describe the vector from memory.")return {"ok": True,"vector": exact,"source": "INSDC vector index (ENA)","evidence": "derived",**({"ena_url": ena_url,"where_to_get_it": (f"The record is at {ena_url}. Note that INSDC holds the ""SEQUENCE, not the physical plasmid β if the user needs ""the material, they still have to source it.")}if ena_url else {}),"caveat": ("A depositor's INSDC record, NOT a hand-verified ""catalogue entry. Its feature table is as complete as ""the person who deposited it made it: a missing ""feature means unannotated, not absent. The curated "f"catalogue ({_vec.catalogue_size()} backbones) is the ""higher standard where it has an entry."),"note": ("Do not add restriction sites, coordinates, markers or ""tags that are not in the returned record."),"mapped": bool(map_ui),"next_action": next_action,**map_ui,}# This is also the BROWSE answer, which is why it is built properly# rather than as a flat list of names. "pCAMBIA" matches no vector169 unmodified lines17017117217317417517617717817913 unmodified lines1931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302884 unmodified lines31153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212193 unmodified lines34063407340834093410341134123413341434153416341734183419342034213422342334243425342612 unmodified lines3439344034413442344334443445169 unmodified linesreturn out# The same shape vector_sequence accepts β one pattern, not two._VS_ACCESSION = re.compile(r"^[A-Z]{1,6}[0-9]{5,8}(\.[0-9]{1,3})?$")def _tool_fetch_sequence(args: Dict[str, Any], user_id: Optional[str] = None) -> Dict[str, Any]:"""Resolve a gene symbol / accession / raw paste to an actual DNAsequence β the same dee.core.resolve.resolve_target() that backs the13 unmodified linesif len(text) > 1_000_000:return {"ok": False, "error": "Input too long. Cap is 1 Mbp."}# ββ an INSDC accession that names a VECTOR is not a gene βββββββββββββ## This is a gene resolver, and for an accession it does exactly what it# says: returns the bases. For a vector that is a silent loss. Measured# on a real transcript (2026-11-23): lookup_vector("pCAMBIA") browsed# correctly and handed back derived_options with accessions in them; the# model took AF234290 to THIS tool, got 6,812 anonymous bases, and# map_plasmid auto-annotated them into seven invented ORFs. The record's# own nine features β T-DNA borders, the kanamycin marker, both origins# β were one call away and went in the bin, and the construct reached# the bench named "untitled".## The fix is not to forbid the shortcut. An agent holding an accession# will use the tool that takes one, so the tool that takes one has to# give back the annotated record. Same answer lookup_vector gives,# through the same helper.## Gated on the INDEX, not on the shape of the string: a row in# vector_index means NCBI taxonomy put this record under node 29278,# "Vectors". A gene accession is not in there and falls straight# through. One primary-key read, only for accession-shaped input.if _VS_ACCESSION.match(text.strip().upper()):try:from dee.core import vector_index as _virow = _vi.by_accession(text)if row and row.get("name"):out = _index_vector_result(row, str(row.get("name")))if out.get("mapped"):return outexcept Exception: # noqa: BLE001logger.exception("vector accession check failed for %r", text)# Pass the organism through as given. The old allow-list silently BLANKED# anything outside {ecoli, human, mouse}, so a user who answered "yeast"# got asked "which species is GAL1?" β the question they had just2884 unmodified lines}def _index_vector_result(exact: Dict[str, Any], asked: str) -> Dict[str, Any]:"""One index row, turned into lookup_vector's hit answer.Extracted so three doors reach the SAME answer: the exact-name matchbelow, an accession passed to lookup_vector, and an accession passed tofetch_sequence. Before that last one existed, an agent that read anaccession out of a browse result and handed it to fetch_sequence got6,812 anonymous bases β and the depositor's feature table, one callaway, was thrown out. Measured on a real transcript (2026-11-23):lookup_vector("pCAMBIA") browsed, the model took AF234290 tofetch_sequence, map_plasmid auto-annotated the bare bases into seveninvented ORFs, and the construct reached the bench called "untitled"."""from dee.core import vectors as _vecmap_ui = {}rec = Nonetry:from dee.core import vector_sequence as _vsrec = _vs.accession_record(str(exact.get("accession") or ""),expect_bp=exact.get("length_bp"))except Exception: # noqa: BLE001logger.exception("INSDC record load failed for %s",exact.get("accession"))if rec:# The destination travels WITH the panel, because the tool that# produced it is not always one the Map tab belongs to β# fetch_sequence's view is None until the thing it resolved turns# out to be a vector. _strip_ui keeps "_ui_view" off the model's# copy with every other _ui* key.map_ui = {"_ui_view": "plasmid", "_ui": {# The index's name, not the record's: an EMBL ID line carries# the accession ("AB014641"), while the index carries what the# depositor called it ("pGEX-PUC-3T"), which is what the user# typed and what they should see on the tab."name": exact.get("name") or rec.get("name") or asked,"sequence": rec.get("sequence"),"length": rec.get("length"),"topology": rec.get("topology"),"gc": rec.get("gc"),"features": rec.get("features") or [],"source": "vector_index","accession": rec.get("accession"),}}acc = exact.get("accession")ena_url = f"https://www.ebi.ac.uk/ena/browser/view/{acc}" if acc else Noneif map_ui:next_action = (f"The Map tab is now open on {exact.get('name') or asked} β "f"INSDC record {acc}, {map_ui['_ui']['length']:,} bp "f"{map_ui['_ui'].get('topology') or 'circular'}, "f"{len(map_ui['_ui'].get('features') or [])} feature(s) as ""annotated by whoever deposited it. Say so in one line, and ""say that this is a depositor's record rather than a ""hand-verified catalogue entry. Describe the backbone ONLY ""from the features in the record; call find_cut_sites or ""scan_construct for sites and coordinates. Do NOT state an ""MCS order, a selection marker or a tag that the record does ""not annotate.")else:next_action = (f"The index has {exact.get('name') or asked} as INSDC "f"accession {acc}, but the record itself could not be ""fetched or did not verify. Give the user the ENA link and ""ask them to paste the file into the Map tab, then call ""map_plasmid. Do NOT describe the vector from memory.")return {"ok": True,"vector": exact,"source": "INSDC vector index (ENA)","evidence": "derived",**({"ena_url": ena_url,"where_to_get_it": (f"The record is at {ena_url}. Note that INSDC holds the ""SEQUENCE, not the physical plasmid β if the user needs ""the material, they still have to source it.")}if ena_url else {}),"caveat": ("A depositor's INSDC record, NOT a hand-verified ""catalogue entry. Its feature table is as complete as ""the person who deposited it made it: a missing ""feature means unannotated, not absent. The curated "f"catalogue ({_vec.catalogue_size()} backbones) is the ""higher standard where it has an entry."),"note": ("Do not add restriction sites, coordinates, markers or ""tags that are not in the returned record."),"mapped": bool(map_ui),"next_action": next_action,**map_ui,}def _tool_lookup_vector(args: Dict[str, Any]) -> Dict[str, Any]:"""What the catalogue says about a cloning backbone β and nothing else.193 unmodified lines# against a product sheet, while an INSDC record carries whatever its# depositor annotated. Both beat recall; conflating them would let a# design rest on the weaker one.# An ACCESSION is a name here too. `vectors.find` does not know one and# `vector_search`'s tsvector does not contain one, so "open AF234290"# used to fall all the way through to "not in the catalogue" β while the# row sat in the index under its primary key. An agent that has just# read accessions out of a browse should be able to hand one straight# back, rather than being pushed toward a tool that drops the features.if _VS_ACCESSION.match(name.strip().upper()):try:from dee.core import vector_index as _virow = _vi.by_accession(name)if row and row.get("name"):return _index_vector_result(row, str(row.get("name")))except Exception: # noqa: BLE001logger.exception("vector accession lookup failed for %r", name)near = _vec.search(name, limit=6)idx_rows: List[Dict[str, Any]] = []try:12 unmodified linesexact = next((r for r in idx_rowsif _vec._norm(str(r.get("name") or "")) == _vec._norm(name)), None)if exact:return _index_vector_result(exact, name)# This is also the BROWSE answer, which is why it is built properly# rather than as a flat list of names. "pCAMBIA" matches no vector
255 unmodified lines2562572582592602612623765 unmodified lines4028402940304031403240334034255 unmodified linesrender a real result instead of an empty tab β the model neither needs itnor should pay for it in context on every subsequent call."""return {k: v for k, v in result.items() if k != "_ui"}def _view_label(view: str) -> str:3765 unmodified lines# "panel" is the full row shape for the real tool view β# present only for tools that can actually paint one."ui": {"view": _tool_view(name),"payload": model_result,"panel": result.get("_ui"),} if result.get("ok") else None,255 unmodified lines2562572582592602612623765 unmodified lines402840294030403140324033403440354036403740384039255 unmodified linesrender a real result instead of an empty tab β the model neither needs itnor should pay for it in context on every subsequent call."""return {k: v for k, v in result.items() if not k.startswith("_ui")}def _view_label(view: str) -> str:3765 unmodified lines# "panel" is the full row shape for the real tool view β# present only for tools that can actually paint one."ui": {# A tool's view is normally fixed. One is not: fetch_sequence# resolves genes (no view) but answers an INSDC VECTOR accession# with a real record, and that belongs on the Map tab. The# result says so with "_ui_view"; _strip_ui keeps it off the# model's copy, like every other _ui* key."view": result.get("_ui_view") or _tool_view(name),"payload": model_result,"panel": result.get("_ui"),} if result.get("ok") else None,
170 unmodified lines171172173174175176170 unmodified lines}def index_size() -> Optional[int]:"""Rows in the index, or None when it cannot be counted.170 unmodified lines171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213170 unmodified lines}def by_accession(accession: str) -> Optional[Dict[str, Any]]:"""The index row for one accession, or None.`vector_search` cannot answer this: its tsvector is built from name,description and keywords, and an accession appears in none of them β sosearching for "AF234290" matches nothing at all. A direct read on theprimary key is both the right query and the cheap one.It exists because an accession is what an agent HAS after a browse:`derived_options` hands over accessions, and without a door that takesone, the agent's next move was fetch_sequence, which returns a vector asanonymous bases. This is that door.RLS is on with no policies, so this works only with the service role βthe same key `_rpc` uses, and the same failure mode: None on anythingthat is not a clean hit."""acc = (accession or "").strip().upper()if not acc or not acc.replace(".", "").isalnum() or len(acc) > 32:return Noneurl, key = _config()if not (url and key):return Noneq = urllib.parse.urlencode({"accession": f"eq.{acc}", "limit": 1})req = urllib.request.Request(f"{url}/rest/v1/vector_index?{q}",headers={"apikey": key, "Authorization": f"Bearer {key}","Accept": "application/json", "User-Agent": _UA})try:with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:rows = json.loads(resp.read().decode("utf-8") or "[]")except Exception as exc: # noqa: BLE001logger.warning("vector_index accession lookup %s failed: %s", acc, exc)return Nonereturn rows[0] if isinstance(rows, list) and rows else Nonedef index_size() -> Optional[int]:"""Rows in the index, or None when it cannot be counted.
1792 unmodified lines1793179417951796179717981792 unmodified lineslookup_vector: function (panel) {return !!(window.TDPlasmid && window.TDPlasmid.paintAgentRun(panel));},// An edit replaces what is in the editor, so it goes through the same// painter β but it carries edited_spans, and the painter selects them// rather than dropping the user at base 1 of a construct that looks1792 unmodified lines1793179417951796179717981799180018011802180318041805180618071808180918101792 unmodified lineslookup_vector: function (panel) {return !!(window.TDPlasmid && window.TDPlasmid.paintAgentRun(panel));},/* fetch_sequence resolves GENES and has no view β except when theaccession it was handed turns out to be a vector, where it answerswith the real INSDC record and the server stamps ui.view"plasmid" on that one result. Safe to register unconditionally:driveUI only calls a painter when ui.panel exists, and a generesult has no panel. Without it the record came back annotated tothe model and the bench still showed nothing, so the modelreached for map_plasmid and auto-annotated bare bases intoinvented ORFs (2026-11-23). */fetch_sequence: function (panel) {return !!(window.TDPlasmid && window.TDPlasmid.paintAgentRun(panel));},// An edit replaces what is in the editor, so it goes through the same// painter β but it carries edited_spans, and the painter selects them// rather than dropping the user at base 1 of a construct that looks
236 unmodified lines2372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752763400 unmodified lines36773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237431 unmodified line374537463747374837493750236 unmodified linescritical path is an availability dependency we don't control.Top-level, not a subdirectory: /static/<path> only minifies andhard-caches assets with no slash in the name. --><link rel="stylesheet" href="/static/open-props-1.7.23.min.css?v=20261122-own-badge" /><link rel="stylesheet" href="/static/app.css?v=20261122-own-badge" /><!-- The work catalog + the draggable rail. Kept out of app.css so two newself-contained surfaces stay reviewable; every colour is an app.csstoken, so both themes work with nothing added. --><link rel="stylesheet" href="/static/catalog.css?v=20261122-own-badge" /><!-- Units, the run strip and the decision trace. Same reasoning ascatalog.css: kept out of app.css so a self-contained surface staysreviewable, and every colour is an app.css token so both themeswork with nothing added. --><link rel="stylesheet" href="/static/trace.css?v=20261122-own-badge" /><!-- Disclosure surfaces added in the 2026-08 scientific review (CRISPRscope strip, provenance "Assumes" line). Separate file for the samereason as catalog.css: small, self-contained, and app.css's cascadeis hostile. Uses app.css tokens only, so both themes work. --><link rel="stylesheet" href="/static/science.css?v=20261122-own-badge" /><link rel="stylesheet" href="/static/workbench.css?v=20261122-own-badge" /><link rel="stylesheet" href="/static/workspaces.css?v=20261122-own-badge" /><link rel="stylesheet" href="/static/collab.css?v=20261122-own-badge" /><link rel="stylesheet" href="/static/interaction.css?v=20261122-own-badge" /><link rel="stylesheet" href="/static/referrals.css?v=20261122-own-badge" /><link rel="stylesheet" href="/static/onboarding.css?v=20261122-own-badge" /><!-- Light, depth and a signature per instrument. After the componentsheets so it can lift them; before motion.css and accent.css, whichkeep the last word on Mission Control's motion and on amber. --><link rel="stylesheet" href="/static/atmosphere.css?v=20261122-own-badge" /><!-- Depth + motion for Mission Control. LAST: it refines .mc-* rules thatapp.css already defines at the same specificity, so it has to win onorder rather than by inflating selectors. Sets no colour. --><link rel="stylesheet" href="/static/motion.css?v=20261122-own-badge" /><!-- The secondary colour (the landing amber) by role: the key action,where you are, and selection. LAST, for the same reason asmotion.css: it overrides colours set earlier at equal specificity. --><link rel="stylesheet" href="/static/accent.css?v=20261122-own-badge" /><link rel="icon" type="image/svg+xml" href="/static/favicon.svg?v=5" /><link rel="apple-touch-icon" sizes="180x180" href="/static/apple-touch-icon.png?v=3" /><!-- Mol* (PDBe) 3-D viewer is ~4.9 MB. We do NOT eager-load it on every3400 unmodified linesAuthorization header on every same-origin /api/* call. Withoutthis, signed-in users would still hit the anonymous-quotagate. --><script src="/static/identity.js?v=20261122-own-badge"></script><script src="/static/notifications.js?v=20261122-own-badge"></script><script src="/static/auth.js?v=20261122-own-badge"></script><!-- Checkout runs on the approved turingdna.com origin, outside this iframe. --><script src="/static/billing.js?v=20261122-own-badge" defer></script><!-- Cloning reference data must load before app.js so the Designercan read VECTORS / ENZYMES / CLONING_METHODS / TAGS / LINKERS. --><script src="/static/cloning_db.js?v=20261122-own-badge" defer></script><!-- Before context.js and tabs.js: which project the bench is in decideswhere each tool keeps its state (tabs.js reads it at mount). --><script src="/static/project.js?v=20261122-own-badge" defer></script><script src="/static/context.js?v=20261122-own-badge" defer></script><script src="/static/lineage.js?v=20261122-own-badge" defer></script><!-- Before app.js: it mounts a strip at init. Both are `defer`, so theyrun in document order. --><script src="/static/tabs.js?v=20261122-own-badge" defer></script><!-- Also before app.js, for the same document-order reason: app.jsregisters its perception provider as it parses. A missingTDPerception is survivable by design β the agent is then blind tothe bench rather than the page being broken β but loading it latewould make that the normal case. --><script src="/static/perception.js?v=20261122-own-badge" defer></script><script src="/static/app.js?v=20261122-own-badge" defer></script><!-- The decision trace, BEFORE cockpit.js: applyEvent calls TDTrace.pushon the very first event, and both are `defer`, so document order isload order. Loading it after would drop the opening events of arestored run on the floor β silently, since the push is guarded. --><script src="/static/trace.js?v=20261122-own-badge" defer></script><!-- THE COCKPIT β the persistent orchestrator rail. Loads after app.js soTDBench/TDStructure exist when a tool result asks the workspace torender something. This is the only conversation surface in the app. --><script src="/static/decisions.js?v=20261122-own-badge" defer></script><script src="/static/cockpit.js?v=20261122-own-badge" defer></script><!-- structcard before catalog: the catalog calls TDStructCard.observe assoon as it paints. Both are defer, so document order is load order. --><script src="/static/structcard.js?v=20261122-own-badge" defer></script><!-- After app.js on purpose: it reuses that file's Mol* helpers(ensureMolstar, _afCreateViewer, _afRefit, _afShowError) rather thanstanding up a second viewer. --><script src="/static/interaction.js?v=20261122-own-badge" defer></script><script src="/static/catalog.js?v=20261122-own-badge" defer></script><script src="/static/workspaces.js?v=20261122-own-badge" defer></script><script src="/static/collab.js?v=20261122-own-badge" defer></script><script src="/static/history.js?v=20261122-own-badge" defer></script><script src="/static/teamwork.js?v=20261122-own-badge" defer></script><script src="/static/order.js?v=20261122-own-badge" defer></script><script src="/static/referrals.js?v=20261122-own-badge" defer></script><!-- Getting started (0064). After referrals.js, whose dialog two of itssteps open; it starts on auth.js's td:account event, not at load. --><script src="/static/onboarding.js?v=20261122-own-badge" defer></script><script src="/static/atmosphere.js?v=20261122-own-badge" defer></script><script src="/static/railsplit.js?v=20261122-own-badge" defer></script><!-- Dwell-time heartbeat. Loads after auth.js so its /api/ping calls gothrough the JWT-attaching fetch wrapper (signed-in attribution). --><script src="/static/telemetry.js?v=20261122-own-badge" defer></script><!-- First-party UX-behaviour collector (dead/rage clicks, scroll depth,funnel steps, feature clicks, client errors). Structure-only, neverreads sequence content; shares telemetry.js's persisted td_session_idand POSTs batches to /api/collect via sendBeacon. First-party /staticfile so it satisfies the strict script-src CSP. --><script src="/static/collector.js?v=20261122-own-badge" defer></script><!-- PostHog, loaded LAST on purpose. It chains window.fetch to turn asuccessful API call into a named product event, and auth.js and1 unmodified lineso it observes the response the user actually got rather than one oftheirs mid-flight. See dee/static/posthog.js for why autocapture andsession replay are off and must stay off. --><script src="/static/posthog.js?v=20261122-own-badge" defer></script></body></html>236 unmodified lines2372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752763400 unmodified lines36773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237431 unmodified line374537463747374837493750236 unmodified linescritical path is an availability dependency we don't control.Top-level, not a subdirectory: /static/<path> only minifies andhard-caches assets with no slash in the name. --><link rel="stylesheet" href="/static/open-props-1.7.23.min.css?v=20261123-vector-accession" /><link rel="stylesheet" href="/static/app.css?v=20261123-vector-accession" /><!-- The work catalog + the draggable rail. Kept out of app.css so two newself-contained surfaces stay reviewable; every colour is an app.csstoken, so both themes work with nothing added. --><link rel="stylesheet" href="/static/catalog.css?v=20261123-vector-accession" /><!-- Units, the run strip and the decision trace. Same reasoning ascatalog.css: kept out of app.css so a self-contained surface staysreviewable, and every colour is an app.css token so both themeswork with nothing added. --><link rel="stylesheet" href="/static/trace.css?v=20261123-vector-accession" /><!-- Disclosure surfaces added in the 2026-08 scientific review (CRISPRscope strip, provenance "Assumes" line). Separate file for the samereason as catalog.css: small, self-contained, and app.css's cascadeis hostile. Uses app.css tokens only, so both themes work. --><link rel="stylesheet" href="/static/science.css?v=20261123-vector-accession" /><link rel="stylesheet" href="/static/workbench.css?v=20261123-vector-accession" /><link rel="stylesheet" href="/static/workspaces.css?v=20261123-vector-accession" /><link rel="stylesheet" href="/static/collab.css?v=20261123-vector-accession" /><link rel="stylesheet" href="/static/interaction.css?v=20261123-vector-accession" /><link rel="stylesheet" href="/static/referrals.css?v=20261123-vector-accession" /><link rel="stylesheet" href="/static/onboarding.css?v=20261123-vector-accession" /><!-- Light, depth and a signature per instrument. After the componentsheets so it can lift them; before motion.css and accent.css, whichkeep the last word on Mission Control's motion and on amber. --><link rel="stylesheet" href="/static/atmosphere.css?v=20261123-vector-accession" /><!-- Depth + motion for Mission Control. LAST: it refines .mc-* rules thatapp.css already defines at the same specificity, so it has to win onorder rather than by inflating selectors. Sets no colour. --><link rel="stylesheet" href="/static/motion.css?v=20261123-vector-accession" /><!-- The secondary colour (the landing amber) by role: the key action,where you are, and selection. LAST, for the same reason asmotion.css: it overrides colours set earlier at equal specificity. --><link rel="stylesheet" href="/static/accent.css?v=20261123-vector-accession" /><link rel="icon" type="image/svg+xml" href="/static/favicon.svg?v=5" /><link rel="apple-touch-icon" sizes="180x180" href="/static/apple-touch-icon.png?v=3" /><!-- Mol* (PDBe) 3-D viewer is ~4.9 MB. We do NOT eager-load it on every3400 unmodified linesAuthorization header on every same-origin /api/* call. Withoutthis, signed-in users would still hit the anonymous-quotagate. --><script src="/static/identity.js?v=20261123-vector-accession"></script><script src="/static/notifications.js?v=20261123-vector-accession"></script><script src="/static/auth.js?v=20261123-vector-accession"></script><!-- Checkout runs on the approved turingdna.com origin, outside this iframe. --><script src="/static/billing.js?v=20261123-vector-accession" defer></script><!-- Cloning reference data must load before app.js so the Designercan read VECTORS / ENZYMES / CLONING_METHODS / TAGS / LINKERS. --><script src="/static/cloning_db.js?v=20261123-vector-accession" defer></script><!-- Before context.js and tabs.js: which project the bench is in decideswhere each tool keeps its state (tabs.js reads it at mount). --><script src="/static/project.js?v=20261123-vector-accession" defer></script><script src="/static/context.js?v=20261123-vector-accession" defer></script><script src="/static/lineage.js?v=20261123-vector-accession" defer></script><!-- Before app.js: it mounts a strip at init. Both are `defer`, so theyrun in document order. --><script src="/static/tabs.js?v=20261123-vector-accession" defer></script><!-- Also before app.js, for the same document-order reason: app.jsregisters its perception provider as it parses. A missingTDPerception is survivable by design β the agent is then blind tothe bench rather than the page being broken β but loading it latewould make that the normal case. --><script src="/static/perception.js?v=20261123-vector-accession" defer></script><script src="/static/app.js?v=20261123-vector-accession" defer></script><!-- The decision trace, BEFORE cockpit.js: applyEvent calls TDTrace.pushon the very first event, and both are `defer`, so document order isload order. Loading it after would drop the opening events of arestored run on the floor β silently, since the push is guarded. --><script src="/static/trace.js?v=20261123-vector-accession" defer></script><!-- THE COCKPIT β the persistent orchestrator rail. Loads after app.js soTDBench/TDStructure exist when a tool result asks the workspace torender something. This is the only conversation surface in the app. --><script src="/static/decisions.js?v=20261123-vector-accession" defer></script><script src="/static/cockpit.js?v=20261123-vector-accession" defer></script><!-- structcard before catalog: the catalog calls TDStructCard.observe assoon as it paints. Both are defer, so document order is load order. --><script src="/static/structcard.js?v=20261123-vector-accession" defer></script><!-- After app.js on purpose: it reuses that file's Mol* helpers(ensureMolstar, _afCreateViewer, _afRefit, _afShowError) rather thanstanding up a second viewer. --><script src="/static/interaction.js?v=20261123-vector-accession" defer></script><script src="/static/catalog.js?v=20261123-vector-accession" defer></script><script src="/static/workspaces.js?v=20261123-vector-accession" defer></script><script src="/static/collab.js?v=20261123-vector-accession" defer></script><script src="/static/history.js?v=20261123-vector-accession" defer></script><script src="/static/teamwork.js?v=20261123-vector-accession" defer></script><script src="/static/order.js?v=20261123-vector-accession" defer></script><script src="/static/referrals.js?v=20261123-vector-accession" defer></script><!-- Getting started (0064). After referrals.js, whose dialog two of itssteps open; it starts on auth.js's td:account event, not at load. --><script src="/static/onboarding.js?v=20261123-vector-accession" defer></script><script src="/static/atmosphere.js?v=20261123-vector-accession" defer></script><script src="/static/railsplit.js?v=20261123-vector-accession" defer></script><!-- Dwell-time heartbeat. Loads after auth.js so its /api/ping calls gothrough the JWT-attaching fetch wrapper (signed-in attribution). --><script src="/static/telemetry.js?v=20261123-vector-accession" defer></script><!-- First-party UX-behaviour collector (dead/rage clicks, scroll depth,funnel steps, feature clicks, client errors). Structure-only, neverreads sequence content; shares telemetry.js's persisted td_session_idand POSTs batches to /api/collect via sendBeacon. First-party /staticfile so it satisfies the strict script-src CSP. --><script src="/static/collector.js?v=20261123-vector-accession" defer></script><!-- PostHog, loaded LAST on purpose. It chains window.fetch to turn asuccessful API call into a named product event, and auth.js and1 unmodified lineso it observes the response the user actually got rather than one oftheirs mid-flight. See dee/static/posthog.js for why autocapture andsession replay are off and must stay off. --><script src="/static/posthog.js?v=20261123-vector-accession" defer></script></body></html>
538 unmodified lines539540541538 unmodified linessql = MIGRATION.read_text(encoding="utf-8")assert "pg_trgm" in sqlassert "gin_trgm_ops" in sql538 unmodified lines539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650538 unmodified linessql = MIGRATION.read_text(encoding="utf-8")assert "pg_trgm" in sqlassert "gin_trgm_ops" in sql# βββ 8. an accession is a door, not a dead end ββββββββββββββββββββββββββββ## A real transcript, 2026-11-23, on the day the index went live:## lookup_vector {"name": "pCAMBIA"} -> browse, derived_options with# accessions in them# fetch_sequence {"text": "AF234290"} -> 6,812 ANONYMOUS bases# map_plasmid {"topology": "circular"} -> auto_annotate invents 7 ORFs## Nothing errored. The index worked, the browse worked, and the construct# still reached the bench called "untitled" with seven guesses on it, while# the model described T-DNA borders and a kanamycin marker it had not been# shown. An agent holding an accession uses the tool that takes one, so the# tool that takes one has to give back the annotated record._ROW = {"accession": "AF234290", "name": "pCAMBIA-0380", "length_bp": 6812,"topology": "circular", "source": "ena", "evidence": "derived"}_REC = {"name": "AF234290", "accession": "AF234290", "sequence": "ACGT" * 1703,"length": 6812, "topology": "circular", "gc": 55.1,"features": [{"name": "right border T-DNA repeat","type": "misc_feature", "start": 350, "end": 376,"strand": 1}]}@pytest.fixturedef _vector_accession(monkeypatch):from dee.core import vector_index as vifrom dee.core import vector_sequence as vsmonkeypatch.setattr(vi, "by_accession",lambda a: _ROW if a.strip().upper() == "AF234290" else None)monkeypatch.setattr(vs, "accession_record", lambda a, **k: _REC)def test_fetch_sequence_returns_the_record_not_bare_bases(_vector_accession):from dee.core import agent_tools as tout = t._tool_fetch_sequence({"text": "AF234290"})assert out["ok"] is Trueassert out.get("mapped") is Trueui = out["_ui"]assert ui["name"] == "pCAMBIA-0380" # what the user typed, not the ID lineassert ui["features"], "the depositor's feature table must survive"assert out["evidence"] == "derived"def test_the_map_tab_is_told_where_to_paint_it(_vector_accession):"""fetch_sequence's view is None β it resolves genes. One result is nota gene, and the destination has to travel with that panel or the recordarrives annotated to the model and invisible on the bench."""from dee.core import agent_tools as tfrom dee.core import orchestrator as Oout = t._tool_fetch_sequence({"text": "AF234290"})assert out["_ui_view"] == "plasmid"assert O._tool_view("fetch_sequence") is Noneassert (out.get("_ui_view") or O._tool_view("fetch_sequence")) == "plasmid"def test_the_view_hint_never_reaches_the_model(_vector_accession):from dee.core import agent_tools as tfrom dee.core import orchestrator as Oout = O._strip_ui(t._tool_fetch_sequence({"text": "AF234290"}))assert not [k for k in out if k.startswith("_ui")]def test_a_gene_is_still_a_gene(monkeypatch):"""The regression that matters. fetch_sequence is called constantly forgenes; the vector branch must be invisible to every one of them."""from dee.core import agent_tools as tfrom dee.core import vector_index as vicalled = []monkeypatch.setattr(vi, "by_accession",lambda a: called.append(a) or None)from dee.core import resolve as _resmonkeypatch.setattr(_res, "resolve_target",lambda text, organism="": {"ok": True, "kind": "gene","sequence": "ATG", "length": 3})out = t._tool_fetch_sequence({"text": "TP53", "organism": "human"})assert "_ui" not in out and "_ui_view" not in outassert called == [], "a gene symbol must not cost an index lookup"def test_lookup_vector_takes_an_accession_too(_vector_accession):"""The sibling hole. vectors.find does not know an accession andvector_search's tsvector does not contain one, so "open AF234290" fellthrough to "not in the catalogue" while the row sat under its ownprimary key."""from dee.core import agent_tools as tout = t._tool_lookup_vector({"name": "AF234290"})assert out["ok"] is True and out.get("mapped") is Trueassert out["_ui"]["name"] == "pCAMBIA-0380"@pytest.mark.parametrize("bad", ["", " ", "; drop table x", "../../etc/passwd","A" * 64])def test_by_accession_refuses_anything_that_is_not_one(bad, monkeypatch):from dee.core import vector_index as vimonkeypatch.setattr(vi, "_config", lambda: ("https://x", "k"))monkeypatch.setattr(vi.urllib.request, "urlopen",lambda *a, **k: pytest.fail("must not reach the network"))assert vi.by_accession(bad) is Nonedef test_the_browser_can_paint_what_fetch_sequence_resolved():"""Server-side `_ui_view` is half of it; without a painter keyed on thetool name the panel arrives and nothing draws."""js = (ROOT / "dee" / "static" / "cockpit.js").read_text(encoding="utf-8")painters = js.split("var PAINTERS", 1)[1]assert "fetch_sequence: function (panel)" in painters
dee/core/agent_tools.py+144-71
dee/core/orchestrator.py+7-2
dee/core/vector_index.py+37
dee/static/cockpit.js+12
dee/static/index.html+43-43
tests/test_vector_index.py+109