Spaces:
Sleeping
Sleeping
Commit History
-
Reliability: bake ESM-2 weights + bound in-memory jobs/rate-limit
Tengo Gzirishvili +1: Claude Opus 4.8Three audit quick-wins: - Dockerfile: HF_HOME moved to a BAKED /opt/hf-cache and the default ESM-2 (35M) weights are prefetched at build time, so a cold start no longer re-downloads them (HF_HOME used to live under ephemeral /tmp). Best-effort prefetch (|| echo) so a build-time hiccup can't break the image — it just lazy-loads at runtime. - server.py: cap _JOBS at 2000 and evict the oldest (with their edit locks) so a long-lived worker can't grow unbounded. - server.py: the rate-limit table now evicts the STALEST buckets when it gets large, instead of clear()-ing the whole thing (which reset every honest user's window and could be abused by a unique-IP flood). Verified: 324 tests pass; _JOBS cap evicts oldest + prunes locks; rate-limit drops stalest buckets (recent kept), no global wipe. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>843e792 -
Reliability: run on gunicorn (auto-restart) + add /healthz
Tengo Gzirishvili +1: Claude Opus 4.8The biggest "trust = uptime" fix from the audit. The Space ran on Flask's dev server (Werkzeug) with no supervisor — one unhandled error downed it until a manual reboot. Now it runs under gunicorn: - Dockerfile CMD → gunicorn dee.server:build_app(), ONE gthread worker (state lives in-process: jobs, sessions, rate-limit, the cached scorer — so a single worker is required), 8 threads for concurrency, 120s timeout (the model load runs in a background thread so requests stay fast). The master auto-restarts the worker on a crash → an error no longer takes the whole Space down. - server.py: extract build_app() (logging + off-target prewarm + create_app) as the shared WSGI entry; serve() reuses it for local dev so both paths behave identically. Add a no-auth /healthz liveness route for an uptime monitor. - requirements.txt: add gunicorn. Verified locally with the exact prod invocation: 324 tests pass; gunicorn boots gthread/1-worker; /healthz -> 200 {"status":"ok"}; / -> 200. C…1259937
-
P0 hardening: model OOM gate + cached scorer + poll give-up
Tengo Gzirishvili +1: Claude Opus 4.8Three reliability fixes from the platform audit: C1 — CPU model gate. The run settings offered ESM-2 650M/3B; the server accepted them; the free Space has no GPU, so a 3B fp32 load (~12–24 GB) OOM-killed the whole container for EVERY user — even an anonymous visitor's one free run could trigger it. Now: _validate_run_settings + _get_scorer downgrade medium/large -> small and drop any cuda/quant request on a non-GPU host; the UI disables the 650M/3B options ("Pro · GPU — coming soon"). Effective model is reflected in settings so analytics + the methods note stay truthful. C2 — Cached scorer. ESM-2 was rebuilt on every /api/run (model reload tax; concurrent runs each resident-loaded a copy → memory multiplied toward OOM). New process-global, lock-guarded _get_scorer() loads weights at most once per effective config and reuses them (warm runs now ~instant on small). M1 — Poll give-up. The frontend polled forever on transient errors. Added a consecutive-error cap (12) and an overall wal…5dde9d0
-
Plasmid: accept SnapGene .dna; fix button hover (black fill, both themes)
Tengo Gzirishvili +1: Claude Opus 4.8Two things: 1) Plasmid Editor now imports SnapGene .dna (binary) alongside GenBank/FASTA/ raw. Biopython 1.87 ships a SnapGene reader, so: - plasmid.py: _record_to_plasmid() shared mapper; parse_snapgene(bytes) + parse_binary() dispatcher (detects .dna by extension OR the 0x09+"SnapGene" signature; size-bounded; filename fallback for unnamed records). - server.py: /api/plasmid/import accepts a base64 `b64` payload (decodes, bounds, parses) in addition to the existing `text` path. - app.js: the Upload-file handler reads .dna/.snapgene/.xdna as bytes → base64 → import; text formats still load into the box. Parsed sequence is dropped into the editor so it's visible + editable. - index.html: accept=".dna,…"; label now says "SnapGene .dna". 2) White/cream buttons now invert to a near-black rectangle with white text on hover — in BOTH themes. The old hover used theme tokens that, in dark mode, flipped to off-white-on-dark (the filled CTAs visib…21dfced -
Add pairwise sequence alignment (Needleman–Wunsch / Smith–Waterman)
Tengo Gzirishvili +1: Claude Opus 4.8Closes the biggest "looks incomplete vs Benchling" gap from the competitive audit — we couldn't align two sequences at all. - dee/core/align.py: numpy global + local pairwise alignment with identity %, match midline, gaps, score; |a|×|b| size cap. +8 unit tests. - POST /api/align (stateless utility, rate-limited, no sign-in gate). - "Align two sequences" card in the Plasmid workbench: two inputs, Global/Local toggle, blocked alignment view + identity/score stats. Verified live: global 88.9% identity with correct midline, local finds the shared region (100%, 0 gaps), empty→400. Full suite 324 passing. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>91ed780
-
Bump v2.0 effective date 2026-07-07 -> 2026-07-08 (full 30-day notice)
Tengo Gzirishvili +1: Claude Opus 4.8The user notice now goes out 2026-06-08, so move the effective date one day to 2026-07-08 to keep the >=30-day advance-notice commitment exact. Updates the aggregation gate constant in both aggregate.py and outcomes.py (the functional gate), the in-app policy-notice banner, and the dating in code/migration comments. Legal docs, emails, and the landing privacy/terms pages updated in their respective trees. Tests: 315 passing (gate tests track the constant symbolically). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>a0ee590 -
Security hardening: RLS-as-user, rate limiting, headers, PII + endpoint cleanup
Tengo Gzirishvili +1: Claude Opus 4.8Defense-in-depth pass so a single mistake or leak can't expose user data: - RLS enforcement: per-user reads/writes now run AS THE USER (anon apikey + the requester's verified JWT) so Postgres RLS enforces row isolation — a forgotten user_id=eq. filter can no longer leak another user's rows. New _user_pgrst_headers() with graceful fallback to the service key when SUPABASE_ANON_KEY is unset (reversible rollout). Background workers and the genuine cross-user aggregates keep the service key. - user_id chokepoint: reject any JWT whose `sub` isn't a UUID (closes PostgREST filter-injection via a crafted sub at the single entry point). - Rate limiting: in-process per-(client,rule) sliding window on /api/* with 429 + Retry-After; bounded memory, fail-open, env escape hatch. - Security headers: X-Content-Type-Options, Referrer-Policy, Permissions-Policy, HSTS, and CSP frame-ancestors allowlisting turingdna.com (iframe-safe). - PII minimization: store only a /24-anonymized IP + s…702b153 -
chore: strip internal HTML comments from the served app page
Tengo Gzirishvili +1: Claude Opus 4.8A user opening dev tools on /app/ could read internal engineering notes embedded as HTML comments. server.py now serves index.html with HTML comments stripped + inline JS/CSS minified (_clean_html, cached by mtime, graceful raw fallback) — the commented SOURCE stays for devs, the SERVED page carries none. Verified: served "/" has 0 HTML comments, inline scripts still valid, internal notes (Phase/anti-FOUC/etc.) gone, engine elements intact. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>cb5e8ef
-
chore: production polish — minify served JS/CSS + proper meta (de-"vibecoded")
Tengo Gzirishvili +1: Claude Opus 4.8Removes the dev-tools tells without touching the (commented) source: - server.py: /static/<*.js|*.css> is now minified on the fly (rjsmin/rcssmin, cached by mtime, long cache headers) — app.js 405→256KB, app.css 202→129KB, comment-free. Source stays the single truth; any minify failure falls back to the raw file. Added rjsmin/rcssmin to requirements. - index.html: meta description, theme-color, color-scheme, referrer policy, and noindex on the raw engine URL (canonical product is turingdna.com). Console already clean (0 console.log). Minified output node-check-valid; app runs on the raw-fallback path in preview with no console warnings. Cache-buster -> v=20260608-min. Suite 285. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>063809e -
feat: richer DE aggregate — substitution × ESM ΔLL bin (opt-in, gated)
Tengo Gzirishvili +1: Claude Opus 4.8aggregate.py: keys can carry an ESM-confidence bin → (wt, mut, bin); bin_ll() buckets the wild-type-marginal ΔLL (lo/mid/hi). build_priors gains an optional ll_maps arg (per-library {label: ΔLL}); apply_global_prior is bin-aware, matching each pool mutation's OWN ΔLL bin (free at blend time) and falling back to the unbinned key. Fully backward compatible — no ll_maps ⇒ plain (wt,mut) keys, so existing behavior + tests are unchanged. +4 tests (binning, split-by-ll, blend, serialize). server.py: DE rebuild accepts an opt-in `esm_bins` flag that recomputes ΔLL per library (WT from libraries.wt_protein) — guarded, never runs pre-gate, degrades to unbinned on any ESM failure. auth.py: lib-aware grouping + get_library_wt. Suite 285. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>21b1923 -
feat: wire the CRISPR on-target prior into scoring (data-out, guarded)
Tengo Gzirishvili +1: Claude Opus 4.8Completes the CRISPR loop's consumption side. outcomes.py: shared crispr_features (used by both extractor + scorer so keys match), crispr_feature_delta (bounded to ±0.15 of the [0,1] score), and a pure calibrate_crispr_guides (folds the prior in, re-sorts, re-ranks). server.py: cached _load_tool_prior(tool); the /api/crispr/design endpoint now calibrates guides before returning ("calibrated" flag). Strict no-op until public.outcome_priors has a 'crispr' aggregate (post effective date) — verified inert: design returns unchanged scores + calibrated:false. +4 tests; suite 278. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>05da2fa -
feat: unified outcomes framework — tool-agnostic capture + aggregate + calibrate
Tengo Gzirishvili +1: Claude Opus 4.8The platform-wide version of the DE flywheel so the moat isn't DE-only. One tool-tagged layer any tool plugs into via a ToolSpec; privacy/gating identical for all. - dee/core/outcomes.py: generic engine (ToolSpec registry, within-design standardize, k-anonymity, EFFECTIVE_DATE gate, Prior with blend/serialize). DE registered as first consumer, delegating to the proven aggregate.py — verified DE-through-framework == aggregate.py exactly. - migration 0009_outcomes.sql: generic public.outcomes (tool-tagged, owner RLS, TTL) + public.outcome_priors (tool, feature_key; service-role; CHECK n_users>=3). Leaves the live DE tables (de_outcomes/mutation_priors) untouched. - auth.py: save/list_outcomes, list_all_outcomes_grouped(tool), get/replace_outcome_priors(tool). - server.py: POST /api/outcomes, GET /api/outcomes/<tool>/<design_id>, admin GET /api/admin/priors/<tool> + POST /api/admin/rebuild-priors/<tool> (date-gated). 8 new tests (genericity via synthetic spec, k-anon, gate, …674bee6 -
feat: primer/PCR versatility — design, multiplex, local specificity (backend)
Tengo Gzirishvili +1: Claude Opus 4.8Three offline (no-NCBI) additions to dee/core/primers.py + endpoints: - design_primers(): de novo F/R pair design from a template (+ optional target region). Enumerates candidates per flank, scores Tm/GC/clamp/hairpin/dimer, pairs by product size + Tm match + cross-dimer. POST /api/primers/design. - multiplex_check(): pairwise 3' cross-dimers + amplicon size clashes for a primer set. POST /api/primers/multiplex. - local_specificity(): in-silico PCR against a user-uploaded genome/FASTA — runs on our server so primers never leave (unlike the NCBI scan). find_sites gained a max_template override so it scans whole chromosomes. POST /api/primers/local-specificity (<=12 Mb). All sign-in gated; offline so no consent step. 12 new tests (structural correctness, k of geometry, dimer/size detection, off-target copies). Verified via test-client (anon->403; design/multiplex/local-spec happy paths). Suite 264. Frontend UI + virtual gel land next. Co-Authored-By: Claud…867ce54 -
feat: cross-user aggregate prior (the data moat) — built, run gated to 2026-07-07
Tengo Gzirishvili +1: Claude Opus 4.8Pools wet-lab outcomes ACROSS users into a de-identified substitution-effect prior that nudges round-1 designs. Aggregated-only per the v2.0 policy; nothing attributable to a person. - dee/core/aggregate.py: pool by amino-acid substitution TYPE (positions are protein-specific, so only type generalizes); standardize within each library before pooling (no assay scale/raw value survives); k-anonymity floor of >=3 DISTINCT users; execution gated to EFFECTIVE_DATE (2026-07-07). Folds in via apply_global_prior (additive, same as the per-user surrogate). numpy-only. - migration 0008_mutation_priors.sql: server-only table (RLS, no policies), CHECK(n_users>=3) k-anon guard at the DB layer too. (USER must run it.) - auth.py: list_all_de_outcomes_grouped (the only cross-user read; service-role, pulls just mutations+value), get/replace_mutation_priors. - server.py: admin-token-gated GET /api/admin/mutation-priors + POST /api/admin/rebuild-priors (date-gated → 423 before effective da…3317015
-
Learning flywheel v1: Directed-Evolution active-learning loop (DBTL)
Tengo Gzirishvili +1: Claude Opus 4.8The first durable-moat feature: TuringDNA learns from a researcher's wet-lab results to design a smarter next round, on data no competitor has. Scoped to Directed Evolution (the only tool with quantitative per-variant fitness). Surrogate (dee/core/active_learning.py): additive ridge over single-site effects with the ESM-2 ΔLL as the prior — y ≈ b + w_prior·ΣΔLL + Σβ_m. Fit closed-form in numpy (no sklearn/scipy needed) on the user's measured variants; β shrinks unseen mutations to the prior; an exploration bonus rewards under-tested positions. Plugs straight into the existing additive SA: round 2 re-runs evolve() with per-mutation score = w_prior·ΔLL + β + κ·uncertainty. Numpy-tested: measured data overrides a misleading prior (Spearman 0.77), 0 labels → pure prior, <4 → honest fallback. Backend: migration 0007_de_outcomes.sql (USER RUNS IT); auth.py save/list/cleanup_de_outcomes; /api/de/outcomes (POST/GET) + /api/de/round2 (score WT → fit surrogate → evolve adjusted pool → assemble…26914b4 -
Port methods paragraph + Primer export; adversarial audit fixes
Tengo Gzirishvili +1: Claude Opus 4.8Cross-pollination (DE → other tools): - "Materials & methods (copy-paste)" paragraph + run-parameter pills now render on CRISPR, Primer Analysis and Plasmid Editor (shared tdRenderMethods() helper, reuses .run-meta CSS + wireCopyButtons). Citable, paste-ready. - Primer Analysis export: new /api/primers/export (CSV + .xlsx via openpyxl, sign-in gated, client posts the held result) + an Export menu in the results head. Primer Analysis had no export before. Adversarial audit (whole platform): - FIXED (high): stored/reflected XSS — the methods paragraphs interpolated user-controlled strings (sequence identifier, primer name, plasmid name; can arrive via a pasted FASTA header or an imported GenBank file) raw into innerHTML. Now escaped (escapeHtml/esc) in all four builders, incl. the pre-existing DE runMeta wtId. - FIXED (low): /api/preview 500 returned the raw exception string to the client (confusing + minor internal leak) → generic message; detail still logged. - Verif…7446d10
-
First-timer UX: identifier fix + goal router + contextual topbar + results key
Tengo Gzirishvili +1: Claude Opus 4.8Bug — sequence identifier showed random letters: Raw (non-FASTA) pastes/uploads fell back to the temp-file stem (tmpXXXX) as their identifier; only sequences pasted WITH a > header (e.g. GFP) worked. Added _humanize_paste_name + _clean_record_identifier (server.py) at both parse sites → raw paste = "Pasted sequence", upload = the real filename, FASTA/GenBank names untouched. UX (the three parked first-timer wins): - "Start here" goal router: dismissible modal ("What are you working on?" → 4 goals route to the right tool). Auto-shows once after the first-use disclaimer; re-openable from a new "Start here" sidebar item. - Contextual topbar: the vague "Engine" title is now the current tool name + a one-line description, updated per route in showRoute() (sub hidden on mobile). - Inline "How to read this": a collapsed-by-default plain-English score key on the Directed Evolution, CRISPR and Primer results cards (ΣΔLL fitness, CFD self-off, KO/FS/Dominance, Tm/specifici…a5e129b -
Unified "My designs" hub: save every tool, not just CRISPR
Tengo Gzirishvili +1: Claude Opus 4.8"My designs" was CRISPR-only; plasmids lived in a separate list and primer/ evolution results couldn't be saved. Now it's one hub with a section per tool. Backend: - migration 0006_primer_analyses.sql (user runs it) — per-user table mirroring crispr_designs (owner-only RLS, 90-day expires_at). - auth.py: save/list/get/delete_primer_analysis (+ lazy cleanup); list_libraries and library_csv_url (signed, owner-checked) reusing the existing public.libraries + Storage bucket from DE auto-save. - server.py: /api/primers/{save,analyses,analyses/<id> GET+DELETE} and per-user /api/library + /api/library/<id>/download — all sign-in gated + owner-guarded. Frontend: - New #savedModal unified hub (Plasmids · CRISPR · Primer sets · Evolution libraries); each tool registers a reopen fn on window.TDSaved. navMyDesigns, the CRISPR "My designs" button, and the Plasmid "My plasmids" button all open it. - Primer Analysis gains a Save button; evolution libraries list with Download CSV (sign…1ee54b6 -
Fix reported production bugs: stuck dropdowns, blocked SNP, session loop
Tengo Gzirishvili +1: Claude Opus 4.8From a user bug report (4 issues): (4) Stuck/overlapping toolbar dropdowns — opening "GenBank ▾" then "Use in ▾" left BOTH open and overlapping: each button's stopPropagation blocked the other menu's outside-click close. Now opening one closes the other (operate on all .plasmid-export-menu); outside-click closes all. Verified. (2) "Couldn't do a single-nucleotide mutation" on the DE engine — a SNP that creates a stop codon was hard-blocked at BOTH layers (client save disabled; server 400) with a FALSE "synthesis vendors will reject this" claim. A premature stop is a legitimate nonsense/truncation mutation; vendors synthesize it fine. Now allowed: server truncates the product at the first stop (no raise); client downgrades the warning high→medium so Save works. Frame-break (non-×3) and non-ACGT still correctly block. +4 tests. (1) "Session out of sync" that reload/re-signin won't clear — confirmed a stale-token loop (works in a fresh/incognito …e52101b
-
Adversarial audit of Plasmid Studio: fix XSS, DoS, and input-validation gaps
Tengo Gzirishvili +1: Claude Opus 4.8Findings + fixes from a full security/robustness pass over M1–M5: 1) Stored XSS (HIGH) — a feature `color` was injected unescaped into an inline `style="--featc:…"` (sequence view), so a saved plasmid whose feature colour broke out of the attribute (`red" onmouseover=…`) ran script on reopen. Fix: client only emits a validated hex colour into any SVG/style attr (pmColor gate); server sanitize_features() forces every stored/exported colour to a safe hex. Verified live: a malicious saved plasmid renders inert (handler never fires) on map, swatch, and sequence views. 2) DoS — find_orfs was O(n²): a long, ATG-rich, stop-less paste pinned the worker. Rewrote to a single linear pass per frame + an ORF cap. (120 kb stop-less input now returns in <2 s vs many seconds.) 3) DoS / crash — unbounded inputs: - parse_plasmid now rejects import text > 2 MB before parsing; GenBank feature parse capped at 5,000. - sanitize_features() clamps coords to [0,len], drops…d67ba8e -
Plasmid Studio M3 + M4: sequence editor + cloning simulation
Tengo Gzirishvili +1: Claude Opus 4.8M3 — Sequence editor (new "Sequence" view tab): - Feature-colored sequence with position ruler; runs grouped by feature so even big plasmids render cheaply (capped at 60 kb). - Find (forward + reverse-complement) with match count + next/prev, highlights + jumps; selection via From/To coords or clicking a feature. - Operations on the selection: Copy, Copy rev-comp, Translate (client genetic code), Annotate (add a feature), Delete, Insert at position, Reverse- complement the whole plasmid. Edits rewrite the sequence, REMAP feature coordinates (delete/insert shift, revcomp flips), and re-scan restriction. M4 — Cloning simulation (dee/core/cloning.py + /api/plasmid/clone + "Clone & assemble" panel): - Gibson / overlap assembly: auto-orders fragments by terminal overlap; native overlaps assemble scarlessly, bare junctions get homology arms DESIGNED into per-fragment primers (annealing core via the codon engine + the neighbour's tail). Circular or linear. - Golden Gate (Type…ec0167c -
Plasmid Studio (M1+M2): import/annotate/map + restriction/digest + library
Tengo Gzirishvili +1: Claude Opus 4.8New "Plasmid" tool — a Benchling/SnapGene-style plasmid design studio, built on primitives we already had (Biopython GenBank I/O + 1,088 REBASE enzymes, ORF detection, Supabase per-user save). Sign-in gated like CRISPR / the Primer Picker; per-user library from day one. Core (dee/core/plasmid.py, fully unit-tested): - parse_plasmid: GenBank / FASTA / raw DNA → one normalized model {name, sequence, topology, gc, length, features[]}. - auto_annotate: ORF detection + curated motif library (T7/T3/SP6/M13/lac/His) when a record has no features; GenBank features kept as-is. - build_genbank / build_fasta export. - restriction_analysis: per-enzyme cut sites over the common set (or any), circular-aware, classified single/double/multi/non-cutters. - digest: combined cut positions → fragment sizes (circular wraps the origin). API (server.py, sign-in gated): /api/plasmid/import, /restriction, /digest, /export, plus the library: /save, /library (list), /library/<id> (get/delete). auth.py: s…be23b1b -
Primer Picker: add strict 3'-end matching knob for the specificity scan
Tengo Gzirishvili +1: Claude Opus 4.8Off-target predictions are *priming sites*, not guaranteed amplicons — and whether a polymerase extends is governed by the 3' terminus. This adds an opt-in stringency control: when on, an off-target priming site only counts if its 3'-terminal 5 bases match the subject perfectly (no mismatch, no gap), trimming borderline sites that share a body but mismatch at the 3' end. - server.py: _three_prime_clean() inspects the tail of the BLAST alignment strings (match/query/sbjct); _hsp_to_event(strict_3p) rejects a hit whose 3' end isn't clean. PrimerJob.three_prime_strict; /api/primers/analyze accepts `strict_3p` (folded into the cache key). Degrades to lenient if the alignment strings aren't present. - Frontend: "Strict 3'-end matching" sub-toggle under the organism selector (shown with the scan), sent as strict_3p. Default off = catch borderline sites too (safer for screening); on = fewer, higher-confidence predictions. Tests: _three_prime_clean (perfect / 3'-mismatch / within…438edb5 -
Primer Picker: separate intended product from off-targets; collapse redundant hits
Tengo Gzirishvili +1: Claude Opus 4.8Live test surfaced a real problem: running the GAPDH/ACTB primers against Human reported "60 unintended products" and branded a perfectly specific pair with "38 off-target products." Those weren't off-targets at all — `nt` holds dozens of redundant GAPDH records, so the ONE intended 197 bp amplicon was counted once per database entry. That's the opposite of helpful. Fix (rank()): - Collapse in-silico PCR hits that are the same primer pair at the same size (±5 bp) into ONE distinct amplicon, with a "seen in N records" count. - Classify distinct amplicons: a detected F/R pair's amplicon at its expected size (on-template size when given, else the pair's dominant size) is the INTENDED product; the same pair at a different size (e.g. a pseudogene) or any cross-/unpaired combo is a genuine off-target. - Per-primer off-target count now counts only true off-target distinct amplicons, so fitness + chips stop punishing specific primers. Frontend: results now show an "Intended product…7df48f4 -
Primer Picker: full in-silico PCR specificity — no more "go to NCBI Primer-BLAST"
Tengo Gzirishvili +1: Claude Opus 4.8The footer used to send users to NCBI Primer-BLAST to finish the job, which defeats the point of an in-house tool. The reason was v1 only counted per-primer matches, not the paired off-target AMPLICONS that Primer-BLAST uniquely finds. Now we do that check ourselves so the workflow is complete here and the user never leaves. - core/primers.py: insilico_pcr() pairs every forward-oriented priming site with every downstream reverse-oriented site on the same subject within MAX_PRODUCT (4 kb) → predicted PCR products, exactly like Primer-BLAST's specificity step. rank() now folds off-target *product* counts (not raw match counts) into fitness + reasoning and surfaces the product list. - server.py: _hsp_to_event() converts a BLAST HSP to a 3'-anchored priming event (strand from sbjct_start/end; rejects 5'-only / low-identity hits); _run_primer_blast() builds events across ALL primers, runs in-silico PCR, and attributes products per primer. Adds organism targeting (entrez_query…eeea851
-
Add Primer Picker: batch-analyse primers, rank, recommend the best
Tengo Gzirishvili +1: Claude Opus 4.8New feature requested by the user: instead of BLASTing candidate primers one at a time and eyeballing which best amplifies their template, paste them all, analyse in one shot, and get a ranked recommendation. What it does: * Parse a batch (FASTA or one-per-line) with optional names + F/R tags; forward/reverse pairs are auto-detected by name stem. * Score each primer ON the user's template (private, on-server): 3'-anchored binding site(s), uniqueness, Tm (NN), GC, 3' G/C clamp, hairpin, 3' self-dimer. * For F/R pairs: amplicon size, Tm match, 3' cross-dimer. * Opt-in NCBI specificity scan — ALL primers in ONE blastn-short submission ("blast them all together"); NCBIXML yields one record per primer, mapped back by query order; counts strong full-length off-target matches. * Transparent fitness rubric in [0,1] (Tm/GC/clamp/dimer/uniqueness/ specificity) ranks them and recommends the best primer + best pair, with the reasoning shown — not a black box.…f0c3f5a -
Fix: Identify/AlphaFold dead-ends on heavily-sequenced proteins (e.g. Cas9)
Tengo Gzirishvili +1: Claude Opus 4.8Reported: opening the closest-structure view on a Cas9 variant said "NO ALPHAFOLD MODEL AVAILABLE" even though SpCas9 obviously has one (UniProt Q99ZW2). Root cause: the Identify BLAST hits `nr`, which is excellent for identification but crowded with redundant GenBank/TPA records — Cas9's top hits are all `tpg|HER…` third-party annotations with NO UniProt accession, so the curated entry is buried and _extract_uniprot finds nothing → no AlphaFold model resolved. Fix: when no parsed `nr` hit carries a UniProt accession, fall back to a homology search against the small curated `swissprot` database. Every UniProtKB/Swiss-Prot entry has an AlphaFold-DB model, so this reliably surfaces the closest KNOWN structure (Cas9 → Q99ZW2). The resolved accession is pinned onto the top hit, with its organism + identity kept separate so the UI labels it honestly as the closest reviewed homolog rather than the exact query. - server.py: _swissprot_uniprot() + _attach_structure_homolog(); called at the…a635fbe -
IP Radar patents (env-gated) + Toxicity & Synthesis Oracle (Red Team)
Tengo Gzirishvili +1: Claude Opus 4.8PART A — free patent layer for the IP Radar (env-gated): - core/ip_radar.check_patents(): recent patents mentioning the target gene + editing terms via the FREE PatentsView Search API. Needs a free, registered PATENTSVIEW_API_KEY env var; without it the radar stays literature-only (graceful). Cached. GENE-LEVEL 'related patents in this space' — NOT a precise sequence-to-claim match (that needs Lens PatSeq, paid), framed accordingly. Merged into /api/crispr/ip_radar; banner shows a 'Related patents' subsection. Mocked tests (no-key + parse). NOTE: Lens.org is NOT free for commercial use (14-day trial only); the free route is PatentsView (metadata) + optional NCBI patent BLAST later. PART B — Toxicity & Synthesis Oracle (pre-export Red Team gate): Pure client-side, ZERO new deps (the engine is vanilla JS + Flask, not React/pnpm — so no installs; minimal bundle). - Synthesis (Twist-style): global+local GC (<20% / >65%), homopolymer (>6), lightweigh…13a90b2 -
Live Collision IP Radar v1 — opt-in literature scan (Europe PMC)
Tengo Gzirishvili +1: Claude Opus 4.8Warns when a generated guide overlaps existing work. v1 = literature only (preprints + papers via free Europe PMC); patents deferred to v2 (needs a Lens.org token). Per the agreed posture: OPT-IN, METADATA-FIRST — only the gene + validated point-mutation set + 20-mer guide leave the Space; never the full novel sequence (the endpoint refuses arbitrary strings in 'mutations'). Matching is on SPECIFIC identifiers, not noise: exact guide spacer (full-text phrase) or gene + mutation set. A novel guide returns 0 hits; a published one returns the papers that printed it (verified: EMX1 guide -> real matches). - core/ip_radar.py: Europe PMC client, query builder, recency classify, result shaping (authors/date/source/link), 24h thread-safe TTL cache that also caches empty results -> 50 users checking the same guide ping PMC once (the rate-limit requirement). Pure stdlib. - POST /api/crispr/ip_radar: sign-in gated; validates spacer (ACGT) + HGVS-ish mutations; non-critical (…61e171c
-
Harden AlphaFold viewer + add CSV export to CRISPR download
Tengo Gzirishvili +1: Claude Opus 4.8AlphaFold (today's 'malfunction' = transient EBI/AlphaFold-DB outage; all deps healthy, nothing regressed in our code). The viewer was fragile to it: a single-shot load + hardcoded model_v6 + a misleading 'model doesn't exist' error with no recovery. Now: - _afFetch: abort-timeout + one retry on network/5xx/429 - _afResolve: ask the prediction API for the CURRENT model URL, then build a fallback ladder (alt .cif format + version walk v6/v5/v4); report whether the entry actually exists - _afTryLoad: walk candidates until a structure really enters the hierarchy - _afShowError: honest copy — 'AlphaFold-DB temporarily unreachable' + a Retry button for transient failures; 'no model for this entry' only when the API confirms absence Applied to both mountAlphaFoldViewer (DE) and _mountCrisprStructure (CRISPR). CSV export: /api/crispr/download was XLSX-only (hardcoded) while the UI still said 'CSV' — users had no real CSV. Added a format param (csv|xlsx); CSV via std…0360d9f
-
Fix AlphaFold viewer showing nothing (stale model version + silent 404)
Tengo Gzirishvili +1: Claude Sonnet 4.6Root cause: AlphaFold-DB bumped its model version DB-wide (v4 → v6), so the hardcoded …AF-{acc}-F1-model_v4.pdb URLs now 404. And Mol*'s loadStructureFromUrl does NOT throw on a 404 — it loads the XML error body, ends up with zero structures, removes our loading overlay, and silently leaves an empty viewer. Net effect: "won't show predicted models." Verified empirically: v4 → HTTP 404; AlphaFold's prediction API (/api/prediction/{acc}, CORS-enabled) reports latestVersion 6; loading the v6 .pdb yields 1 structure in the Mol* hierarchy. Fix (both the directed-evolution embed and the CRISPR M5 cut-site viewer): - _afResolveModelUrl(): pull the accession out of whatever URL we were given and resolve the CURRENT file URL from the AlphaFold API (falls back to the given URL on any error). Future-proof against the next version bump. - _afHasStructure(): after loadStructureFromUrl, assert a structure actually landed in the hierarchy; if not, throw so the catch surfaces a real message …20cdca4
-
CRISPR M4: save & revisit designs (per-user, 90-day TTL)
Tengo Gzirishvili +1: Claude Opus 4.8Per-user saved guide sets in public.crispr_designs (migration 0004, run in Supabase). Designs are small JSON → stored as a JSONB row, no Storage upload (unlike libraries). Backend (auth.py): save_crispr_design (synchronous insert, returns id), list_crispr_designs (metadata, newest first), get_crispr_design (full row, server-side user_id ownership), cleanup_expired_crispr_designs_async (lazy expiry sweep piggybacked on save). Free TTL = 90 days (FREE_LIBRARY_TTL_DAYS); pro = forever (has_pro_plan → NULL expires_at). Design id is UUID-validated before going into the REST filter. Endpoints (sign-in gated): POST /api/crispr/save, GET /api/crispr/designs, GET /api/crispr/designs/<id>. Missing-table is reported gracefully ("saved designs aren't enabled yet") so a pre-migration deploy never hard-errors. Frontend: "Save design" + "My designs" in the results header; a saved- designs modal lists past designs (label · mode · guide count · date) and reopens one — restoring its mode/editor/organ…1c7c498 -
CRISPR M5: structure viewer — cut site on the AlphaFold model
Tengo Gzirishvili +1: Claude Opus 4.8Reuses the Mol* 5.9.0 viewer already loaded for the directed-evolution page to show a guide's cut site on the gene's predicted 3-D structure. Backend: - Guide.cut_residue: maps each Cas9 cut → 1-based protein residue when a reading frame is resolvable (gene+organism aligned to CDS, or the input is itself a coding sequence). Exposed in /api/crispr/design. - resolve.resolve_uniprot(): gene symbol + organism → reviewed UniProt accession via the UniProt REST API → AlphaFold-DB model URL. Only the (gene, organism) leaves the Space. - GET-style POST /api/crispr/structure (sign-in gated) returns the UniProt accession + AlphaFold URLs. Frontend: - A "View 3-D structure · cut at residue N" button inside the M3 "why this guide" panel (shown only when a human/mouse gene context + a resolved residue exist — no new table column). - Structure modal mounts AlphaFold-DB via the proven mountAlphaFold path; header reads "GENE · UniProt XXXXX · cut at residue N…73b3e85 -
CRISPR M2: paste-anything input + fix phantom progress bar
Tengo Gzirishvili +1: Claude Opus 4.8Resolver (dee/core/resolve.py, new): one input box auto-detects and resolves a gene symbol, an accession (ENST…/ENSG…/NM_…/XM_…), or raw DNA into an editable sequence + a human label. - gene symbol → Ensembl canonical-transcript CDS (reuses exon.fetch_gene_structure; human/mouse). - Ensembl ID → /sequence/id?type=cds (gene IDs resolve to canonical tx). - RefSeq → NCBI efetch FASTA. - raw / FASTA → used as-is, makes NO network call (privacy: a pasted sequence never leaves the Space; only the identifier is sent). Conservative classifier: a long DNA-dominant blob is always a sequence. Endpoint POST /api/crispr/resolve (sign-in gated, same as design), returns {ok, kind, sequence, gene_symbol, label, source}. Frontend: a resolver row above the paste box (input + Fetch, Enter to submit) fills the textarea with the resolved sequence, shows a result chip, and auto-sets the gene-symbol field so base-edit AA consequences and exon context get the reading frame. Bug fix surfaced…4229225 -
CRISPR M1: base-editing design mode (CBE/ABE + iSTOP + AA consequence)
Tengo Gzirishvili +1: Claude Opus 4.8Promotes the base-editor flag into a first-class design mode that out-classes tools which only flag editability. Backend (dee/core/base_editor.py, new): - Editor library: BE4max/BE3/evoCDA (CBE C→T), ABE8e/ABE7.10 (ABE A→G), each with activity window + per-position profile (Komor/Koblan/ Thuronyi/Gaudelli/Richter). - predict_base_edits(): edits in window, per-position efficiency, bystander detection, editability score. - codon_consequence(): frame-aware AA call — silent/missense/nonsense/ stop-loss + CRISPR-STOP / iSTOP detection. Returns None (never guesses) on alignment mismatch or incomplete codon. find_guides() gains mode="base_edit" + base_editor= kwargs (defaults keep every existing caller unchanged). New Guide fields are all defaulted. AA consequence fills only when a reading frame is trusted — gene_symbol+ organism aligned to CDS, or the input is itself a clean coding sequence (_looks_like_cds). Base editing is SpCas9-only; annotation is gated to it.…dd2d535
-
Genome off-target — non-blocking + background prewarm + status banner
Tengo Gzirishvili +1: Claude Opus 4.7Founder report: human-index build went 300+ s, browser request had timed out, user staring at frozen spinner. Architecture was broken — the synchronous kmer-index build inside the HTTP request handler can easily blow past HF Spaces' ~120 s request timeout. Three fixes: 1. offtarget.find_genomic_offtargets() no longer blocks on a build. If the cached index isn't ready when the request arrives, we kick off a background daemon-thread build (idempotent — won't duplicate if one is already running) and return EMPTY hits + a per-organism "building" status. The user's design request returns immediately with on-target / CFD-self / indel / oligo data, just without the genome off-target column populated. 2. server.serve() prewarms all ready organisms (ecoli + human + mouse) in daemon threads at Flask startup. The Space rebuild itself takes 1-2 min; by the time it goes green and a user arrives, the small E. coli index is done (~5 s) and the large…6983e3b -
CRISPR Phase 2C-1 — cloning oligos + vendor buttons + vector picker
Tengo Gzirishvili +1: Claude Opus 4.7Ports the directed-evolution page's "design → order" loop to CRISPR. Three things, all matching the design-page pattern: 1. Vector picker (dropdown above results table). 5 popular Cas9 vectors + 1 Cas12a vector seeded: - px330 (Addgene 42230, BbsI) — original Zhang Cas9+gRNA - pX458 (Addgene 48138, BbsI) — px330 + 2A-GFP, FACS sortable - pX459 V2 (Addgene 62988, BbsI) — px330 + 2A-Puro - lentiCRISPRv2 (Addgene 52961, BsmBI) — lentiviral all-in-one - pLentiGuide-Puro (Addgene 52963, BsmBI) — gRNA-only lentiviral - pY094 (Addgene 84739, BsmBI) — lentiCpf1 for Cas12a Default = pX459 V2 (covers the most common knockout workflow). 2. Per-guide oligo pair. Standard Zhang-lab format: sense: 5'-CACCG[20 nt spacer]-3' antisense: 5'-AAAC[reverse complement]C-3' Cas12a (pY094) uses the AGAT / AAAA overhang convention from Zetsche 2017. Two new table columns (Sense oligo, Antisense oligo) each with a Copy bu…7a41c01 -
CRISPR Phase 2B-1 — E. coli genome off-target + Ensembl exon-aware design
Tengo Gzirishvili +1: Claude Opus 4.7Two new optional features, both backward-compatible (no params = pre-2B behavior): 1. Genome off-target search. New dee/core/offtarget.py: - Lazy NCBI download (~3 s) on first request after a cold start. - 8-mer-seeded kmer index in memory; pure-Python (no BWA/bowtie deps). - For each Cas9 guide: search every NGG site in the genome with up to 4 mismatches in the spacer + 1 mismatch in the seed (positions 13-20), CFD-score each candidate, return top hits. - E. coli K-12 MG1655 ready today (5 MB FASTA, ~240k sites, ~5 s build). - Human / mouse stubbed as placeholders pending pre-built indexes hosted externally (Phase 2B-2). - Thread-safe build lock; degrades open on any error. 2. Exon-aware annotation. New dee/core/exon.py: - Ensembl REST lookup for (organism, gene_symbol) → canonical transcript + exon structure + CDS sequence. Cached in-memory. - Align user's pasted DNA to the gene's CDS via fast substring seed …345b9c9 -
CRISPR Phase 2A polish — replace Cleanliness (saturated at 6) with Dominance %
Tengo Gzirishvili +1: Claude Opus 4.7Founder feedback: every guide on EGFP showed Cleanliness=6. The count was useless — algorithm caps top_n at 5 + "other" = 6 items, and the 5% threshold lets all of them through. Replaced with top_dominance_pct: the frequency of the single most- likely repair outcome. Direct biological readout — answers "will I get one main edit product or many?" with one number: 40%+ = clean predictable cut (one dominant edit) — green 25-40% = typical heterogeneous repair — amber <25% = messy (smear of alleles) — red API field renamed outcome_diversity → top_dominance_pct. CSV column "Outcome diversity" → "Top outcome dominance %". UI column "Cleanliness" → "Dominance". Frontend keeps a soft fallback for one deploy cycle so cached browsers don't render "—". XLSX column width adjusted. Cache buster bumped to 20260529-crispr-dominance. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>7c54abf -
CRISPR Phase 2A — inDelphi-inspired indel prediction + base-editor flag
Tengo Gzirishvili +1: Claude Opus 4.7Two new capabilities, both empirical heuristics that ship as pure Python with no new deps (defer the neural-network inDelphi to Phase 2B if benchmark gap demands). 1. Indel outcome prediction. For each Cas9 guide we scan ±17 bp of the cut site for microhomologies (2-6 bp), score MMEJ deletions by MH_length × exp(-del_length/10) per Bae 2014, add the templated +1 insertion class (~32% of events, templated from position -4 per van Overbeek 2016 / Lemos 2018), plus a small MH-less baseline. Aggregate per-guide: top_indel_label "-3 (ATG) (28%)" / "+1 T (32%)" / ... frameshift_pct total % of outcomes that are frameshift outcome_diversity # of outcomes ≥ 5% (low = clean cut) predicted_indels top-5 outcomes with frequencies Smoke-tested against EGFP — predictions are biologically plausible: in-frame -3 dels dominate in coding sequence (trinucleotide periodicity → frequent microhomologies), templated +1 inse…db7532c -
Replace CRISPR CSV export with native XLSX (fixes ;-locale Excel mangle)
Tengo Gzirishvili +1: Claude Opus 4.7Founder hit the bug immediately after the Phase 1 ship: opening the downloaded CSV in Excel on macOS with a Georgian locale split every data row on ";" instead of ",", because Excel's CSV import uses the OS list-separator (";" in most non-English locales) regardless of what the file actually uses. Visible symptom: 15-column data showing up as 2 columns with the KO reasoning text broken in half on the embedded semicolon. Two fixes, shipped together: 1. dee/core/crispr.py — KO reasoning strings now use en-dash "—" instead of ";" so even the fallback CSV path is safe. 2. dee/server.py — /api/crispr/download now emits a proper XLSX via openpyxl. Native Excel format: no delimiter ambiguity, opens cleanly in Excel / Numbers / Google Sheets regardless of locale. Headers bold + paper-fill, numeric columns emitted as proper numbers so sort + cell formats work natively, header row frozen, sensible column widths. 3. Frontend — button label "Download CSV" → …ec5933d -
CRISPR Phase 1 — Doench-inspired scoring + CFD self-off-target + Cas12a + KO efficacy
Tengo Gzirishvili +1: Claude Opus 4.7Closes the credibility gap vs CRISPOR/CHOPCHOP. Five things: 1. Doench-inspired on-target scoring. Strongest published sequence-only features from Doench 2016 (RS2) — per-position single-nt weights at all 20 positions (was 5), dinucleotide weights at PAM-coupled positions, kept GC + homopolymer + PAM contributions. Honest UI label: "TuringDNA on-target" — not "Doench RS2", since we skipped the gradient-boosted ML layer. 2. CFD self-off-target scoring. The exact 20-position mismatch-penalty matrix from Doench 2016 Supplementary Table 19 plus PAM multiplier table. For each guide, scores every OTHER NGG site in the pasted input as a potential off-target. None of CRISPOR/CHOPCHOP/Synthego does CFD-within-input — defensible novel angle, especially useful when editing tagged constructs where the tag may harbor an unintended cut site. Returns per-guide max_cfd_offtarget + offtarget_count. 3. Cas12a / Cpf1 support. TTTV PAM a…995ee2a -
Verify ES256 JWTs via Supabase JWKS (project migrated off HS256)
Tengo Gzirishvili +1: Claude Opus 4.7Diagnostic confirmed (via /api/whoami): this Supabase project signs access tokens with ES256 using an asymmetric key, not HS256 against the Legacy JWT Secret. Result: every signed-in user was failing verification and getting treated as anonymous → CRISPR 403 → "session out of sync" modal on every click. What this commit ships: 1. requirements.txt — adds PyJWT[crypto]>=2.8.0 (~6 MB), brings in the cryptography backend needed for ECDSA + JWKS support. 2. auth.py — keeps the legacy HS256 path intact (Supabase anon + service_role keys are still HS256, and projects that haven't migrated still need it). Adds two new functions: _verify_jwt_jwks(token, alg) — uses PyJWT.PyJWKClient against <project>/auth/v1/.well-known/jwks.json Cached, refreshes on kid miss. _verify_jwt_any(token) — reads the JWT header's `alg` and dispatches to HS25…e377126 -
Add /api/whoami diagnostic endpoint to pinpoint auth state
Tengo Gzirishvili +1: Claude Opus 4.7Founder report: even after re-pasting SUPABASE_JWT_SECRET on the HF Space, signed-in users may still hit the "session out of sync" modal on CRISPR. Could be: missing env var, wrong value, trailing whitespace from paste, clock skew, missing Authorization header, etc. Stop guessing — expose what the backend actually sees. GET /api/whoami returns booleans + token fingerprints (NEVER the full token or the JWT secret): - auth_enabled, supabase_secret_set, supabase_secret_len - header_seen, header_starts_bearer, token_len, token_fingerprint - decode_ok (JWT well-formed), decoded_iss, decoded_aud, sub/email present - verified (signature matched the configured secret) - anonymous (final auth state the request handlers see) - server_time, jwt_iat, jwt_exp, seconds until expiry / since issuance Usage from the iframe DevTools console: fetch('/api/whoami').then(r => r.json()).then(console.log) The result tells us in one shot whether the JWT is missing, malformed, expired, has cloc…a4197dc
-
CRISPR MVP: Cas9 knockout gRNA designer (sign-in gated, free for accounts)
Verified signaturee64c086 -
Library TTL: 90-day expiry for free tier + lazy cleanup on /api/run
Verified signature8a15b07
-
Security audit fixes: C1 ownership guards, C2/C3 remove unsafe endpoints, H1 server-side BLAST consent, H2 strip filesystem paths
Verified signature752bedc -
Save libraries to Supabase Storage on run completion + plan helpers
Verified signature550d5be
-
Strip LLM: dee/server.py
Verified signature2017fcd
-
Chat proxy: auth via HF_TOKEN env var for PRO-tier ZeroGPU quota
Verified signatureb323ffc