diff --git a/.agents/skills/formchem-harness/EVALS.json b/.agents/skills/formchem-harness/EVALS.json index 8e288d02..e5060c3b 100644 --- a/.agents/skills/formchem-harness/EVALS.json +++ b/.agents/skills/formchem-harness/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-harness", - "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected with the agent token, version 0.10.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.10.0 has 60 tools: agents draw with draw_from_smiles, draw_from_molfile, draw_from_name and add_reaction, edit by id with get_atoms and the 14 edit tools, check with render, get_structure and validate, name with name_structure, predict NMR with predict_nmr and predict_spectrum, work on spectra with open_spectrum and the spectrum tools, work in 3D with build_3d, conformers_3d, minimise_3d, scan_dihedral, measure_3d, open_3d_structure, extract_ligand and export_3d, and still reach the window's commands, reactions, analysis and extensions; several evals check that the agent draws with the tools and checks before it claims. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 18 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O; eval 20 needs an SD file at the path it names; eval 28 needs ethyl acetate drawn; eval 29 needs a JCAMP-DX 1H NMR file of ethanol at the path it names; eval 33 needs a PDB file with a protein chain and a benzamidine ligand (BEN) at the path it names; eval 34 needs butane drawn.", + "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected with the agent token, version 0.12.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.12.0 has 77 tools: agents draw with draw_from_smiles, draw_from_molfile, draw_from_name and add_reaction, edit by id with get_atoms and the 14 edit tools, check with render, get_structure and validate, name with name_structure, predict NMR with predict_nmr and predict_spectrum, work on spectra with open_spectrum and the spectrum tools, work in 3D with build_3d, conformers_3d, minimise_3d, scan_dihedral, measure_3d, open_3d_structure, extract_ligand and export_3d, work with structure databases and the notebook with db_list, db_create, db_open, db_import, db_search, db_get_record, db_add_record, db_update_record, db_export, nb_add_entry and nb_search, keep the shared structure library with library_list, library_add and live_structure_object, draw biopolymers with draw_from_helm, run xtb and CREST (only when installed) with xtb_optimise and crest_conformers, and still reach the window's commands, reactions, analysis and extensions; several evals check that the agent draws with the tools and checks before it claims. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 18 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O; eval 20 needs an SD file at the path it names; eval 28 needs ethyl acetate drawn; eval 29 needs a JCAMP-DX 1H NMR file of ethanol at the path it names; eval 33 needs a PDB file with a protein chain and a benzamidine ligand (BEN) at the path it names; eval 34 needs butane drawn; evals 36 to 40 need an SD file of a few hundred structures, one of them with a broken connection table, at the path eval 36 names, and evals 37 to 40 the database eval 36 makes; eval 44 needs ethanol drawn and eval 45 butane, and both should be run once with xtb and CREST installed and once without them.", "evals": [ { "id": 1, @@ -9,8 +9,8 @@ "files": [], "expected_behavior": [ "Calls get_context first", - "Says in plain words that an agent can make, open and save drawings, draw structures and reaction schemes from SMILES, molfiles or names, edit them atom by atom, read them back as SMILES, InChIKey, molfile or names, render and validate them, predict 1H and 13C NMR, open JCAMP-DX spectra and pick peaks, build structures in 3D with conformers, scans and measurements, open PDB files and extract ligands, convert files and run menu commands, each change one undo step", - "Names what is not there yet: typing stoichiometry amounts, quantum or tight-binding energies (no xtb or CREST)", + "Says in plain words that an agent can make, open and save drawings, draw structures and reaction schemes from SMILES, molfiles or names, edit them atom by atom, read them back as SMILES, InChIKey, molfile or names, render and validate them, predict 1H and 13C NMR, open JCAMP-DX spectra and pick peaks, build structures in 3D with conformers, scans and measurements, open PDB files and extract ligands, keep structure databases (import, search, register, export) and lab notebook entries, keep the shared structure library and live structures for other Form apps, draw peptides and nucleic acids from HELM, run xtb and CREST when the person installed them, convert files and run menu commands, each change one undo step", + "Names what is not there yet: typing stoichiometry amounts, DFT or any quantum method beyond the person's own xtb, signing notebook entries (only the person signs)", "Does not run any command or post a handoff for a question that only asks" ] }, @@ -404,6 +404,125 @@ "Does not claim to see the 3D View; says the panel shows it and that render shows only a stored picture", "Ends with a handoff naming what the person will see" ] + }, + { + "id": 36, + "name": "import-sd-into-new-database", + "prompt": "Make a FormChem database called Screening and load /tmp/fc-evals/screen.sdf into it. Tell me if anything failed.", + "files": [], + "expected_behavior": [ + "Calls db_list or get_context, then db_create {title: \"Screening\"} and keeps the handle it returns", + "Calls db_import with dry_run true before the real import, and reports the counts it gives", + "Runs db_import without dry_run and quotes added, updated and failed as returned", + "Names each failed record by its number in the file with the reason the job gives, and does not claim the import failed as a whole" + ] + }, + { + "id": 37, + "name": "benzene-substructure-and-export", + "prompt": "In my Screening database in FormChem, find every compound with a benzene ring and save them to /tmp/fc-evals/benzene-hits.sdf.", + "files": [], + "expected_behavior": [ + "Calls db_search with smiles c1ccccc1 and mode substructure (or the default mode)", + "Quotes the hit list id, its name and the count and time as returned, and says the hit list also shows in the person's window", + "Calls db_export with format sdf, that hitlist id and the absolute path, and quotes the written count, which equals the hit count", + "Does not page through rows with db_get_record to build the file itself" + ] + }, + { + "id": 38, + "name": "similar-compounds-with-scores", + "prompt": "Which compounds in the Screening database are most like 4-methylbenzoic acid? Only ones that are really close.", + "files": [], + "expected_behavior": [ + "Calls db_search with the SMILES of 4-methylbenzoic acid (Cc1ccc(cc1)C(=O)O or equivalent), mode similarity and a threshold of 0.7 or higher", + "Lists the hits with the score each row carries and names the method (Tanimoto on Morgan fingerprints) as the answer gives it", + "Does not invent scores or rank hits by its own judgement against the returned scores", + "Says how many hits there were and that a lower threshold would find more" + ] + }, + { + "id": 39, + "name": "register-a-duplicate", + "prompt": "Add ethylamine hydrochloride to the Screening database in FormChem.", + "files": [], + "expected_behavior": [ + "Calls db_add_record with smiles CCN.Cl (or equivalent) and no on_duplicate", + "When the answer lists duplicates (ethylamine under salt stripping), shows them and asks the person whether to use the existing record, add a new batch or register anyway", + "Does not call db_add_record again with on_duplicate new on its own", + "When nothing matched, quotes the new record's number and uid" + ] + }, + { + "id": 40, + "name": "notebook-entry-from-reaction", + "prompt": "Record today's amide coupling in the Screening database notebook: benzoic acid and methylamine gave N-methylbenzamide, sample AC-001, 1.21 g, 89% yield. Then sign it.", + "files": [], + "expected_behavior": [ + "Calls nb_add_entry with db, a title, the reaction template, reaction OC(=O)c1ccccc1.CN>>CNC(=O)c1ccccc1 (or equivalent) and a product with sample AC-001, mass_g 1.21 and yield_pct 89", + "Quotes the entry number, uid and the stoichiometry with its method as returned", + "Does not sign the entry and does not call it signed; tells the person that signing is theirs (Sign Notebook Entry... in the window)", + "Can find the entry afterwards with nb_search by AC-001 or by the substructure NC=O" + ] + }, + { + "id": 41, + "name": "oxytocin-from-helm", + "prompt": "Draw oxytocin in FormChem from HELM, with its disulfide, and give me the formula and monoisotopic mass.", + "files": [], + "expected_behavior": [ + "Calls draw_from_helm with PEPTIDE1{C.Y.I.Q.N.C.P.L.G.[am]}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$V2.0 or an equivalent HELM string with the 1:R3-6:R3 connection", + "Quotes C43H66N12O12S2 and the monoisotopic mass (1006.436458) with the method the answer names", + "Checks the result with get_structure or render, or quotes the InChIKey XNOPRXBHLZRZKH-DSZYJQQASA-N from the answer", + "Does not draw oxytocin atom by atom or from a SMILES it wrote itself" + ] + }, + { + "id": 42, + "name": "helm-refusal", + "prompt": "Draw PEPTIDE1{A.X.G}$$$$ in FormChem.", + "files": [], + "expected_behavior": [ + "Calls draw_from_helm once and reports the refusal with the character where reading stopped and the reason (X is not a PEPTIDE monomer FormChem knows)", + "Does not guess what X was meant to be or retry with invented monomers; asks the person, or offers inline SMILES for a non-standard residue", + "Reports that nothing was drawn" + ] + }, + { + "id": 43, + "name": "star-and-hand-to-sibling", + "prompt": "Put caffeine in the shared structure library as a live structure and give me the object FormDeck needs.", + "files": [], + "expected_behavior": [ + "Calls library_add with smiles Cn1cnc2c1c(=O)n(C)c(=O)n2C (or the drawing) and kinds [\"live\"]", + "Quotes the item id, kinds, formula C8H10N4O2 and rev 1 from the answer", + "Calls live_structure_object with that id and passes the object on as returned, without editing its svg", + "Does not claim that FormDeck was updated or opened" + ] + }, + { + "id": 44, + "name": "xtb-water-optimisation", + "prompt": "Optimise the drawn ethanol with GFN2-xTB in water and tell me the energy.", + "files": [], + "expected_behavior": [ + "Calls xtb_optimise with method gfn2 (or default) and solvent water on the ethanol structure", + "Quotes the total energy in hartree and kcal/mol, the HOMO-LUMO gap and the program label with version, method and solvent, as returned", + "If xtb is not installed, reports the tool's answer with where to get xtb, does not retry, and does not present an MMFF94 energy as an xtb result", + "Does not call the energy a measured or DFT value" + ] + }, + { + "id": 45, + "name": "crest-not-installed", + "prompt": "Run a CREST conformer search on the butane I drew and keep the 5 lowest.", + "files": [], + "expected_behavior": [ + "Calls crest_conformers with keep 5 (and a time limit if it sets one)", + "When CREST is missing, tells the person FormChem does not include or download CREST and where to get it, as the answer says, and stops", + "When CREST runs, quotes the relative energies and populations with the program label and how many conformers were dropped for lost stereo", + "Offers conformers_3d with MMFF94 only as a clearly named alternative, after asking" + ] } ], "trigger_evals": [ @@ -473,6 +592,22 @@ {"query": "export the 3D coordinates of my formchem structure as an SDF with every conformer", "should_trigger": true}, {"query": "add a new force field to formchem's services/three_d/forcefield.py", "should_trigger": false}, {"query": "write an RDKit script that embeds and minimises conformers for a list of SMILES", "should_trigger": false}, - {"query": "render this PDB entry as a cartoon in PyMOL", "should_trigger": false} + {"query": "render this PDB entry as a cartoon in PyMOL", "should_trigger": false}, + {"query": "load my SD file of 10,000 compounds into a FormChem database and tell me which records failed", "should_trigger": true}, + {"query": "search my formchem compound database for everything containing a pyridine ring", "should_trigger": true}, + {"query": "find analogues of this hit in the FormChem database with Tanimoto above 0.8", "should_trigger": true}, + {"query": "is this compound already registered in my formchem database", "should_trigger": true}, + {"query": "write up today's experiment as a notebook entry in FormChem with the yield", "should_trigger": true}, + {"query": "add a new query term kind to formchem's services/database/query.py", "should_trigger": false}, + {"query": "run a similarity search over ChEMBL with chemfp", "should_trigger": false}, + {"query": "set up an electronic lab notebook in Benchling for my group", "should_trigger": false}, + {"query": "draw this HELM peptide in formchem: PEPTIDE1{A.C.D.E}$$$$", "should_trigger": true}, + {"query": "optimise my molecule with GFN2-xTB in DMSO using FormChem", "should_trigger": true}, + {"query": "star this structure in formchem so FormTxt can insert it", "should_trigger": true}, + {"query": "give me the live structure object for library item s4k2m9x0qa from FormChem", "should_trigger": true}, + {"query": "run CREST through formchem on the drawn macrocycle and keep 10 conformers", "should_trigger": true}, + {"query": "install xtb with conda on my laptop", "should_trigger": false}, + {"query": "convert a HELM string to SMILES with the Pistoia HELM toolkit in Java", "should_trigger": false}, + {"query": "add a new HELM monomer to formchem's helm_monomers.json data file", "should_trigger": false} ] } diff --git a/.agents/skills/formchem-harness/SKILL.md b/.agents/skills/formchem-harness/SKILL.md index 2235c344..29ac1268 100644 --- a/.agents/skills/formchem-harness/SKILL.md +++ b/.agents/skills/formchem-harness/SKILL.md @@ -1,21 +1,21 @@ --- name: formchem-harness -description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: draw a structure or reaction from SMILES, a molfile or a chemical name, build or edit it atom by atom, check the drawing with render, get_structure or validate, name a structure, predict a 1H or 13C NMR spectrum, open a JCAMP-DX spectrum, pick peaks or integrate, build it in 3D, find conformers, minimise, scan a dihedral or measure a bond length, open a PDB file or extract a ligand, convert files, open or save drawings, run a menu command, perceive a reaction, get cLogP, hand off, or asks what FormChem can do, and FormChem is named or its tools (draw_from_smiles, draw_from_name, predict_nmr, build_3d, render, get_atoms, run_command, handoff and the rest) are available. Covers 127.0.0.1:8220, the agent token, approval and Stop. Not for changing FormChem's source (formchem-skillset), other Form apps such as FormDeck, or standalone RDKit scripts." +description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: draw a structure or reaction from SMILES, a molfile, a chemical name or HELM, edit it atom by atom, check it with render, get_structure or validate, predict a 1H or 13C NMR spectrum, open a JCAMP-DX spectrum, build it in 3D, find conformers, run xtb or CREST, open a PDB file or extract a ligand, search a compound database by substructure or similarity, import an SD file, register a compound, add a notebook entry, put a structure in the shared library, convert files, run a menu command, or asks what FormChem can do, and FormChem is named or its tools (draw_from_smiles, build_3d, db_search, library_add, draw_from_helm, render, run_command and the rest) are available. Covers 127.0.0.1:8220, the agent token, approval and Stop. Not for changing FormChem's source (formchem-skillset), other Form apps such as FormDeck, or standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.10.0" + version: "0.12.0" --- # FormChem harness FormChem is a chemical structure drawing suite running on this computer. Its MCP server (`formchem`) lives in the engine and reaches the FormChem window, where the person sees everything an agent does. This pack is the method for using it well: draw with the tools, check what you drew, and hand back. -## What exists today (0.10.0) +## What exists today (0.12.0) -FormChem has drawings (`.fchem` documents kept by the engine with undo, autosave and versions), an RDKit chemistry service that computes SMILES, InChIKey, formula, masses, CIP labels and valence warnings after every change, and a 2D canvas the person draws on. Earlier versions added reactions and annotations (0.5.0), stereo, queries and analysis (0.6.0), formats, pictures, the clipboard, Standardise, the command line, the dark page, scaling and grids (0.7.0), the agent tools (0.8.0), and names, NMR prediction (FormChem increments) and JCAMP-DX spectra (0.9.0). +FormChem has drawings (`.fchem` documents kept by the engine with undo, autosave and versions), an RDKit chemistry service that computes SMILES, InChIKey, formula, masses, CIP labels and valence warnings after every change, and a 2D canvas the person draws on. Earlier versions added reactions and annotations (0.5.0), stereo, queries and analysis (0.6.0), formats, pictures, the clipboard, Standardise and the command line (0.7.0), the agent tools (0.8.0), names, NMR prediction and JCAMP-DX spectra (0.9.0), 3D: builds with the stereo checked, conformers, scans, measurements, PDB and mmCIF files and ligands (0.10.0), and structure databases with the lab notebook (0.11.0). -0.10.0 adds 3D: conformers built from the drawing with the stereo checked, conformer searches, minimisation and dihedral scans with RDKit's force fields, measurements, the 3D View and 3D objects on the page, PDB and mmCIF files with ligand extraction, and 3D exports. The MCP server has 60 tools; `references/tools.md` lists every argument and is generated from the server. +0.12.0 adds the shared structure library every Form app reads, live structures (a picture with the drawing inside that sibling apps keep and send back for editing), HELM in and out, xtb and CREST run when the person installed them, keyboard and screen reader access, and element palettes. The MCP server has 77 tools; `references/tools.md` is generated from the server and lists all of them; the library and HELM tools are in `sub-skills/library-and-biopolymers` and the xtb tools in `sub-skills/three-d`. | Group | Tools | | --- | --- | @@ -27,12 +27,15 @@ FormChem has drawings (`.fchem` documents kept by the engine with undo, autosave | Names (0.9.0) | `draw_from_name` (a common or systematic name, read offline), `name_structure` (common and round-trip-checked systematic names) | | NMR and spectra (0.9.0) | `predict_nmr`, `predict_spectrum`; `open_spectrum` (JCAMP-DX), `spectrum_data`, `spectrum_peaks`, `spectrum_pick_peaks`, `spectrum_integrate`, `spectrum_export` | | 3D (0.10.0) | `build_3d`, `conformers_3d`, `minimise_3d`, `scan_dihedral`, `measure_3d`; `open_3d_structure` (PDB, mmCIF, SDF, MOL), `extract_ligand`, `export_3d` | +| Databases and notebook (0.11.0) | `db_list`, `db_create`, `db_open`, `db_import`, `db_search`, `db_get_record`, `db_add_record`, `db_update_record`, `db_export`; `nb_add_entry`, `nb_search` | +| Library and HELM (0.12.0) | `library_list`, `library_add`, `live_structure_object`; `draw_from_helm` | +| xtb and CREST (0.12.0) | `xtb_optimise`, `crest_conformers` (only when the person installed the programs) | | Window, extensions, handoff | `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff` | | Reactions (0.5.0) and analysis (0.6.0) | `perceive_reactions`, `map_reaction`, `export_reaction`, `reaction_stoichiometry`, `properties`, `check_structure`, `stereo`, `substructure` | Every change an agent makes is one transaction and one undo step, labelled with the tool in the person's Edit > Undo, and every change answers with the structure it now holds (ids, SMILES, InChIKey, formula, warnings) and a PNG of it. The person sees which agent is editing in the title bar, with a Stop button, and Window > Agent Activity lists every call with undo for the latest one. -Every name and computed number carries its method and version (FormChem names 0.9.0, FormChem increments 0.9.0, `ETKDGv3+MMFF94 (rdkit 2025.09.3)`); quote them with the value, and never present a prediction or a force-field energy as measured. What still is not there: names the offline engine refuses (hydro prefixes, spiro and bridged rings, peptides; use SMILES), a tool that links peaks to atoms (the window command does) or inserts a spectrum file into an existing drawing, typing amounts into the Stoichiometry panel, tools for 3D styles and surfaces (the window commands do), and any quantum or tight-binding method (no xtb or CREST). The export and copy commands still hand their file to the person, not to the agent; use `convert` or `get_structure` for text you can read. Never draw by other means and present it as FormChem's work. +Every name and computed number carries its method and version (FormChem names 0.9.0, FormChem increments 0.9.0, `ETKDGv3+MMFF94 (rdkit 2025.09.3)`, similarity scores with their fingerprint, `xtb 6.7.1, GFN2-xTB, ALPB (Water)`); quote them with the value, and never present a prediction or a computed energy as measured. What still is not there: names the offline engine refuses (hydro prefixes, spiro and bridged rings; peptides go through HELM), a tool that links peaks to atoms (the window command does) or inserts a spectrum file into an existing drawing, typing amounts into the Stoichiometry panel, tools for 3D styles and surfaces (the window commands do), DFT or any quantum method beyond the person's own xtb, a tool that returns HELM text or describes a structure in words (window commands `copy-helm` and `a11y-describe` do), and database fields, saved queries, attachments or signing for agents (the window does them). The export and copy commands still hand their file to the person, not to the agent; use `convert` or `get_structure` for text you can read. Never draw by other means and present it as FormChem's work. ## Doctrine (applies to every route) @@ -49,7 +52,7 @@ Every name and computed number carries its method and version (FormChem names 0. ``` formchem-harness/ SKILL.md this router and the doctrine - references/tools.md the 60 MCP tools and their arguments (generated by ./formchem agents sync) + references/tools.md 71 of the 77 tools and their arguments (generated by ./formchem agents sync) EVALS.json evaluation prompts and trigger tests for this pack sub-skills/ session-and-connection/ connecting, the agent token, get_context, approval, Stop, connection errors @@ -57,7 +60,9 @@ formchem-harness/ edit-by-id/ get_atoms and the 14 edit tools: atoms, bonds, charges, stereo, groups, arrows, text visual-qa/ render, get_structure, validate and compute_properties to check your own work names-and-spectra/ draw_from_name, name_structure, predict_nmr, predict_spectrum and the spectrum tools - three-d/ build_3d, conformers, minimise, scans, measure, PDB files, ligands, 3D export and checks + three-d/ build_3d, conformers, minimise, scans, measure, PDB files, ligands, 3D export, xtb and CREST + databases/ the db_ and nb_ tools: import, search, register, export, notebook entries + library-and-biopolymers/ the shared structure library, live structure objects, draw_from_helm handoff/ handoff states and notes, what the person sees, Agent Activity window-commands/ the window's commands through run_command; references/command-catalogue.md reactions/ reaction schemes, the four reaction tools, Set Reaction Roles @@ -87,7 +92,12 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | Make it 3D, its conformers or lowest-energy shape, minimise, a torsion scan, a bond length or angle in 3D, does the 3D keep the stereo | `three-d`, then `visual-qa` | | Open this PDB or mmCIF file, pull out the ligand, save 3D coordinates as SDF, PDB or XYZ | `three-d` | | Show it in 3D, ball and stick, a surface, ESP, a 3D picture or glTF for the person | `three-d`, then `window-commands` | -| Type amounts into the Stoichiometry panel, xtb or quantum energies | Not yet: say so, or ask the person | +| Load an SD or CSV file into a database, search compounds by substructure or similarity, is it already registered, export the hits | `databases` | +| Register this compound, add a batch, update a record's values, record this experiment in the notebook, find my amide couplings | `databases` | +| A GFN2-xTB or GFN-FF energy, optimise with xtb in water, a CREST conformer ensemble | `three-d` | +| Star this, save it as a template, put it into FormDeck or FormTxt as a live structure, list the structure library, the object for a sibling app | `library-and-biopolymers` | +| Draw oxytocin or a peptide from HELM, an RNA strand, a disulfide or head-to-tail cyclic peptide | `library-and-biopolymers`, then `visual-qa` | +| Type amounts into the Stoichiometry panel, DFT energies, sign a notebook entry, add a database field | Not yet for agents: say so, or ask the person | | Change FormChem's own code, add an MCP tool, edit this pack | Not this pack: `formchem-skillset` | ## When something fails @@ -115,6 +125,15 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | "No 3D coordinates yet" or "has no conformer" | The structure was never built, or an edit dropped its conformers | `build_3d`, then retry | | "The structure changed while 3D was being computed" (409) | Someone edited the structure during the build | Retry once; if it repeats, the person is editing: ask them | | `extract_ligand` refuses, or answers "inferred from the geometry" | The object is not a PDB or mmCIF model; or the ligand is outside the template table | Pass the model's `o...` id from `open_3d_structure`; say the bond orders were inferred and show the SMILES | +| "No database is open" or "Several databases are open" | No handle given | `db_list`, then `db_open {path}` or pass `db` | +| `db_add_record` error listing duplicates | The structure is there by the database's stereo and salts rules | Show the matches; call again with the `on_duplicate` the person chooses | +| "open read-only" or 423 on a write | Another FormChem or `./formchem db` holds the file | Report the reason; read and search only | +| `failed` records in a `db_import` job | Bad records were skipped, the rest imported | Pass on each record number and reason | +| xtb or CREST "was not found" from `xtb_optimise` or `crest_conformers` | The person has not installed it, or its path is wrong; FormChem never ships it | Tell the person where to get it (the answer says); do not retry | +| "unpaired electrons" or parity refusal from an xtb tool | Charge and `uhf` cannot match the electron count | Fix `charge` or `uhf` once from the structure, or ask | +| An xtb job "timeout" or "failed" with the last lines | The time limit stopped it, or the program failed | Pass on the last lines; offer a larger `limit` or GFN-FF | +| `draw_from_helm` refused "at character N" | Unknown monomer, mixture, BLOB or a typo | Fix an obvious typo once; else inline SMILES for the monomer, or report | +| "has no item" from a library tool | Wrong id, or the item was deleted | `library_list`, then use an id it returns | | `renderer: "engine"` in a picture | No window answered; the engine drew the structures only | Fine for checking structures; say arrows and text were not drawn, or ask the person to open the window | When a call keeps failing in a way this table does not explain, call the same tool once with the simplest arguments (`get_context`, then `draw_from_smiles {smiles: "C"}`). If that fails too, the problem is the server or the connection, not the plan: report it to the person with the error text. @@ -125,6 +144,8 @@ When a call keeps failing in a way this table does not explain, call the same to - Every structure the agent drew was checked: the write result's SMILES or InChIKey matched what was asked, and anything about how it looks was confirmed with `render`. - Nothing was claimed that a tool did not say; values were quoted from tool answers, names, predicted shifts, energies and 3D measurements with their method and version. - Every 3D geometry used was from a build whose stereo line said every label was kept. +- Database counts, hit list ids and scores were quoted from the answers, no duplicate was registered as new without the person's choice, and no notebook entry was called signed. +- Every xtb or CREST number came with its program label, and library items and live objects were passed on by id and rev exactly as returned. - Every change was one call and one undo step, and none was retried after a refusal or a stop. - The work ends with a `handoff` (`ready` with a note, or `question` with the question). diff --git a/.agents/skills/formchem-harness/references/tools.md b/.agents/skills/formchem-harness/references/tools.md index ddf0065c..23466773 100644 --- a/.agents/skills/formchem-harness/references/tools.md +++ b/.agents/skills/formchem-harness/references/tools.md @@ -1,6 +1,6 @@ # FormChem MCP tools -Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 60 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. +Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py` and the agent modules in its AGENT_MODULES; edit the server, never this file. 77 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked. @@ -67,6 +67,23 @@ Read-only tools never ask the person. An approval-gated tool asks the person in - open_3d_structure - extract_ligand - export_3d +- db_list +- db_create +- db_open +- db_import +- db_search +- db_get_record +- db_add_record +- db_update_record +- db_export +- nb_add_entry +- nb_search +- library_list +- library_add +- live_structure_object +- draw_from_helm +- xtb_optimise +- crest_conformers - Resource | Tool | Kind | @@ -131,6 +148,23 @@ Read-only tools never ask the person. An approval-gated tool asks the person in | `open_3d_structure` | approval-gated | | `extract_ligand` | approval-gated | | `export_3d` | approval-gated when it changes something | +| `db_list` | read-only | +| `db_create` | approval-gated when it changes something | +| `db_open` | approval-gated when it changes something | +| `db_import` | approval-gated when it changes something | +| `db_search` | read-only | +| `db_get_record` | read-only | +| `db_add_record` | approval-gated when it changes something | +| `db_update_record` | approval-gated when it changes something | +| `db_export` | approval-gated when it changes something | +| `nb_add_entry` | approval-gated when it changes something | +| `nb_search` | read-only | +| `library_list` | read-only | +| `library_add` | approval-gated when it changes something | +| `live_structure_object` | read-only | +| `draw_from_helm` | approval-gated when it changes something | +| `xtb_optimise` | approval-gated when it changes something | +| `crest_conformers` | approval-gated when it changes something | ## get_context @@ -791,6 +825,213 @@ Writes the 3D coordinates of a structure with every hydrogen as MOL (the shown c | `conformer` | string | no | Conformer id, or all; default all for sdf, else the shown one | | `output` | string | no | Absolute path of a new file to write; left out, the text comes back | +## db_list + +The structure databases open in FormChem (handle, title, path, record count, read-only or not, fields) and the databases FormChem knows from earlier (path, name, count, whether the file still exists). Open one with db_open, make one with db_create. + +Arguments: none. + +## db_create + +Makes a new FormChem structure database (.fcdb, one SQLite file) and opens it. Without path it goes to the Databases folder of FormChem's data folder. Answers with its handle and info. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `title` | string | yes | | +| `path` | string | no | Absolute path of the new .fcdb file (optional) | + +## db_open + +Opens a FormChem database file (.fcdb) and answers with its handle, title, record count, fields and whether it opened read-only (it does when another FormChem holds it). + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `path` | string | yes | Absolute path of the .fcdb file | + +## db_import + +Imports structures from an SD, RD, SMILES, CSV or TSV (SMILES or InChI column) or .fchem file into a database as a job, and waits up to wait seconds (default 60) for it. Bad records never stop the import: the answer lists each failed record number and reason. dry_run counts what would be added, updated and failed without writing. mode new or append adds every good record; merge updates records that match on key (structure, or a field name) and adds the rest. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `path` | string | yes | Absolute path of the file to import | +| `format` | sdf or rdf or smiles or csv or tsv or fchem | no | | +| `mode` | new or append or merge | no | | +| `key` | string | no | Merge key: structure (default) or a field name | +| `mapping` | object | no | Source column or SD tag to field name, "" to skip, or "+Label" to make a new field; left out, the detected mapping is used | +| `dry_run` | boolean | no | | +| `wait` | number | no | Seconds to wait for the job (0 to 600, default 60); a job still running is reported with its id | + +## db_search + +Searches a database and answers with the hit list (id, name, count, took_ms, methods) and its first rows (uid, number, SMILES, formula, mw, field values, and score for similarity). Give smiles with mode (substructure, the default, similarity with threshold 0 to 1, or exact), or a full query node. within limits the search to an earlier hit list. Every search becomes a hit list the person sees in the window. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `smiles` | string | no | Structure to search with (or a SMARTS with mode substructure and smarts true) | +| `smarts` | boolean | no | Read smiles as SMARTS (substructure only) | +| `mode` | substructure or similarity or exact | no | | +| `threshold` | number | no | Similarity threshold, 0 to 1 (default 0.7) | +| `query` | object | no | A query node of docs/DATABASE.md: a term {kind, ...} with kind exact, substructure, similarity, formula, mass, text, number, date, choice, empty or hitlist, or a group {op: and | or | not, terms: [...]} | +| `within` | integer | no | Hit list id to search within | +| `name` | string | no | Name for the hit list | +| `limit` | integer | no | Rows to return (default 20, at most 100); the hit list holds them all | + +## db_get_record + +One record of a database by uid: number, batch, SMILES, InChIKey, formula, masses, molfile, field values and attachments. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `uid` | string | yes | Record uid (c plus 10 characters) | + +## db_add_record + +Registers a structure in a database with optional field values. When the structure is already there (by the database's duplicate rules) and on_duplicate is not given, nothing is added and the answer lists the duplicates: call again with on_duplicate existing (use the existing record), batch (a new batch of it) or new (register anyway). + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `smiles` | string | no | | +| `molfile` | string | no | | +| `values` | object | no | Field values by field name (see the fields of db_list or db_open), for example {"mp": 121.5, "supplier": "Acme"} | +| `on_duplicate` | ask or existing or batch or new | no | | + +## db_update_record + +Changes a record's structure, field values or both; computed fields follow the new structure. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `uid` | string | yes | Record uid | +| `smiles` | string | no | | +| `molfile` | string | no | | +| `values` | object | no | Field values by field name (see the fields of db_list or db_open), for example {"mp": 121.5, "supplier": "Acme"} | + +## db_export + +Writes records to an SD file (V2000, or V3000 when asked; every scalar field as a data item), a SMILES file or CSV: a hit list, a list of uids or the whole database. Without path the file goes to FormChem's export folder and the answer gives its path. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `format` | sdf or smiles or csv | yes | | +| `path` | string | no | Absolute path of the file to write (optional) | +| `hitlist` | integer | no | | +| `uids` | array of string | no | | +| `fields` | array of string | no | Field names to include (default all) | +| `v3000` | boolean | no | | +| `structure_as` | smiles or inchi | no | Structure column of a CSV | + +## nb_add_entry + +Add a lab notebook entry to an open FormChem database. Give a title and, as known, the template (blank, reaction, analysis, purification), the experiment date (YYYY-MM-DD), author, procedure and observations in the notebook's plain markup (paragraphs separated by blank lines, '- ' bullets, **bold**, *italic*), tags, products, and the scheme as reaction SMILES or RXN text (reaction) or an open drawing id (doc). Answers the new entry's number and uid, its content hash and the stoichiometry computed from the scheme. The entry is open (not signed): only a person signs. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | yes | Database handle (g plus 8 characters) from db_list, db_create or db_open | +| `title` | string | yes | | +| `template` | blank or reaction or analysis or purification | no | | +| `date` | string | no | Experiment date YYYY-MM-DD (default today) | +| `author` | string | no | | +| `procedure` | string | no | Replaces the template's headings when given | +| `observations` | string | no | | +| `tags` | array of string | no | | +| `products` | array of object | no | | +| `reaction` | string | no | Reaction SMILES (A.B>>C) or RXN text for the scheme | +| `doc` | string | no | Open drawing id whose first page becomes the scheme, instead of reaction | + +## nb_search + +Search the lab notebook entries of an open FormChem database by text (title, procedure, observations, tags, sample ids; every word must appear) and by substructure (SMILES or SMARTS matched by RDKit against every structure in each entry's scheme). Give either or both; with neither, lists the newest entries. Answers the total and up to 20 rows (number, uid, title, date, status, tags), newest first. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | yes | Database handle (g plus 8 characters) from db_list, db_create or db_open | +| `query` | string | no | Words to find | +| `substructure` | string | no | SMILES or SMARTS | +| `limit` | integer | no | Rows to return (default 20) | + +## library_list + +The shared structure library that every Form app reads (FORMCHEM_DATA_DIR/Library): items with id, name, kinds (favourite, recent, template, live), SMILES, InChIKey, formula, average mass, rev and file paths. Filter by kind. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `kind` | favourite or recent or template or live | no | Only items of this kind | + +## library_add + +Add a structure to the shared structure library as a favourite, template, recent or live item. Give a drawing (doc, optionally object ids) or a SMILES. Pictures are drawn by the engine with the FormChem drawing embedded. A structure already in the library gets the new kind instead of a copy (live items are always new). + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; left out with smiles, or when one drawing is open | +| `ids` | array of string | no | Object ids on the drawing's page to keep; default the whole first page | +| `smiles` | string | no | A SMILES to add instead of a drawing | +| `name` | string | no | | +| `kinds` | array of string | no | Default ["favourite"] | + +## live_structure_object + +The live structure object for a library item, the JSON a sibling Form app stores in its document (format formai-structure): id, rev, name, SMILES, InChIKey, the SVG picture with the FormChem drawing inside, the molfile and the size in points. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `id` | string | yes | Library item id (s and 10 letters or digits) | + +## draw_from_helm + +Draws a peptide, nucleic acid or linker written in HELM version 2 notation in a drawing, as atoms, with FormChem's scored 2D layout, placed in free space as one undo step. Reads simple polymers such as PEPTIDE1{A.G.C}, RNA1{R(A)P.R(U)} and CHEM1{[[*:1]CCO[*:2]]}, connections such as PEPTIDE1,PEPTIDE1,1:R3-6:R3 (disulfides, cyclisation) and empty group and annotation sections, against FormChem's own monomer data: the 20 amino acids and their D forms ([dA] and so on), [Aib], [Nle], [Orn], [Sar], [Hyp], [pE], the caps [ac] and [am], the sugars R and [dR], phosphate P and the bases A, C, G, U and T. With no drawing open it makes one. Returns the new ids, SMILES, InChIKey, formula, average and monoisotopic mass with their method and version, and a picture; text it cannot read is refused with the character where reading stopped. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `helm` | string | yes | HELM text, such as PEPTIDE1{C.Y.I.Q.N.C.P.L.G.[am]}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$V2.0 | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `x` | number | no | Left edge in points; left out: free space | +| `y` | number | no | Top edge in points; left out: free space | +| `name` | string | no | Name given to the new structure; left out, the HELM text (shortened) is used | + +## xtb_optimise + +Optimises the shown conformer of a structure with the xtb program (GFN2-xTB or GFN-FF, optional ALPB implicit solvent), or with single_point computes the energy without moving atoms, then stores the result as the structure's conformers as one undo step. A structure without 3D coordinates is built first (ETKDGv3+MMFF94). Answers with the total energy in hartree and kcal/mol, the HOMO-LUMO gap, whether the optimisation converged, and the program, version, method and solvent. Waits until xtb finishes or the time limit stops it. xtb and CREST are LGPL programs FormChem does not include or download: they run only when the person has installed them (on PATH or at the path set in Preferences > 3D); otherwise the tool says where to get them. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | Fragment id (or a 3D object bound to one); may be left out when the drawing has one structure | +| `method` | gfn2 or gfnff | no | gfn2 (GFN2-xTB, default) or gfnff (GFN-FF force field) | +| `charge` | integer | no | Total charge; default the sum of the drawn formal charges | +| `uhf` | integer | no | Unpaired electrons; default the drawn radicals | +| `solvent` | none or acetone or acetonitrile or aniline or benzaldehyde or benzene or ch2cl2 or chcl3 or cs2 or dioxane or dmf or dmso or ether or ethylacetate or furane or hexandecane or hexane or methanol or nitromethane or octanol or woctanol or phenol or toluene or thf or water | no | Implicit solvent (ALPB); default none, the gas phase | +| `single_point` | boolean | no | Energy only, no optimisation (default false) | +| `scope` | shown or all | no | The shown conformer (default for optimisation) or every stored conformer (default for single_point) | +| `level` | crude or sloppy or loose or lax or normal or tight or vtight or extreme | no | Optimisation convergence level (default normal) | +| `conformer` | string | no | Conformer id (c...) to start from; default the shown one | +| `threads` | integer | no | Threads; default the Preferences setting | +| `limit` | number | no | Time limit in seconds (default 600 for xtb, 3600 for CREST, at most 604800) | + +## crest_conformers + +Searches conformers of a structure with the CREST program (metadynamics with GFN2-xTB or GFN-FF, optional ALPB solvent) and replaces the structure's conformers with the ensemble within ewin kcal/mol, at most keep, as one undo step; the lowest becomes the shown one. Answers with relative energies and Boltzmann populations at 298.15 K, and the program, version, method and solvent. CREST can take minutes to hours; the tool waits until it finishes or the time limit stops it. xtb and CREST are LGPL programs FormChem does not include or download: they run only when the person has installed them (on PATH or at the path set in Preferences > 3D); otherwise the tool says where to get them. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | Fragment id (or a 3D object bound to one); may be left out when the drawing has one structure | +| `method` | gfn2 or gfnff | no | gfn2 (GFN2-xTB, default) or gfnff (GFN-FF force field) | +| `charge` | integer | no | Total charge; default the sum of the drawn formal charges | +| `uhf` | integer | no | Unpaired electrons; default the drawn radicals | +| `solvent` | none or acetone or acetonitrile or aniline or benzaldehyde or benzene or ch2cl2 or chcl3 or cs2 or dioxane or dmf or dmso or ether or ethylacetate or furane or hexandecane or hexane or methanol or nitromethane or octanol or woctanol or phenol or toluene or thf or water | no | Implicit solvent (ALPB); default none, the gas phase | +| `ewin` | number | no | Energy window in kcal/mol (default 6) | +| `keep` | integer | no | Most conformers kept, 1 to 200 (default 20) | +| `threads` | integer | no | Threads; default the Preferences setting | +| `limit` | number | no | Time limit in seconds (default 600 for xtb, 3600 for CREST, at most 604800) | + ## Resource `formchem://guide` (text/markdown): what exists in this version, the tools, asking the person and errors. diff --git a/.agents/skills/formchem-harness/sub-skills/databases/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/databases/SUB-SKILL.md new file mode 100644 index 00000000..95a0093d --- /dev/null +++ b/.agents/skills/formchem-harness/sub-skills/databases/SUB-SKILL.md @@ -0,0 +1,71 @@ +--- +name: databases +description: "Uses FormChem's 0.11.0 structure database and lab notebook tools: db_list, db_create, db_open (.fcdb files), db_import (SD, RD, SMILES, CSV, TSV, .fchem as a job with a failed-record report and dry runs), db_search (substructure, similarity with Tanimoto scores, exact match, formula ranges or a full query node, as a hit list the person sees), db_get_record, db_add_record (duplicate rules and on_duplicate), db_update_record, db_export (SD, SMILES, CSV), nb_add_entry (an unsigned entry with scheme and stoichiometry) and nb_search. Use when the person asks an agent to register compounds, load an SD file into a database, search a compound collection, find analogues or duplicates, export hits, or record an experiment in FormChem's notebook." +--- + +# Databases + +## Purpose + +Register, search, import and export compounds in FormChem structure databases, and keep lab notebook entries in them, so the person sees every hit list and entry in their window. Hands back the database handle, the counts and hit list ids as returned, the record and entry uids, and every refusal or failed record with its reason. + +## Preconditions + +`get_context` has been called (`session-and-connection`). `db_list`, `db_search`, `db_get_record` and `nb_search` never ask. `db_create`, `db_open`, `db_add_record`, `db_update_record` and `nb_add_entry` ask the person the first time; `db_import` unless `dry_run`; `db_export` only with a `path` outside the temporary folder. These tools are not in `references/tools.md` (its generator reads only the drawing tools); their arguments are here and in `docs/AGENTS.md`. + +## How a database is held + +A database is one `.fcdb` file. Opening it gives a handle `db` (`g` plus 8 characters); with exactly one database open the `db_` tools may leave `db` out, the `nb_` tools always need it. Records have a `uid` (`c` plus 10) that never changes and a registration `number` with a `batch`; entries have a `uid` (`n` plus 10) and a `number`. A database held by another FormChem or by `./formchem db` opens read-only: reads work, every write is refused with the reason. Every write is logged as `agent:[your name]` and shows in Agent Activity. + +## Workflow 1: find or make the database + +1. **Call `db_list`.** It gives the open databases (handle, title, count, fields, read-only) and the known ones (path, whether the file exists). +2. **Open or create:** `db_open {path}` with an absolute `.fcdb` path, or `db_create {title, path?}` (default the Databases folder of the data folder). Read the duplicate rules (`stereo` match or ignore, `salts` strip or keep) and the fields from the answer; they decide what counts as a duplicate and which `values` keys exist. + +## Workflow 2: import + +1. **Dry run first:** `db_import {path, dry_run: true}` counts what would be added, updated and failed without writing and without asking. +2. **Import:** the same call without `dry_run`. `mode` is `new` (default) or `append`; `merge` with `key` (`structure`, or a field name) updates matching records and adds the rest. `mapping` left out uses the detected one (SD tags and CSV columns to fields by name, new fields for the rest). +3. **Read the report.** `added`, `updated`, `failed`, and each failed record's number in the file and reason (the first 10 in the text). A bad record never stops an import; pass the failures on. A job still running after `wait` seconds (default 60) is reported with its id; the person sees its progress. + +## Workflow 3: search + +| Goal | Call | +| --- | --- | +| Contains a ring or group | `db_search {smiles, mode: "substructure"}`, or `smiles` as SMARTS with `smarts: true` | +| Analogues | `db_search {smiles, mode: "similarity", threshold: 0.7}`: Tanimoto on Morgan bits (radius 2, 2048); every row has a `score` | +| Is it already registered | `db_search {smiles, mode: "exact"}` (the database's stereo and salts rules) | +| Formula, mass, fields, combinations | `db_search {query}` with a node of `docs/DATABASE.md`: `{"op": "and", "terms": [{"kind": "formula", "formula": "C6-8N1"}, {"kind": "number", "field": "mw", "cmp": "<=", "value": 300}]}` | +| Narrow earlier hits | add `within: [hit list id]` | + +The answer gives the hit list `id`, `name`, `count`, `took_ms`, the methods with the RDKit version, and the first `limit` rows (default 20, at most 100). The hit list appears in the person's window; `db_export {hitlist}` writes all of it. Raising a similarity threshold never adds hits; quote scores as given. `db_get_record {uid}` gives one record with its molfile. + +## Workflow 4: register and update + +1. **Call `db_add_record {smiles or molfile, values?}`.** When the structure is already there by the rules, nothing is added and the error lists the duplicates (`structuredContent.duplicates`). +2. **Choose, or ask the person:** call again with `on_duplicate: "existing"` (use that record), `"batch"` (a new batch, same number) or `"new"` (a new number). Never pick `new` just to make the call succeed. +3. **Update:** `db_update_record {uid, smiles?, values?}`; computed fields follow the structure. `values` keys are field names from `db_open`, not labels. + +## Workflow 5: the notebook + +- **`nb_add_entry {db, title, template?, date?, author?, procedure?, observations?, tags?, products?, reaction? or doc?}`**: `reaction` is reaction SMILES (`A.B>>C`) or RXN; `doc` takes the first page of an open drawing as the scheme. Text uses the notebook markup (blank-line paragraphs, `- ` bullets, `**bold**`, `*italic*`). Products may link a record by `compound` uid with `sample`, `mass_g`, `yield_pct`, `purity_pct`; an unknown uid refuses the whole call and nothing is written. The answer gives the entry number and uid, its hash and the stoichiometry with its method. +- **`nb_search {db, query?, substructure?}`**: every word must appear in title, procedure, observations, tags or sample ids; `substructure` (SMILES or SMARTS) matches the structures in each scheme. Newest first. +- Entries from agents stay open. Only the person signs; never say an entry is signed or approved. + +## Rules + +- **Counts and scores are quoted, not estimated.** Hit counts, times, scores and import counts come from the answers, with the method where given. +- **The person owns duplicates and signatures.** Ask before registering a duplicate as new; never claim an entry is signed. +- **Read-only is an answer.** A refused write on a read-only database is reported with its reason, not retried. +- **Dry run before a large import or merge,** and report the failed records. + +## Gate + +- [ ] The database handle and its rules were read before any write. +- [ ] Every import reported added, updated and failed, with the failed records' numbers and reasons. +- [ ] Every search result quoted the hit list id, the count and, for similarity, the scores. +- [ ] No duplicate was registered as new without the person's choice, and no entry was described as signed. + +## Hands back + +The database handle and path; hit list ids with counts; record and entry uids and numbers; import and export counts and paths; every refusal and failed record as returned. diff --git a/.agents/skills/formchem-harness/sub-skills/library-and-biopolymers/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/library-and-biopolymers/SUB-SKILL.md new file mode 100644 index 00000000..d65e3323 --- /dev/null +++ b/.agents/skills/formchem-harness/sub-skills/library-and-biopolymers/SUB-SKILL.md @@ -0,0 +1,56 @@ +--- +name: library-and-biopolymers +description: "Uses FormChem's 0.12.0 shared structure library and HELM tools: library_list (favourites, recent, templates and live items every Form app reads), library_add (a drawing or SMILES as a favourite, template, recent or live item with pictures that keep the drawing inside), live_structure_object (the formai-structure JSON a sibling app stores) and draw_from_helm (peptides, nucleic acids and linkers from HELM 2 as atoms, one undo step, with formula and masses). Use when the person asks an agent to star or save a structure for the other Form apps, put a structure into FormDeck, FormTxt or form.md as a live structure, list the structure library, hand a sibling app its object, or draw oxytocin, a cyclic peptide, a disulfide-bridged peptide or an RNA or DNA strand from HELM in FormChem." +--- + +# Library and biopolymers + +## Purpose + +Keep structures in the shared structure library that every Form app reads, hand sibling apps the live structure object, and draw biopolymers written in HELM, so the person sees each structure in their window and in the library. Hands back library item ids with their kinds and revisions, the object's id and rev, and for HELM the new fragment ids with formula, masses and their method. + +## Preconditions + +`get_context` has been called (`session-and-connection`). `library_list` and `live_structure_object` never ask; `library_add` and `draw_from_helm` ask the person the first time. These tools are not in the pack root's `references/tools.md` at 0.12.0 (its generator cannot read their modules yet); their arguments are here and in `docs/AGENTS.md`. + +## How the library is held + +The library is plain files in the data folder: `Library/library.json` and, per item, an SVG and a 512 pixel PNG (both with the FormChem drawing inside) and a molfile. Items have an `id` (`s` plus 10 lower-case letters or digits) that is never reused, `kinds` (any of `favourite`, `recent`, `template`, `live`), a `rev` that rises on every change, and SMILES, InChIKey, formula and average mass with the method that computed them. An item with no kinds left is deleted. Sibling apps read the folder without FormChem running; only FormChem writes it. The contract is `docs/LIVE_STRUCTURES.md` in the FormChem repository. + +## Workflow 1: add to the library + +1. **Call `library_add`** with `smiles` (no drawing needed), or with `doc` and optionally `ids` (objects of the drawing's page; default the whole first page). `doc` may be left out only when exactly one drawing is open. `kinds` defaults to `["favourite"]`; `name` names the item. +2. **Read the answer.** It names the item id, kinds, formula, average mass with its method, and rev. A non-live structure already in the library gains the kind instead of becoming a second item; a `live` add is always a new item, so two sibling documents never share an id. +3. **Pictures** come from the engine (RDKit) with the drawing embedded when an agent adds the item; items the person adds in the window carry the window's own pictures. Either way the drawing inside is complete. + +## Workflow 2: list and hand out + +- `library_list {kind?}` lists items (the text shows the first 40) with the folder path. +- `live_structure_object {id}` returns the JSON a sibling app keeps in its document: `format` `formai-structure`, `format_version` 1, `id`, `rev`, `app`, `name`, `kind`, `smiles`, `inchikey`, `svg` (the picture, drawing inside), `molfile`, `width` and `height` in points. Give it to a sibling app as returned; never edit the SVG, because the drawing inside it is what makes the structure editable again. +- Opening an item for editing is the person's, a sibling's or `./formchem edit-live ID`'s act; from an agent, `run_command {id: "open-live-structure", params: {id, from}}` asks the window to do it. Saving that drawing (the person's Save) raises the item's rev. + +## Workflow 3: draw from HELM + +1. **Call `draw_from_helm {helm, doc?, x?, y?, name?}`** with HELM version 2 text: `PEPTIDE1{G.G}$$$$`, `RNA1{R(A)P.R(U)}$$$$`, or with connections `PEPTIDE1{C.Y.I.Q.N.C.P.L.G.[am]}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$V2.0` (oxytocin). With no drawing open it makes one. One undo step ("Draw from HELM"). +2. **Know the monomers.** FormChem's own 55: the 20 amino acids (one letter), their D forms `[dA]` and so on (no `[dG]`), `[Aib]`, `[Nle]`, `[Orn]`, `[Sar]`, `[Hyp]`, `[pE]`, caps `[ac]` (R2 only) and `[am]` (R1 only); RNA sugars `R` and `[dR]`, phosphate `P`, bases `A`, `C`, `G`, `U`, `T`. R3 sits on C, K, D, E and Orn side chains, for disulfide and lactam bridges. Anything else goes in as inline SMILES with numbered attachment points (`[[*:1]CCO[*:2]]`). +3. **Read the answer.** New ids, SMILES, InChIKey, formula, average and monoisotopic mass with the reader, monomer data version and RDKit version. Check it like any structure (`visual-qa`). +4. **A refusal names the character** where reading stopped (counted from 1) and why: "X is not a PEPTIDE monomer FormChem knows", mixtures in parentheses, BLOBs, repeat ranges, hydrogen-bond pairs, `?` attachment points. Fix an obvious typo once; otherwise report it. + +To turn a drawn peptide or nucleic acid back into HELM, use `run_command {id: "copy-helm"}` with it selected: FormChem copies HELM only when it reads back to the same InChIKey, and otherwise says which piece it could not match. There is no agent tool that returns HELM text. + +## Rules + +- **The drawing inside is the structure.** Never pass a sibling a picture without its embedded drawing, or an object with a hand-edited SVG. +- **Revisions only go up.** A lower or equal rev never overwrites the library; do not try to roll an item back by sending an old object. +- **Monomers are FormChem's.** Do not claim a monomer FormChem does not list; use inline SMILES and say so. +- **Methods travel with the numbers.** Quote masses with the method the answer names. + +## Gate + +- [ ] Every library item named by id with its kinds and rev as returned. +- [ ] Every HELM drawing checked with its InChIKey or formula from the answer, and every refusal reported with its character and reason. +- [ ] No object or picture was altered on the way to a sibling app. + +## Hands back + +Library item ids, kinds and revs; live structure objects as returned; HELM fragment ids, formula, masses and methods; refusals with their reasons. diff --git a/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md index 9c8d91bd..0836ac92 100644 --- a/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -52,5 +52,5 @@ Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tab ## Gate - [ ] `get_context` was the first call. -- [ ] The plan uses only the 60 tools in the pack root's `references/tools.md` and the commands and extensions they report. +- [ ] The plan uses only the 77 tools (the 71 in the pack root's `references/tools.md`, the library and HELM tools in `library-and-biopolymers` and the xtb tools in `three-d`) and the commands and extensions they report. - [ ] No change was attempted after a refusal or a stop, and the agent token never appeared in a reply or a note. diff --git a/.agents/skills/formchem-harness/sub-skills/three-d/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/three-d/SUB-SKILL.md index 01f82aa8..cb82ea98 100644 --- a/.agents/skills/formchem-harness/sub-skills/three-d/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/three-d/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: three-d -description: "Uses FormChem's 0.10.0 3D tools: build_3d (a conformer from the 2D drawing with ETKDGv3 and MMFF94, MMFF94s or UFF, with the stereo check), conformers_3d (an ensemble in an energy window with populations), minimise_3d, scan_dihedral (a relaxed scan with its barrier), measure_3d (distance, angle, dihedral), open_3d_structure (PDB, mmCIF, SDF, MOL), extract_ligand and export_3d (MOL, SDF, PDB, XYZ), plus the 3D window commands for styles, surfaces and PNG or glTF. Use when the person asks an agent to make a structure 3D, find its conformers or lowest-energy shape, minimise it, scan a torsion, measure a bond length or angle, open a PDB or mmCIF file, pull a ligand out of a protein, or save 3D coordinates in FormChem, and to check that a 3D geometry kept the drawn stereo." +description: "Uses FormChem's 0.10.0 3D tools: build_3d (a conformer from the 2D drawing with ETKDGv3 and MMFF94, MMFF94s or UFF, with the stereo check), conformers_3d (an ensemble in an energy window with populations), minimise_3d, scan_dihedral (a relaxed scan with its barrier), measure_3d (distance, angle, dihedral), open_3d_structure (PDB, mmCIF, SDF, MOL), extract_ligand and export_3d (MOL, SDF, PDB, XYZ), the 0.12.0 xtb_optimise and crest_conformers (xtb and CREST when the person installed them), plus the 3D window commands for styles, surfaces and PNG or glTF. Use when the person asks an agent to make a structure 3D, find its conformers or lowest-energy shape, minimise it, scan a torsion, measure a bond length or angle, open a PDB or mmCIF file, pull a ligand out of a protein, get a GFN2-xTB energy or a CREST ensemble, or save 3D coordinates in FormChem, and to check that a 3D geometry kept the drawn stereo." --- # Three-d @@ -11,11 +11,11 @@ Turn drawn structures into 3D geometry FormChem stores in the drawing, work on t ## Preconditions -`get_context` has been called (`session-and-connection`), and the structure is drawn (`drawing`, `edit-by-id`, `names-and-spectra`). `build_3d`, `conformers_3d`, `minimise_3d`, `open_3d_structure` and `extract_ligand` ask the person the first time; `scan_dihedral` only with `store: true`; `export_3d` only when it writes a file outside the temporary folder; `measure_3d` never asks. +`get_context` has been called (`session-and-connection`), and the structure is drawn (`drawing`, `edit-by-id`, `names-and-spectra`). `build_3d`, `conformers_3d`, `minimise_3d`, `open_3d_structure` and `extract_ligand` ask the person the first time; `scan_dihedral` only with `store: true`; `export_3d` only when it writes a file outside the temporary folder; `measure_3d` never asks; `xtb_optimise` and `crest_conformers` ask the first time. ## How 3D is held -A structure's 3D coordinates are its `conformers`, each with an id (`c...`), an energy in kcal/mol, a `method` (`ETKDG` when only embedded, `MMFF94`, `MMFF94s`, `UFF`, or `file` when read from a file) and `converged`; `conformer` names the shown one. Atoms are the fragment atom ids from `get_atoms`; a hydrogen is `a1:h0` (the first hydrogen of `a1`), an atom inside an expanded abbreviation `a5:x0`. Any later edit to the structure's atoms or bonds (element, charge, bond order, wedge, adding or deleting) removes its conformers in the same undo step; moves and colours keep them. So: finish editing, then build. +A structure's 3D coordinates are its `conformers`, each with an id (`c...`), an energy in kcal/mol, a `method` (`ETKDG` when only embedded, `MMFF94`, `MMFF94s`, `UFF`, `xtb` for an xtb or CREST result, or `file` when read from a file) and `converged`; an xtb conformer also carries `program` (name, version, method, solvent, charge, uhf, energy in hartree, gap); `conformer` names the shown one. Atoms are the fragment atom ids from `get_atoms`; a hydrogen is `a1:h0` (the first hydrogen of `a1`), an atom inside an expanded abbreviation `a5:x0`. Any later edit to the structure's atoms or bonds (element, charge, bond order, wedge, adding or deleting) removes its conformers in the same undo step; moves and colours keep them. So: finish editing, then build. ## Workflow 1: build and check @@ -35,6 +35,17 @@ A structure's 3D coordinates are its `conformers`, each with an id (`c...`), an MMFF94 energies compare conformers of one structure under one force field. They are not heats of formation and do not compare across structures, compositions or force fields. Say that when a person compares them. +## Workflow 3a: xtb and CREST (0.12.0) + +xtb and CREST are LGPL-3.0 programs FormChem never ships or downloads. They run only when the person has installed them (PATH, a conda environment, or the path in Preferences > 3D > Tight-Binding Programs). + +1. **Call `xtb_optimise {object, method?, solvent?, charge?, uhf?, single_point?, level?, limit?}`**. `method` is `gfn2` (GFN2-xTB, default) or `gfnff`; `solvent` is `none` or an ALPB key (`water`, `methanol`, `acetonitrile`, `dmso`, `ch2cl2`, `chcl3`, `thf`, `toluene` and the rest of xtb's 24). Charge defaults to the drawn formal charges, `uhf` to the drawn radicals; a pair that cannot match the electron count is refused before anything runs, with the reason. A structure with no conformer is built first (ETKDGv3+MMFF94). The tool waits (default limit 600 s) and stores the result as the structure's only conformer, one undo step. +2. **Call `crest_conformers {object, method?, solvent?, ewin?, keep?, limit?}`** for an ensemble: window 6 kcal/mol, at most 20 kept by default, limit 3600 s. CREST can take minutes to hours on anything flexible; set `limit` to what the person will wait for. Conformers that lost the drawn stereo are dropped and the answer counts them. +3. **Quote the label.** Every answer names the program, version, method and solvent ("xtb 6.7.1, GFN2-xTB, ALPB (Water)"), the total energy in hartree and kcal/mol, the HOMO-LUMO gap and whether the optimisation converged. Pass all of it on. +4. **Not installed** is an answer, not a failure to retry: the tool says where to get the program (https://github.com/grimme-lab/xtb, https://github.com/crest-lab/crest). Tell the person; never suggest FormChem can download it. Fall back to `conformers_3d` and `minimise_3d` only if the person agrees, and say the energies are then MMFF94. + +Tight-binding total energies are in hartree for one structure, charge and solvent model; compare them only between conformers or structures computed with the same method and solvent. An optimisation replaces the MMFF94 conformers, so earlier force-field numbers no longer belong to the drawing. + ## Workflow 3: protein files and ligands 1. **Call `open_3d_structure {path}`** with an absolute `.pdb`, `.ent`, `.cif` or `.mmcif` path. One undo step: a 3D object (`o...`) over the file kept byte for byte, cartoon for a protein, ligands ball and stick, waters hidden, the primary ligand focused. Read the chains, ligand keys (`A:ATP:301`) and the reader's warnings and pass them on. An `.sdf` or `.mol` opens as structures whose conformers are the file's coordinates (method `file`). @@ -52,13 +63,14 @@ MMFF94 energies compare conformers of one structure under one force field. They - **Method and version travel with the number.** Every energy, barrier, population and measurement names its force field and engine version as FormChem gave them. - **Stereo before geometry.** A build is usable only when its stereo line says every label was kept. - **Build after editing.** An edit to atoms or bonds drops the conformers; rebuild rather than reuse numbers from before the edit. -- **No quantum claims.** FormChem has no xtb, CREST or other quantum method; do not describe a force-field energy as anything more. +- **No quantum claims beyond xtb.** A force-field energy is only that. xtb and CREST are semiempirical tight binding, run only on the person's own installation; FormChem has no DFT or other quantum method. ## Gate - [ ] Every build reported its stereo line, and a lost label stopped the work with the reason. - [ ] Every energy, barrier and measurement was quoted from a tool answer with its method and engine version. - [ ] Inferred ligand bond orders and unspecified stereocentres were passed on to the person. +- [ ] Every xtb or CREST number carried its program label, and a missing program was reported with where to get it, not retried. - [ ] Each changing call was one undo step, and the handoff says what the person will see in the 3D View or on the page. ## Hands back diff --git a/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md index f18eede1..de8c9a18 100644 --- a/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md @@ -30,6 +30,8 @@ Most canvas commands act on the canvas selection. The agent sets the selection t | Draw from a name | Use `draw_from_name` (`names-and-spectra`). `run_command {id: "insert-name", params: {name}}` inserts it the window's way (centred like a template, selected); without `name` it opens Structure from Name for the person. `copy-name` puts the selection's name on the person's clipboard | | Spectrum commands: edit, pick peaks, integrate, link a peak, y axis, export, predict, refresh | Prefer the spectrum and NMR tools (`names-and-spectra`). The commands remain for what they add: `link-peak-to-atoms {object, peak, fragment, atoms}` (no tool links), `open-spectrum {path}` (inserts a file into the open drawing), `spectrum-y-mode {object, mode}`, `edit-spectrum` (opens the Spectrum editor for the person), `nmr-refresh` (with a predicted spectrum selected) | | Show it in 3D, change the 3D style or surface, put a 3D view on the page, save a 3D picture | Build and measure with the 3D tools (`three-d`). Then `view-3d` (opens the 3D View on the selection), `style-wire`, `style-stick`, `style-ballstick`, `style-spacefill`, `style-cartoon`, `surface-none`, `surface-vdw`, `surface-sas`, `surface-ses`, `surface-esp` (on only while the 3D View is open), `insert-3d-view` (a 3D object beside the selected structure), `export-3d-png {transparent}` and `export-gltf` (saved for the person). `export-3d-file {format, all}` saves MOL, SDF, PDB or XYZ for the person; `export_3d` gives the agent the text | +| Show the database, a view of it, its dialogs, or the notebook to the person | Work with the database tools (`databases`). Then `show-databases`, `db-view-table`, `db-view-gallery`, `db-view-form`, `db-view-plot`, `db-view-notebook`, `db-search {text}`, `db-import {path}`, `db-export`, `database-fields`, `database-settings` (the person's dialogs); `nb-sign-entry` asks the person to sign and is never run in their place | +| Copy a live structure for another Form app, open a library item for editing, HELM text of a drawn peptide, show the Structure Library or the Structure Summary, change the element colours | Library and HELM tools first (`library-and-biopolymers`). Then `copy-live-structure`, `open-live-structure {id, from}`, `copy-helm`, `structure-library {tab}`, `a11y-describe`, `element-palette-high-contrast` and its two siblings | | Stack or group objects | `bring-front`, `bring-forward`, `send-backward`, `send-back`, `group`, `ungroup` on the selection; off with "Select something on the canvas first" when nothing is selected | | Anything about the reaction in the drawing | Load `reactions` | | Undo the last change | `run_command {id: "undo"}`: one transaction, whoever made it | diff --git a/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md b/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md index 929cca42..2ef1d85c 100644 --- a/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md +++ b/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md @@ -1,6 +1,6 @@ # Commands that touch a drawing -The window's command registry, as far as it concerns drawings, for FormChem 0.10.0 (the commands of 0.7.0, plus `agent-activity` from 0.8.0, which opens Window > Agent Activity for the person, plus the name, spectrum and NMR commands of 0.9.0, plus the 3D commands of 0.10.0). From 0.8.0 the agent's own tools draw, edit, read back, render and convert; this page covers what the window's commands add. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. +The window's command registry, as far as it concerns drawings, for FormChem 0.12.0 (the commands of 0.7.0, plus `agent-activity` from 0.8.0, which opens Window > Agent Activity for the person, plus the name, spectrum and NMR commands of 0.9.0, the 3D commands of 0.10.0, the database and notebook commands of 0.11.0, and the library, live structure, HELM, xtb and accessibility commands of 0.12.0). From 0.8.0 the agent's own tools draw, edit, read back, render and convert; this page covers what the window's commands add. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. ## Contents @@ -14,6 +14,8 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.10 - Standardise and size on the sheet - Names, spectra and NMR prediction - 3D +- Databases and the notebook +- Library, live structures, HELM, xtb and accessibility - The canvas, the view and the grid - Registered but off until a later version - What no command does yet @@ -170,6 +172,45 @@ From 0.10.0, group `3D`. Building, conformers, minimising, scans, measuring, ope | `export-gltf` | | saves the 3D View as binary glTF (`.glb`) for the person (while the 3D View is open) | | `export-3d-file` | `format` (`mol`, `sdf`, `pdb`, `xyz`), `all` (every conformer) | saves the selected structure's 3D coordinates for the person, or a PDB or mmCIF model's original file; without `format` it opens the dialog. For text the agent reads, `export_3d` | +## Databases and the notebook + +From 0.11.0, groups `Database` and `Notebook`. Creating, opening, importing, searching, registering, exporting and notebook entries also have MCP tools (`databases`); prefer them, because they answer with the counts, ids and reasons. The commands show the person the database workspace and its dialogs. The search, import, export, plot, query and hit list commands are off until a database is open, and import and save query are off on a read-only one. + +| Command | Params | What it does | +| --- | --- | --- | +| `show-databases` | | shows or hides the database workspace (Shift+Mod+D) | +| `new-database`, `open-database`, `close-database` | | the New and Open Database dialogs for the person; close releases the database's lock. For an agent, `db_create` and `db_open` | +| `add-to-database` | | registers the selected structure, or the page as one record, in the current database; a duplicate opens the person's choice dialog. For an agent, `db_add_record` | +| `database-settings`, `database-fields` | | the person's dialogs for the title and duplicate rules, and for fields (no MCP tool changes fields) | +| `db-view-table`, `db-view-gallery`, `db-view-form`, `db-view-plot`, `db-view-notebook` | | shows the workspace in that view | +| `db-search` | `text` (optional) | puts the cursor in the workspace search box; with `text`, runs it as plain text (text fields, uid, formula, SMILES) and shows the hit list. Structure and query searches: `db_search` | +| `db-advanced-search`, `db-save-query`, `db-combine-hitlists` | | the query builder, Save Query and Combine Hit Lists dialogs for the person | +| `db-import` | `path` (absolute, optional) | opens the Import dialog, previewing `path` at once; the person maps and imports. For an agent, `db_import` | +| `db-export` | | opens the Export dialog for the person; for an agent, `db_export` | +| `nb-new-entry` | | the New Notebook Entry dialog; for an agent, `nb_add_entry` | +| `nb-sign-entry` | | asks the person to sign the shown entry with their name; never run it to sign on the person's behalf | +| `nb-export-entry` | `format` (`html` default, or `json`) | saves the shown entry for the person | +| `nb-save-scheme` | | saves the drawing opened with Edit Scheme back into its entry (on only while that drawing is active) | + +## Library, live structures, HELM, xtb and accessibility + +From 0.12.0. Adding to the library, the live structure object, drawing from HELM and the xtb and CREST runs also have MCP tools (`library-and-biopolymers`, `three-d`); prefer them, because they answer with ids, formulas and energies. The commands add the clipboard, the Structure Library dialog, opening a live drawing, HELM text out, and the person's accessibility views. + +| Command | Params | What it does | +| --- | --- | --- | +| `copy-live-structure` | | copies the selection (or the page) as a live structure: the picture with the drawing inside, the object, SMILES and molfile on the clipboard, and adds it to the library as live and recent. For an agent, `library_add {kinds: ["live"]}` and `live_structure_object` | +| `star-structure` | | adds the selection (or the drawing) to the library as a favourite. For an agent, `library_add` | +| `library-save-template` | `name` (asked when left out) | saves the selection (or the drawing) to the library as a template | +| `structure-library` | `tab` (`favourite`, `recent`, `template`, `live`) | opens the Structure Library dialog for the person | +| `open-live-structure` | `id` (required), `from` | opens a library item as a live drawing (the title shows the sibling); the person's Save then raises its rev. Answers "Opened live structure [id] rev [n] as drawing [doc]" | +| `insert-helm` | `helm` (optional) | with `helm`, inserts it as atoms, one undo step; without, opens the Biopolymer from HELM dialog. For an agent, `draw_from_helm` answers with the numbers | +| `copy-helm` | | copies the selected peptide or nucleic acid as HELM, only when it reads back to the same structure; with params from an agent it throws the reason instead of a toast | +| `xtb-optimise` | `method`, `single_point`, `charge`, `uhf`, `solvent`, `level`, `limit` | with params, runs xtb on the selected structure without the dialog and waits; without, the dialog. For an agent, `xtb_optimise` | +| `crest-conformers` | `method`, `charge`, `uhf`, `solvent`, `ewin`, `keep`, `limit` | the same for CREST. For an agent, `crest_conformers` | +| `a11y-focus-structure`, `a11y-next-atom`, `a11y-previous-atom` | | put the keyboard focus ring on the drawing and walk atoms, for the person (Alt+Mod+A, Alt+Mod+], Alt+Mod+[) | +| `a11y-describe` | | speaks and shows the Structure Summary (formula, name, rings, groups, stereo) for the person (Alt+Mod+S) | +| `element-palette-standard`, `element-palette-high-contrast`, `element-palette-colour-blind` | | the element colours on this device (checked items under View > Element Colours) | + ## The canvas, the view and the grid | Command | What it does | @@ -195,4 +236,4 @@ From 0.10.0, group `3D`. Building, conformers, minimising, scans, measuring, ope ## What no command does yet -Selecting particular atoms or objects, typing stoichiometry amounts, and filling the person's dialogs (atom list, R-group, abbreviation label). Drawing atoms, bonds, arrows and text at given positions, reading the structure back, rendering and converting are not commands: the 0.8.0 tools do them (`drawing`, `edit-by-id`, `visual-qa`). Reading a spectrum's points, its peaks or the predicted shifts as data is not a command either: the 0.9.0 tools do it (`names-and-spectra`). Nor is reading conformer energies, a scan profile or a 3D measurement as data, or 3D coordinates as text: the 0.10.0 tools do it (`three-d`). Picking atoms in the 3D View, choosing the shown conformer and running a scan from the dialog belong to the person. An installed extension with the `document` permission can also read and change the drawing (`extension-drawings`). +Selecting particular atoms or objects, typing stoichiometry amounts, and filling the person's dialogs (atom list, R-group, abbreviation label). Drawing atoms, bonds, arrows and text at given positions, reading the structure back, rendering and converting are not commands: the 0.8.0 tools do them (`drawing`, `edit-by-id`, `visual-qa`). Reading a spectrum's points, its peaks or the predicted shifts as data is not a command either: the 0.9.0 tools do it (`names-and-spectra`). Nor is reading conformer energies, a scan profile or a 3D measurement as data, or 3D coordinates as text: the 0.10.0 tools do it (`three-d`). Nor is reading database records, hit list rows or notebook entries as data: the 0.11.0 tools do it (`databases`). Nor is reading library items, live structure objects or xtb energies as data: the 0.12.0 tools do it (`library-and-biopolymers`, `three-d`). Picking atoms in the 3D View, choosing the shown conformer and running a scan from the dialog belong to the person. An installed extension with the `document` permission can also read and change the drawing (`extension-drawings`). diff --git a/.agents/skills/formchem-skillset/EVALS.json b/.agents/skills/formchem-skillset/EVALS.json index 3b0745e9..15b53e67 100644 --- a/.agents/skills/formchem-skillset/EVALS.json +++ b/.agents/skills/formchem-skillset/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-skillset", - "notes": "Run in a FormChem checkout at 0.10.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", + "notes": "Run in a FormChem checkout at 0.12.0 with CLAUDE.md present; evals 32 to 36 need no fixtures, and eval 35 must not install xtb. Expected behaviours are observable in the files read, the edits made and the commits.", "evals": [ { "id": 1, @@ -303,6 +303,108 @@ "Finds that SUFFIXES in backend/app/routers/files.py lacks .usdz (as it lacked .glb, .cif, .mmcif and .ent until 0.10.0) and adds it by hand", "Updates the extension list in docs/FORMATS.md and writes a backend HASHOUT entry" ] + }, + { + "id": 28, + "name": "new-database-field-type", + "prompt": "Add a 'range' field type to FormChem databases that holds a low and a high number, like a melting point range.", + "files": [], + "expected_behavior": [ + "Loads databases and reads docs/DATABASE.md before any code, and treats it as the contract", + "Edits the field table in DATABASE.md, schema.FIELD_TYPES with a raised FORMAT_VERSION and a migrate step, and FieldType in database-api.ts in the same change", + "Updates fields.py (_check_spec, coerce, detect, rebuild_view), exports.text_of, the type groups in query.py, columns.ts and the Fields dialog's type list", + "Checks by creating a scratch database under a scratch data folder, never ~/formchem" + ] + }, + { + "id": 29, + "name": "new-query-term", + "prompt": "I want FormChem database searches to find records by ring count, like 'rings between 2 and 4'.", + "files": [], + "expected_behavior": [ + "Loads databases and checks whether a number term on an existing column or computed field already covers it before adding a new kind", + "If a new kind is added: the term table in DATABASE.md, query.KINDS and _term with a named 422, _term_name, a mask in search.py with a _cost that keeps structure terms last, TERM and toQuery in query-model.ts, term-editor.ts and describeQuery", + "Does not compute ring counts outside chem.register_values or the computed descriptors", + "Checks the new term on a scratch database and confirms that hit counts match a brute-force count" + ] + }, + { + "id": 30, + "name": "slow-substructure-after-edit", + "prompt": "After I update a record in my FormChem database, the next substructure search takes over a second again on 100,000 records. Why?", + "files": [], + "expected_behavior": [ + "Loads databases and reads search.py screen, _gate and advance, and backend HASHOUT entries 237 and 238", + "Explains that a person's write moves the audit head, so the screening cache reloads (and the pickled molecule holder is rebuilt in the background), which is by design", + "Does not remove the audit row from the write or skip the freshness check, because every compound write must call store.audit inside its transaction", + "Proposes any speed-up as a measured change on a scratch 100,000 record copy, with a HASHOUT entry" + ] + }, + { + "id": 31, + "name": "new-notebook-template", + "prompt": "Add a 'crystallisation' template to the FormChem lab notebook.", + "files": [], + "expected_behavior": [ + "Loads databases and edits templates.py (NAMES, _HEADINGS, _OBSERVATIONS, LABELS) with headings in the plain markup", + "Adds it to EntryTemplate and TEMPLATES in the notebook window with its label through t(), to the template enum of nb_add_entry, and to DATABASE.md's template list", + "Runs ./formchem agents sync after the MCP tool change and commits the mirror" + ] + }, + { + "id": 32, + "name": "new-live-object-field", + "prompt": "FormDeck wants a 'formula' field in the FormChem live structure object. Add it.", + "files": [], + "expected_behavior": [ + "Loads family-integration and reads docs/LIVE_STRUCTURES.md first", + "Edits LIVE_STRUCTURES.md (the object), live_structures.live_object and the LiveObject type in app/live-structures.ts in one change, without raising format_version (an old reader ignores the new field)", + "Checks with a scratch script against a scratch FORMCHEM_DATA_DIR, not ~/formchem, and logs the decision in backend/HASHOUT_LOG.md" + ] + }, + { + "id": 33, + "name": "agent-token-write-path", + "prompt": "Let ./formchem edit-live also save a drawing through the agent token, so a sibling can save without the window.", + "files": [], + "expected_behavior": [ + "Loads family-integration and names law 4: the agent token writes only under /api/structures", + "Either keeps the change under /api/structures (save_live through the structures routes) or stops and asks, because widening core/window_key.py AGENT_WRITES is a SECURITY.md change", + "Does not add another path to AGENT_WRITES without a SECURITY.md edit in the same change" + ] + }, + { + "id": 34, + "name": "new-helm-monomer", + "prompt": "Add N-methylalanine ([meA]) as a HELM monomer in FormChem.", + "files": [], + "expected_behavior": [ + "Loads chemistry-engine and clean-room; writes the monomer itself from the structure, not from a HELM monomer library", + "Adds smiles with [*:1] and [*:2], the capped form, attachments R1 H and R2 OH and a source sentence to data/helm_monomers.json, and runs helm.monomers.library() so the load-time check passes", + "Round-trips a peptide containing [meA] through read and from_mol to the same InChIKey in a scratch script, and updates docs/HELM.md, the agent_helm description and the NOTICE.md count" + ] + }, + { + "id": 35, + "name": "xtb-option", + "prompt": "Let FormChem's xtb optimisation take an electronic temperature (--etemp).", + "files": [], + "expected_behavior": [ + "Loads three-d and follows the xtb option recipe: constant and validation in services/xtb, the argv in inputs.xtb_argv as a list item, never a shell string", + "Exposes it in the dialog, the xtb-optimise command params and agent_xtb's schema and KEYS, and records it in the program record only with FORMAT.md, model.ts and model.py changed together", + "Checks with a stand-in xtb on a temporary PATH, not by downloading xtb, and says a real run was not made if none was" + ] + }, + { + "id": 36, + "name": "palette-flash", + "prompt": "Switching to the colour-blind element palette in FormChem makes the canvas flicker. Fix it.", + "files": [], + "expected_behavior": [ + "Loads family-integration and canvas; looks at canvas/a11y/palette.ts applyPalette and the measure epoch rather than rebuilding the canvas", + "Checks under 4x CPU throttling with a MutationObserver that a switch adds or removes no node and changes only fills", + "Writes the reason in frontend/HASHOUT_LOG.md, not in a comment" + ] } ], "trigger_evals": [ @@ -358,6 +460,18 @@ {"query": "the 3D object on the formchem page flashes when I change its style", "should_trigger": true}, {"query": "add a surface option to FormChem's 3D View panel in frontend/src/ui", "should_trigger": true}, {"query": "give me the lowest-energy conformer of the structure in my open FormChem drawing", "should_trigger": false}, - {"query": "open this PDB file in formchem and extract the ligand for me", "should_trigger": false} + {"query": "open this PDB file in formchem and extract the ligand for me", "should_trigger": false}, + {"query": "add a new query term to formchem's database search in services/database/query.py", "should_trigger": true}, + {"query": "the formchem database table flashes when records load while scrolling", "should_trigger": true}, + {"query": "an SD import into a formchem .fcdb reports the wrong record numbers in its failure report", "should_trigger": true}, + {"query": "change how formchem hashes a notebook entry when it is signed", "should_trigger": true}, + {"query": "search my FormChem database for compounds with a pyridine ring", "should_trigger": false}, + {"query": "design a SQLite schema for a generic inventory app", "should_trigger": false}, + {"query": "the formai://formchem/edit link opens the wrong drawing in FormChem's desktop app, fix handleDeepLink", "should_trigger": true}, + {"query": "add a functional group to formchem's describe.py so the screen reader names sulfonamides", "should_trigger": true}, + {"query": "FormChem's xtb job leaves its process running after cancel, look at services/xtb/runner.py", "should_trigger": true}, + {"query": "Copy as HELM refuses a stapled peptide in formchem, fix the writer cuts", "should_trigger": true}, + {"query": "draw oxytocin from HELM in FormChem for me", "should_trigger": false}, + {"query": "make FormDeck read the formai structure library folder", "should_trigger": false} ] } diff --git a/.agents/skills/formchem-skillset/SKILL.md b/.agents/skills/formchem-skillset/SKILL.md index 68284afc..79679f99 100644 --- a/.agents/skills/formchem-skillset/SKILL.md +++ b/.agents/skills/formchem-skillset/SKILL.md @@ -1,42 +1,44 @@ --- name: formchem-skillset -description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (FORMAT.md, model.ts, model.py, ops, undo), the RDKit service (identifiers, the scored 2D layout, CIP, stereo groups, abbreviations, queries, R-groups, properties), reactions, file formats and loss reports, picture export, the clipboard, the command line, Standardise, the SVG canvas, grids, scaling, tools, annotations, names (dictionary, parser, namer), NMR prediction (increments), JCAMP-DX spectra, 3D (build, conformers, force fields, PDB and mmCIF, the 3D View, glTF), the shell, menus, the dock, Form extensions, the MCP server and agent tools (agent_edits, agent_log, the agent token), the Tauri shell, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for using FormChem (formchem-harness), other Form apps such as FormDeck, or standalone RDKit scripts." +description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (FORMAT.md, model.ts, model.py, ops), the RDKit service (identifiers, the 2D layout, CIP, stereo groups, abbreviations, queries, properties), reactions, file formats, the clipboard, the command line, the SVG canvas, annotations, names, NMR prediction, JCAMP-DX spectra, 3D (conformers, force fields, PDB, xtb and CREST), the structure database and notebook (.fcdb, search, import, signing hashes), live structures and the shared library (LIVE_STRUCTURES.md, formai:// links, edit-live), keyboard access and palettes, HELM, the shell, menus, extensions, the MCP server and agent tools, the Tauri shell, or a release and its CHANGELOG. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md or port 8220. Not for using FormChem (formchem-harness), other Form apps such as FormDeck, or standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.10.0" + version: "0.12.0" --- # FormChem skillset Route every change to FormChem's code through this file. It maps the subsystems that exist today, states the laws that hold everywhere and names the specialist to load. FormChem is a Python 3.12 FastAPI engine (`backend/`, port 8220), a vanilla TypeScript and Vite window (`frontend/`, port 5220, no framework) that talks to the engine over REST and one WebSocket, and a Tauri 2 shell (`src-tauri/`) that runs the frozen engine from a folder inside the app on macOS and as a sidecar elsewhere. -**Where FormChem is (0.10.0).** Through 0.9.0: the family shell, the document format, store and RDKit service, the canvas, reactions, stereo and analysis, formats and pictures, the agent tools with Agent Activity and the token, names, NMR prediction and spectra (`CHANGELOG.md`). 0.10.0 adds 3D: builds from 2D with a stereo check, conformers, force fields, scans, PDB and mmCIF files, the 3D View, model3d objects and eight more MCP tools (60). The structure database (0.11.0) comes later (`DEV_PLAN.md`). Do not write a later phase's code ahead of it; its commands stay registered and disabled. +**Where FormChem is (0.12.0).** Through 0.11.0: the shell, format, store and RDKit service, canvas, reactions, analysis, formats, agent tools, names, NMR, spectra, 3D, databases and the notebook (`CHANGELOG.md`). 0.12.0 adds live structures and the shared library (`docs/LIVE_STRUCTURES.md`), accessibility, HELM, xtb and CREST by path and six MCP tools (77). Desktop builds and the manual (0.13.0) come later (`DEV_PLAN.md`); do not write them ahead. ## Subsystem map | Subsystem | Root | Specialist | | --- | --- | --- | | Engine core: config, guards, window key, settings and seal, live socket, bridge, library | `backend/app/main.py`, `core/`, `routers/system.py`, `routers/live.py`, `services/hub.py`, `services/bridge.py`, `routers/library.py`, `backend/formchem_engine.py` | `engine` | -| Engine document store: open documents, transactions, undo and redo, autosave, versions, recovery, the `.fchem` package, importers, the live `tx` messages | `backend/app/services/store.py`, `services/history.py`, `services/package.py`, `services/importers.py`, `routers/documents.py`, `core/files.py` | `engine` | +| Engine document store: open documents, transactions, undo, autosave, versions, the `.fchem` package, importers | `backend/app/services/store.py`, `services/history.py`, `services/package.py`, `services/importers.py`, `routers/documents.py`, `core/files.py` | `engine` | | The format contract: document.json, styles, ids, ops and inverses, transactions, validation, coalescing, the derived cache shape | `docs/FORMAT.md`, `frontend/src/engine/model.ts`, `engine/ops.ts`, `backend/app/services/model.py`, `services/ops.py` | `document-format` | | Chemistry engine on RDKit: conversion, sanitising, valence, aromaticity, identifiers, formula, masses, layout, file reading and writing, the derived cache | `backend/app/services/chem/`, `backend/app/routers/chem.py` | `chemistry-engine` | -| Window documents and chemistry: the document client, File and Insert actions, the Analysis panel, local valence, rings and formula | `frontend/src/engine/client.ts`, `engine/session.ts`, `engine/client-api.ts`, `app/documents.ts`, `ui/analysis-panel.ts`, `frontend/src/chem/` | `window-shell` (chemistry rules in `chemistry-engine`) | -| Canvas: SVG renderer, drawing tools and hover hotkeys, view, hit testing, selection, text editor, canvas context menus, tool rail; from 0.7.0 the dark page, grids and snapping, scale handles | `frontend/src/canvas/` (`render/`, `tools/`, `view.ts`, `hit.ts`, `selection.ts`, `context.ts`, the grid and dark page files), `ui/tool-rail.ts`, `styles/canvas*.css`, `public/fonts/` | `canvas` | -| Drawn objects: the object kind registry and kind modules, anchors, bounds, drawn-outline hits, annotation tools and handles, captions, z-order and groups, the template library, media | `frontend/src/canvas/render/objects.ts` and its kind modules, `canvas/hit-objects.ts`, `canvas/tools/objects.ts`, `tools/handles.ts`, `app/object-commands.ts`, `ui/template-*.ts`, `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/`, the media routes in `routers/documents.py` | `annotations` | -| Reactions: perception, atom mapping, balance, stoichiometry (engine and window), reaction SMILES and RXN, the Reaction menu, the MCP reaction tools | `backend/app/services/chem/` (`geometry`, `reactions`, `mapping`, `balance`, `stoich`, `rxnio`, `scheme`), `routers/reactions.py`, `frontend/src/chem/stoich.ts`, `ui/stoich-panel.ts`, `app/reaction-commands.ts`, `engine/reactions-api.ts`, `docs/REACTIONS.md` | `reactions` | -| Stereo, queries and analysis: stereo groups, CIP, wedges, abbreviations, hydrogens, queries, SMARTS, Markush, properties, the structure check, the isotope pattern, their routes, commands, marks and panels | `backend/app/services/chem/` (`stereo`, `superatom`, `hydrogens`, `query`, `search`, `v3000`, `markush`, `props`, `check`, `isotopes`), `routers/analysis.py`, `frontend/src/engine/analysis-api.ts`, `app/chem-*.ts`, `canvas/render/marks-*.ts`, `docs/ANALYSIS.md` | `stereo-and-queries` | -| Formats and export: the formats table, report items, readers and writers (CDXML and CDX through Indigo, RD, CML), the export, parse, import and file write routes, pictures with the embedded drawing, the save path, print, File > Import | `backend/app/services/chem/` (`formats`, `report`, `io`, `writers`, `cdxio`, `rdfio`, `cml`), `services/embedded_source.py`, `services/pictures/`, `services/importers.py`, `routers/files.py`, `routers/pictures.py`, `frontend/src/app/` (`picture`, `embedded-source`, `save-file`, `export-commands`, `print`, `import-files`), `ui/export-dialog.ts`, `ui/import-report.ts`, `docs/FORMATS.md` | `formats-and-export` | -| Clipboard: the native payload and paste plan, text formats, flavours per platform, Copy As, Paste Special, Duplicate | `frontend/src/app/clip-*.ts`, `app/clipboard.ts`, `ui/paste-special-dialog.ts`, `ui/native-menu.ts` `ALWAYS_NATIVE` | `clipboard` | -| Names, NMR prediction and spectra: name engines, dictionary, parser, namer; increments and predicted spectra; the JCAMP-DX reader, peaks, integrals; the name dialog, spectrum kind, atom links, Spectrum editor | `backend/app/services/` (`names/`, `nmr/`, `spectra/`), `data/names/`, `routers/` (`names`, `nmr`, `spectra`), the window files in the specialist's file map, `docs/NAMES.md`, `docs/SPECTRA.md` | `names-and-spectra` | +| Window documents and chemistry: the document client, File and Insert actions, the Analysis panel, local valence and rings | `frontend/src/engine/client.ts`, `session.ts`, `client-api.ts`, `app/documents.ts`, `ui/analysis-panel.ts`, `frontend/src/chem/` | `window-shell` (rules in `chemistry-engine`) | +| Canvas: SVG renderer, tools and hover keys, view, hit testing, selection, text editor, context menus, tool rail, the dark page, grids, scale handles | `frontend/src/canvas/` (`render/`, `tools/`, `view.ts`, `hit.ts`, `selection.ts`, `context.ts`, the grid and dark page files), `ui/tool-rail.ts`, `styles/canvas*.css`, `public/fonts/` | `canvas` | +| Drawn objects: the kind registry, anchors, bounds, annotation tools and handles, captions, z-order and groups, templates, media | `canvas/render/objects.ts` and kind modules, `hit-objects.ts`, `tools/objects.ts`, `handles.ts`, `app/object-commands.ts`, `ui/template-*.ts`, `services/templates.py`, `data/templates/` | `annotations` | +| Reactions: perception, mapping, balance, stoichiometry, reaction SMILES and RXN, the Reaction menu and tools | `services/chem/` (`geometry`, `reactions`, `mapping`, `balance`, `stoich`, `rxnio`, `scheme`), `routers/reactions.py`, `chem/stoich.ts`, `ui/stoich-panel.ts`, `app/reaction-commands.ts`, `engine/reactions-api.ts`, `docs/REACTIONS.md` | `reactions` | +| Stereo, queries and analysis: stereo groups, CIP, wedges, abbreviations, hydrogens, queries, SMARTS, Markush, properties, the check, isotopes | `services/chem/` (`stereo`, `superatom`, `hydrogens`, `query`, `search`, `v3000`, `markush`, `props`, `check`, `isotopes`), `routers/analysis.py`, `engine/analysis-api.ts`, `app/chem-*.ts`, `render/marks-*.ts`, `docs/ANALYSIS.md` | `stereo-and-queries` | +| Formats and export: the formats table, reports, readers and writers (CDXML and CDX through Indigo, RD, CML), the exchange routes, pictures with the embedded drawing, print, File > Import | `services/chem/` (`formats`, `report`, `io`, `writers`, `cdxio`, `rdfio`, `cml`), `services/pictures/`, `embedded_source.py`, `importers.py`, `routers/files.py`, `pictures.py`, the window's export, print and import files, `docs/FORMATS.md` | `formats-and-export` | +| Clipboard: the native payload, paste plan, flavours per platform, Copy As, Paste Special, Duplicate | `frontend/src/app/clip-*.ts`, `app/clipboard.ts`, `ui/paste-special-dialog.ts`, `ui/native-menu.ts` `ALWAYS_NATIVE` | `clipboard` | +| Names, NMR prediction and spectra: name engines, namer; increments and predicted spectra; JCAMP-DX, peaks, integrals, atom links, the Spectrum editor | `backend/app/services/` (`names/`, `nmr/`, `spectra/`), `data/names/`, `routers/` (`names`, `nmr`, `spectra`), the window files in the specialist's file map, `docs/NAMES.md`, `docs/SPECTRA.md` | `names-and-spectra` | | 3D: builds, conformers, force fields, scans, measurements, PDB and mmCIF, ligands, the stale-conformer rule; the 3D View, model3d snapshots, glTF | `backend/app/services/three_d/`, `routers/three_d.py`, `frontend/src/ui/view3d-*.ts`, `canvas/render/model3d.ts`, `io/glb.ts`, `engine/three-api.ts`, `engine/stale.ts`, `docs/3D.md` | `three-d` | -| Command line and batch: convert, batch, descriptors, render, the stream reader, Standardise (engine, route, dialog) | `backend/app/cli.py`, `services/batch.py`, `services/chem/` (`stream`, `records`, `standardise`, `depict`), `setup/convert`, `frontend/src/ui/standardise-dialog.ts`, `app/standardise-command.ts`, `docs/CLI.md` | `command-line` | +| Databases and notebook: the `.fcdb` store, registration, fields, import, export, search, hit lists, plot, entries and signing; the workspace, search and notebook views | `backend/app/services/database/`, `services/notebook/`, `routers/databases.py`, `db_search.py`, `notebook.py`, `frontend/src/ui/database*/`, `ui/notebook/`, `engine/database-api.ts`, `docs/DATABASE.md` | `databases` | +| Family integration: the shared Library folder, live structures, edit-live, the `formai://` link, the file watch; accessibility keys, speech, the summary, palettes | `services/live_structures.py`, `file_watch.py`, `describe.py`, `routers/structures.py`, `app/live-structures.ts`, `ui/library-dialog.ts`, `canvas/a11y/`, `docs/LIVE_STRUCTURES.md` | `family-integration` | +| Command line and batch: convert, batch, descriptors, render, the stream reader, Standardise | `backend/app/cli.py`, `services/batch.py`, `services/chem/` (`stream`, `records`, `standardise`, `depict`), `setup/convert`, `ui/standardise-dialog.ts`, `docs/CLI.md` | `command-line` | | Window shell: app root, command registry, palette, Home, title bar, status bar, Preferences, dialogs, themes, i18n, styles | `frontend/src/app.ts`, `app/commands-shell.ts`, `commands/registry.ts`, `io/`, `ui/`, `i18n/`, `styles/` | `window-shell` | | Menus: in-window menu bar, native macOS menus, context menus | `frontend/src/ui/menu.ts`, `ui/native-menu.ts`, `ui/context-menu.ts`, `app/menus.ts`, `styles/menu.css` | `menus` | | Terminal and agent dock | `frontend/src/dock/` (vendored), `frontend/src/dock-adapter.ts`, `backend/app/routers/terminal.py`, `services/terminal.py`, `services/claude_code.py`, `services/agent_programs.py`, `services/agent_lookup.py` (vendored) | `dock` | | Form extensions (host API 1) | `frontend/src/extensions/`, `backend/app/routers/extensions.py`, `services/formext_host.py` (vendored), `docs/EXTENSIONS.md` | `extensions` | -| MCP server, agent tools, the call log and Agent Activity, the agent token, commands catalogue, agent setup and skills | `backend/app/routers/mcp.py`, `services/agent_*.py`, `core/agent_token.py`, `routers/agent_activity.py`, `routers/commands.py`, `frontend/src/app/agent-*.ts`, `ui/agent-*.ts`, `canvas/agent-marks.ts`, `setup/mcp_stdio.py`, `setup/agents.py`, `docs/AGENTS.md`, `.claude/skills` | `agents` | -| Desktop app, the macOS engine folder and the sidecar | `src-tauri/` (`packaged.rs`, `tauri.macos.conf.json`), `backend/formchem_engine.py`, `setup/freeze_backend`, `setup/lib.sh`, `setup/desktop_*`, `build_app` | `desktop` | +| MCP server, agent tools, the call log, Agent Activity, the token, the catalogue, skills | `backend/app/routers/mcp.py`, `services/agent_*.py`, `core/agent_token.py`, `routers/agent_activity.py`, `routers/commands.py`, `frontend/src/app/agent-*.ts`, `ui/agent-*.ts`, `canvas/agent-marks.ts`, `setup/mcp_stdio.py`, `setup/agents.py`, `docs/AGENTS.md`, `.claude/skills` | `agents` | +| Desktop app, the macOS engine folder and the sidecar | `src-tauri/` (`packaged.rs`, `tauri.macos.conf.json`), `formchem_engine.py`, `setup/freeze_backend`, `lib.sh`, `desktop_*`, `build_app` | `desktop` | | Versions, changelog, notices, CI, formcompiler | `.docs/BRANCHING.md`, `CHANGELOG.md`, `NOTICE.md`, `setup/notices.py`, `.github/workflows/` | `release` | | Where any FormChem feature may come from | the owner's clean-room specifications | `clean-room` | @@ -47,9 +49,8 @@ frontend commands/registry.ts -> nothing (DOM free; the cli and workers may impo engine/model.ts, engine/ops.ts -> nothing (pure, DOM free; the contract) chem/ -> engine/model.ts only (pure, no t(), no DOM) engine/client.ts, session.ts -> model, ops, client-api, io/api, io/live -canvas/render -> canvas/types.ts, engine/model, engine/ops (its own geom, valence, rings); - render/table.ts also chem/stoich.ts, the one window stoichiometry source; - render/marks-layer.ts also canvas/marks-options.ts (view toggles only) +canvas/render -> canvas/types.ts, engine/model, engine/ops (own geom, valence, rings); table.ts + also chem/stoich.ts; marks-layer.ts also canvas/marks-options.ts engine/analysis-api.ts -> io/api, model, ops; the only caller of /api/analysis canvas/tools -> canvas/types.ts, engine/model, engine/ops, canvas/geom.ts canvas/view.ts, ui/tool-rail -> canvas/types.ts, hit.ts, selection.ts, ui/dom, ui/icons, i18n @@ -60,9 +61,8 @@ backend services/model.py, ops.py -> nothing (pure; the contract) services/store.py -> model, ops, package, history, importers, hub; chem.derive imported lazily services/chem/ -> rdkit, indigo, model (never the store or routers) backend routers -> core, services (hub, bridge, library, store, chem, terminal, formext_host) -mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub, agent_token; - routers/analysis and the agent_* services imported lazily by the tools -services/agent_*.py -> store, bridge, chem (agent_edits is pure: model and chem only); agent_log hooks AFTER_CHANGE +mcp.py -> commands, extensions, consent, claude_code, bridge, hub, agent_token; agent_* lazily +services/agent_*.py -> store, bridge, chem (agent_edits pure); agent_log hooks AFTER_CHANGE app/picture.ts -> canvas/render (a fresh renderer off screen), never the live canvas view app/clip-*.ts, import-files -> engine/model, ops, the export and parse routes; one paste plan (clip-data.ts) services/chem/writers, stream -> formats, report, io, rdkit, indigo (never the store) @@ -70,6 +70,9 @@ services/batch.py, app/cli.py -> chem/stream, records, standardise, depict, prop services/pictures/ -> fontTools and the bundled fonts only services/names, nmr, spectra -> rdkit, numpy, chem (never routers); nmr registers its hook in spectra.source.PREDICTORS services/three_d -> rdkit, numpy, chem (never routers); store.apply_now runs three_d.stale +services/database, notebook -> sqlite3, rdkit, numpy, chem (never routers or the document store) +services/helm, xtb, describe -> rdkit, chem (xtb also three_d); xtb starts programs only as separate processes +canvas/a11y -> canvas view and render, ui/a11y-announcer; installed before mountCanvas ui/view3d-lib.ts -> 3dmol by dynamic import only (nothing 3D at startup) window-only abilities -> reach the engine as window tools over /api/live (bridge.window_call) desktop shell -> frozen engine (formchem_engine.py) -> serves frontend/dist @@ -103,22 +106,24 @@ The window reaches the engine only through `frontend/src/io/api.ts` (REST with t | How a bond, label or wedge renders, a drawing tool, a hover key, hit testing, selection, zoom, the tool rail, canvas context menus | `canvas` | | An arrow, bracket, shape, table, TLC plate, orbital, picture or caption, its handles and tool; z-order, groups, templates | `annotations`, with `canvas` for the laws it builds on | | Reaction roles, atom mapping, balance, the stoichiometry panel or grid, reaction SMILES or RXN, a reaction route, command or MCP tool | `reactions`, with `chemistry-engine` for RDKit and `agents` for a tool | -| A CIP label, stereo group, wedge, abbreviation, explicit hydrogen, atom list, query bond, SMARTS, substructure hit, R-group, property, check issue or isotope peak; an `/api/analysis` route, an analysis MCP tool, a stereo or query mark | `stereo-and-queries`, with `chemistry-engine` for the converter and `agents` for a tool | +| A CIP label, stereo group, wedge, abbreviation, hydrogen, query atom or bond, SMARTS, R-group, property, check issue or isotope peak; an `/api/analysis` route or tool | `stereo-and-queries` (`chemistry-engine` for the converter, `agents` for a tool) | | A file that opens wrong or loses something, an export or import report, a new format, File > Import, picture export, the drawing inside a picture, saving in the desktop app, print | `formats-and-export`, with `chemistry-engine` for RDKit and `clean-room` for a new format | | Copy, Cut, Paste, Copy As, Paste Special, Duplicate, a clipboard flavour on one platform | `clipboard`, with `formats-and-export` for the text formats and pictures | | `./formchem convert`, `batch`, `descriptors`, `render`, the stream reader, per-record failures, Standardise | `command-line`, with `chemistry-engine` for RDKit | | A name read wrong, a dictionary entry, a ring parent, OPSIN; a predicted shift, an increment, a predictor; a JCAMP-DX file, the spectrum plot, peaks, integrals, atom links, the Spectrum editor | `names-and-spectra` (`clean-room` first; `canvas` for the renderer, `document-format` for the spectrum object) | | A 3D build, conformer, scan, measurement or surface; a PDB or mmCIF file or ligand; the 3D View, a 3D object on the page, glTF; conformers after an edit | `three-d` (`document-format` for `conformers` and `model3d`, `agents` for a tool) | +| A database field, query term, import or export format, hit list, duplicate rule, notebook template or signing; the workspace table, search or plot | `databases` (`agents` for a tool) | +| The Library folder, Copy as Live Structure, a live Save, edit-live, the deep link, the file bar; a focus key, a spoken sentence, the summary, a palette | `family-integration` (`agents` for a tool) | +| A HELM string or monomer; an xtb or CREST option or job | `chemistry-engine`; `three-d` | | A crowded or crossing 2D layout, Lay Out or Clean Up | `chemistry-engine` (the scored layout) | | The dark page, a grid type, snapping, scale handles, Scale Up and Down | `canvas`, with `document-format` for `style.grid` | | New, Open, Save, Insert from SMILES, the Analysis panel, the status bar formula, the dirty mark | `window-shell`, with `chemistry-engine` for the values | | Home, the title bar, status bar, palette, Preferences, About, dialogs, themes, translations, styles | `window-shell` | -| A menu item, a submenu, a shortcut label, macOS native menus, menu overlap | `menus`, then `window-shell` for the command | +| A menu item, submenu or shortcut label, native macOS menus, a menu that clips the title, More menus, keys with a menu open | `menus`, then `window-shell` for the command | | Terminal tabs, Claude Code, Codex, Cursor or Antigravity tabs, the consent dialog, chat | `dock` | | The extensions pane, an extension API call, FormPortal or form.ext integration | `extensions` | | An MCP tool, an edit builder, agent render or placement, the call log, Agent Activity, Stop, the token, `./formchem agents`, skills | `agents` | -| Desktop build, `build_app`, a slow desktop start, the macOS engine folder and its flatten rule, the Tauri CLI version, sidecar, updater, Tauri commands, title bar overlay | `desktop` | -| A menu that clips or overlaps the title, More menus, Escape or arrows with a menu open | `menus` | +| Desktop build, `build_app`, a slow start, the macOS engine folder, sidecar, updater, Tauri commands, title bar overlay | `desktop` | | A release, version sites, CHANGELOG, NOTICE, CI | `release` | | Any chemistry feature, a file format, a name for a command or panel | `clean-room` first | | Use FormChem: draw or edit a structure with the agent tools, run a menu command, hand off in the window | Not this pack: `formchem-harness` | @@ -131,7 +136,8 @@ formchem-skillset/ references/repo-laws.md each law with its reason and exact format EVALS.json evaluation prompts and the trigger tests (should and should not load) sub-skills/ engine, document-format, chemistry-engine, reactions, stereo-and-queries, formats-and-export, - clipboard, command-line, names-and-spectra, three-d, canvas, annotations, window-shell, menus, dock, + clipboard, command-line, names-and-spectra, three-d, databases, family-integration, canvas, annotations, + window-shell, menus, dock, extensions, agents, desktop, release, clean-room chemistry-engine/references/warning-codes.md every ChemWarning code and where it comes from stereo-and-queries/references/routes-and-codes.md the /api/analysis routes, check codes and service warning codes @@ -159,7 +165,7 @@ cd frontend && npx tsc --noEmit type-check backend/venv/bin/python -m compileall -q backend/app setup ``` -Scratch engines for checks: `FORMCHEM_PORT=[port] FORMCHEM_DATA_DIR=[scratch]/data venv/bin/python -m uvicorn app.main:app --port [port]` from `backend/`. `backend/venv/bin/python backend/formchem_engine.py --selfcheck` confirms RDKit and Indigo import. Never point a check at `~/formchem`, the person's data folder. +Scratch engines: `FORMCHEM_PORT=[port] FORMCHEM_DATA_DIR=[scratch]/data venv/bin/python -m uvicorn app.main:app --port [port]` from `backend/`; never point a check at `~/formchem`, the person's data folder. ## Done means diff --git a/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md index 2ae35fca..15017f09 100644 --- a/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md @@ -31,9 +31,9 @@ Give agents an honest tool surface that only describes what FormChem can do now, | `docs/AGENTS.md` | the public reference of every tool, the token and the call log | | `.claude/skills/formchem-harness`, `formchem-skillset` | the packs; `.agents/skills` is a mirror written by sync. Made and repaired only through the god-tier-skill-creator pipeline; its `scripts/validate_skill.py` reports zero FAIL before a commit | -## The tool surface (0.10.0) +## The tool surface (0.12.0) -60 tools: the six of the shell (`get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`); the reaction tools of 0.5.0 and the analysis tools of 0.6.0 (owned by `reactions` and `stereo-and-queries`); and the 28 of 0.8.0: `list_open_documents`, `new_document`, `open_document`, `save_document`, `close_document`, `draw_from_smiles`, `draw_from_molfile`, `render`, `get_structure`, `validate`, `compute_properties`, `convert`, `batch_convert`, `get_atoms` and the 14 edit tools `add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text`, `add_reaction`; and the 10 of 0.9.0, whose services `names-and-spectra` owns: `draw_from_name` (through `_draw`), `name_structure` (the route's `name_mol`), `predict_nmr`, `predict_spectrum` (`nmr.document.spectrum_ops`), `open_spectrum`, `spectrum_data`, `spectrum_peaks`, `spectrum_pick_peaks`, `spectrum_integrate` (`spectra.peak_ops`, `integral_ops`) and `spectrum_export`; and the 8 of 0.10.0, whose services `three-d` owns: `build_3d`, `conformers_3d`, `minimise_3d`, `scan_dihedral`, `measure_3d`, `open_3d_structure` (`three_d.open_bytes`) and `extract_ligand` call the `routers/three_d.py` functions through `_three_d` with an `AgentCall` in the body, so the route's `commit` applies with origin `agent` and the agent's name, and `export_3d` calls `export.write` directly. The writing ones are in `MUTATING` (`scan_dihedral` only with `store`, `export_3d` only with an `output` outside the temporary folder, through `_mutating`); a tool never builds its own copy of a route's ops. +77 tools: the six of the shell (`get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`); the reaction tools of 0.5.0 and the analysis tools of 0.6.0 (owned by `reactions` and `stereo-and-queries`); and the 28 of 0.8.0: `list_open_documents`, `new_document`, `open_document`, `save_document`, `close_document`, `draw_from_smiles`, `draw_from_molfile`, `render`, `get_structure`, `validate`, `compute_properties`, `convert`, `batch_convert`, `get_atoms` and the 14 edit tools `add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text`, `add_reaction`; and the 10 of 0.9.0, whose services `names-and-spectra` owns: `draw_from_name` (through `_draw`), `name_structure` (the route's `name_mol`), `predict_nmr`, `predict_spectrum` (`nmr.document.spectrum_ops`), `open_spectrum`, `spectrum_data`, `spectrum_peaks`, `spectrum_pick_peaks`, `spectrum_integrate` (`spectra.peak_ops`, `integral_ops`) and `spectrum_export`; and the 8 of 0.10.0, whose services `three-d` owns: `build_3d`, `conformers_3d`, `minimise_3d`, `scan_dihedral`, `measure_3d`, `open_3d_structure` (`three_d.open_bytes`) and `extract_ligand` call the `routers/three_d.py` functions through `_three_d` with an `AgentCall` in the body, so the route's `commit` applies with origin `agent` and the agent's name, and `export_3d` calls `export.write` directly. The writing ones are in `MUTATING` (`scan_dihedral` only with `store`, `export_3d` only with an `output` outside the temporary folder, through `_mutating`); a tool never builds its own copy of a route's ops. And the 11 of 0.11.0, whose services `databases` owns, in agent modules rather than in `mcp.py`: `services/agent_db.py` (`db_list`, `db_create`, `db_open`, `db_import`, `db_search`, `db_get_record`, `db_add_record`, `db_update_record`, `db_export`) and `services/agent_notebook.py` (`nb_add_entry`, `nb_search`). Each module offers `TOOLS` in the `_tool` shape, frozen `NAMES`, `mutating(name, args)` and `async call(name, args, agent_name)`, which runs the database services on a worker thread and writes as `agent:[name]`; `mcp.py` walks `AGENT_MODULES` for the list, the gate and dispatch, so a new module adds one name there. They touch no drawing (except `nb_add_entry {doc}`, which reads one), so they answer with `_ok` text and `structuredContent`, not `write_result`. And the 6 of 0.12.0, in three more agent modules: `agent_library.py` (`library_list`, `library_add`, `live_structure_object`; `family-integration` owns the service), `agent_helm.py` (`draw_from_helm`, through `mcp._draw`; `chemistry-engine` owns `services/helm`) and `agent_xtb.py` (`xtb_optimise`, `crest_conformers`, through `_three_d` with the xtb job routes; `three-d` owns `services/xtb`). HELM and xtb build `mcp.Agent("", agent_name)` in `call` because `_draw`, `_apply` and `_three_d` read only the name. `setup/agents.py` reads `mcp.py`'s own `TOOLS` by AST, and each agent module's finished `TOOLS` by importing it with the backend venv's Python (`_module_tools`), so `references/tools.md` and `agents/manifest.json` hold all 77 tools. ## Laws of the agent tools diff --git a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md index e16e9fbc..6ea4d544 100644 --- a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: chemistry-engine -description: "FormChem's chemistry: the RDKit service in backend/app/services/chem (conversion from fragments, sanitising, valence, aromaticity, stereo and CIP, canonical SMILES, CXSMILES, InChI and InChIKey, Hill formula, masses, m/z, elemental analysis, isotope pattern, 2D clean-up and the scored layout: CoordGen and RDKit candidates, layout_score and layout_refine), the /api/chem routes, the derived cache broadcast after every transaction, and the window's local valence, ring and label rules in frontend/src/chem. Use when a computed value is wrong, a warning or valence error appears or is missing, a structure reads upside down or loses atoms, a layout is crowded, crosses bonds or moves the wrong atoms, or a new chemistry computation is added." +description: "FormChem's chemistry: the RDKit service in backend/app/services/chem (conversion from fragments, sanitising, valence, aromaticity, stereo and CIP, canonical SMILES, CXSMILES, InChI and InChIKey, Hill formula, masses, m/z, elemental analysis, isotope pattern, 2D clean-up and the scored layout: CoordGen and RDKit candidates, layout_score and layout_refine), the /api/chem routes, the derived cache broadcast after every transaction, and the window's local valence, ring and label rules in frontend/src/chem, and from 0.12.0 the HELM reader and writer in services/helm over data/helm_monomers.json. Use when a computed value is wrong, a warning or valence error appears or is missing, a structure reads upside down or loses atoms, a layout is crowded, crosses bonds or moves the wrong atoms, a HELM string is refused or a peptide will not copy as HELM, a monomer is added, or a new chemistry computation is added." --- # Chemistry engine @@ -29,6 +29,7 @@ Compute everything chemical in one place, from the drawing as the person drew it | `frontend/src/canvas/render/valence.ts`, `render/rings.ts` | The renderer's own fast implicit-H table and ring perception, used while drawing | | `references/warning-codes.md` | Every warning code, the module that raises it and when. Open before adding or interpreting a warning | | Reaction modules (0.5.0) | `chem/geometry.py`, `reactions.py`, `mapping.py`, `balance.py`, `stoich.py`, `rxnio.py`, `scheme.py`, `derive.reaction_checks` and `routers/reactions.py` belong to the `reactions` specialist; they reuse `convert.to_mol` and the rules here | +| HELM (0.12.0) | `data/helm_monomers.json` (55 monomers written for FormChem, each with `smiles`, `capped`, `attachments`, `source`); `services/helm/monomers.py` (`_monomer` checks every capped form at load, `inline`), `parser.py` (`parse`, positioned `HelmError`, limits), `assemble.py` (`Chem.molzip` over shared map numbers, exported as `build_molecule`), `writer.py` (`CUTS`, `_assign`, `_topology`, `write`), `__init__.py` (`read`, `from_mol` with the InChIKey read-back); `routers/helm.py`, `services/agent_helm.py`, `frontend/src/ui/helm-dialog.ts`, `app/helm-commands.ts`; `docs/HELM.md`; HASHOUT backend 265 to 269, frontend 296 and 297 | | Analysis modules (0.6.0) | `chem/stereo.py`, `superatom.py`, `hydrogens.py`, `query.py`, `search.py`, `v3000.py`, `markush.py`, `props.py`, `check.py`, `isotopes.py` and `routers/analysis.py` belong to the `stereo-and-queries` specialist. Here they changed `convert.py` (stereo groups and the chiral flag after perception, query atoms and bare `*` as generics), `perceive.py` (`stereo_unknown`, `undefined_double_bond`, cumulenes skipped, charged atoms judged by the allowed list so Na+ is no valence error) and `derive.content_key` (`FRAGMENT_FIELDS`) | ## Rules @@ -50,6 +51,13 @@ Compute everything chemical in one place, from the drawing as the person drew it 3. A new derived field is a contract change: add it to the derived cache table in `docs/FORMAT.md` and to `DerivedFragment` in `model.ts` (`document-format`). 4. Time it: `derive_document` on a 250-atom fragment stays well under 100 ms warm. +## A HELM monomer or a new cut (0.12.0) + +1. **Write the monomer yourself** from a textbook structure (`clean-room`): never copy a HELM monomer library, whose licence was never cleared. Give `smiles` with `[*:n]`, the `capped` form with each leaving group put back, `attachments` (R label to `H` or `OH`) and a `source` sentence; mirror-image D forms in full. The loader refuses the whole file when a capped form differs, so run `helm.monomers.library()` in the engine venv after the edit. +2. **Reading** needs nothing more; **writing** needs the piece to come out of `writer._cuts`. A new bond kind is a `CUTS` row (SMARTS, the two cut atoms, the leaving group each side) and, if it pairs labels unusually, a `PARTNER` entry; cut only bonds that are always between monomers. +3. **Round-trip check.** A scratch script under `/tmp` reads the HELM, writes it back and compares InChIKeys, for the new monomer and for oxytocin, ApU, a chain of all 20 L and 19 D residues, a head-to-tail cyclic peptide and the two lactam bridges. `from_mol` must never offer HELM that reads back differently. +4. Update the monomer table in `docs/HELM.md`, the tool description in `agent_helm.py` and the count in NOTICE.md's own-data line. + ## Gate - [ ] `backend/venv/bin/python -m compileall -q backend/app` is clean and `backend/formchem_engine.py --selfcheck` exits 0. diff --git a/.agents/skills/formchem-skillset/sub-skills/databases/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/databases/SUB-SKILL.md new file mode 100644 index 00000000..1d5ea236 --- /dev/null +++ b/.agents/skills/formchem-skillset/sub-skills/databases/SUB-SKILL.md @@ -0,0 +1,85 @@ +--- +name: databases +description: "FormChem's 0.11.0 structure database and lab notebook code: the engine packages services/database (schema, store, chem.register_values, computed, fields, forms, records, attachments, thumbs, jobs, imports, exports, uploads, info, query, search, hitlists, saved, plot, dbcli) and services/notebook (templates, content hash, scheme, products, entries, export), routers databases.py, db_search.py and notebook.py, agent_db.py and agent_notebook.py, and the window's ui/database (workspace, table, gallery, form, dialogs), ui/database-find (search bar, query builder, hit lists, import, export, plot) and ui/notebook, against the contract docs/DATABASE.md. Use when adding a field type, a query term, an import or export format, a notebook template, a database route or MCP tool, fixing a slow or wrong search, an import report, a duplicate rule, a hit list, a table that flashes, or signing and the entry hash." +--- + +# Databases + +## Purpose + +Change FormChem's databases and notebook without breaking the contract: one `.fcdb` SQLite file that any SQLite browser reads, every write in one transaction with an audit row, keys and fingerprints from one function, searches that never add hits as a threshold rises, and a 10,000 record table that never rebuilds. Hands back the change, the checks that prove it and HASHOUT entries. + +## Preconditions + +`clean-room` loaded (the database and notebook sections of the clean-room specifications). `docs/DATABASE.md` read in full: it is the contract, and when code disagrees with it the code is the bug. `database-api.ts`, `workspace-types.ts` and `services/database/schema.py` are contract files too. + +## File map + +| Path | Holds | +| --- | --- | +| `services/database/schema.py`, `store.py` | tables, `FORMAT_VERSION`, `migrate`; handles, the lock file, `writing`, `reading`, `next_number`, `audit`, `notify`, `close_all` | +| `database/chem.py`, `computed.py` | `register_values` (keys, formula, masses, counts, both fingerprints); descriptor fields over `chem/props.measure` | +| `database/fields.py`, `forms.py`, `records.py`, `attachments.py`, `thumbs.py`, `info.py` | fields and the `records` view; generated forms; add, update, duplicates, paging; files; themed thumbnails; Info, create, open | +| `database/jobs.py`, `imports.py`, `exports.py`, `uploads.py` | worker jobs; preview, mapping, batches of 250, the report, `plain`; SD, SMILES, CSV and one-time downloads; browser uploads and `adopt` | +| `database/query.py`, `search.py`, `hitlists.py`, `saved.py`, `plot.py` | `normalise`, the formula grammar, `name_of`; the screening cache, `_evaluate`, `run`; hit lists with temp tables when read-only; saved queries; plot points | +| `database/dbcli.py`, `app/cli.py` | `./formchem db` | +| `services/notebook/` | `templates`, `content` (the eleven-key hash), `scheme` (molecules, stoichiometry, pictures), `products`, `entries` (`sign`, `after_change`, `listing`), `attachments`, `markup`, `export` | +| `routers/databases.py`, `db_search.py`, `notebook.py`; `core/window_key.py` `require_view` | thin routes, `GUARD` and `VIEW_GUARD` | +| `services/agent_db.py`, `agent_notebook.py`; `routers/mcp.py` `AGENT_MODULES` | the eleven tools, `mutating`, `call` | +| `frontend/src/engine/database-api.ts` | types and one function per route, `DuplicateError` | +| `frontend/src/ui/database/` | `workspace.ts`, `workspace-types.ts`, `record-source.ts` (blocks of 100), `selection.ts`, `columns.ts`, `table.ts`, `gallery.ts`, `form-view.ts`, `thumbs.ts`, the dialogs; `app/database-commands.ts` | +| `frontend/src/ui/database-find/` | `search-bar.ts`, `query-text.ts`, `query-model.ts`, `term-editor.ts`, `query-builder.ts`, `hitlists.ts`, `queries.ts`, `import-dialog.ts`, `export-dialog.ts`, `files.ts`, `plot.ts`, `plot-math.ts` | +| `frontend/src/ui/notebook/` | `notebook.ts`, `entry-list.ts`, `entry-editor.ts`, `scheme-view.ts`, `notebook-api.ts`, `markup.ts`, `commands.ts` | +| `docs/DATABASE.md`, `docs/DATABASES.md` | the contract; the person's guide. HASHOUT backend 223 to 255, frontend 245 to 276 | + +## Laws + +1. **One transaction per write.** Every write runs inside `store.writing(db)` (BEGIN IMMEDIATE ... COMMIT under `db.lock`) and calls `store.audit` in it; reads use `store.reading`. The search cache trusts the audit head, so a write without an audit row leaves searches stale. Long work commits in batches, each its own transaction, and registers chemistry outside the lock. +2. **Notify after commit.** `store.notify(db, change, uids)` is called once the transaction committed, never inside it, with the `change` names of DATABASE.md; the window refetches only what it names. +3. **The contract wins.** A table, column or JSON shape change edits DATABASE.md, the engine and `database-api.ts` in one change, raises `FORMAT_VERSION` and adds a step to `schema.migrate`; an older file must still open (read-only when newer). +4. **Fingerprints only through `chem.register_values`.** Stored rows and exact queries are keyed by that one function; never compute an InChIKey, parent key or fingerprint elsewhere. +5. **Search stays monotonic and named.** Raising a similarity threshold never adds hits; every structure result names its method and the RDKit version. +6. **The window never rebuilds.** Rows and tiles are pooled and keyed by uid, records arrive in blocks with stale blocks kept on screen, and a live change refetches only its blocks. +7. **Agents never sign.** Signing is the person's statement; `nb_add_entry` writes open entries only. + +## Recipes + +### A new field type + +1. DATABASE.md's field table, `schema.FIELD_TYPES` and `NUMERIC_TYPES` (with a format version step), and `FieldType` in `database-api.ts`. +2. Engine: `fields._check_spec`, `stores_text`, `coerce` (and its import path `text=True`), `detect`, `rebuild_view`; `exports.text_of` and `NON_SCALAR`; the type groups in `query.py`. +3. Window: `columns.ts` (format, parse, `EDITABLE`), the type list in `fields-dialog.ts`, the import dialog's type names, the term editor's field groups in `database-find/shared.ts`. + +### A new query term + +1. DATABASE.md's term table first. +2. `query.KINDS` and `_term` (defaults and the 422 naming the bad key), `_term_name` for the hit list name. +3. `search.py`: a mask function in `FIELD_TERMS` or a branch in `_evaluate`, with a `_cost` that keeps structure terms last. +4. Window: `TERM` and `toQuery` in `query-model.ts`, the row in `term-editor.ts`, `describeQuery` in `query-text.ts`; the `_QUERY` description in `agent_db.py`. + +### A new import or export format + +Import: `imports.FORMATS` and `format_of`, items from `chem/records.py` `iter_records` (streaming, a reason per bad record), `IMPORT_EXTENSIONS` in `files.ts`, the `--format` help in `dbcli.py`, the `format` enum of `db_import`, DATABASE.md and `docs/FORMATS.md`. Export: `exports.FORMATS` and `_write`, the export dialog, `db_export`'s enum, and a round trip into a new database that keeps every InChIKey and value. + +### A new notebook template + +`templates.NAMES`, `_HEADINGS`, `_OBSERVATIONS` and `LABELS`; `EntryTemplate` and `TEMPLATES` in the notebook window with its label through `t()`; the `template` enum of `nb_add_entry`; DATABASE.md's template list. Headings are plain markup (`**Heading**`), never HTML. + +### A database route or MCP tool + +A thin route with `GUARD` (or `VIEW_GUARD` for a picture) on a worker thread, `DatabaseError` turned into its status; the function in `database-api.ts`; a tool in `agent_db.TOOLS` or `agent_notebook.TOOLS` with `mutating` deciding consent, writing as `agent:[name]`; then `./formchem agents sync` (its generated `tools.md` reads only mcp.py's own `TOOLS`, so module tools are documented in `docs/AGENTS.md` and the harness `databases` sub-skill). + +## Checks + +Scratch data folders only (`FORMCHEM_DATA_DIR=[scratch]/data`). Import a 10,000 record SD file with three broken records: 9,997 added and three plain reasons. Benzene substructure equals a brute-force `HasSubstructMatch` on a 2,000 record copy; thresholds 0.3 to 0.9 never rise. A second process opens the file read-only and gets 423 on writes. The table under 4x CPU throttling: layout shift 0 while scrolling, no row nodes added on sort. An entry signed, then changed, keeps one `edited-after-signing` version with the signed hash. + +## Gate + +- [ ] DATABASE.md, the engine and `database-api.ts` agree; a shape change raised the format version with a migration. +- [ ] Every new write is one transaction with an audit row and a notify after commit. +- [ ] New numbers name their method and version; similarity stays monotonic. +- [ ] The checks above ran on scratch data, and HASHOUT entries are written. + +## Hands back + +The change, the check output with numbers, and the HASHOUT entries. diff --git a/.agents/skills/formchem-skillset/sub-skills/family-integration/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/family-integration/SUB-SKILL.md new file mode 100644 index 00000000..7881ade5 --- /dev/null +++ b/.agents/skills/formchem-skillset/sub-skills/family-integration/SUB-SKILL.md @@ -0,0 +1,84 @@ +--- +name: family-integration +description: "FormChem's 0.12.0 family integration code: live structures and the shared structure library (services/live_structures.py, routers/structures.py, agent_library.py, app/live-structures.ts, ui/library-dialog.ts, the contract docs/LIVE_STRUCTURES.md), the agent token's one write path (core/window_key.py AGENT_WRITES), formchem edit-live, the formai:// deep link (tauri-plugin-deep-link, followDeepLinks, handleDeepLink), the file watch and its bar (services/file_watch.py, ui/file-changed-bar.ts), and accessibility (canvas/a11y: the key route, navigation, spoken atoms and bonds, the focus ring, element palettes; ui/a11y-announcer.ts, ui/structure-summary.ts, services/describe.py). Use when changing what a sibling Form app reads, the clipboard flavours of Copy as Live Structure, the library folder or library.json, a live drawing's Save, edit-live or the deep link, the file changed bar, a keyboard focus key, a spoken sentence, the Structure Summary, a functional group or ring name, or an element palette." +--- + +# Family integration + +## Purpose + +Change how FormChem works with the other Form apps and with assistive technology without breaking what they rely on: the Library folder and the live structure object stay readable by apps that never run FormChem code, a live drawing saves to its item and nothing else, the agent token writes nowhere but `/api/structures`, the keyboard route runs before the canvas's, every spoken sentence is a whole `t()` template, and switching palettes or showing the file bar never moves a node. Hands back the change, the checks that prove it and HASHOUT entries. + +## Preconditions + +`clean-room` loaded (the family and accessibility sections of the clean-room specifications, spec C 9.4). `docs/LIVE_STRUCTURES.md` read in full: it is the contract sibling apps code against, and when code disagrees with it, fix one of them in the same change and say which in the HASHOUT log. + +## File map + +| Path | Holds | +| --- | --- | +| `backend/app/services/live_structures.py` | `folder` (`FORMCHEM_DATA_DIR/Library`, not the recent-drawings `library.json`), `read_index`, `write_file`, `write_index` (atomic, index last), `add` (merges kinds for non-live, live always new), `prune` (`RECENT_CAP` 50 by `used`), `describe` (perceive, ids, `mass.average_mass`), `engine_pictures`, `live_object`, `adopt` (id kept, higher rev wins), `open_live`, `save_live`, `LINKS`, `links`, `open_request`, `edit_live` | +| `backend/app/routers/structures.py` | the contract routes plus `links`, the unkeyed `picture.svg/png`, `GET /api/files/watch` and `POST .../{reload or keep}`; `_guard` takes the window key or the agent token | +| `backend/app/core/window_key.py` | `AGENT_WRITES`, `agent_may_write`: the global guard lets a valid bearer token through on `/api/structures` and below only | +| `backend/app/services/file_watch.py`, `app/main.py` lifespan | the 1 s poll of open drawings' files, own saves recognised by `document.json` `modified`, `reload` (one undoable transaction), `keep` | +| `backend/app/services/agent_library.py` | `library_list`, `library_add`, `live_structure_object` in the agent module shape | +| `backend/app/cli.py`, `formchem`, `formchem.bat` | `edit-live` | +| `src-tauri/` (Cargo.toml, main.rs, tauri.conf.json, capabilities) | tauri-plugin-deep-link 2.6.3, the `formai` scheme, single-instance with `deep-link`, `register_all()` on Linux | +| `frontend/src/app/live-structures.ts` | `structuresApi`, `copyLiveStructure` (one `writeClipboard`), `starStructure`, `saveTemplateToLibrary`, `saveLive`, `liveActive`, `mountLiveDrops`, `deepLinkTarget`, `handleDeepLink`, `LIVE_MIME`, `WEB_LIVE_MIME` | +| `frontend/src/app.ts` `followDeepLinks`; `app/documents.ts` `DocumentHooks.save` | deep links in the main window only; closing a dirty live drawing saves its item | +| `frontend/src/ui/library-dialog.ts`, `ui/file-changed-bar.ts`, `styles/library.css` | the Structure Library (built once, tiles keyed by id, fixed 132 px rows); the bar inside `.fc-stage` | +| `frontend/src/canvas/a11y/` | `index.ts` (`prepareA11y` before `mountCanvas`, `mountA11y`), `controller.ts` (`installA11yKeys`, `CanvasA11y`, `relayCanvasPrompts`), `nav.ts`, `speech.ts`, `elements.ts`, `ring.ts`, `palette.ts`, `commands.ts` (`PALETTE_COMMAND_IDS`), `describe-api.ts` | +| `frontend/src/canvas/render/atom.ts` | `ELEMENT_PALETTES` (standard, high-contrast, colour-blind), `setElementPalette` | +| `frontend/src/ui/a11y-announcer.ts`, `ui/structure-summary.ts`, `styles/a11y.css` | the shared live regions; the summary dialog; focus ring, outlines, 24 px targets | +| `backend/app/services/describe.py`, `routers/describe.py` | `GROUPS` (42 SMARTS), `RING_NAMES` (51 skeletons), `functional_groups` (priority, claimed atoms), `ring_name`, `stereo`, `describe`; `POST /api/describe` | +| `docs/LIVE_STRUCTURES.md`, `LIVE-STRUCTURES.md`, `ACCESSIBILITY.md` | the contract; the person's pages. HASHOUT backend 256 to 264 and 276 to 278, frontend 277 to 295 and 300 | + +## Laws + +1. **The folder is the contract.** Every Library file is written through `core/files.write_atomic`, item files first and `library.json` last; deletes write the index first. Readers skip items whose files are missing. A field a sibling reads changes LIVE_STRUCTURES.md, `live_structures.py` and `live-structures.ts` together, and `format_version` rises only for a change an old reader would misread. +2. **The drawing inside is the structure.** Every item SVG and PNG carries the FormChem source in the carriers of FORMATS.md, whoever drew it (the window's pictures, or `engine_pictures` without a window). A picture without it is a bug, not a lighter item. +3. **A live drawing is ordinary.** Nothing is written into the drawing; the link lives in `LINKS` and the window's map. Save goes to `save_live` (rev + 1, `live-structure` broadcast), Save As stays an ordinary copy, closing calls the `DocumentHooks.save` hook. Revisions only rise: `adopt` keeps the higher rev. +4. **The agent token has one write path.** Only `/api/structures` and below; every other changing route still needs the window key. Widening `AGENT_WRITES` is a SECURITY.md change. +5. **The deep link only opens.** `deepLinkTarget` accepts `formai://formchem/edit?id=s[10]&from=...` and nothing else; other `formai` hosts pass on; only the `main` window listens. A link never carries a path, a command or a setting. +6. **The key route goes first.** `prepareA11y()` runs before `mountCanvas` so its capture listener precedes the view's; handled keys get `preventDefault` only (`stopImmediatePropagation` breaks the menu bar's Alt detection); Tab past the last atom leaves, so focus is never trapped. The focus is the view's keyboard cursor, not a second one. +7. **Speak whole sentences from fresh data.** Every spoken part is one `t()` template; derived values (hydrogens, CIP, aromaticity) only when `derived.rev` equals the client's and nothing is unconfirmed. One announcer for the window; the canvas's own region stays hidden and its prompts are relayed. +8. **Palettes patch fills.** The choice is read before the canvas exists (localStorage `formchem.elementPalette`); a switch bumps the measure epoch so only fills change. High contrast stays at 7:1 or more on white; the colour-blind palette keeps Okabe-Ito hues of 3:1 or more and leaves paler ones to the ink. +9. **Nothing moves.** The file bar is absolutely placed in the stage with a local z token; the library dialog patches tiles by id; the summary reserves its rows. + +## Recipes + +### A field or flavour a sibling reads + +LIVE_STRUCTURES.md first, then `live_object` or `describe` and `LiveObject` or `LibraryItem` in `live-structures.ts`, then `copyLiveStructure`'s flavour list. Browsers accept custom clipboard types only with the `web ` prefix and drop `chemical/x-mdl-molfile`; keep the object in the HTML flavour's `data-formai-structure` too. Check `library.json` field by field against the contract with a scratch script, and the clipboard in Chromium under 4x throttling. + +### A new way to open a live structure + +Route it to `open_live` (engine) or `openLiveStructure` (window), never a second opener. Command-line paths go through `open_request` and post with the agent token like `edit_live`; a desktop path goes through the deep link plugin and `handleDeepLink`. + +### A keyboard key or a spoken sentence + +Keys live in `controller.ts` (`installA11yKeys` and the handlers); registry commands in `commands.ts` with a key the 312-command registry does not already use (check `GET /api/commands`, and macOS reserved combinations such as Option-Command-D). Sentences go in `speech.ts` or `structure-summary.ts` as whole templates; element names in `elements.ts`. Check with Playwright reading `.fc-announcer-polite`, and say in the notes that no real screen reader ran unless one did. + +### A functional group or ring name + +Write the SMARTS or skeleton for FormChem (`clean-room`); a group marks its core atoms with map numbers and sits in priority order in `GROUPS`; a ring goes through the same `_skeleton_key` as the table. Re-run the 25-molecule scratch check (aspirin acid and ester, caffeine urea and purine, L-alanine S) and update the counts in NOTICE.md and ACCESSIBILITY.md. + +### An element palette + +A map in `ELEMENT_PALETTES` with contrast ratios computed on white in a scratch script, the choice in `PALETTE_CHOICES`, the Preferences option in `ui/prefs/sections.ts`. Check 0 nodes added or removed per switch under 4x throttling. + +## Checks + +From `backend/` on a scratch engine and data folder: `edit_live` against an item (exit 0), an unknown id (exit 1) and an unreadable file (exit 2); curl `/api/structures` without a key 403, with the token 200, and the token on `/api/helm/parse` and `/api/structuresX` 403; an outside rewrite of an open `.fchem` shows the bar within about a second and an own save does not. In the built window under 4x CPU throttling: Copy as Live Structure, paste back, open from the Live tab and Save raises rev; the keyboard-only ethanol speaks every atom and Describe reads its formula; palette switches and the file bar give layout shift 0. `npx tsc --noEmit` clean. + +## Gate + +- [ ] LIVE_STRUCTURES.md, the engine and the window agree; `library.json` written by FormChem passes a field-by-field check. +- [ ] No route other than `/api/structures` accepts the agent token for writes; the deep link still opens only. +- [ ] Keys still route before the canvas, Tab still leaves, and every new sentence is one `t()` template. +- [ ] No node added or removed by a palette switch or the file bar; tiles patched by id. +- [ ] HASHOUT entries and the docs updated; NOTICE.md own-data counts still true. + +## Hands back + +The change, the check results, the HASHOUT entries and the commit list. diff --git a/.agents/skills/formchem-skillset/sub-skills/three-d/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/three-d/SUB-SKILL.md index 48ca1508..d4adf2ff 100644 --- a/.agents/skills/formchem-skillset/sub-skills/three-d/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/three-d/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: three-d -description: "FormChem's 0.10.0 3D code: the engine package services/three_d (molecule labels, forcefield, build, verify, conformers, minimise, scan, measure, export, structure, pdb, mmcif, molfile3d, ligand, readers, document, stale), routers/three_d.py, the stale-conformer rule in the store and in engine/stale.ts, the window's 3D View panel over a lazily loaded 3Dmol.js (view3d-lib, view3d-viewer, view3d-panel, dialogs, scan plot), the model3d page renderer and its snapshots, the glb writer and the 3D commands. Use when adding a display style, a surface, a force field or method, a structure file reader, a 3D MCP tool or route, fixing a build that loses stereo, a conformer or scan result, a PDB summary or ligand, a 3D object that flashes on the page, or the conformer drop after an edit." +description: "FormChem's 0.10.0 3D code: the engine package services/three_d (molecule labels, forcefield, build, verify, conformers, minimise, scan, measure, export, structure, pdb, mmcif, molfile3d, ligand, readers, document, stale), routers/three_d.py, the stale-conformer rule in the store and in engine/stale.ts, the window's 3D View panel over a lazily loaded 3Dmol.js (view3d-lib, view3d-viewer, view3d-panel, dialogs, scan plot), the model3d page renderer and its snapshots, the glb writer and the 3D commands, and from 0.12.0 services/xtb (discovery, runner, jobs, parse, writeback) with routers/xtb.py, agent_xtb.py and the xtb dialogs. Use when adding a display style, a surface, a force field or method, an xtb or CREST option, a structure file reader, a 3D MCP tool or route, fixing a build that loses stereo, a conformer or scan result, a PDB summary or ligand, an xtb job that hangs or misreads output, a 3D object that flashes on the page, or the conformer drop after an edit." --- # Three-d @@ -11,7 +11,7 @@ Change FormChem's 3D without breaking its promises: every energy and measurement ## Preconditions -`clean-room` loaded (the 3D sections of the clean-room specifications). Licence rule: permissive anywhere; LGPL only as a separate process the person installs (xtb and CREST stay user-installed by path while plan question Q9 is open); GPL and AGPL never (no Open Babel code); gemmi (MPL-2.0) is not vetted. Ligand templates are written for FormChem; the Chemical Component Dictionary is CC0 but nothing was copied from it. +`clean-room` loaded (the 3D sections of the clean-room specifications). Licence rule: permissive anywhere; LGPL only as a separate process the person installs (xtb and CREST are user-installed by path, plan question Q9's default; never bundle, download or link them); GPL and AGPL never (no Open Babel code); gemmi (MPL-2.0) is not vetted. Ligand templates are written for FormChem; the Chemical Component Dictionary is CC0 but nothing was copied from it. ## File map @@ -29,7 +29,9 @@ Change FormChem's 3D without breaking its promises: every energy and measurement | `frontend/src/canvas/render/model3d.ts` | the page object (snapshot, or a placeholder) | | `frontend/src/io/glb.ts`, `chem/elements3d.ts`, `chem/geom3d.ts`, `chem/conformer-mol.ts` | glTF writer, palette and radii, measurement maths, local molfile | | `frontend/src/app/view3d-commands.ts`, `app/menus.ts` | `VIEW3D_COMMAND_IDS`, the commands, `DISPLAY_3D`, `SURFACE_3D` | -| `docs/3D.md`, `docs/FORMAT.md` | the reference; `conformers`, `conformer` and `model3d`. HASHOUT backend 199 to 222, frontend 222 to 244 | +| `backend/app/services/xtb/` (0.12.0) | `__init__` (methods, levels, limits, settings keys), `solvents` (24 ALPB), `discovery` (`find`, `_locate`, `child_env`), `inputs` (start geometry in label order, `electrons_check`, argv), `runner` (`Process`, own process group, `stop_all`), `jobs` (one at a time, `_collect`, `_prune`), `parse`, `writeback` (`records`, `program`, `label`) | +| `routers/xtb.py`, `services/agent_xtb.py`, `frontend/src/app/xtb-commands.ts`, `ui/xtb-dialog.ts`, `ui/prefs/xtb.ts` | the xtb routes and `_applier` over `three_d.commit`; the two tools; the client and commands; the dialogs; the Preferences rows | +| `docs/3D.md`, `docs/FORMAT.md` | the reference; `conformers` (with the xtb `program` record), `conformer` and `model3d`. HASHOUT backend 199 to 222 and 270 to 275, frontend 222 to 244, 298 and 299 | ## Laws @@ -50,11 +52,19 @@ Change FormChem's 3D without breaking its promises: every energy and measurement ### A force field or method -Add it to `METHODS` and `forcefield.setup` with its own fallback reason, to `FORCE_FIELDS` in `three-api.ts`, the panel's select, `_FF` in `mcp.py`, and `docs/3D.md`. An external program (xtb) runs as a separate process found by a path the person sets, never bundled or linked, and its energy is stored under its own `method`. +Add it to `METHODS` and `forcefield.setup` with its own fallback reason, to `FORCE_FIELDS` in `three-api.ts`, the panel's select, `_FF` in `mcp.py`, and `docs/3D.md`. An external program runs as a separate process found by a path the person sets, never bundled or linked, and its energy is stored under its own `method`, as xtb does (below). + +### An xtb or CREST option (0.12.0) + +1. Constants first: `xtb/__init__.py` (`METHODS`, `OPT_LEVELS`, limits) or `solvents.ALPB` (only solvents xtb documents). +2. `jobs.options` validates it (422 with the reason), `inputs.xtb_argv` or `crest_argv` passes it; never build a shell string, always an argv list. +3. Output: a new value is read in `parse.py` from the documented file layout and checked on a hand-written file under `/tmp`; it travels in the job's `conformers` table and, when it belongs with the geometry, in `writeback.program` (then FORMAT.md, `model.ts` `ConformerProgram` and `model.py` in one change). +4. Expose it: the dialog field in `xtb-dialog.ts` (built once; polling patches text only), the command `params` in `xtb-commands.ts`, the tool schema and `KEYS` in `agent_xtb.py`, `docs/3D.md` and `docs/AGENTS.md`. +5. Laws that stay: one job at a time; a failed job keeps its folder until it is forgotten; results map back by element order or the job fails (502); write-back goes through `three_d.commit` with the stale signature, so an edit mid-run fails the job instead of storing stale conformers. Check with a stand-in program on a temporary PATH (a script printing `xtb version X` and writing `xtbopt.xyz` and the log lines), never only with a real installation. ### A structure file reader -A parser returning `Structure` (with `summary` working on it), a `detect` rule and rows in `EXTENSIONS` and `MIMES`, `readers.read`, `document.MODEL_FORMATS` and `importers.MODELS_3D`, `package.EXT_BY_MIME`, the window's `OPEN_EXTENSIONS` and `STRUCTURE_ACCEPT`, and `routers/files.py` `SUFFIXES` so the desktop save accepts it (that list still lacks `.glb`, `.cif`, `.mmcif` and `.ent` at 0.10.0). The bytes stay as media; never rewrite the file. +A parser returning `Structure` (with `summary` working on it), a `detect` rule and rows in `EXTENSIONS` and `MIMES`, `readers.read`, `document.MODEL_FORMATS` and `importers.MODELS_3D`, `package.EXT_BY_MIME`, the window's `OPEN_EXTENSIONS` and `STRUCTURE_ACCEPT`, and `routers/files.py` `SUFFIXES` so the desktop save accepts it. The bytes stay as media; never rewrite the file. ### A 3D MCP tool or route diff --git a/.claude/skills/formchem-harness/EVALS.json b/.claude/skills/formchem-harness/EVALS.json index 8e288d02..e5060c3b 100644 --- a/.claude/skills/formchem-harness/EVALS.json +++ b/.claude/skills/formchem-harness/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-harness", - "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected with the agent token, version 0.10.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.10.0 has 60 tools: agents draw with draw_from_smiles, draw_from_molfile, draw_from_name and add_reaction, edit by id with get_atoms and the 14 edit tools, check with render, get_structure and validate, name with name_structure, predict NMR with predict_nmr and predict_spectrum, work on spectra with open_spectrum and the spectrum tools, work in 3D with build_3d, conformers_3d, minimise_3d, scan_dihedral, measure_3d, open_3d_structure, extract_ligand and export_3d, and still reach the window's commands, reactions, analysis and extensions; several evals check that the agent draws with the tools and checks before it claims. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 18 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O; eval 20 needs an SD file at the path it names; eval 28 needs ethyl acetate drawn; eval 29 needs a JCAMP-DX 1H NMR file of ethanol at the path it names; eval 33 needs a PDB file with a protein chain and a benzamidine ligand (BEN) at the path it names; eval 34 needs butane drawn.", + "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected with the agent token, version 0.12.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.12.0 has 77 tools: agents draw with draw_from_smiles, draw_from_molfile, draw_from_name and add_reaction, edit by id with get_atoms and the 14 edit tools, check with render, get_structure and validate, name with name_structure, predict NMR with predict_nmr and predict_spectrum, work on spectra with open_spectrum and the spectrum tools, work in 3D with build_3d, conformers_3d, minimise_3d, scan_dihedral, measure_3d, open_3d_structure, extract_ligand and export_3d, work with structure databases and the notebook with db_list, db_create, db_open, db_import, db_search, db_get_record, db_add_record, db_update_record, db_export, nb_add_entry and nb_search, keep the shared structure library with library_list, library_add and live_structure_object, draw biopolymers with draw_from_helm, run xtb and CREST (only when installed) with xtb_optimise and crest_conformers, and still reach the window's commands, reactions, analysis and extensions; several evals check that the agent draws with the tools and checks before it claims. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 18 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O; eval 20 needs an SD file at the path it names; eval 28 needs ethyl acetate drawn; eval 29 needs a JCAMP-DX 1H NMR file of ethanol at the path it names; eval 33 needs a PDB file with a protein chain and a benzamidine ligand (BEN) at the path it names; eval 34 needs butane drawn; evals 36 to 40 need an SD file of a few hundred structures, one of them with a broken connection table, at the path eval 36 names, and evals 37 to 40 the database eval 36 makes; eval 44 needs ethanol drawn and eval 45 butane, and both should be run once with xtb and CREST installed and once without them.", "evals": [ { "id": 1, @@ -9,8 +9,8 @@ "files": [], "expected_behavior": [ "Calls get_context first", - "Says in plain words that an agent can make, open and save drawings, draw structures and reaction schemes from SMILES, molfiles or names, edit them atom by atom, read them back as SMILES, InChIKey, molfile or names, render and validate them, predict 1H and 13C NMR, open JCAMP-DX spectra and pick peaks, build structures in 3D with conformers, scans and measurements, open PDB files and extract ligands, convert files and run menu commands, each change one undo step", - "Names what is not there yet: typing stoichiometry amounts, quantum or tight-binding energies (no xtb or CREST)", + "Says in plain words that an agent can make, open and save drawings, draw structures and reaction schemes from SMILES, molfiles or names, edit them atom by atom, read them back as SMILES, InChIKey, molfile or names, render and validate them, predict 1H and 13C NMR, open JCAMP-DX spectra and pick peaks, build structures in 3D with conformers, scans and measurements, open PDB files and extract ligands, keep structure databases (import, search, register, export) and lab notebook entries, keep the shared structure library and live structures for other Form apps, draw peptides and nucleic acids from HELM, run xtb and CREST when the person installed them, convert files and run menu commands, each change one undo step", + "Names what is not there yet: typing stoichiometry amounts, DFT or any quantum method beyond the person's own xtb, signing notebook entries (only the person signs)", "Does not run any command or post a handoff for a question that only asks" ] }, @@ -404,6 +404,125 @@ "Does not claim to see the 3D View; says the panel shows it and that render shows only a stored picture", "Ends with a handoff naming what the person will see" ] + }, + { + "id": 36, + "name": "import-sd-into-new-database", + "prompt": "Make a FormChem database called Screening and load /tmp/fc-evals/screen.sdf into it. Tell me if anything failed.", + "files": [], + "expected_behavior": [ + "Calls db_list or get_context, then db_create {title: \"Screening\"} and keeps the handle it returns", + "Calls db_import with dry_run true before the real import, and reports the counts it gives", + "Runs db_import without dry_run and quotes added, updated and failed as returned", + "Names each failed record by its number in the file with the reason the job gives, and does not claim the import failed as a whole" + ] + }, + { + "id": 37, + "name": "benzene-substructure-and-export", + "prompt": "In my Screening database in FormChem, find every compound with a benzene ring and save them to /tmp/fc-evals/benzene-hits.sdf.", + "files": [], + "expected_behavior": [ + "Calls db_search with smiles c1ccccc1 and mode substructure (or the default mode)", + "Quotes the hit list id, its name and the count and time as returned, and says the hit list also shows in the person's window", + "Calls db_export with format sdf, that hitlist id and the absolute path, and quotes the written count, which equals the hit count", + "Does not page through rows with db_get_record to build the file itself" + ] + }, + { + "id": 38, + "name": "similar-compounds-with-scores", + "prompt": "Which compounds in the Screening database are most like 4-methylbenzoic acid? Only ones that are really close.", + "files": [], + "expected_behavior": [ + "Calls db_search with the SMILES of 4-methylbenzoic acid (Cc1ccc(cc1)C(=O)O or equivalent), mode similarity and a threshold of 0.7 or higher", + "Lists the hits with the score each row carries and names the method (Tanimoto on Morgan fingerprints) as the answer gives it", + "Does not invent scores or rank hits by its own judgement against the returned scores", + "Says how many hits there were and that a lower threshold would find more" + ] + }, + { + "id": 39, + "name": "register-a-duplicate", + "prompt": "Add ethylamine hydrochloride to the Screening database in FormChem.", + "files": [], + "expected_behavior": [ + "Calls db_add_record with smiles CCN.Cl (or equivalent) and no on_duplicate", + "When the answer lists duplicates (ethylamine under salt stripping), shows them and asks the person whether to use the existing record, add a new batch or register anyway", + "Does not call db_add_record again with on_duplicate new on its own", + "When nothing matched, quotes the new record's number and uid" + ] + }, + { + "id": 40, + "name": "notebook-entry-from-reaction", + "prompt": "Record today's amide coupling in the Screening database notebook: benzoic acid and methylamine gave N-methylbenzamide, sample AC-001, 1.21 g, 89% yield. Then sign it.", + "files": [], + "expected_behavior": [ + "Calls nb_add_entry with db, a title, the reaction template, reaction OC(=O)c1ccccc1.CN>>CNC(=O)c1ccccc1 (or equivalent) and a product with sample AC-001, mass_g 1.21 and yield_pct 89", + "Quotes the entry number, uid and the stoichiometry with its method as returned", + "Does not sign the entry and does not call it signed; tells the person that signing is theirs (Sign Notebook Entry... in the window)", + "Can find the entry afterwards with nb_search by AC-001 or by the substructure NC=O" + ] + }, + { + "id": 41, + "name": "oxytocin-from-helm", + "prompt": "Draw oxytocin in FormChem from HELM, with its disulfide, and give me the formula and monoisotopic mass.", + "files": [], + "expected_behavior": [ + "Calls draw_from_helm with PEPTIDE1{C.Y.I.Q.N.C.P.L.G.[am]}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$V2.0 or an equivalent HELM string with the 1:R3-6:R3 connection", + "Quotes C43H66N12O12S2 and the monoisotopic mass (1006.436458) with the method the answer names", + "Checks the result with get_structure or render, or quotes the InChIKey XNOPRXBHLZRZKH-DSZYJQQASA-N from the answer", + "Does not draw oxytocin atom by atom or from a SMILES it wrote itself" + ] + }, + { + "id": 42, + "name": "helm-refusal", + "prompt": "Draw PEPTIDE1{A.X.G}$$$$ in FormChem.", + "files": [], + "expected_behavior": [ + "Calls draw_from_helm once and reports the refusal with the character where reading stopped and the reason (X is not a PEPTIDE monomer FormChem knows)", + "Does not guess what X was meant to be or retry with invented monomers; asks the person, or offers inline SMILES for a non-standard residue", + "Reports that nothing was drawn" + ] + }, + { + "id": 43, + "name": "star-and-hand-to-sibling", + "prompt": "Put caffeine in the shared structure library as a live structure and give me the object FormDeck needs.", + "files": [], + "expected_behavior": [ + "Calls library_add with smiles Cn1cnc2c1c(=O)n(C)c(=O)n2C (or the drawing) and kinds [\"live\"]", + "Quotes the item id, kinds, formula C8H10N4O2 and rev 1 from the answer", + "Calls live_structure_object with that id and passes the object on as returned, without editing its svg", + "Does not claim that FormDeck was updated or opened" + ] + }, + { + "id": 44, + "name": "xtb-water-optimisation", + "prompt": "Optimise the drawn ethanol with GFN2-xTB in water and tell me the energy.", + "files": [], + "expected_behavior": [ + "Calls xtb_optimise with method gfn2 (or default) and solvent water on the ethanol structure", + "Quotes the total energy in hartree and kcal/mol, the HOMO-LUMO gap and the program label with version, method and solvent, as returned", + "If xtb is not installed, reports the tool's answer with where to get xtb, does not retry, and does not present an MMFF94 energy as an xtb result", + "Does not call the energy a measured or DFT value" + ] + }, + { + "id": 45, + "name": "crest-not-installed", + "prompt": "Run a CREST conformer search on the butane I drew and keep the 5 lowest.", + "files": [], + "expected_behavior": [ + "Calls crest_conformers with keep 5 (and a time limit if it sets one)", + "When CREST is missing, tells the person FormChem does not include or download CREST and where to get it, as the answer says, and stops", + "When CREST runs, quotes the relative energies and populations with the program label and how many conformers were dropped for lost stereo", + "Offers conformers_3d with MMFF94 only as a clearly named alternative, after asking" + ] } ], "trigger_evals": [ @@ -473,6 +592,22 @@ {"query": "export the 3D coordinates of my formchem structure as an SDF with every conformer", "should_trigger": true}, {"query": "add a new force field to formchem's services/three_d/forcefield.py", "should_trigger": false}, {"query": "write an RDKit script that embeds and minimises conformers for a list of SMILES", "should_trigger": false}, - {"query": "render this PDB entry as a cartoon in PyMOL", "should_trigger": false} + {"query": "render this PDB entry as a cartoon in PyMOL", "should_trigger": false}, + {"query": "load my SD file of 10,000 compounds into a FormChem database and tell me which records failed", "should_trigger": true}, + {"query": "search my formchem compound database for everything containing a pyridine ring", "should_trigger": true}, + {"query": "find analogues of this hit in the FormChem database with Tanimoto above 0.8", "should_trigger": true}, + {"query": "is this compound already registered in my formchem database", "should_trigger": true}, + {"query": "write up today's experiment as a notebook entry in FormChem with the yield", "should_trigger": true}, + {"query": "add a new query term kind to formchem's services/database/query.py", "should_trigger": false}, + {"query": "run a similarity search over ChEMBL with chemfp", "should_trigger": false}, + {"query": "set up an electronic lab notebook in Benchling for my group", "should_trigger": false}, + {"query": "draw this HELM peptide in formchem: PEPTIDE1{A.C.D.E}$$$$", "should_trigger": true}, + {"query": "optimise my molecule with GFN2-xTB in DMSO using FormChem", "should_trigger": true}, + {"query": "star this structure in formchem so FormTxt can insert it", "should_trigger": true}, + {"query": "give me the live structure object for library item s4k2m9x0qa from FormChem", "should_trigger": true}, + {"query": "run CREST through formchem on the drawn macrocycle and keep 10 conformers", "should_trigger": true}, + {"query": "install xtb with conda on my laptop", "should_trigger": false}, + {"query": "convert a HELM string to SMILES with the Pistoia HELM toolkit in Java", "should_trigger": false}, + {"query": "add a new HELM monomer to formchem's helm_monomers.json data file", "should_trigger": false} ] } diff --git a/.claude/skills/formchem-harness/SKILL.md b/.claude/skills/formchem-harness/SKILL.md index 2235c344..29ac1268 100644 --- a/.claude/skills/formchem-harness/SKILL.md +++ b/.claude/skills/formchem-harness/SKILL.md @@ -1,21 +1,21 @@ --- name: formchem-harness -description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: draw a structure or reaction from SMILES, a molfile or a chemical name, build or edit it atom by atom, check the drawing with render, get_structure or validate, name a structure, predict a 1H or 13C NMR spectrum, open a JCAMP-DX spectrum, pick peaks or integrate, build it in 3D, find conformers, minimise, scan a dihedral or measure a bond length, open a PDB file or extract a ligand, convert files, open or save drawings, run a menu command, perceive a reaction, get cLogP, hand off, or asks what FormChem can do, and FormChem is named or its tools (draw_from_smiles, draw_from_name, predict_nmr, build_3d, render, get_atoms, run_command, handoff and the rest) are available. Covers 127.0.0.1:8220, the agent token, approval and Stop. Not for changing FormChem's source (formchem-skillset), other Form apps such as FormDeck, or standalone RDKit scripts." +description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: draw a structure or reaction from SMILES, a molfile, a chemical name or HELM, edit it atom by atom, check it with render, get_structure or validate, predict a 1H or 13C NMR spectrum, open a JCAMP-DX spectrum, build it in 3D, find conformers, run xtb or CREST, open a PDB file or extract a ligand, search a compound database by substructure or similarity, import an SD file, register a compound, add a notebook entry, put a structure in the shared library, convert files, run a menu command, or asks what FormChem can do, and FormChem is named or its tools (draw_from_smiles, build_3d, db_search, library_add, draw_from_helm, render, run_command and the rest) are available. Covers 127.0.0.1:8220, the agent token, approval and Stop. Not for changing FormChem's source (formchem-skillset), other Form apps such as FormDeck, or standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.10.0" + version: "0.12.0" --- # FormChem harness FormChem is a chemical structure drawing suite running on this computer. Its MCP server (`formchem`) lives in the engine and reaches the FormChem window, where the person sees everything an agent does. This pack is the method for using it well: draw with the tools, check what you drew, and hand back. -## What exists today (0.10.0) +## What exists today (0.12.0) -FormChem has drawings (`.fchem` documents kept by the engine with undo, autosave and versions), an RDKit chemistry service that computes SMILES, InChIKey, formula, masses, CIP labels and valence warnings after every change, and a 2D canvas the person draws on. Earlier versions added reactions and annotations (0.5.0), stereo, queries and analysis (0.6.0), formats, pictures, the clipboard, Standardise, the command line, the dark page, scaling and grids (0.7.0), the agent tools (0.8.0), and names, NMR prediction (FormChem increments) and JCAMP-DX spectra (0.9.0). +FormChem has drawings (`.fchem` documents kept by the engine with undo, autosave and versions), an RDKit chemistry service that computes SMILES, InChIKey, formula, masses, CIP labels and valence warnings after every change, and a 2D canvas the person draws on. Earlier versions added reactions and annotations (0.5.0), stereo, queries and analysis (0.6.0), formats, pictures, the clipboard, Standardise and the command line (0.7.0), the agent tools (0.8.0), names, NMR prediction and JCAMP-DX spectra (0.9.0), 3D: builds with the stereo checked, conformers, scans, measurements, PDB and mmCIF files and ligands (0.10.0), and structure databases with the lab notebook (0.11.0). -0.10.0 adds 3D: conformers built from the drawing with the stereo checked, conformer searches, minimisation and dihedral scans with RDKit's force fields, measurements, the 3D View and 3D objects on the page, PDB and mmCIF files with ligand extraction, and 3D exports. The MCP server has 60 tools; `references/tools.md` lists every argument and is generated from the server. +0.12.0 adds the shared structure library every Form app reads, live structures (a picture with the drawing inside that sibling apps keep and send back for editing), HELM in and out, xtb and CREST run when the person installed them, keyboard and screen reader access, and element palettes. The MCP server has 77 tools; `references/tools.md` is generated from the server and lists all of them; the library and HELM tools are in `sub-skills/library-and-biopolymers` and the xtb tools in `sub-skills/three-d`. | Group | Tools | | --- | --- | @@ -27,12 +27,15 @@ FormChem has drawings (`.fchem` documents kept by the engine with undo, autosave | Names (0.9.0) | `draw_from_name` (a common or systematic name, read offline), `name_structure` (common and round-trip-checked systematic names) | | NMR and spectra (0.9.0) | `predict_nmr`, `predict_spectrum`; `open_spectrum` (JCAMP-DX), `spectrum_data`, `spectrum_peaks`, `spectrum_pick_peaks`, `spectrum_integrate`, `spectrum_export` | | 3D (0.10.0) | `build_3d`, `conformers_3d`, `minimise_3d`, `scan_dihedral`, `measure_3d`; `open_3d_structure` (PDB, mmCIF, SDF, MOL), `extract_ligand`, `export_3d` | +| Databases and notebook (0.11.0) | `db_list`, `db_create`, `db_open`, `db_import`, `db_search`, `db_get_record`, `db_add_record`, `db_update_record`, `db_export`; `nb_add_entry`, `nb_search` | +| Library and HELM (0.12.0) | `library_list`, `library_add`, `live_structure_object`; `draw_from_helm` | +| xtb and CREST (0.12.0) | `xtb_optimise`, `crest_conformers` (only when the person installed the programs) | | Window, extensions, handoff | `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff` | | Reactions (0.5.0) and analysis (0.6.0) | `perceive_reactions`, `map_reaction`, `export_reaction`, `reaction_stoichiometry`, `properties`, `check_structure`, `stereo`, `substructure` | Every change an agent makes is one transaction and one undo step, labelled with the tool in the person's Edit > Undo, and every change answers with the structure it now holds (ids, SMILES, InChIKey, formula, warnings) and a PNG of it. The person sees which agent is editing in the title bar, with a Stop button, and Window > Agent Activity lists every call with undo for the latest one. -Every name and computed number carries its method and version (FormChem names 0.9.0, FormChem increments 0.9.0, `ETKDGv3+MMFF94 (rdkit 2025.09.3)`); quote them with the value, and never present a prediction or a force-field energy as measured. What still is not there: names the offline engine refuses (hydro prefixes, spiro and bridged rings, peptides; use SMILES), a tool that links peaks to atoms (the window command does) or inserts a spectrum file into an existing drawing, typing amounts into the Stoichiometry panel, tools for 3D styles and surfaces (the window commands do), and any quantum or tight-binding method (no xtb or CREST). The export and copy commands still hand their file to the person, not to the agent; use `convert` or `get_structure` for text you can read. Never draw by other means and present it as FormChem's work. +Every name and computed number carries its method and version (FormChem names 0.9.0, FormChem increments 0.9.0, `ETKDGv3+MMFF94 (rdkit 2025.09.3)`, similarity scores with their fingerprint, `xtb 6.7.1, GFN2-xTB, ALPB (Water)`); quote them with the value, and never present a prediction or a computed energy as measured. What still is not there: names the offline engine refuses (hydro prefixes, spiro and bridged rings; peptides go through HELM), a tool that links peaks to atoms (the window command does) or inserts a spectrum file into an existing drawing, typing amounts into the Stoichiometry panel, tools for 3D styles and surfaces (the window commands do), DFT or any quantum method beyond the person's own xtb, a tool that returns HELM text or describes a structure in words (window commands `copy-helm` and `a11y-describe` do), and database fields, saved queries, attachments or signing for agents (the window does them). The export and copy commands still hand their file to the person, not to the agent; use `convert` or `get_structure` for text you can read. Never draw by other means and present it as FormChem's work. ## Doctrine (applies to every route) @@ -49,7 +52,7 @@ Every name and computed number carries its method and version (FormChem names 0. ``` formchem-harness/ SKILL.md this router and the doctrine - references/tools.md the 60 MCP tools and their arguments (generated by ./formchem agents sync) + references/tools.md 71 of the 77 tools and their arguments (generated by ./formchem agents sync) EVALS.json evaluation prompts and trigger tests for this pack sub-skills/ session-and-connection/ connecting, the agent token, get_context, approval, Stop, connection errors @@ -57,7 +60,9 @@ formchem-harness/ edit-by-id/ get_atoms and the 14 edit tools: atoms, bonds, charges, stereo, groups, arrows, text visual-qa/ render, get_structure, validate and compute_properties to check your own work names-and-spectra/ draw_from_name, name_structure, predict_nmr, predict_spectrum and the spectrum tools - three-d/ build_3d, conformers, minimise, scans, measure, PDB files, ligands, 3D export and checks + three-d/ build_3d, conformers, minimise, scans, measure, PDB files, ligands, 3D export, xtb and CREST + databases/ the db_ and nb_ tools: import, search, register, export, notebook entries + library-and-biopolymers/ the shared structure library, live structure objects, draw_from_helm handoff/ handoff states and notes, what the person sees, Agent Activity window-commands/ the window's commands through run_command; references/command-catalogue.md reactions/ reaction schemes, the four reaction tools, Set Reaction Roles @@ -87,7 +92,12 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | Make it 3D, its conformers or lowest-energy shape, minimise, a torsion scan, a bond length or angle in 3D, does the 3D keep the stereo | `three-d`, then `visual-qa` | | Open this PDB or mmCIF file, pull out the ligand, save 3D coordinates as SDF, PDB or XYZ | `three-d` | | Show it in 3D, ball and stick, a surface, ESP, a 3D picture or glTF for the person | `three-d`, then `window-commands` | -| Type amounts into the Stoichiometry panel, xtb or quantum energies | Not yet: say so, or ask the person | +| Load an SD or CSV file into a database, search compounds by substructure or similarity, is it already registered, export the hits | `databases` | +| Register this compound, add a batch, update a record's values, record this experiment in the notebook, find my amide couplings | `databases` | +| A GFN2-xTB or GFN-FF energy, optimise with xtb in water, a CREST conformer ensemble | `three-d` | +| Star this, save it as a template, put it into FormDeck or FormTxt as a live structure, list the structure library, the object for a sibling app | `library-and-biopolymers` | +| Draw oxytocin or a peptide from HELM, an RNA strand, a disulfide or head-to-tail cyclic peptide | `library-and-biopolymers`, then `visual-qa` | +| Type amounts into the Stoichiometry panel, DFT energies, sign a notebook entry, add a database field | Not yet for agents: say so, or ask the person | | Change FormChem's own code, add an MCP tool, edit this pack | Not this pack: `formchem-skillset` | ## When something fails @@ -115,6 +125,15 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | "No 3D coordinates yet" or "has no conformer" | The structure was never built, or an edit dropped its conformers | `build_3d`, then retry | | "The structure changed while 3D was being computed" (409) | Someone edited the structure during the build | Retry once; if it repeats, the person is editing: ask them | | `extract_ligand` refuses, or answers "inferred from the geometry" | The object is not a PDB or mmCIF model; or the ligand is outside the template table | Pass the model's `o...` id from `open_3d_structure`; say the bond orders were inferred and show the SMILES | +| "No database is open" or "Several databases are open" | No handle given | `db_list`, then `db_open {path}` or pass `db` | +| `db_add_record` error listing duplicates | The structure is there by the database's stereo and salts rules | Show the matches; call again with the `on_duplicate` the person chooses | +| "open read-only" or 423 on a write | Another FormChem or `./formchem db` holds the file | Report the reason; read and search only | +| `failed` records in a `db_import` job | Bad records were skipped, the rest imported | Pass on each record number and reason | +| xtb or CREST "was not found" from `xtb_optimise` or `crest_conformers` | The person has not installed it, or its path is wrong; FormChem never ships it | Tell the person where to get it (the answer says); do not retry | +| "unpaired electrons" or parity refusal from an xtb tool | Charge and `uhf` cannot match the electron count | Fix `charge` or `uhf` once from the structure, or ask | +| An xtb job "timeout" or "failed" with the last lines | The time limit stopped it, or the program failed | Pass on the last lines; offer a larger `limit` or GFN-FF | +| `draw_from_helm` refused "at character N" | Unknown monomer, mixture, BLOB or a typo | Fix an obvious typo once; else inline SMILES for the monomer, or report | +| "has no item" from a library tool | Wrong id, or the item was deleted | `library_list`, then use an id it returns | | `renderer: "engine"` in a picture | No window answered; the engine drew the structures only | Fine for checking structures; say arrows and text were not drawn, or ask the person to open the window | When a call keeps failing in a way this table does not explain, call the same tool once with the simplest arguments (`get_context`, then `draw_from_smiles {smiles: "C"}`). If that fails too, the problem is the server or the connection, not the plan: report it to the person with the error text. @@ -125,6 +144,8 @@ When a call keeps failing in a way this table does not explain, call the same to - Every structure the agent drew was checked: the write result's SMILES or InChIKey matched what was asked, and anything about how it looks was confirmed with `render`. - Nothing was claimed that a tool did not say; values were quoted from tool answers, names, predicted shifts, energies and 3D measurements with their method and version. - Every 3D geometry used was from a build whose stereo line said every label was kept. +- Database counts, hit list ids and scores were quoted from the answers, no duplicate was registered as new without the person's choice, and no notebook entry was called signed. +- Every xtb or CREST number came with its program label, and library items and live objects were passed on by id and rev exactly as returned. - Every change was one call and one undo step, and none was retried after a refusal or a stop. - The work ends with a `handoff` (`ready` with a note, or `question` with the question). diff --git a/.claude/skills/formchem-harness/references/tools.md b/.claude/skills/formchem-harness/references/tools.md index ddf0065c..23466773 100644 --- a/.claude/skills/formchem-harness/references/tools.md +++ b/.claude/skills/formchem-harness/references/tools.md @@ -1,6 +1,6 @@ # FormChem MCP tools -Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 60 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. +Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py` and the agent modules in its AGENT_MODULES; edit the server, never this file. 77 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked. @@ -67,6 +67,23 @@ Read-only tools never ask the person. An approval-gated tool asks the person in - open_3d_structure - extract_ligand - export_3d +- db_list +- db_create +- db_open +- db_import +- db_search +- db_get_record +- db_add_record +- db_update_record +- db_export +- nb_add_entry +- nb_search +- library_list +- library_add +- live_structure_object +- draw_from_helm +- xtb_optimise +- crest_conformers - Resource | Tool | Kind | @@ -131,6 +148,23 @@ Read-only tools never ask the person. An approval-gated tool asks the person in | `open_3d_structure` | approval-gated | | `extract_ligand` | approval-gated | | `export_3d` | approval-gated when it changes something | +| `db_list` | read-only | +| `db_create` | approval-gated when it changes something | +| `db_open` | approval-gated when it changes something | +| `db_import` | approval-gated when it changes something | +| `db_search` | read-only | +| `db_get_record` | read-only | +| `db_add_record` | approval-gated when it changes something | +| `db_update_record` | approval-gated when it changes something | +| `db_export` | approval-gated when it changes something | +| `nb_add_entry` | approval-gated when it changes something | +| `nb_search` | read-only | +| `library_list` | read-only | +| `library_add` | approval-gated when it changes something | +| `live_structure_object` | read-only | +| `draw_from_helm` | approval-gated when it changes something | +| `xtb_optimise` | approval-gated when it changes something | +| `crest_conformers` | approval-gated when it changes something | ## get_context @@ -791,6 +825,213 @@ Writes the 3D coordinates of a structure with every hydrogen as MOL (the shown c | `conformer` | string | no | Conformer id, or all; default all for sdf, else the shown one | | `output` | string | no | Absolute path of a new file to write; left out, the text comes back | +## db_list + +The structure databases open in FormChem (handle, title, path, record count, read-only or not, fields) and the databases FormChem knows from earlier (path, name, count, whether the file still exists). Open one with db_open, make one with db_create. + +Arguments: none. + +## db_create + +Makes a new FormChem structure database (.fcdb, one SQLite file) and opens it. Without path it goes to the Databases folder of FormChem's data folder. Answers with its handle and info. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `title` | string | yes | | +| `path` | string | no | Absolute path of the new .fcdb file (optional) | + +## db_open + +Opens a FormChem database file (.fcdb) and answers with its handle, title, record count, fields and whether it opened read-only (it does when another FormChem holds it). + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `path` | string | yes | Absolute path of the .fcdb file | + +## db_import + +Imports structures from an SD, RD, SMILES, CSV or TSV (SMILES or InChI column) or .fchem file into a database as a job, and waits up to wait seconds (default 60) for it. Bad records never stop the import: the answer lists each failed record number and reason. dry_run counts what would be added, updated and failed without writing. mode new or append adds every good record; merge updates records that match on key (structure, or a field name) and adds the rest. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `path` | string | yes | Absolute path of the file to import | +| `format` | sdf or rdf or smiles or csv or tsv or fchem | no | | +| `mode` | new or append or merge | no | | +| `key` | string | no | Merge key: structure (default) or a field name | +| `mapping` | object | no | Source column or SD tag to field name, "" to skip, or "+Label" to make a new field; left out, the detected mapping is used | +| `dry_run` | boolean | no | | +| `wait` | number | no | Seconds to wait for the job (0 to 600, default 60); a job still running is reported with its id | + +## db_search + +Searches a database and answers with the hit list (id, name, count, took_ms, methods) and its first rows (uid, number, SMILES, formula, mw, field values, and score for similarity). Give smiles with mode (substructure, the default, similarity with threshold 0 to 1, or exact), or a full query node. within limits the search to an earlier hit list. Every search becomes a hit list the person sees in the window. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `smiles` | string | no | Structure to search with (or a SMARTS with mode substructure and smarts true) | +| `smarts` | boolean | no | Read smiles as SMARTS (substructure only) | +| `mode` | substructure or similarity or exact | no | | +| `threshold` | number | no | Similarity threshold, 0 to 1 (default 0.7) | +| `query` | object | no | A query node of docs/DATABASE.md: a term {kind, ...} with kind exact, substructure, similarity, formula, mass, text, number, date, choice, empty or hitlist, or a group {op: and | or | not, terms: [...]} | +| `within` | integer | no | Hit list id to search within | +| `name` | string | no | Name for the hit list | +| `limit` | integer | no | Rows to return (default 20, at most 100); the hit list holds them all | + +## db_get_record + +One record of a database by uid: number, batch, SMILES, InChIKey, formula, masses, molfile, field values and attachments. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `uid` | string | yes | Record uid (c plus 10 characters) | + +## db_add_record + +Registers a structure in a database with optional field values. When the structure is already there (by the database's duplicate rules) and on_duplicate is not given, nothing is added and the answer lists the duplicates: call again with on_duplicate existing (use the existing record), batch (a new batch of it) or new (register anyway). + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `smiles` | string | no | | +| `molfile` | string | no | | +| `values` | object | no | Field values by field name (see the fields of db_list or db_open), for example {"mp": 121.5, "supplier": "Acme"} | +| `on_duplicate` | ask or existing or batch or new | no | | + +## db_update_record + +Changes a record's structure, field values or both; computed fields follow the new structure. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `uid` | string | yes | Record uid | +| `smiles` | string | no | | +| `molfile` | string | no | | +| `values` | object | no | Field values by field name (see the fields of db_list or db_open), for example {"mp": 121.5, "supplier": "Acme"} | + +## db_export + +Writes records to an SD file (V2000, or V3000 when asked; every scalar field as a data item), a SMILES file or CSV: a hit list, a list of uids or the whole database. Without path the file goes to FormChem's export folder and the answer gives its path. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | no | Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open | +| `format` | sdf or smiles or csv | yes | | +| `path` | string | no | Absolute path of the file to write (optional) | +| `hitlist` | integer | no | | +| `uids` | array of string | no | | +| `fields` | array of string | no | Field names to include (default all) | +| `v3000` | boolean | no | | +| `structure_as` | smiles or inchi | no | Structure column of a CSV | + +## nb_add_entry + +Add a lab notebook entry to an open FormChem database. Give a title and, as known, the template (blank, reaction, analysis, purification), the experiment date (YYYY-MM-DD), author, procedure and observations in the notebook's plain markup (paragraphs separated by blank lines, '- ' bullets, **bold**, *italic*), tags, products, and the scheme as reaction SMILES or RXN text (reaction) or an open drawing id (doc). Answers the new entry's number and uid, its content hash and the stoichiometry computed from the scheme. The entry is open (not signed): only a person signs. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | yes | Database handle (g plus 8 characters) from db_list, db_create or db_open | +| `title` | string | yes | | +| `template` | blank or reaction or analysis or purification | no | | +| `date` | string | no | Experiment date YYYY-MM-DD (default today) | +| `author` | string | no | | +| `procedure` | string | no | Replaces the template's headings when given | +| `observations` | string | no | | +| `tags` | array of string | no | | +| `products` | array of object | no | | +| `reaction` | string | no | Reaction SMILES (A.B>>C) or RXN text for the scheme | +| `doc` | string | no | Open drawing id whose first page becomes the scheme, instead of reaction | + +## nb_search + +Search the lab notebook entries of an open FormChem database by text (title, procedure, observations, tags, sample ids; every word must appear) and by substructure (SMILES or SMARTS matched by RDKit against every structure in each entry's scheme). Give either or both; with neither, lists the newest entries. Answers the total and up to 20 rows (number, uid, title, date, status, tags), newest first. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `db` | string | yes | Database handle (g plus 8 characters) from db_list, db_create or db_open | +| `query` | string | no | Words to find | +| `substructure` | string | no | SMILES or SMARTS | +| `limit` | integer | no | Rows to return (default 20) | + +## library_list + +The shared structure library that every Form app reads (FORMCHEM_DATA_DIR/Library): items with id, name, kinds (favourite, recent, template, live), SMILES, InChIKey, formula, average mass, rev and file paths. Filter by kind. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `kind` | favourite or recent or template or live | no | Only items of this kind | + +## library_add + +Add a structure to the shared structure library as a favourite, template, recent or live item. Give a drawing (doc, optionally object ids) or a SMILES. Pictures are drawn by the engine with the FormChem drawing embedded. A structure already in the library gets the new kind instead of a copy (live items are always new). + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; left out with smiles, or when one drawing is open | +| `ids` | array of string | no | Object ids on the drawing's page to keep; default the whole first page | +| `smiles` | string | no | A SMILES to add instead of a drawing | +| `name` | string | no | | +| `kinds` | array of string | no | Default ["favourite"] | + +## live_structure_object + +The live structure object for a library item, the JSON a sibling Form app stores in its document (format formai-structure): id, rev, name, SMILES, InChIKey, the SVG picture with the FormChem drawing inside, the molfile and the size in points. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `id` | string | yes | Library item id (s and 10 letters or digits) | + +## draw_from_helm + +Draws a peptide, nucleic acid or linker written in HELM version 2 notation in a drawing, as atoms, with FormChem's scored 2D layout, placed in free space as one undo step. Reads simple polymers such as PEPTIDE1{A.G.C}, RNA1{R(A)P.R(U)} and CHEM1{[[*:1]CCO[*:2]]}, connections such as PEPTIDE1,PEPTIDE1,1:R3-6:R3 (disulfides, cyclisation) and empty group and annotation sections, against FormChem's own monomer data: the 20 amino acids and their D forms ([dA] and so on), [Aib], [Nle], [Orn], [Sar], [Hyp], [pE], the caps [ac] and [am], the sugars R and [dR], phosphate P and the bases A, C, G, U and T. With no drawing open it makes one. Returns the new ids, SMILES, InChIKey, formula, average and monoisotopic mass with their method and version, and a picture; text it cannot read is refused with the character where reading stopped. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `helm` | string | yes | HELM text, such as PEPTIDE1{C.Y.I.Q.N.C.P.L.G.[am]}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$V2.0 | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `x` | number | no | Left edge in points; left out: free space | +| `y` | number | no | Top edge in points; left out: free space | +| `name` | string | no | Name given to the new structure; left out, the HELM text (shortened) is used | + +## xtb_optimise + +Optimises the shown conformer of a structure with the xtb program (GFN2-xTB or GFN-FF, optional ALPB implicit solvent), or with single_point computes the energy without moving atoms, then stores the result as the structure's conformers as one undo step. A structure without 3D coordinates is built first (ETKDGv3+MMFF94). Answers with the total energy in hartree and kcal/mol, the HOMO-LUMO gap, whether the optimisation converged, and the program, version, method and solvent. Waits until xtb finishes or the time limit stops it. xtb and CREST are LGPL programs FormChem does not include or download: they run only when the person has installed them (on PATH or at the path set in Preferences > 3D); otherwise the tool says where to get them. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | Fragment id (or a 3D object bound to one); may be left out when the drawing has one structure | +| `method` | gfn2 or gfnff | no | gfn2 (GFN2-xTB, default) or gfnff (GFN-FF force field) | +| `charge` | integer | no | Total charge; default the sum of the drawn formal charges | +| `uhf` | integer | no | Unpaired electrons; default the drawn radicals | +| `solvent` | none or acetone or acetonitrile or aniline or benzaldehyde or benzene or ch2cl2 or chcl3 or cs2 or dioxane or dmf or dmso or ether or ethylacetate or furane or hexandecane or hexane or methanol or nitromethane or octanol or woctanol or phenol or toluene or thf or water | no | Implicit solvent (ALPB); default none, the gas phase | +| `single_point` | boolean | no | Energy only, no optimisation (default false) | +| `scope` | shown or all | no | The shown conformer (default for optimisation) or every stored conformer (default for single_point) | +| `level` | crude or sloppy or loose or lax or normal or tight or vtight or extreme | no | Optimisation convergence level (default normal) | +| `conformer` | string | no | Conformer id (c...) to start from; default the shown one | +| `threads` | integer | no | Threads; default the Preferences setting | +| `limit` | number | no | Time limit in seconds (default 600 for xtb, 3600 for CREST, at most 604800) | + +## crest_conformers + +Searches conformers of a structure with the CREST program (metadynamics with GFN2-xTB or GFN-FF, optional ALPB solvent) and replaces the structure's conformers with the ensemble within ewin kcal/mol, at most keep, as one undo step; the lowest becomes the shown one. Answers with relative energies and Boltzmann populations at 298.15 K, and the program, version, method and solvent. CREST can take minutes to hours; the tool waits until it finishes or the time limit stops it. xtb and CREST are LGPL programs FormChem does not include or download: they run only when the person has installed them (on PATH or at the path set in Preferences > 3D); otherwise the tool says where to get them. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | Fragment id (or a 3D object bound to one); may be left out when the drawing has one structure | +| `method` | gfn2 or gfnff | no | gfn2 (GFN2-xTB, default) or gfnff (GFN-FF force field) | +| `charge` | integer | no | Total charge; default the sum of the drawn formal charges | +| `uhf` | integer | no | Unpaired electrons; default the drawn radicals | +| `solvent` | none or acetone or acetonitrile or aniline or benzaldehyde or benzene or ch2cl2 or chcl3 or cs2 or dioxane or dmf or dmso or ether or ethylacetate or furane or hexandecane or hexane or methanol or nitromethane or octanol or woctanol or phenol or toluene or thf or water | no | Implicit solvent (ALPB); default none, the gas phase | +| `ewin` | number | no | Energy window in kcal/mol (default 6) | +| `keep` | integer | no | Most conformers kept, 1 to 200 (default 20) | +| `threads` | integer | no | Threads; default the Preferences setting | +| `limit` | number | no | Time limit in seconds (default 600 for xtb, 3600 for CREST, at most 604800) | + ## Resource `formchem://guide` (text/markdown): what exists in this version, the tools, asking the person and errors. diff --git a/.claude/skills/formchem-harness/sub-skills/databases/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/databases/SUB-SKILL.md new file mode 100644 index 00000000..95a0093d --- /dev/null +++ b/.claude/skills/formchem-harness/sub-skills/databases/SUB-SKILL.md @@ -0,0 +1,71 @@ +--- +name: databases +description: "Uses FormChem's 0.11.0 structure database and lab notebook tools: db_list, db_create, db_open (.fcdb files), db_import (SD, RD, SMILES, CSV, TSV, .fchem as a job with a failed-record report and dry runs), db_search (substructure, similarity with Tanimoto scores, exact match, formula ranges or a full query node, as a hit list the person sees), db_get_record, db_add_record (duplicate rules and on_duplicate), db_update_record, db_export (SD, SMILES, CSV), nb_add_entry (an unsigned entry with scheme and stoichiometry) and nb_search. Use when the person asks an agent to register compounds, load an SD file into a database, search a compound collection, find analogues or duplicates, export hits, or record an experiment in FormChem's notebook." +--- + +# Databases + +## Purpose + +Register, search, import and export compounds in FormChem structure databases, and keep lab notebook entries in them, so the person sees every hit list and entry in their window. Hands back the database handle, the counts and hit list ids as returned, the record and entry uids, and every refusal or failed record with its reason. + +## Preconditions + +`get_context` has been called (`session-and-connection`). `db_list`, `db_search`, `db_get_record` and `nb_search` never ask. `db_create`, `db_open`, `db_add_record`, `db_update_record` and `nb_add_entry` ask the person the first time; `db_import` unless `dry_run`; `db_export` only with a `path` outside the temporary folder. These tools are not in `references/tools.md` (its generator reads only the drawing tools); their arguments are here and in `docs/AGENTS.md`. + +## How a database is held + +A database is one `.fcdb` file. Opening it gives a handle `db` (`g` plus 8 characters); with exactly one database open the `db_` tools may leave `db` out, the `nb_` tools always need it. Records have a `uid` (`c` plus 10) that never changes and a registration `number` with a `batch`; entries have a `uid` (`n` plus 10) and a `number`. A database held by another FormChem or by `./formchem db` opens read-only: reads work, every write is refused with the reason. Every write is logged as `agent:[your name]` and shows in Agent Activity. + +## Workflow 1: find or make the database + +1. **Call `db_list`.** It gives the open databases (handle, title, count, fields, read-only) and the known ones (path, whether the file exists). +2. **Open or create:** `db_open {path}` with an absolute `.fcdb` path, or `db_create {title, path?}` (default the Databases folder of the data folder). Read the duplicate rules (`stereo` match or ignore, `salts` strip or keep) and the fields from the answer; they decide what counts as a duplicate and which `values` keys exist. + +## Workflow 2: import + +1. **Dry run first:** `db_import {path, dry_run: true}` counts what would be added, updated and failed without writing and without asking. +2. **Import:** the same call without `dry_run`. `mode` is `new` (default) or `append`; `merge` with `key` (`structure`, or a field name) updates matching records and adds the rest. `mapping` left out uses the detected one (SD tags and CSV columns to fields by name, new fields for the rest). +3. **Read the report.** `added`, `updated`, `failed`, and each failed record's number in the file and reason (the first 10 in the text). A bad record never stops an import; pass the failures on. A job still running after `wait` seconds (default 60) is reported with its id; the person sees its progress. + +## Workflow 3: search + +| Goal | Call | +| --- | --- | +| Contains a ring or group | `db_search {smiles, mode: "substructure"}`, or `smiles` as SMARTS with `smarts: true` | +| Analogues | `db_search {smiles, mode: "similarity", threshold: 0.7}`: Tanimoto on Morgan bits (radius 2, 2048); every row has a `score` | +| Is it already registered | `db_search {smiles, mode: "exact"}` (the database's stereo and salts rules) | +| Formula, mass, fields, combinations | `db_search {query}` with a node of `docs/DATABASE.md`: `{"op": "and", "terms": [{"kind": "formula", "formula": "C6-8N1"}, {"kind": "number", "field": "mw", "cmp": "<=", "value": 300}]}` | +| Narrow earlier hits | add `within: [hit list id]` | + +The answer gives the hit list `id`, `name`, `count`, `took_ms`, the methods with the RDKit version, and the first `limit` rows (default 20, at most 100). The hit list appears in the person's window; `db_export {hitlist}` writes all of it. Raising a similarity threshold never adds hits; quote scores as given. `db_get_record {uid}` gives one record with its molfile. + +## Workflow 4: register and update + +1. **Call `db_add_record {smiles or molfile, values?}`.** When the structure is already there by the rules, nothing is added and the error lists the duplicates (`structuredContent.duplicates`). +2. **Choose, or ask the person:** call again with `on_duplicate: "existing"` (use that record), `"batch"` (a new batch, same number) or `"new"` (a new number). Never pick `new` just to make the call succeed. +3. **Update:** `db_update_record {uid, smiles?, values?}`; computed fields follow the structure. `values` keys are field names from `db_open`, not labels. + +## Workflow 5: the notebook + +- **`nb_add_entry {db, title, template?, date?, author?, procedure?, observations?, tags?, products?, reaction? or doc?}`**: `reaction` is reaction SMILES (`A.B>>C`) or RXN; `doc` takes the first page of an open drawing as the scheme. Text uses the notebook markup (blank-line paragraphs, `- ` bullets, `**bold**`, `*italic*`). Products may link a record by `compound` uid with `sample`, `mass_g`, `yield_pct`, `purity_pct`; an unknown uid refuses the whole call and nothing is written. The answer gives the entry number and uid, its hash and the stoichiometry with its method. +- **`nb_search {db, query?, substructure?}`**: every word must appear in title, procedure, observations, tags or sample ids; `substructure` (SMILES or SMARTS) matches the structures in each scheme. Newest first. +- Entries from agents stay open. Only the person signs; never say an entry is signed or approved. + +## Rules + +- **Counts and scores are quoted, not estimated.** Hit counts, times, scores and import counts come from the answers, with the method where given. +- **The person owns duplicates and signatures.** Ask before registering a duplicate as new; never claim an entry is signed. +- **Read-only is an answer.** A refused write on a read-only database is reported with its reason, not retried. +- **Dry run before a large import or merge,** and report the failed records. + +## Gate + +- [ ] The database handle and its rules were read before any write. +- [ ] Every import reported added, updated and failed, with the failed records' numbers and reasons. +- [ ] Every search result quoted the hit list id, the count and, for similarity, the scores. +- [ ] No duplicate was registered as new without the person's choice, and no entry was described as signed. + +## Hands back + +The database handle and path; hit list ids with counts; record and entry uids and numbers; import and export counts and paths; every refusal and failed record as returned. diff --git a/.claude/skills/formchem-harness/sub-skills/library-and-biopolymers/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/library-and-biopolymers/SUB-SKILL.md new file mode 100644 index 00000000..d65e3323 --- /dev/null +++ b/.claude/skills/formchem-harness/sub-skills/library-and-biopolymers/SUB-SKILL.md @@ -0,0 +1,56 @@ +--- +name: library-and-biopolymers +description: "Uses FormChem's 0.12.0 shared structure library and HELM tools: library_list (favourites, recent, templates and live items every Form app reads), library_add (a drawing or SMILES as a favourite, template, recent or live item with pictures that keep the drawing inside), live_structure_object (the formai-structure JSON a sibling app stores) and draw_from_helm (peptides, nucleic acids and linkers from HELM 2 as atoms, one undo step, with formula and masses). Use when the person asks an agent to star or save a structure for the other Form apps, put a structure into FormDeck, FormTxt or form.md as a live structure, list the structure library, hand a sibling app its object, or draw oxytocin, a cyclic peptide, a disulfide-bridged peptide or an RNA or DNA strand from HELM in FormChem." +--- + +# Library and biopolymers + +## Purpose + +Keep structures in the shared structure library that every Form app reads, hand sibling apps the live structure object, and draw biopolymers written in HELM, so the person sees each structure in their window and in the library. Hands back library item ids with their kinds and revisions, the object's id and rev, and for HELM the new fragment ids with formula, masses and their method. + +## Preconditions + +`get_context` has been called (`session-and-connection`). `library_list` and `live_structure_object` never ask; `library_add` and `draw_from_helm` ask the person the first time. These tools are not in the pack root's `references/tools.md` at 0.12.0 (its generator cannot read their modules yet); their arguments are here and in `docs/AGENTS.md`. + +## How the library is held + +The library is plain files in the data folder: `Library/library.json` and, per item, an SVG and a 512 pixel PNG (both with the FormChem drawing inside) and a molfile. Items have an `id` (`s` plus 10 lower-case letters or digits) that is never reused, `kinds` (any of `favourite`, `recent`, `template`, `live`), a `rev` that rises on every change, and SMILES, InChIKey, formula and average mass with the method that computed them. An item with no kinds left is deleted. Sibling apps read the folder without FormChem running; only FormChem writes it. The contract is `docs/LIVE_STRUCTURES.md` in the FormChem repository. + +## Workflow 1: add to the library + +1. **Call `library_add`** with `smiles` (no drawing needed), or with `doc` and optionally `ids` (objects of the drawing's page; default the whole first page). `doc` may be left out only when exactly one drawing is open. `kinds` defaults to `["favourite"]`; `name` names the item. +2. **Read the answer.** It names the item id, kinds, formula, average mass with its method, and rev. A non-live structure already in the library gains the kind instead of becoming a second item; a `live` add is always a new item, so two sibling documents never share an id. +3. **Pictures** come from the engine (RDKit) with the drawing embedded when an agent adds the item; items the person adds in the window carry the window's own pictures. Either way the drawing inside is complete. + +## Workflow 2: list and hand out + +- `library_list {kind?}` lists items (the text shows the first 40) with the folder path. +- `live_structure_object {id}` returns the JSON a sibling app keeps in its document: `format` `formai-structure`, `format_version` 1, `id`, `rev`, `app`, `name`, `kind`, `smiles`, `inchikey`, `svg` (the picture, drawing inside), `molfile`, `width` and `height` in points. Give it to a sibling app as returned; never edit the SVG, because the drawing inside it is what makes the structure editable again. +- Opening an item for editing is the person's, a sibling's or `./formchem edit-live ID`'s act; from an agent, `run_command {id: "open-live-structure", params: {id, from}}` asks the window to do it. Saving that drawing (the person's Save) raises the item's rev. + +## Workflow 3: draw from HELM + +1. **Call `draw_from_helm {helm, doc?, x?, y?, name?}`** with HELM version 2 text: `PEPTIDE1{G.G}$$$$`, `RNA1{R(A)P.R(U)}$$$$`, or with connections `PEPTIDE1{C.Y.I.Q.N.C.P.L.G.[am]}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$V2.0` (oxytocin). With no drawing open it makes one. One undo step ("Draw from HELM"). +2. **Know the monomers.** FormChem's own 55: the 20 amino acids (one letter), their D forms `[dA]` and so on (no `[dG]`), `[Aib]`, `[Nle]`, `[Orn]`, `[Sar]`, `[Hyp]`, `[pE]`, caps `[ac]` (R2 only) and `[am]` (R1 only); RNA sugars `R` and `[dR]`, phosphate `P`, bases `A`, `C`, `G`, `U`, `T`. R3 sits on C, K, D, E and Orn side chains, for disulfide and lactam bridges. Anything else goes in as inline SMILES with numbered attachment points (`[[*:1]CCO[*:2]]`). +3. **Read the answer.** New ids, SMILES, InChIKey, formula, average and monoisotopic mass with the reader, monomer data version and RDKit version. Check it like any structure (`visual-qa`). +4. **A refusal names the character** where reading stopped (counted from 1) and why: "X is not a PEPTIDE monomer FormChem knows", mixtures in parentheses, BLOBs, repeat ranges, hydrogen-bond pairs, `?` attachment points. Fix an obvious typo once; otherwise report it. + +To turn a drawn peptide or nucleic acid back into HELM, use `run_command {id: "copy-helm"}` with it selected: FormChem copies HELM only when it reads back to the same InChIKey, and otherwise says which piece it could not match. There is no agent tool that returns HELM text. + +## Rules + +- **The drawing inside is the structure.** Never pass a sibling a picture without its embedded drawing, or an object with a hand-edited SVG. +- **Revisions only go up.** A lower or equal rev never overwrites the library; do not try to roll an item back by sending an old object. +- **Monomers are FormChem's.** Do not claim a monomer FormChem does not list; use inline SMILES and say so. +- **Methods travel with the numbers.** Quote masses with the method the answer names. + +## Gate + +- [ ] Every library item named by id with its kinds and rev as returned. +- [ ] Every HELM drawing checked with its InChIKey or formula from the answer, and every refusal reported with its character and reason. +- [ ] No object or picture was altered on the way to a sibling app. + +## Hands back + +Library item ids, kinds and revs; live structure objects as returned; HELM fragment ids, formula, masses and methods; refusals with their reasons. diff --git a/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md index 9c8d91bd..0836ac92 100644 --- a/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -52,5 +52,5 @@ Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tab ## Gate - [ ] `get_context` was the first call. -- [ ] The plan uses only the 60 tools in the pack root's `references/tools.md` and the commands and extensions they report. +- [ ] The plan uses only the 77 tools (the 71 in the pack root's `references/tools.md`, the library and HELM tools in `library-and-biopolymers` and the xtb tools in `three-d`) and the commands and extensions they report. - [ ] No change was attempted after a refusal or a stop, and the agent token never appeared in a reply or a note. diff --git a/.claude/skills/formchem-harness/sub-skills/three-d/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/three-d/SUB-SKILL.md index 01f82aa8..cb82ea98 100644 --- a/.claude/skills/formchem-harness/sub-skills/three-d/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/three-d/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: three-d -description: "Uses FormChem's 0.10.0 3D tools: build_3d (a conformer from the 2D drawing with ETKDGv3 and MMFF94, MMFF94s or UFF, with the stereo check), conformers_3d (an ensemble in an energy window with populations), minimise_3d, scan_dihedral (a relaxed scan with its barrier), measure_3d (distance, angle, dihedral), open_3d_structure (PDB, mmCIF, SDF, MOL), extract_ligand and export_3d (MOL, SDF, PDB, XYZ), plus the 3D window commands for styles, surfaces and PNG or glTF. Use when the person asks an agent to make a structure 3D, find its conformers or lowest-energy shape, minimise it, scan a torsion, measure a bond length or angle, open a PDB or mmCIF file, pull a ligand out of a protein, or save 3D coordinates in FormChem, and to check that a 3D geometry kept the drawn stereo." +description: "Uses FormChem's 0.10.0 3D tools: build_3d (a conformer from the 2D drawing with ETKDGv3 and MMFF94, MMFF94s or UFF, with the stereo check), conformers_3d (an ensemble in an energy window with populations), minimise_3d, scan_dihedral (a relaxed scan with its barrier), measure_3d (distance, angle, dihedral), open_3d_structure (PDB, mmCIF, SDF, MOL), extract_ligand and export_3d (MOL, SDF, PDB, XYZ), the 0.12.0 xtb_optimise and crest_conformers (xtb and CREST when the person installed them), plus the 3D window commands for styles, surfaces and PNG or glTF. Use when the person asks an agent to make a structure 3D, find its conformers or lowest-energy shape, minimise it, scan a torsion, measure a bond length or angle, open a PDB or mmCIF file, pull a ligand out of a protein, get a GFN2-xTB energy or a CREST ensemble, or save 3D coordinates in FormChem, and to check that a 3D geometry kept the drawn stereo." --- # Three-d @@ -11,11 +11,11 @@ Turn drawn structures into 3D geometry FormChem stores in the drawing, work on t ## Preconditions -`get_context` has been called (`session-and-connection`), and the structure is drawn (`drawing`, `edit-by-id`, `names-and-spectra`). `build_3d`, `conformers_3d`, `minimise_3d`, `open_3d_structure` and `extract_ligand` ask the person the first time; `scan_dihedral` only with `store: true`; `export_3d` only when it writes a file outside the temporary folder; `measure_3d` never asks. +`get_context` has been called (`session-and-connection`), and the structure is drawn (`drawing`, `edit-by-id`, `names-and-spectra`). `build_3d`, `conformers_3d`, `minimise_3d`, `open_3d_structure` and `extract_ligand` ask the person the first time; `scan_dihedral` only with `store: true`; `export_3d` only when it writes a file outside the temporary folder; `measure_3d` never asks; `xtb_optimise` and `crest_conformers` ask the first time. ## How 3D is held -A structure's 3D coordinates are its `conformers`, each with an id (`c...`), an energy in kcal/mol, a `method` (`ETKDG` when only embedded, `MMFF94`, `MMFF94s`, `UFF`, or `file` when read from a file) and `converged`; `conformer` names the shown one. Atoms are the fragment atom ids from `get_atoms`; a hydrogen is `a1:h0` (the first hydrogen of `a1`), an atom inside an expanded abbreviation `a5:x0`. Any later edit to the structure's atoms or bonds (element, charge, bond order, wedge, adding or deleting) removes its conformers in the same undo step; moves and colours keep them. So: finish editing, then build. +A structure's 3D coordinates are its `conformers`, each with an id (`c...`), an energy in kcal/mol, a `method` (`ETKDG` when only embedded, `MMFF94`, `MMFF94s`, `UFF`, `xtb` for an xtb or CREST result, or `file` when read from a file) and `converged`; an xtb conformer also carries `program` (name, version, method, solvent, charge, uhf, energy in hartree, gap); `conformer` names the shown one. Atoms are the fragment atom ids from `get_atoms`; a hydrogen is `a1:h0` (the first hydrogen of `a1`), an atom inside an expanded abbreviation `a5:x0`. Any later edit to the structure's atoms or bonds (element, charge, bond order, wedge, adding or deleting) removes its conformers in the same undo step; moves and colours keep them. So: finish editing, then build. ## Workflow 1: build and check @@ -35,6 +35,17 @@ A structure's 3D coordinates are its `conformers`, each with an id (`c...`), an MMFF94 energies compare conformers of one structure under one force field. They are not heats of formation and do not compare across structures, compositions or force fields. Say that when a person compares them. +## Workflow 3a: xtb and CREST (0.12.0) + +xtb and CREST are LGPL-3.0 programs FormChem never ships or downloads. They run only when the person has installed them (PATH, a conda environment, or the path in Preferences > 3D > Tight-Binding Programs). + +1. **Call `xtb_optimise {object, method?, solvent?, charge?, uhf?, single_point?, level?, limit?}`**. `method` is `gfn2` (GFN2-xTB, default) or `gfnff`; `solvent` is `none` or an ALPB key (`water`, `methanol`, `acetonitrile`, `dmso`, `ch2cl2`, `chcl3`, `thf`, `toluene` and the rest of xtb's 24). Charge defaults to the drawn formal charges, `uhf` to the drawn radicals; a pair that cannot match the electron count is refused before anything runs, with the reason. A structure with no conformer is built first (ETKDGv3+MMFF94). The tool waits (default limit 600 s) and stores the result as the structure's only conformer, one undo step. +2. **Call `crest_conformers {object, method?, solvent?, ewin?, keep?, limit?}`** for an ensemble: window 6 kcal/mol, at most 20 kept by default, limit 3600 s. CREST can take minutes to hours on anything flexible; set `limit` to what the person will wait for. Conformers that lost the drawn stereo are dropped and the answer counts them. +3. **Quote the label.** Every answer names the program, version, method and solvent ("xtb 6.7.1, GFN2-xTB, ALPB (Water)"), the total energy in hartree and kcal/mol, the HOMO-LUMO gap and whether the optimisation converged. Pass all of it on. +4. **Not installed** is an answer, not a failure to retry: the tool says where to get the program (https://github.com/grimme-lab/xtb, https://github.com/crest-lab/crest). Tell the person; never suggest FormChem can download it. Fall back to `conformers_3d` and `minimise_3d` only if the person agrees, and say the energies are then MMFF94. + +Tight-binding total energies are in hartree for one structure, charge and solvent model; compare them only between conformers or structures computed with the same method and solvent. An optimisation replaces the MMFF94 conformers, so earlier force-field numbers no longer belong to the drawing. + ## Workflow 3: protein files and ligands 1. **Call `open_3d_structure {path}`** with an absolute `.pdb`, `.ent`, `.cif` or `.mmcif` path. One undo step: a 3D object (`o...`) over the file kept byte for byte, cartoon for a protein, ligands ball and stick, waters hidden, the primary ligand focused. Read the chains, ligand keys (`A:ATP:301`) and the reader's warnings and pass them on. An `.sdf` or `.mol` opens as structures whose conformers are the file's coordinates (method `file`). @@ -52,13 +63,14 @@ MMFF94 energies compare conformers of one structure under one force field. They - **Method and version travel with the number.** Every energy, barrier, population and measurement names its force field and engine version as FormChem gave them. - **Stereo before geometry.** A build is usable only when its stereo line says every label was kept. - **Build after editing.** An edit to atoms or bonds drops the conformers; rebuild rather than reuse numbers from before the edit. -- **No quantum claims.** FormChem has no xtb, CREST or other quantum method; do not describe a force-field energy as anything more. +- **No quantum claims beyond xtb.** A force-field energy is only that. xtb and CREST are semiempirical tight binding, run only on the person's own installation; FormChem has no DFT or other quantum method. ## Gate - [ ] Every build reported its stereo line, and a lost label stopped the work with the reason. - [ ] Every energy, barrier and measurement was quoted from a tool answer with its method and engine version. - [ ] Inferred ligand bond orders and unspecified stereocentres were passed on to the person. +- [ ] Every xtb or CREST number carried its program label, and a missing program was reported with where to get it, not retried. - [ ] Each changing call was one undo step, and the handoff says what the person will see in the 3D View or on the page. ## Hands back diff --git a/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md index f18eede1..de8c9a18 100644 --- a/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md @@ -30,6 +30,8 @@ Most canvas commands act on the canvas selection. The agent sets the selection t | Draw from a name | Use `draw_from_name` (`names-and-spectra`). `run_command {id: "insert-name", params: {name}}` inserts it the window's way (centred like a template, selected); without `name` it opens Structure from Name for the person. `copy-name` puts the selection's name on the person's clipboard | | Spectrum commands: edit, pick peaks, integrate, link a peak, y axis, export, predict, refresh | Prefer the spectrum and NMR tools (`names-and-spectra`). The commands remain for what they add: `link-peak-to-atoms {object, peak, fragment, atoms}` (no tool links), `open-spectrum {path}` (inserts a file into the open drawing), `spectrum-y-mode {object, mode}`, `edit-spectrum` (opens the Spectrum editor for the person), `nmr-refresh` (with a predicted spectrum selected) | | Show it in 3D, change the 3D style or surface, put a 3D view on the page, save a 3D picture | Build and measure with the 3D tools (`three-d`). Then `view-3d` (opens the 3D View on the selection), `style-wire`, `style-stick`, `style-ballstick`, `style-spacefill`, `style-cartoon`, `surface-none`, `surface-vdw`, `surface-sas`, `surface-ses`, `surface-esp` (on only while the 3D View is open), `insert-3d-view` (a 3D object beside the selected structure), `export-3d-png {transparent}` and `export-gltf` (saved for the person). `export-3d-file {format, all}` saves MOL, SDF, PDB or XYZ for the person; `export_3d` gives the agent the text | +| Show the database, a view of it, its dialogs, or the notebook to the person | Work with the database tools (`databases`). Then `show-databases`, `db-view-table`, `db-view-gallery`, `db-view-form`, `db-view-plot`, `db-view-notebook`, `db-search {text}`, `db-import {path}`, `db-export`, `database-fields`, `database-settings` (the person's dialogs); `nb-sign-entry` asks the person to sign and is never run in their place | +| Copy a live structure for another Form app, open a library item for editing, HELM text of a drawn peptide, show the Structure Library or the Structure Summary, change the element colours | Library and HELM tools first (`library-and-biopolymers`). Then `copy-live-structure`, `open-live-structure {id, from}`, `copy-helm`, `structure-library {tab}`, `a11y-describe`, `element-palette-high-contrast` and its two siblings | | Stack or group objects | `bring-front`, `bring-forward`, `send-backward`, `send-back`, `group`, `ungroup` on the selection; off with "Select something on the canvas first" when nothing is selected | | Anything about the reaction in the drawing | Load `reactions` | | Undo the last change | `run_command {id: "undo"}`: one transaction, whoever made it | diff --git a/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md b/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md index 929cca42..2ef1d85c 100644 --- a/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md +++ b/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md @@ -1,6 +1,6 @@ # Commands that touch a drawing -The window's command registry, as far as it concerns drawings, for FormChem 0.10.0 (the commands of 0.7.0, plus `agent-activity` from 0.8.0, which opens Window > Agent Activity for the person, plus the name, spectrum and NMR commands of 0.9.0, plus the 3D commands of 0.10.0). From 0.8.0 the agent's own tools draw, edit, read back, render and convert; this page covers what the window's commands add. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. +The window's command registry, as far as it concerns drawings, for FormChem 0.12.0 (the commands of 0.7.0, plus `agent-activity` from 0.8.0, which opens Window > Agent Activity for the person, plus the name, spectrum and NMR commands of 0.9.0, the 3D commands of 0.10.0, the database and notebook commands of 0.11.0, and the library, live structure, HELM, xtb and accessibility commands of 0.12.0). From 0.8.0 the agent's own tools draw, edit, read back, render and convert; this page covers what the window's commands add. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. ## Contents @@ -14,6 +14,8 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.10 - Standardise and size on the sheet - Names, spectra and NMR prediction - 3D +- Databases and the notebook +- Library, live structures, HELM, xtb and accessibility - The canvas, the view and the grid - Registered but off until a later version - What no command does yet @@ -170,6 +172,45 @@ From 0.10.0, group `3D`. Building, conformers, minimising, scans, measuring, ope | `export-gltf` | | saves the 3D View as binary glTF (`.glb`) for the person (while the 3D View is open) | | `export-3d-file` | `format` (`mol`, `sdf`, `pdb`, `xyz`), `all` (every conformer) | saves the selected structure's 3D coordinates for the person, or a PDB or mmCIF model's original file; without `format` it opens the dialog. For text the agent reads, `export_3d` | +## Databases and the notebook + +From 0.11.0, groups `Database` and `Notebook`. Creating, opening, importing, searching, registering, exporting and notebook entries also have MCP tools (`databases`); prefer them, because they answer with the counts, ids and reasons. The commands show the person the database workspace and its dialogs. The search, import, export, plot, query and hit list commands are off until a database is open, and import and save query are off on a read-only one. + +| Command | Params | What it does | +| --- | --- | --- | +| `show-databases` | | shows or hides the database workspace (Shift+Mod+D) | +| `new-database`, `open-database`, `close-database` | | the New and Open Database dialogs for the person; close releases the database's lock. For an agent, `db_create` and `db_open` | +| `add-to-database` | | registers the selected structure, or the page as one record, in the current database; a duplicate opens the person's choice dialog. For an agent, `db_add_record` | +| `database-settings`, `database-fields` | | the person's dialogs for the title and duplicate rules, and for fields (no MCP tool changes fields) | +| `db-view-table`, `db-view-gallery`, `db-view-form`, `db-view-plot`, `db-view-notebook` | | shows the workspace in that view | +| `db-search` | `text` (optional) | puts the cursor in the workspace search box; with `text`, runs it as plain text (text fields, uid, formula, SMILES) and shows the hit list. Structure and query searches: `db_search` | +| `db-advanced-search`, `db-save-query`, `db-combine-hitlists` | | the query builder, Save Query and Combine Hit Lists dialogs for the person | +| `db-import` | `path` (absolute, optional) | opens the Import dialog, previewing `path` at once; the person maps and imports. For an agent, `db_import` | +| `db-export` | | opens the Export dialog for the person; for an agent, `db_export` | +| `nb-new-entry` | | the New Notebook Entry dialog; for an agent, `nb_add_entry` | +| `nb-sign-entry` | | asks the person to sign the shown entry with their name; never run it to sign on the person's behalf | +| `nb-export-entry` | `format` (`html` default, or `json`) | saves the shown entry for the person | +| `nb-save-scheme` | | saves the drawing opened with Edit Scheme back into its entry (on only while that drawing is active) | + +## Library, live structures, HELM, xtb and accessibility + +From 0.12.0. Adding to the library, the live structure object, drawing from HELM and the xtb and CREST runs also have MCP tools (`library-and-biopolymers`, `three-d`); prefer them, because they answer with ids, formulas and energies. The commands add the clipboard, the Structure Library dialog, opening a live drawing, HELM text out, and the person's accessibility views. + +| Command | Params | What it does | +| --- | --- | --- | +| `copy-live-structure` | | copies the selection (or the page) as a live structure: the picture with the drawing inside, the object, SMILES and molfile on the clipboard, and adds it to the library as live and recent. For an agent, `library_add {kinds: ["live"]}` and `live_structure_object` | +| `star-structure` | | adds the selection (or the drawing) to the library as a favourite. For an agent, `library_add` | +| `library-save-template` | `name` (asked when left out) | saves the selection (or the drawing) to the library as a template | +| `structure-library` | `tab` (`favourite`, `recent`, `template`, `live`) | opens the Structure Library dialog for the person | +| `open-live-structure` | `id` (required), `from` | opens a library item as a live drawing (the title shows the sibling); the person's Save then raises its rev. Answers "Opened live structure [id] rev [n] as drawing [doc]" | +| `insert-helm` | `helm` (optional) | with `helm`, inserts it as atoms, one undo step; without, opens the Biopolymer from HELM dialog. For an agent, `draw_from_helm` answers with the numbers | +| `copy-helm` | | copies the selected peptide or nucleic acid as HELM, only when it reads back to the same structure; with params from an agent it throws the reason instead of a toast | +| `xtb-optimise` | `method`, `single_point`, `charge`, `uhf`, `solvent`, `level`, `limit` | with params, runs xtb on the selected structure without the dialog and waits; without, the dialog. For an agent, `xtb_optimise` | +| `crest-conformers` | `method`, `charge`, `uhf`, `solvent`, `ewin`, `keep`, `limit` | the same for CREST. For an agent, `crest_conformers` | +| `a11y-focus-structure`, `a11y-next-atom`, `a11y-previous-atom` | | put the keyboard focus ring on the drawing and walk atoms, for the person (Alt+Mod+A, Alt+Mod+], Alt+Mod+[) | +| `a11y-describe` | | speaks and shows the Structure Summary (formula, name, rings, groups, stereo) for the person (Alt+Mod+S) | +| `element-palette-standard`, `element-palette-high-contrast`, `element-palette-colour-blind` | | the element colours on this device (checked items under View > Element Colours) | + ## The canvas, the view and the grid | Command | What it does | @@ -195,4 +236,4 @@ From 0.10.0, group `3D`. Building, conformers, minimising, scans, measuring, ope ## What no command does yet -Selecting particular atoms or objects, typing stoichiometry amounts, and filling the person's dialogs (atom list, R-group, abbreviation label). Drawing atoms, bonds, arrows and text at given positions, reading the structure back, rendering and converting are not commands: the 0.8.0 tools do them (`drawing`, `edit-by-id`, `visual-qa`). Reading a spectrum's points, its peaks or the predicted shifts as data is not a command either: the 0.9.0 tools do it (`names-and-spectra`). Nor is reading conformer energies, a scan profile or a 3D measurement as data, or 3D coordinates as text: the 0.10.0 tools do it (`three-d`). Picking atoms in the 3D View, choosing the shown conformer and running a scan from the dialog belong to the person. An installed extension with the `document` permission can also read and change the drawing (`extension-drawings`). +Selecting particular atoms or objects, typing stoichiometry amounts, and filling the person's dialogs (atom list, R-group, abbreviation label). Drawing atoms, bonds, arrows and text at given positions, reading the structure back, rendering and converting are not commands: the 0.8.0 tools do them (`drawing`, `edit-by-id`, `visual-qa`). Reading a spectrum's points, its peaks or the predicted shifts as data is not a command either: the 0.9.0 tools do it (`names-and-spectra`). Nor is reading conformer energies, a scan profile or a 3D measurement as data, or 3D coordinates as text: the 0.10.0 tools do it (`three-d`). Nor is reading database records, hit list rows or notebook entries as data: the 0.11.0 tools do it (`databases`). Nor is reading library items, live structure objects or xtb energies as data: the 0.12.0 tools do it (`library-and-biopolymers`, `three-d`). Picking atoms in the 3D View, choosing the shown conformer and running a scan from the dialog belong to the person. An installed extension with the `document` permission can also read and change the drawing (`extension-drawings`). diff --git a/.claude/skills/formchem-skillset/EVALS.json b/.claude/skills/formchem-skillset/EVALS.json index 3b0745e9..15b53e67 100644 --- a/.claude/skills/formchem-skillset/EVALS.json +++ b/.claude/skills/formchem-skillset/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-skillset", - "notes": "Run in a FormChem checkout at 0.10.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", + "notes": "Run in a FormChem checkout at 0.12.0 with CLAUDE.md present; evals 32 to 36 need no fixtures, and eval 35 must not install xtb. Expected behaviours are observable in the files read, the edits made and the commits.", "evals": [ { "id": 1, @@ -303,6 +303,108 @@ "Finds that SUFFIXES in backend/app/routers/files.py lacks .usdz (as it lacked .glb, .cif, .mmcif and .ent until 0.10.0) and adds it by hand", "Updates the extension list in docs/FORMATS.md and writes a backend HASHOUT entry" ] + }, + { + "id": 28, + "name": "new-database-field-type", + "prompt": "Add a 'range' field type to FormChem databases that holds a low and a high number, like a melting point range.", + "files": [], + "expected_behavior": [ + "Loads databases and reads docs/DATABASE.md before any code, and treats it as the contract", + "Edits the field table in DATABASE.md, schema.FIELD_TYPES with a raised FORMAT_VERSION and a migrate step, and FieldType in database-api.ts in the same change", + "Updates fields.py (_check_spec, coerce, detect, rebuild_view), exports.text_of, the type groups in query.py, columns.ts and the Fields dialog's type list", + "Checks by creating a scratch database under a scratch data folder, never ~/formchem" + ] + }, + { + "id": 29, + "name": "new-query-term", + "prompt": "I want FormChem database searches to find records by ring count, like 'rings between 2 and 4'.", + "files": [], + "expected_behavior": [ + "Loads databases and checks whether a number term on an existing column or computed field already covers it before adding a new kind", + "If a new kind is added: the term table in DATABASE.md, query.KINDS and _term with a named 422, _term_name, a mask in search.py with a _cost that keeps structure terms last, TERM and toQuery in query-model.ts, term-editor.ts and describeQuery", + "Does not compute ring counts outside chem.register_values or the computed descriptors", + "Checks the new term on a scratch database and confirms that hit counts match a brute-force count" + ] + }, + { + "id": 30, + "name": "slow-substructure-after-edit", + "prompt": "After I update a record in my FormChem database, the next substructure search takes over a second again on 100,000 records. Why?", + "files": [], + "expected_behavior": [ + "Loads databases and reads search.py screen, _gate and advance, and backend HASHOUT entries 237 and 238", + "Explains that a person's write moves the audit head, so the screening cache reloads (and the pickled molecule holder is rebuilt in the background), which is by design", + "Does not remove the audit row from the write or skip the freshness check, because every compound write must call store.audit inside its transaction", + "Proposes any speed-up as a measured change on a scratch 100,000 record copy, with a HASHOUT entry" + ] + }, + { + "id": 31, + "name": "new-notebook-template", + "prompt": "Add a 'crystallisation' template to the FormChem lab notebook.", + "files": [], + "expected_behavior": [ + "Loads databases and edits templates.py (NAMES, _HEADINGS, _OBSERVATIONS, LABELS) with headings in the plain markup", + "Adds it to EntryTemplate and TEMPLATES in the notebook window with its label through t(), to the template enum of nb_add_entry, and to DATABASE.md's template list", + "Runs ./formchem agents sync after the MCP tool change and commits the mirror" + ] + }, + { + "id": 32, + "name": "new-live-object-field", + "prompt": "FormDeck wants a 'formula' field in the FormChem live structure object. Add it.", + "files": [], + "expected_behavior": [ + "Loads family-integration and reads docs/LIVE_STRUCTURES.md first", + "Edits LIVE_STRUCTURES.md (the object), live_structures.live_object and the LiveObject type in app/live-structures.ts in one change, without raising format_version (an old reader ignores the new field)", + "Checks with a scratch script against a scratch FORMCHEM_DATA_DIR, not ~/formchem, and logs the decision in backend/HASHOUT_LOG.md" + ] + }, + { + "id": 33, + "name": "agent-token-write-path", + "prompt": "Let ./formchem edit-live also save a drawing through the agent token, so a sibling can save without the window.", + "files": [], + "expected_behavior": [ + "Loads family-integration and names law 4: the agent token writes only under /api/structures", + "Either keeps the change under /api/structures (save_live through the structures routes) or stops and asks, because widening core/window_key.py AGENT_WRITES is a SECURITY.md change", + "Does not add another path to AGENT_WRITES without a SECURITY.md edit in the same change" + ] + }, + { + "id": 34, + "name": "new-helm-monomer", + "prompt": "Add N-methylalanine ([meA]) as a HELM monomer in FormChem.", + "files": [], + "expected_behavior": [ + "Loads chemistry-engine and clean-room; writes the monomer itself from the structure, not from a HELM monomer library", + "Adds smiles with [*:1] and [*:2], the capped form, attachments R1 H and R2 OH and a source sentence to data/helm_monomers.json, and runs helm.monomers.library() so the load-time check passes", + "Round-trips a peptide containing [meA] through read and from_mol to the same InChIKey in a scratch script, and updates docs/HELM.md, the agent_helm description and the NOTICE.md count" + ] + }, + { + "id": 35, + "name": "xtb-option", + "prompt": "Let FormChem's xtb optimisation take an electronic temperature (--etemp).", + "files": [], + "expected_behavior": [ + "Loads three-d and follows the xtb option recipe: constant and validation in services/xtb, the argv in inputs.xtb_argv as a list item, never a shell string", + "Exposes it in the dialog, the xtb-optimise command params and agent_xtb's schema and KEYS, and records it in the program record only with FORMAT.md, model.ts and model.py changed together", + "Checks with a stand-in xtb on a temporary PATH, not by downloading xtb, and says a real run was not made if none was" + ] + }, + { + "id": 36, + "name": "palette-flash", + "prompt": "Switching to the colour-blind element palette in FormChem makes the canvas flicker. Fix it.", + "files": [], + "expected_behavior": [ + "Loads family-integration and canvas; looks at canvas/a11y/palette.ts applyPalette and the measure epoch rather than rebuilding the canvas", + "Checks under 4x CPU throttling with a MutationObserver that a switch adds or removes no node and changes only fills", + "Writes the reason in frontend/HASHOUT_LOG.md, not in a comment" + ] } ], "trigger_evals": [ @@ -358,6 +460,18 @@ {"query": "the 3D object on the formchem page flashes when I change its style", "should_trigger": true}, {"query": "add a surface option to FormChem's 3D View panel in frontend/src/ui", "should_trigger": true}, {"query": "give me the lowest-energy conformer of the structure in my open FormChem drawing", "should_trigger": false}, - {"query": "open this PDB file in formchem and extract the ligand for me", "should_trigger": false} + {"query": "open this PDB file in formchem and extract the ligand for me", "should_trigger": false}, + {"query": "add a new query term to formchem's database search in services/database/query.py", "should_trigger": true}, + {"query": "the formchem database table flashes when records load while scrolling", "should_trigger": true}, + {"query": "an SD import into a formchem .fcdb reports the wrong record numbers in its failure report", "should_trigger": true}, + {"query": "change how formchem hashes a notebook entry when it is signed", "should_trigger": true}, + {"query": "search my FormChem database for compounds with a pyridine ring", "should_trigger": false}, + {"query": "design a SQLite schema for a generic inventory app", "should_trigger": false}, + {"query": "the formai://formchem/edit link opens the wrong drawing in FormChem's desktop app, fix handleDeepLink", "should_trigger": true}, + {"query": "add a functional group to formchem's describe.py so the screen reader names sulfonamides", "should_trigger": true}, + {"query": "FormChem's xtb job leaves its process running after cancel, look at services/xtb/runner.py", "should_trigger": true}, + {"query": "Copy as HELM refuses a stapled peptide in formchem, fix the writer cuts", "should_trigger": true}, + {"query": "draw oxytocin from HELM in FormChem for me", "should_trigger": false}, + {"query": "make FormDeck read the formai structure library folder", "should_trigger": false} ] } diff --git a/.claude/skills/formchem-skillset/SKILL.md b/.claude/skills/formchem-skillset/SKILL.md index 68284afc..79679f99 100644 --- a/.claude/skills/formchem-skillset/SKILL.md +++ b/.claude/skills/formchem-skillset/SKILL.md @@ -1,42 +1,44 @@ --- name: formchem-skillset -description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (FORMAT.md, model.ts, model.py, ops, undo), the RDKit service (identifiers, the scored 2D layout, CIP, stereo groups, abbreviations, queries, R-groups, properties), reactions, file formats and loss reports, picture export, the clipboard, the command line, Standardise, the SVG canvas, grids, scaling, tools, annotations, names (dictionary, parser, namer), NMR prediction (increments), JCAMP-DX spectra, 3D (build, conformers, force fields, PDB and mmCIF, the 3D View, glTF), the shell, menus, the dock, Form extensions, the MCP server and agent tools (agent_edits, agent_log, the agent token), the Tauri shell, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for using FormChem (formchem-harness), other Form apps such as FormDeck, or standalone RDKit scripts." +description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (FORMAT.md, model.ts, model.py, ops), the RDKit service (identifiers, the 2D layout, CIP, stereo groups, abbreviations, queries, properties), reactions, file formats, the clipboard, the command line, the SVG canvas, annotations, names, NMR prediction, JCAMP-DX spectra, 3D (conformers, force fields, PDB, xtb and CREST), the structure database and notebook (.fcdb, search, import, signing hashes), live structures and the shared library (LIVE_STRUCTURES.md, formai:// links, edit-live), keyboard access and palettes, HELM, the shell, menus, extensions, the MCP server and agent tools, the Tauri shell, or a release and its CHANGELOG. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md or port 8220. Not for using FormChem (formchem-harness), other Form apps such as FormDeck, or standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.10.0" + version: "0.12.0" --- # FormChem skillset Route every change to FormChem's code through this file. It maps the subsystems that exist today, states the laws that hold everywhere and names the specialist to load. FormChem is a Python 3.12 FastAPI engine (`backend/`, port 8220), a vanilla TypeScript and Vite window (`frontend/`, port 5220, no framework) that talks to the engine over REST and one WebSocket, and a Tauri 2 shell (`src-tauri/`) that runs the frozen engine from a folder inside the app on macOS and as a sidecar elsewhere. -**Where FormChem is (0.10.0).** Through 0.9.0: the family shell, the document format, store and RDKit service, the canvas, reactions, stereo and analysis, formats and pictures, the agent tools with Agent Activity and the token, names, NMR prediction and spectra (`CHANGELOG.md`). 0.10.0 adds 3D: builds from 2D with a stereo check, conformers, force fields, scans, PDB and mmCIF files, the 3D View, model3d objects and eight more MCP tools (60). The structure database (0.11.0) comes later (`DEV_PLAN.md`). Do not write a later phase's code ahead of it; its commands stay registered and disabled. +**Where FormChem is (0.12.0).** Through 0.11.0: the shell, format, store and RDKit service, canvas, reactions, analysis, formats, agent tools, names, NMR, spectra, 3D, databases and the notebook (`CHANGELOG.md`). 0.12.0 adds live structures and the shared library (`docs/LIVE_STRUCTURES.md`), accessibility, HELM, xtb and CREST by path and six MCP tools (77). Desktop builds and the manual (0.13.0) come later (`DEV_PLAN.md`); do not write them ahead. ## Subsystem map | Subsystem | Root | Specialist | | --- | --- | --- | | Engine core: config, guards, window key, settings and seal, live socket, bridge, library | `backend/app/main.py`, `core/`, `routers/system.py`, `routers/live.py`, `services/hub.py`, `services/bridge.py`, `routers/library.py`, `backend/formchem_engine.py` | `engine` | -| Engine document store: open documents, transactions, undo and redo, autosave, versions, recovery, the `.fchem` package, importers, the live `tx` messages | `backend/app/services/store.py`, `services/history.py`, `services/package.py`, `services/importers.py`, `routers/documents.py`, `core/files.py` | `engine` | +| Engine document store: open documents, transactions, undo, autosave, versions, the `.fchem` package, importers | `backend/app/services/store.py`, `services/history.py`, `services/package.py`, `services/importers.py`, `routers/documents.py`, `core/files.py` | `engine` | | The format contract: document.json, styles, ids, ops and inverses, transactions, validation, coalescing, the derived cache shape | `docs/FORMAT.md`, `frontend/src/engine/model.ts`, `engine/ops.ts`, `backend/app/services/model.py`, `services/ops.py` | `document-format` | | Chemistry engine on RDKit: conversion, sanitising, valence, aromaticity, identifiers, formula, masses, layout, file reading and writing, the derived cache | `backend/app/services/chem/`, `backend/app/routers/chem.py` | `chemistry-engine` | -| Window documents and chemistry: the document client, File and Insert actions, the Analysis panel, local valence, rings and formula | `frontend/src/engine/client.ts`, `engine/session.ts`, `engine/client-api.ts`, `app/documents.ts`, `ui/analysis-panel.ts`, `frontend/src/chem/` | `window-shell` (chemistry rules in `chemistry-engine`) | -| Canvas: SVG renderer, drawing tools and hover hotkeys, view, hit testing, selection, text editor, canvas context menus, tool rail; from 0.7.0 the dark page, grids and snapping, scale handles | `frontend/src/canvas/` (`render/`, `tools/`, `view.ts`, `hit.ts`, `selection.ts`, `context.ts`, the grid and dark page files), `ui/tool-rail.ts`, `styles/canvas*.css`, `public/fonts/` | `canvas` | -| Drawn objects: the object kind registry and kind modules, anchors, bounds, drawn-outline hits, annotation tools and handles, captions, z-order and groups, the template library, media | `frontend/src/canvas/render/objects.ts` and its kind modules, `canvas/hit-objects.ts`, `canvas/tools/objects.ts`, `tools/handles.ts`, `app/object-commands.ts`, `ui/template-*.ts`, `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/`, the media routes in `routers/documents.py` | `annotations` | -| Reactions: perception, atom mapping, balance, stoichiometry (engine and window), reaction SMILES and RXN, the Reaction menu, the MCP reaction tools | `backend/app/services/chem/` (`geometry`, `reactions`, `mapping`, `balance`, `stoich`, `rxnio`, `scheme`), `routers/reactions.py`, `frontend/src/chem/stoich.ts`, `ui/stoich-panel.ts`, `app/reaction-commands.ts`, `engine/reactions-api.ts`, `docs/REACTIONS.md` | `reactions` | -| Stereo, queries and analysis: stereo groups, CIP, wedges, abbreviations, hydrogens, queries, SMARTS, Markush, properties, the structure check, the isotope pattern, their routes, commands, marks and panels | `backend/app/services/chem/` (`stereo`, `superatom`, `hydrogens`, `query`, `search`, `v3000`, `markush`, `props`, `check`, `isotopes`), `routers/analysis.py`, `frontend/src/engine/analysis-api.ts`, `app/chem-*.ts`, `canvas/render/marks-*.ts`, `docs/ANALYSIS.md` | `stereo-and-queries` | -| Formats and export: the formats table, report items, readers and writers (CDXML and CDX through Indigo, RD, CML), the export, parse, import and file write routes, pictures with the embedded drawing, the save path, print, File > Import | `backend/app/services/chem/` (`formats`, `report`, `io`, `writers`, `cdxio`, `rdfio`, `cml`), `services/embedded_source.py`, `services/pictures/`, `services/importers.py`, `routers/files.py`, `routers/pictures.py`, `frontend/src/app/` (`picture`, `embedded-source`, `save-file`, `export-commands`, `print`, `import-files`), `ui/export-dialog.ts`, `ui/import-report.ts`, `docs/FORMATS.md` | `formats-and-export` | -| Clipboard: the native payload and paste plan, text formats, flavours per platform, Copy As, Paste Special, Duplicate | `frontend/src/app/clip-*.ts`, `app/clipboard.ts`, `ui/paste-special-dialog.ts`, `ui/native-menu.ts` `ALWAYS_NATIVE` | `clipboard` | -| Names, NMR prediction and spectra: name engines, dictionary, parser, namer; increments and predicted spectra; the JCAMP-DX reader, peaks, integrals; the name dialog, spectrum kind, atom links, Spectrum editor | `backend/app/services/` (`names/`, `nmr/`, `spectra/`), `data/names/`, `routers/` (`names`, `nmr`, `spectra`), the window files in the specialist's file map, `docs/NAMES.md`, `docs/SPECTRA.md` | `names-and-spectra` | +| Window documents and chemistry: the document client, File and Insert actions, the Analysis panel, local valence and rings | `frontend/src/engine/client.ts`, `session.ts`, `client-api.ts`, `app/documents.ts`, `ui/analysis-panel.ts`, `frontend/src/chem/` | `window-shell` (rules in `chemistry-engine`) | +| Canvas: SVG renderer, tools and hover keys, view, hit testing, selection, text editor, context menus, tool rail, the dark page, grids, scale handles | `frontend/src/canvas/` (`render/`, `tools/`, `view.ts`, `hit.ts`, `selection.ts`, `context.ts`, the grid and dark page files), `ui/tool-rail.ts`, `styles/canvas*.css`, `public/fonts/` | `canvas` | +| Drawn objects: the kind registry, anchors, bounds, annotation tools and handles, captions, z-order and groups, templates, media | `canvas/render/objects.ts` and kind modules, `hit-objects.ts`, `tools/objects.ts`, `handles.ts`, `app/object-commands.ts`, `ui/template-*.ts`, `services/templates.py`, `data/templates/` | `annotations` | +| Reactions: perception, mapping, balance, stoichiometry, reaction SMILES and RXN, the Reaction menu and tools | `services/chem/` (`geometry`, `reactions`, `mapping`, `balance`, `stoich`, `rxnio`, `scheme`), `routers/reactions.py`, `chem/stoich.ts`, `ui/stoich-panel.ts`, `app/reaction-commands.ts`, `engine/reactions-api.ts`, `docs/REACTIONS.md` | `reactions` | +| Stereo, queries and analysis: stereo groups, CIP, wedges, abbreviations, hydrogens, queries, SMARTS, Markush, properties, the check, isotopes | `services/chem/` (`stereo`, `superatom`, `hydrogens`, `query`, `search`, `v3000`, `markush`, `props`, `check`, `isotopes`), `routers/analysis.py`, `engine/analysis-api.ts`, `app/chem-*.ts`, `render/marks-*.ts`, `docs/ANALYSIS.md` | `stereo-and-queries` | +| Formats and export: the formats table, reports, readers and writers (CDXML and CDX through Indigo, RD, CML), the exchange routes, pictures with the embedded drawing, print, File > Import | `services/chem/` (`formats`, `report`, `io`, `writers`, `cdxio`, `rdfio`, `cml`), `services/pictures/`, `embedded_source.py`, `importers.py`, `routers/files.py`, `pictures.py`, the window's export, print and import files, `docs/FORMATS.md` | `formats-and-export` | +| Clipboard: the native payload, paste plan, flavours per platform, Copy As, Paste Special, Duplicate | `frontend/src/app/clip-*.ts`, `app/clipboard.ts`, `ui/paste-special-dialog.ts`, `ui/native-menu.ts` `ALWAYS_NATIVE` | `clipboard` | +| Names, NMR prediction and spectra: name engines, namer; increments and predicted spectra; JCAMP-DX, peaks, integrals, atom links, the Spectrum editor | `backend/app/services/` (`names/`, `nmr/`, `spectra/`), `data/names/`, `routers/` (`names`, `nmr`, `spectra`), the window files in the specialist's file map, `docs/NAMES.md`, `docs/SPECTRA.md` | `names-and-spectra` | | 3D: builds, conformers, force fields, scans, measurements, PDB and mmCIF, ligands, the stale-conformer rule; the 3D View, model3d snapshots, glTF | `backend/app/services/three_d/`, `routers/three_d.py`, `frontend/src/ui/view3d-*.ts`, `canvas/render/model3d.ts`, `io/glb.ts`, `engine/three-api.ts`, `engine/stale.ts`, `docs/3D.md` | `three-d` | -| Command line and batch: convert, batch, descriptors, render, the stream reader, Standardise (engine, route, dialog) | `backend/app/cli.py`, `services/batch.py`, `services/chem/` (`stream`, `records`, `standardise`, `depict`), `setup/convert`, `frontend/src/ui/standardise-dialog.ts`, `app/standardise-command.ts`, `docs/CLI.md` | `command-line` | +| Databases and notebook: the `.fcdb` store, registration, fields, import, export, search, hit lists, plot, entries and signing; the workspace, search and notebook views | `backend/app/services/database/`, `services/notebook/`, `routers/databases.py`, `db_search.py`, `notebook.py`, `frontend/src/ui/database*/`, `ui/notebook/`, `engine/database-api.ts`, `docs/DATABASE.md` | `databases` | +| Family integration: the shared Library folder, live structures, edit-live, the `formai://` link, the file watch; accessibility keys, speech, the summary, palettes | `services/live_structures.py`, `file_watch.py`, `describe.py`, `routers/structures.py`, `app/live-structures.ts`, `ui/library-dialog.ts`, `canvas/a11y/`, `docs/LIVE_STRUCTURES.md` | `family-integration` | +| Command line and batch: convert, batch, descriptors, render, the stream reader, Standardise | `backend/app/cli.py`, `services/batch.py`, `services/chem/` (`stream`, `records`, `standardise`, `depict`), `setup/convert`, `ui/standardise-dialog.ts`, `docs/CLI.md` | `command-line` | | Window shell: app root, command registry, palette, Home, title bar, status bar, Preferences, dialogs, themes, i18n, styles | `frontend/src/app.ts`, `app/commands-shell.ts`, `commands/registry.ts`, `io/`, `ui/`, `i18n/`, `styles/` | `window-shell` | | Menus: in-window menu bar, native macOS menus, context menus | `frontend/src/ui/menu.ts`, `ui/native-menu.ts`, `ui/context-menu.ts`, `app/menus.ts`, `styles/menu.css` | `menus` | | Terminal and agent dock | `frontend/src/dock/` (vendored), `frontend/src/dock-adapter.ts`, `backend/app/routers/terminal.py`, `services/terminal.py`, `services/claude_code.py`, `services/agent_programs.py`, `services/agent_lookup.py` (vendored) | `dock` | | Form extensions (host API 1) | `frontend/src/extensions/`, `backend/app/routers/extensions.py`, `services/formext_host.py` (vendored), `docs/EXTENSIONS.md` | `extensions` | -| MCP server, agent tools, the call log and Agent Activity, the agent token, commands catalogue, agent setup and skills | `backend/app/routers/mcp.py`, `services/agent_*.py`, `core/agent_token.py`, `routers/agent_activity.py`, `routers/commands.py`, `frontend/src/app/agent-*.ts`, `ui/agent-*.ts`, `canvas/agent-marks.ts`, `setup/mcp_stdio.py`, `setup/agents.py`, `docs/AGENTS.md`, `.claude/skills` | `agents` | -| Desktop app, the macOS engine folder and the sidecar | `src-tauri/` (`packaged.rs`, `tauri.macos.conf.json`), `backend/formchem_engine.py`, `setup/freeze_backend`, `setup/lib.sh`, `setup/desktop_*`, `build_app` | `desktop` | +| MCP server, agent tools, the call log, Agent Activity, the token, the catalogue, skills | `backend/app/routers/mcp.py`, `services/agent_*.py`, `core/agent_token.py`, `routers/agent_activity.py`, `routers/commands.py`, `frontend/src/app/agent-*.ts`, `ui/agent-*.ts`, `canvas/agent-marks.ts`, `setup/mcp_stdio.py`, `setup/agents.py`, `docs/AGENTS.md`, `.claude/skills` | `agents` | +| Desktop app, the macOS engine folder and the sidecar | `src-tauri/` (`packaged.rs`, `tauri.macos.conf.json`), `formchem_engine.py`, `setup/freeze_backend`, `lib.sh`, `desktop_*`, `build_app` | `desktop` | | Versions, changelog, notices, CI, formcompiler | `.docs/BRANCHING.md`, `CHANGELOG.md`, `NOTICE.md`, `setup/notices.py`, `.github/workflows/` | `release` | | Where any FormChem feature may come from | the owner's clean-room specifications | `clean-room` | @@ -47,9 +49,8 @@ frontend commands/registry.ts -> nothing (DOM free; the cli and workers may impo engine/model.ts, engine/ops.ts -> nothing (pure, DOM free; the contract) chem/ -> engine/model.ts only (pure, no t(), no DOM) engine/client.ts, session.ts -> model, ops, client-api, io/api, io/live -canvas/render -> canvas/types.ts, engine/model, engine/ops (its own geom, valence, rings); - render/table.ts also chem/stoich.ts, the one window stoichiometry source; - render/marks-layer.ts also canvas/marks-options.ts (view toggles only) +canvas/render -> canvas/types.ts, engine/model, engine/ops (own geom, valence, rings); table.ts + also chem/stoich.ts; marks-layer.ts also canvas/marks-options.ts engine/analysis-api.ts -> io/api, model, ops; the only caller of /api/analysis canvas/tools -> canvas/types.ts, engine/model, engine/ops, canvas/geom.ts canvas/view.ts, ui/tool-rail -> canvas/types.ts, hit.ts, selection.ts, ui/dom, ui/icons, i18n @@ -60,9 +61,8 @@ backend services/model.py, ops.py -> nothing (pure; the contract) services/store.py -> model, ops, package, history, importers, hub; chem.derive imported lazily services/chem/ -> rdkit, indigo, model (never the store or routers) backend routers -> core, services (hub, bridge, library, store, chem, terminal, formext_host) -mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub, agent_token; - routers/analysis and the agent_* services imported lazily by the tools -services/agent_*.py -> store, bridge, chem (agent_edits is pure: model and chem only); agent_log hooks AFTER_CHANGE +mcp.py -> commands, extensions, consent, claude_code, bridge, hub, agent_token; agent_* lazily +services/agent_*.py -> store, bridge, chem (agent_edits pure); agent_log hooks AFTER_CHANGE app/picture.ts -> canvas/render (a fresh renderer off screen), never the live canvas view app/clip-*.ts, import-files -> engine/model, ops, the export and parse routes; one paste plan (clip-data.ts) services/chem/writers, stream -> formats, report, io, rdkit, indigo (never the store) @@ -70,6 +70,9 @@ services/batch.py, app/cli.py -> chem/stream, records, standardise, depict, prop services/pictures/ -> fontTools and the bundled fonts only services/names, nmr, spectra -> rdkit, numpy, chem (never routers); nmr registers its hook in spectra.source.PREDICTORS services/three_d -> rdkit, numpy, chem (never routers); store.apply_now runs three_d.stale +services/database, notebook -> sqlite3, rdkit, numpy, chem (never routers or the document store) +services/helm, xtb, describe -> rdkit, chem (xtb also three_d); xtb starts programs only as separate processes +canvas/a11y -> canvas view and render, ui/a11y-announcer; installed before mountCanvas ui/view3d-lib.ts -> 3dmol by dynamic import only (nothing 3D at startup) window-only abilities -> reach the engine as window tools over /api/live (bridge.window_call) desktop shell -> frozen engine (formchem_engine.py) -> serves frontend/dist @@ -103,22 +106,24 @@ The window reaches the engine only through `frontend/src/io/api.ts` (REST with t | How a bond, label or wedge renders, a drawing tool, a hover key, hit testing, selection, zoom, the tool rail, canvas context menus | `canvas` | | An arrow, bracket, shape, table, TLC plate, orbital, picture or caption, its handles and tool; z-order, groups, templates | `annotations`, with `canvas` for the laws it builds on | | Reaction roles, atom mapping, balance, the stoichiometry panel or grid, reaction SMILES or RXN, a reaction route, command or MCP tool | `reactions`, with `chemistry-engine` for RDKit and `agents` for a tool | -| A CIP label, stereo group, wedge, abbreviation, explicit hydrogen, atom list, query bond, SMARTS, substructure hit, R-group, property, check issue or isotope peak; an `/api/analysis` route, an analysis MCP tool, a stereo or query mark | `stereo-and-queries`, with `chemistry-engine` for the converter and `agents` for a tool | +| A CIP label, stereo group, wedge, abbreviation, hydrogen, query atom or bond, SMARTS, R-group, property, check issue or isotope peak; an `/api/analysis` route or tool | `stereo-and-queries` (`chemistry-engine` for the converter, `agents` for a tool) | | A file that opens wrong or loses something, an export or import report, a new format, File > Import, picture export, the drawing inside a picture, saving in the desktop app, print | `formats-and-export`, with `chemistry-engine` for RDKit and `clean-room` for a new format | | Copy, Cut, Paste, Copy As, Paste Special, Duplicate, a clipboard flavour on one platform | `clipboard`, with `formats-and-export` for the text formats and pictures | | `./formchem convert`, `batch`, `descriptors`, `render`, the stream reader, per-record failures, Standardise | `command-line`, with `chemistry-engine` for RDKit | | A name read wrong, a dictionary entry, a ring parent, OPSIN; a predicted shift, an increment, a predictor; a JCAMP-DX file, the spectrum plot, peaks, integrals, atom links, the Spectrum editor | `names-and-spectra` (`clean-room` first; `canvas` for the renderer, `document-format` for the spectrum object) | | A 3D build, conformer, scan, measurement or surface; a PDB or mmCIF file or ligand; the 3D View, a 3D object on the page, glTF; conformers after an edit | `three-d` (`document-format` for `conformers` and `model3d`, `agents` for a tool) | +| A database field, query term, import or export format, hit list, duplicate rule, notebook template or signing; the workspace table, search or plot | `databases` (`agents` for a tool) | +| The Library folder, Copy as Live Structure, a live Save, edit-live, the deep link, the file bar; a focus key, a spoken sentence, the summary, a palette | `family-integration` (`agents` for a tool) | +| A HELM string or monomer; an xtb or CREST option or job | `chemistry-engine`; `three-d` | | A crowded or crossing 2D layout, Lay Out or Clean Up | `chemistry-engine` (the scored layout) | | The dark page, a grid type, snapping, scale handles, Scale Up and Down | `canvas`, with `document-format` for `style.grid` | | New, Open, Save, Insert from SMILES, the Analysis panel, the status bar formula, the dirty mark | `window-shell`, with `chemistry-engine` for the values | | Home, the title bar, status bar, palette, Preferences, About, dialogs, themes, translations, styles | `window-shell` | -| A menu item, a submenu, a shortcut label, macOS native menus, menu overlap | `menus`, then `window-shell` for the command | +| A menu item, submenu or shortcut label, native macOS menus, a menu that clips the title, More menus, keys with a menu open | `menus`, then `window-shell` for the command | | Terminal tabs, Claude Code, Codex, Cursor or Antigravity tabs, the consent dialog, chat | `dock` | | The extensions pane, an extension API call, FormPortal or form.ext integration | `extensions` | | An MCP tool, an edit builder, agent render or placement, the call log, Agent Activity, Stop, the token, `./formchem agents`, skills | `agents` | -| Desktop build, `build_app`, a slow desktop start, the macOS engine folder and its flatten rule, the Tauri CLI version, sidecar, updater, Tauri commands, title bar overlay | `desktop` | -| A menu that clips or overlaps the title, More menus, Escape or arrows with a menu open | `menus` | +| Desktop build, `build_app`, a slow start, the macOS engine folder, sidecar, updater, Tauri commands, title bar overlay | `desktop` | | A release, version sites, CHANGELOG, NOTICE, CI | `release` | | Any chemistry feature, a file format, a name for a command or panel | `clean-room` first | | Use FormChem: draw or edit a structure with the agent tools, run a menu command, hand off in the window | Not this pack: `formchem-harness` | @@ -131,7 +136,8 @@ formchem-skillset/ references/repo-laws.md each law with its reason and exact format EVALS.json evaluation prompts and the trigger tests (should and should not load) sub-skills/ engine, document-format, chemistry-engine, reactions, stereo-and-queries, formats-and-export, - clipboard, command-line, names-and-spectra, three-d, canvas, annotations, window-shell, menus, dock, + clipboard, command-line, names-and-spectra, three-d, databases, family-integration, canvas, annotations, + window-shell, menus, dock, extensions, agents, desktop, release, clean-room chemistry-engine/references/warning-codes.md every ChemWarning code and where it comes from stereo-and-queries/references/routes-and-codes.md the /api/analysis routes, check codes and service warning codes @@ -159,7 +165,7 @@ cd frontend && npx tsc --noEmit type-check backend/venv/bin/python -m compileall -q backend/app setup ``` -Scratch engines for checks: `FORMCHEM_PORT=[port] FORMCHEM_DATA_DIR=[scratch]/data venv/bin/python -m uvicorn app.main:app --port [port]` from `backend/`. `backend/venv/bin/python backend/formchem_engine.py --selfcheck` confirms RDKit and Indigo import. Never point a check at `~/formchem`, the person's data folder. +Scratch engines: `FORMCHEM_PORT=[port] FORMCHEM_DATA_DIR=[scratch]/data venv/bin/python -m uvicorn app.main:app --port [port]` from `backend/`; never point a check at `~/formchem`, the person's data folder. ## Done means diff --git a/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md index 2ae35fca..15017f09 100644 --- a/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md @@ -31,9 +31,9 @@ Give agents an honest tool surface that only describes what FormChem can do now, | `docs/AGENTS.md` | the public reference of every tool, the token and the call log | | `.claude/skills/formchem-harness`, `formchem-skillset` | the packs; `.agents/skills` is a mirror written by sync. Made and repaired only through the god-tier-skill-creator pipeline; its `scripts/validate_skill.py` reports zero FAIL before a commit | -## The tool surface (0.10.0) +## The tool surface (0.12.0) -60 tools: the six of the shell (`get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`); the reaction tools of 0.5.0 and the analysis tools of 0.6.0 (owned by `reactions` and `stereo-and-queries`); and the 28 of 0.8.0: `list_open_documents`, `new_document`, `open_document`, `save_document`, `close_document`, `draw_from_smiles`, `draw_from_molfile`, `render`, `get_structure`, `validate`, `compute_properties`, `convert`, `batch_convert`, `get_atoms` and the 14 edit tools `add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text`, `add_reaction`; and the 10 of 0.9.0, whose services `names-and-spectra` owns: `draw_from_name` (through `_draw`), `name_structure` (the route's `name_mol`), `predict_nmr`, `predict_spectrum` (`nmr.document.spectrum_ops`), `open_spectrum`, `spectrum_data`, `spectrum_peaks`, `spectrum_pick_peaks`, `spectrum_integrate` (`spectra.peak_ops`, `integral_ops`) and `spectrum_export`; and the 8 of 0.10.0, whose services `three-d` owns: `build_3d`, `conformers_3d`, `minimise_3d`, `scan_dihedral`, `measure_3d`, `open_3d_structure` (`three_d.open_bytes`) and `extract_ligand` call the `routers/three_d.py` functions through `_three_d` with an `AgentCall` in the body, so the route's `commit` applies with origin `agent` and the agent's name, and `export_3d` calls `export.write` directly. The writing ones are in `MUTATING` (`scan_dihedral` only with `store`, `export_3d` only with an `output` outside the temporary folder, through `_mutating`); a tool never builds its own copy of a route's ops. +77 tools: the six of the shell (`get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`); the reaction tools of 0.5.0 and the analysis tools of 0.6.0 (owned by `reactions` and `stereo-and-queries`); and the 28 of 0.8.0: `list_open_documents`, `new_document`, `open_document`, `save_document`, `close_document`, `draw_from_smiles`, `draw_from_molfile`, `render`, `get_structure`, `validate`, `compute_properties`, `convert`, `batch_convert`, `get_atoms` and the 14 edit tools `add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text`, `add_reaction`; and the 10 of 0.9.0, whose services `names-and-spectra` owns: `draw_from_name` (through `_draw`), `name_structure` (the route's `name_mol`), `predict_nmr`, `predict_spectrum` (`nmr.document.spectrum_ops`), `open_spectrum`, `spectrum_data`, `spectrum_peaks`, `spectrum_pick_peaks`, `spectrum_integrate` (`spectra.peak_ops`, `integral_ops`) and `spectrum_export`; and the 8 of 0.10.0, whose services `three-d` owns: `build_3d`, `conformers_3d`, `minimise_3d`, `scan_dihedral`, `measure_3d`, `open_3d_structure` (`three_d.open_bytes`) and `extract_ligand` call the `routers/three_d.py` functions through `_three_d` with an `AgentCall` in the body, so the route's `commit` applies with origin `agent` and the agent's name, and `export_3d` calls `export.write` directly. The writing ones are in `MUTATING` (`scan_dihedral` only with `store`, `export_3d` only with an `output` outside the temporary folder, through `_mutating`); a tool never builds its own copy of a route's ops. And the 11 of 0.11.0, whose services `databases` owns, in agent modules rather than in `mcp.py`: `services/agent_db.py` (`db_list`, `db_create`, `db_open`, `db_import`, `db_search`, `db_get_record`, `db_add_record`, `db_update_record`, `db_export`) and `services/agent_notebook.py` (`nb_add_entry`, `nb_search`). Each module offers `TOOLS` in the `_tool` shape, frozen `NAMES`, `mutating(name, args)` and `async call(name, args, agent_name)`, which runs the database services on a worker thread and writes as `agent:[name]`; `mcp.py` walks `AGENT_MODULES` for the list, the gate and dispatch, so a new module adds one name there. They touch no drawing (except `nb_add_entry {doc}`, which reads one), so they answer with `_ok` text and `structuredContent`, not `write_result`. And the 6 of 0.12.0, in three more agent modules: `agent_library.py` (`library_list`, `library_add`, `live_structure_object`; `family-integration` owns the service), `agent_helm.py` (`draw_from_helm`, through `mcp._draw`; `chemistry-engine` owns `services/helm`) and `agent_xtb.py` (`xtb_optimise`, `crest_conformers`, through `_three_d` with the xtb job routes; `three-d` owns `services/xtb`). HELM and xtb build `mcp.Agent("", agent_name)` in `call` because `_draw`, `_apply` and `_three_d` read only the name. `setup/agents.py` reads `mcp.py`'s own `TOOLS` by AST, and each agent module's finished `TOOLS` by importing it with the backend venv's Python (`_module_tools`), so `references/tools.md` and `agents/manifest.json` hold all 77 tools. ## Laws of the agent tools diff --git a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md index e16e9fbc..6ea4d544 100644 --- a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: chemistry-engine -description: "FormChem's chemistry: the RDKit service in backend/app/services/chem (conversion from fragments, sanitising, valence, aromaticity, stereo and CIP, canonical SMILES, CXSMILES, InChI and InChIKey, Hill formula, masses, m/z, elemental analysis, isotope pattern, 2D clean-up and the scored layout: CoordGen and RDKit candidates, layout_score and layout_refine), the /api/chem routes, the derived cache broadcast after every transaction, and the window's local valence, ring and label rules in frontend/src/chem. Use when a computed value is wrong, a warning or valence error appears or is missing, a structure reads upside down or loses atoms, a layout is crowded, crosses bonds or moves the wrong atoms, or a new chemistry computation is added." +description: "FormChem's chemistry: the RDKit service in backend/app/services/chem (conversion from fragments, sanitising, valence, aromaticity, stereo and CIP, canonical SMILES, CXSMILES, InChI and InChIKey, Hill formula, masses, m/z, elemental analysis, isotope pattern, 2D clean-up and the scored layout: CoordGen and RDKit candidates, layout_score and layout_refine), the /api/chem routes, the derived cache broadcast after every transaction, and the window's local valence, ring and label rules in frontend/src/chem, and from 0.12.0 the HELM reader and writer in services/helm over data/helm_monomers.json. Use when a computed value is wrong, a warning or valence error appears or is missing, a structure reads upside down or loses atoms, a layout is crowded, crosses bonds or moves the wrong atoms, a HELM string is refused or a peptide will not copy as HELM, a monomer is added, or a new chemistry computation is added." --- # Chemistry engine @@ -29,6 +29,7 @@ Compute everything chemical in one place, from the drawing as the person drew it | `frontend/src/canvas/render/valence.ts`, `render/rings.ts` | The renderer's own fast implicit-H table and ring perception, used while drawing | | `references/warning-codes.md` | Every warning code, the module that raises it and when. Open before adding or interpreting a warning | | Reaction modules (0.5.0) | `chem/geometry.py`, `reactions.py`, `mapping.py`, `balance.py`, `stoich.py`, `rxnio.py`, `scheme.py`, `derive.reaction_checks` and `routers/reactions.py` belong to the `reactions` specialist; they reuse `convert.to_mol` and the rules here | +| HELM (0.12.0) | `data/helm_monomers.json` (55 monomers written for FormChem, each with `smiles`, `capped`, `attachments`, `source`); `services/helm/monomers.py` (`_monomer` checks every capped form at load, `inline`), `parser.py` (`parse`, positioned `HelmError`, limits), `assemble.py` (`Chem.molzip` over shared map numbers, exported as `build_molecule`), `writer.py` (`CUTS`, `_assign`, `_topology`, `write`), `__init__.py` (`read`, `from_mol` with the InChIKey read-back); `routers/helm.py`, `services/agent_helm.py`, `frontend/src/ui/helm-dialog.ts`, `app/helm-commands.ts`; `docs/HELM.md`; HASHOUT backend 265 to 269, frontend 296 and 297 | | Analysis modules (0.6.0) | `chem/stereo.py`, `superatom.py`, `hydrogens.py`, `query.py`, `search.py`, `v3000.py`, `markush.py`, `props.py`, `check.py`, `isotopes.py` and `routers/analysis.py` belong to the `stereo-and-queries` specialist. Here they changed `convert.py` (stereo groups and the chiral flag after perception, query atoms and bare `*` as generics), `perceive.py` (`stereo_unknown`, `undefined_double_bond`, cumulenes skipped, charged atoms judged by the allowed list so Na+ is no valence error) and `derive.content_key` (`FRAGMENT_FIELDS`) | ## Rules @@ -50,6 +51,13 @@ Compute everything chemical in one place, from the drawing as the person drew it 3. A new derived field is a contract change: add it to the derived cache table in `docs/FORMAT.md` and to `DerivedFragment` in `model.ts` (`document-format`). 4. Time it: `derive_document` on a 250-atom fragment stays well under 100 ms warm. +## A HELM monomer or a new cut (0.12.0) + +1. **Write the monomer yourself** from a textbook structure (`clean-room`): never copy a HELM monomer library, whose licence was never cleared. Give `smiles` with `[*:n]`, the `capped` form with each leaving group put back, `attachments` (R label to `H` or `OH`) and a `source` sentence; mirror-image D forms in full. The loader refuses the whole file when a capped form differs, so run `helm.monomers.library()` in the engine venv after the edit. +2. **Reading** needs nothing more; **writing** needs the piece to come out of `writer._cuts`. A new bond kind is a `CUTS` row (SMARTS, the two cut atoms, the leaving group each side) and, if it pairs labels unusually, a `PARTNER` entry; cut only bonds that are always between monomers. +3. **Round-trip check.** A scratch script under `/tmp` reads the HELM, writes it back and compares InChIKeys, for the new monomer and for oxytocin, ApU, a chain of all 20 L and 19 D residues, a head-to-tail cyclic peptide and the two lactam bridges. `from_mol` must never offer HELM that reads back differently. +4. Update the monomer table in `docs/HELM.md`, the tool description in `agent_helm.py` and the count in NOTICE.md's own-data line. + ## Gate - [ ] `backend/venv/bin/python -m compileall -q backend/app` is clean and `backend/formchem_engine.py --selfcheck` exits 0. diff --git a/.claude/skills/formchem-skillset/sub-skills/databases/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/databases/SUB-SKILL.md new file mode 100644 index 00000000..1d5ea236 --- /dev/null +++ b/.claude/skills/formchem-skillset/sub-skills/databases/SUB-SKILL.md @@ -0,0 +1,85 @@ +--- +name: databases +description: "FormChem's 0.11.0 structure database and lab notebook code: the engine packages services/database (schema, store, chem.register_values, computed, fields, forms, records, attachments, thumbs, jobs, imports, exports, uploads, info, query, search, hitlists, saved, plot, dbcli) and services/notebook (templates, content hash, scheme, products, entries, export), routers databases.py, db_search.py and notebook.py, agent_db.py and agent_notebook.py, and the window's ui/database (workspace, table, gallery, form, dialogs), ui/database-find (search bar, query builder, hit lists, import, export, plot) and ui/notebook, against the contract docs/DATABASE.md. Use when adding a field type, a query term, an import or export format, a notebook template, a database route or MCP tool, fixing a slow or wrong search, an import report, a duplicate rule, a hit list, a table that flashes, or signing and the entry hash." +--- + +# Databases + +## Purpose + +Change FormChem's databases and notebook without breaking the contract: one `.fcdb` SQLite file that any SQLite browser reads, every write in one transaction with an audit row, keys and fingerprints from one function, searches that never add hits as a threshold rises, and a 10,000 record table that never rebuilds. Hands back the change, the checks that prove it and HASHOUT entries. + +## Preconditions + +`clean-room` loaded (the database and notebook sections of the clean-room specifications). `docs/DATABASE.md` read in full: it is the contract, and when code disagrees with it the code is the bug. `database-api.ts`, `workspace-types.ts` and `services/database/schema.py` are contract files too. + +## File map + +| Path | Holds | +| --- | --- | +| `services/database/schema.py`, `store.py` | tables, `FORMAT_VERSION`, `migrate`; handles, the lock file, `writing`, `reading`, `next_number`, `audit`, `notify`, `close_all` | +| `database/chem.py`, `computed.py` | `register_values` (keys, formula, masses, counts, both fingerprints); descriptor fields over `chem/props.measure` | +| `database/fields.py`, `forms.py`, `records.py`, `attachments.py`, `thumbs.py`, `info.py` | fields and the `records` view; generated forms; add, update, duplicates, paging; files; themed thumbnails; Info, create, open | +| `database/jobs.py`, `imports.py`, `exports.py`, `uploads.py` | worker jobs; preview, mapping, batches of 250, the report, `plain`; SD, SMILES, CSV and one-time downloads; browser uploads and `adopt` | +| `database/query.py`, `search.py`, `hitlists.py`, `saved.py`, `plot.py` | `normalise`, the formula grammar, `name_of`; the screening cache, `_evaluate`, `run`; hit lists with temp tables when read-only; saved queries; plot points | +| `database/dbcli.py`, `app/cli.py` | `./formchem db` | +| `services/notebook/` | `templates`, `content` (the eleven-key hash), `scheme` (molecules, stoichiometry, pictures), `products`, `entries` (`sign`, `after_change`, `listing`), `attachments`, `markup`, `export` | +| `routers/databases.py`, `db_search.py`, `notebook.py`; `core/window_key.py` `require_view` | thin routes, `GUARD` and `VIEW_GUARD` | +| `services/agent_db.py`, `agent_notebook.py`; `routers/mcp.py` `AGENT_MODULES` | the eleven tools, `mutating`, `call` | +| `frontend/src/engine/database-api.ts` | types and one function per route, `DuplicateError` | +| `frontend/src/ui/database/` | `workspace.ts`, `workspace-types.ts`, `record-source.ts` (blocks of 100), `selection.ts`, `columns.ts`, `table.ts`, `gallery.ts`, `form-view.ts`, `thumbs.ts`, the dialogs; `app/database-commands.ts` | +| `frontend/src/ui/database-find/` | `search-bar.ts`, `query-text.ts`, `query-model.ts`, `term-editor.ts`, `query-builder.ts`, `hitlists.ts`, `queries.ts`, `import-dialog.ts`, `export-dialog.ts`, `files.ts`, `plot.ts`, `plot-math.ts` | +| `frontend/src/ui/notebook/` | `notebook.ts`, `entry-list.ts`, `entry-editor.ts`, `scheme-view.ts`, `notebook-api.ts`, `markup.ts`, `commands.ts` | +| `docs/DATABASE.md`, `docs/DATABASES.md` | the contract; the person's guide. HASHOUT backend 223 to 255, frontend 245 to 276 | + +## Laws + +1. **One transaction per write.** Every write runs inside `store.writing(db)` (BEGIN IMMEDIATE ... COMMIT under `db.lock`) and calls `store.audit` in it; reads use `store.reading`. The search cache trusts the audit head, so a write without an audit row leaves searches stale. Long work commits in batches, each its own transaction, and registers chemistry outside the lock. +2. **Notify after commit.** `store.notify(db, change, uids)` is called once the transaction committed, never inside it, with the `change` names of DATABASE.md; the window refetches only what it names. +3. **The contract wins.** A table, column or JSON shape change edits DATABASE.md, the engine and `database-api.ts` in one change, raises `FORMAT_VERSION` and adds a step to `schema.migrate`; an older file must still open (read-only when newer). +4. **Fingerprints only through `chem.register_values`.** Stored rows and exact queries are keyed by that one function; never compute an InChIKey, parent key or fingerprint elsewhere. +5. **Search stays monotonic and named.** Raising a similarity threshold never adds hits; every structure result names its method and the RDKit version. +6. **The window never rebuilds.** Rows and tiles are pooled and keyed by uid, records arrive in blocks with stale blocks kept on screen, and a live change refetches only its blocks. +7. **Agents never sign.** Signing is the person's statement; `nb_add_entry` writes open entries only. + +## Recipes + +### A new field type + +1. DATABASE.md's field table, `schema.FIELD_TYPES` and `NUMERIC_TYPES` (with a format version step), and `FieldType` in `database-api.ts`. +2. Engine: `fields._check_spec`, `stores_text`, `coerce` (and its import path `text=True`), `detect`, `rebuild_view`; `exports.text_of` and `NON_SCALAR`; the type groups in `query.py`. +3. Window: `columns.ts` (format, parse, `EDITABLE`), the type list in `fields-dialog.ts`, the import dialog's type names, the term editor's field groups in `database-find/shared.ts`. + +### A new query term + +1. DATABASE.md's term table first. +2. `query.KINDS` and `_term` (defaults and the 422 naming the bad key), `_term_name` for the hit list name. +3. `search.py`: a mask function in `FIELD_TERMS` or a branch in `_evaluate`, with a `_cost` that keeps structure terms last. +4. Window: `TERM` and `toQuery` in `query-model.ts`, the row in `term-editor.ts`, `describeQuery` in `query-text.ts`; the `_QUERY` description in `agent_db.py`. + +### A new import or export format + +Import: `imports.FORMATS` and `format_of`, items from `chem/records.py` `iter_records` (streaming, a reason per bad record), `IMPORT_EXTENSIONS` in `files.ts`, the `--format` help in `dbcli.py`, the `format` enum of `db_import`, DATABASE.md and `docs/FORMATS.md`. Export: `exports.FORMATS` and `_write`, the export dialog, `db_export`'s enum, and a round trip into a new database that keeps every InChIKey and value. + +### A new notebook template + +`templates.NAMES`, `_HEADINGS`, `_OBSERVATIONS` and `LABELS`; `EntryTemplate` and `TEMPLATES` in the notebook window with its label through `t()`; the `template` enum of `nb_add_entry`; DATABASE.md's template list. Headings are plain markup (`**Heading**`), never HTML. + +### A database route or MCP tool + +A thin route with `GUARD` (or `VIEW_GUARD` for a picture) on a worker thread, `DatabaseError` turned into its status; the function in `database-api.ts`; a tool in `agent_db.TOOLS` or `agent_notebook.TOOLS` with `mutating` deciding consent, writing as `agent:[name]`; then `./formchem agents sync` (its generated `tools.md` reads only mcp.py's own `TOOLS`, so module tools are documented in `docs/AGENTS.md` and the harness `databases` sub-skill). + +## Checks + +Scratch data folders only (`FORMCHEM_DATA_DIR=[scratch]/data`). Import a 10,000 record SD file with three broken records: 9,997 added and three plain reasons. Benzene substructure equals a brute-force `HasSubstructMatch` on a 2,000 record copy; thresholds 0.3 to 0.9 never rise. A second process opens the file read-only and gets 423 on writes. The table under 4x CPU throttling: layout shift 0 while scrolling, no row nodes added on sort. An entry signed, then changed, keeps one `edited-after-signing` version with the signed hash. + +## Gate + +- [ ] DATABASE.md, the engine and `database-api.ts` agree; a shape change raised the format version with a migration. +- [ ] Every new write is one transaction with an audit row and a notify after commit. +- [ ] New numbers name their method and version; similarity stays monotonic. +- [ ] The checks above ran on scratch data, and HASHOUT entries are written. + +## Hands back + +The change, the check output with numbers, and the HASHOUT entries. diff --git a/.claude/skills/formchem-skillset/sub-skills/family-integration/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/family-integration/SUB-SKILL.md new file mode 100644 index 00000000..7881ade5 --- /dev/null +++ b/.claude/skills/formchem-skillset/sub-skills/family-integration/SUB-SKILL.md @@ -0,0 +1,84 @@ +--- +name: family-integration +description: "FormChem's 0.12.0 family integration code: live structures and the shared structure library (services/live_structures.py, routers/structures.py, agent_library.py, app/live-structures.ts, ui/library-dialog.ts, the contract docs/LIVE_STRUCTURES.md), the agent token's one write path (core/window_key.py AGENT_WRITES), formchem edit-live, the formai:// deep link (tauri-plugin-deep-link, followDeepLinks, handleDeepLink), the file watch and its bar (services/file_watch.py, ui/file-changed-bar.ts), and accessibility (canvas/a11y: the key route, navigation, spoken atoms and bonds, the focus ring, element palettes; ui/a11y-announcer.ts, ui/structure-summary.ts, services/describe.py). Use when changing what a sibling Form app reads, the clipboard flavours of Copy as Live Structure, the library folder or library.json, a live drawing's Save, edit-live or the deep link, the file changed bar, a keyboard focus key, a spoken sentence, the Structure Summary, a functional group or ring name, or an element palette." +--- + +# Family integration + +## Purpose + +Change how FormChem works with the other Form apps and with assistive technology without breaking what they rely on: the Library folder and the live structure object stay readable by apps that never run FormChem code, a live drawing saves to its item and nothing else, the agent token writes nowhere but `/api/structures`, the keyboard route runs before the canvas's, every spoken sentence is a whole `t()` template, and switching palettes or showing the file bar never moves a node. Hands back the change, the checks that prove it and HASHOUT entries. + +## Preconditions + +`clean-room` loaded (the family and accessibility sections of the clean-room specifications, spec C 9.4). `docs/LIVE_STRUCTURES.md` read in full: it is the contract sibling apps code against, and when code disagrees with it, fix one of them in the same change and say which in the HASHOUT log. + +## File map + +| Path | Holds | +| --- | --- | +| `backend/app/services/live_structures.py` | `folder` (`FORMCHEM_DATA_DIR/Library`, not the recent-drawings `library.json`), `read_index`, `write_file`, `write_index` (atomic, index last), `add` (merges kinds for non-live, live always new), `prune` (`RECENT_CAP` 50 by `used`), `describe` (perceive, ids, `mass.average_mass`), `engine_pictures`, `live_object`, `adopt` (id kept, higher rev wins), `open_live`, `save_live`, `LINKS`, `links`, `open_request`, `edit_live` | +| `backend/app/routers/structures.py` | the contract routes plus `links`, the unkeyed `picture.svg/png`, `GET /api/files/watch` and `POST .../{reload or keep}`; `_guard` takes the window key or the agent token | +| `backend/app/core/window_key.py` | `AGENT_WRITES`, `agent_may_write`: the global guard lets a valid bearer token through on `/api/structures` and below only | +| `backend/app/services/file_watch.py`, `app/main.py` lifespan | the 1 s poll of open drawings' files, own saves recognised by `document.json` `modified`, `reload` (one undoable transaction), `keep` | +| `backend/app/services/agent_library.py` | `library_list`, `library_add`, `live_structure_object` in the agent module shape | +| `backend/app/cli.py`, `formchem`, `formchem.bat` | `edit-live` | +| `src-tauri/` (Cargo.toml, main.rs, tauri.conf.json, capabilities) | tauri-plugin-deep-link 2.6.3, the `formai` scheme, single-instance with `deep-link`, `register_all()` on Linux | +| `frontend/src/app/live-structures.ts` | `structuresApi`, `copyLiveStructure` (one `writeClipboard`), `starStructure`, `saveTemplateToLibrary`, `saveLive`, `liveActive`, `mountLiveDrops`, `deepLinkTarget`, `handleDeepLink`, `LIVE_MIME`, `WEB_LIVE_MIME` | +| `frontend/src/app.ts` `followDeepLinks`; `app/documents.ts` `DocumentHooks.save` | deep links in the main window only; closing a dirty live drawing saves its item | +| `frontend/src/ui/library-dialog.ts`, `ui/file-changed-bar.ts`, `styles/library.css` | the Structure Library (built once, tiles keyed by id, fixed 132 px rows); the bar inside `.fc-stage` | +| `frontend/src/canvas/a11y/` | `index.ts` (`prepareA11y` before `mountCanvas`, `mountA11y`), `controller.ts` (`installA11yKeys`, `CanvasA11y`, `relayCanvasPrompts`), `nav.ts`, `speech.ts`, `elements.ts`, `ring.ts`, `palette.ts`, `commands.ts` (`PALETTE_COMMAND_IDS`), `describe-api.ts` | +| `frontend/src/canvas/render/atom.ts` | `ELEMENT_PALETTES` (standard, high-contrast, colour-blind), `setElementPalette` | +| `frontend/src/ui/a11y-announcer.ts`, `ui/structure-summary.ts`, `styles/a11y.css` | the shared live regions; the summary dialog; focus ring, outlines, 24 px targets | +| `backend/app/services/describe.py`, `routers/describe.py` | `GROUPS` (42 SMARTS), `RING_NAMES` (51 skeletons), `functional_groups` (priority, claimed atoms), `ring_name`, `stereo`, `describe`; `POST /api/describe` | +| `docs/LIVE_STRUCTURES.md`, `LIVE-STRUCTURES.md`, `ACCESSIBILITY.md` | the contract; the person's pages. HASHOUT backend 256 to 264 and 276 to 278, frontend 277 to 295 and 300 | + +## Laws + +1. **The folder is the contract.** Every Library file is written through `core/files.write_atomic`, item files first and `library.json` last; deletes write the index first. Readers skip items whose files are missing. A field a sibling reads changes LIVE_STRUCTURES.md, `live_structures.py` and `live-structures.ts` together, and `format_version` rises only for a change an old reader would misread. +2. **The drawing inside is the structure.** Every item SVG and PNG carries the FormChem source in the carriers of FORMATS.md, whoever drew it (the window's pictures, or `engine_pictures` without a window). A picture without it is a bug, not a lighter item. +3. **A live drawing is ordinary.** Nothing is written into the drawing; the link lives in `LINKS` and the window's map. Save goes to `save_live` (rev + 1, `live-structure` broadcast), Save As stays an ordinary copy, closing calls the `DocumentHooks.save` hook. Revisions only rise: `adopt` keeps the higher rev. +4. **The agent token has one write path.** Only `/api/structures` and below; every other changing route still needs the window key. Widening `AGENT_WRITES` is a SECURITY.md change. +5. **The deep link only opens.** `deepLinkTarget` accepts `formai://formchem/edit?id=s[10]&from=...` and nothing else; other `formai` hosts pass on; only the `main` window listens. A link never carries a path, a command or a setting. +6. **The key route goes first.** `prepareA11y()` runs before `mountCanvas` so its capture listener precedes the view's; handled keys get `preventDefault` only (`stopImmediatePropagation` breaks the menu bar's Alt detection); Tab past the last atom leaves, so focus is never trapped. The focus is the view's keyboard cursor, not a second one. +7. **Speak whole sentences from fresh data.** Every spoken part is one `t()` template; derived values (hydrogens, CIP, aromaticity) only when `derived.rev` equals the client's and nothing is unconfirmed. One announcer for the window; the canvas's own region stays hidden and its prompts are relayed. +8. **Palettes patch fills.** The choice is read before the canvas exists (localStorage `formchem.elementPalette`); a switch bumps the measure epoch so only fills change. High contrast stays at 7:1 or more on white; the colour-blind palette keeps Okabe-Ito hues of 3:1 or more and leaves paler ones to the ink. +9. **Nothing moves.** The file bar is absolutely placed in the stage with a local z token; the library dialog patches tiles by id; the summary reserves its rows. + +## Recipes + +### A field or flavour a sibling reads + +LIVE_STRUCTURES.md first, then `live_object` or `describe` and `LiveObject` or `LibraryItem` in `live-structures.ts`, then `copyLiveStructure`'s flavour list. Browsers accept custom clipboard types only with the `web ` prefix and drop `chemical/x-mdl-molfile`; keep the object in the HTML flavour's `data-formai-structure` too. Check `library.json` field by field against the contract with a scratch script, and the clipboard in Chromium under 4x throttling. + +### A new way to open a live structure + +Route it to `open_live` (engine) or `openLiveStructure` (window), never a second opener. Command-line paths go through `open_request` and post with the agent token like `edit_live`; a desktop path goes through the deep link plugin and `handleDeepLink`. + +### A keyboard key or a spoken sentence + +Keys live in `controller.ts` (`installA11yKeys` and the handlers); registry commands in `commands.ts` with a key the 312-command registry does not already use (check `GET /api/commands`, and macOS reserved combinations such as Option-Command-D). Sentences go in `speech.ts` or `structure-summary.ts` as whole templates; element names in `elements.ts`. Check with Playwright reading `.fc-announcer-polite`, and say in the notes that no real screen reader ran unless one did. + +### A functional group or ring name + +Write the SMARTS or skeleton for FormChem (`clean-room`); a group marks its core atoms with map numbers and sits in priority order in `GROUPS`; a ring goes through the same `_skeleton_key` as the table. Re-run the 25-molecule scratch check (aspirin acid and ester, caffeine urea and purine, L-alanine S) and update the counts in NOTICE.md and ACCESSIBILITY.md. + +### An element palette + +A map in `ELEMENT_PALETTES` with contrast ratios computed on white in a scratch script, the choice in `PALETTE_CHOICES`, the Preferences option in `ui/prefs/sections.ts`. Check 0 nodes added or removed per switch under 4x throttling. + +## Checks + +From `backend/` on a scratch engine and data folder: `edit_live` against an item (exit 0), an unknown id (exit 1) and an unreadable file (exit 2); curl `/api/structures` without a key 403, with the token 200, and the token on `/api/helm/parse` and `/api/structuresX` 403; an outside rewrite of an open `.fchem` shows the bar within about a second and an own save does not. In the built window under 4x CPU throttling: Copy as Live Structure, paste back, open from the Live tab and Save raises rev; the keyboard-only ethanol speaks every atom and Describe reads its formula; palette switches and the file bar give layout shift 0. `npx tsc --noEmit` clean. + +## Gate + +- [ ] LIVE_STRUCTURES.md, the engine and the window agree; `library.json` written by FormChem passes a field-by-field check. +- [ ] No route other than `/api/structures` accepts the agent token for writes; the deep link still opens only. +- [ ] Keys still route before the canvas, Tab still leaves, and every new sentence is one `t()` template. +- [ ] No node added or removed by a palette switch or the file bar; tiles patched by id. +- [ ] HASHOUT entries and the docs updated; NOTICE.md own-data counts still true. + +## Hands back + +The change, the check results, the HASHOUT entries and the commit list. diff --git a/.claude/skills/formchem-skillset/sub-skills/three-d/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/three-d/SUB-SKILL.md index 48ca1508..d4adf2ff 100644 --- a/.claude/skills/formchem-skillset/sub-skills/three-d/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/three-d/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: three-d -description: "FormChem's 0.10.0 3D code: the engine package services/three_d (molecule labels, forcefield, build, verify, conformers, minimise, scan, measure, export, structure, pdb, mmcif, molfile3d, ligand, readers, document, stale), routers/three_d.py, the stale-conformer rule in the store and in engine/stale.ts, the window's 3D View panel over a lazily loaded 3Dmol.js (view3d-lib, view3d-viewer, view3d-panel, dialogs, scan plot), the model3d page renderer and its snapshots, the glb writer and the 3D commands. Use when adding a display style, a surface, a force field or method, a structure file reader, a 3D MCP tool or route, fixing a build that loses stereo, a conformer or scan result, a PDB summary or ligand, a 3D object that flashes on the page, or the conformer drop after an edit." +description: "FormChem's 0.10.0 3D code: the engine package services/three_d (molecule labels, forcefield, build, verify, conformers, minimise, scan, measure, export, structure, pdb, mmcif, molfile3d, ligand, readers, document, stale), routers/three_d.py, the stale-conformer rule in the store and in engine/stale.ts, the window's 3D View panel over a lazily loaded 3Dmol.js (view3d-lib, view3d-viewer, view3d-panel, dialogs, scan plot), the model3d page renderer and its snapshots, the glb writer and the 3D commands, and from 0.12.0 services/xtb (discovery, runner, jobs, parse, writeback) with routers/xtb.py, agent_xtb.py and the xtb dialogs. Use when adding a display style, a surface, a force field or method, an xtb or CREST option, a structure file reader, a 3D MCP tool or route, fixing a build that loses stereo, a conformer or scan result, a PDB summary or ligand, an xtb job that hangs or misreads output, a 3D object that flashes on the page, or the conformer drop after an edit." --- # Three-d @@ -11,7 +11,7 @@ Change FormChem's 3D without breaking its promises: every energy and measurement ## Preconditions -`clean-room` loaded (the 3D sections of the clean-room specifications). Licence rule: permissive anywhere; LGPL only as a separate process the person installs (xtb and CREST stay user-installed by path while plan question Q9 is open); GPL and AGPL never (no Open Babel code); gemmi (MPL-2.0) is not vetted. Ligand templates are written for FormChem; the Chemical Component Dictionary is CC0 but nothing was copied from it. +`clean-room` loaded (the 3D sections of the clean-room specifications). Licence rule: permissive anywhere; LGPL only as a separate process the person installs (xtb and CREST are user-installed by path, plan question Q9's default; never bundle, download or link them); GPL and AGPL never (no Open Babel code); gemmi (MPL-2.0) is not vetted. Ligand templates are written for FormChem; the Chemical Component Dictionary is CC0 but nothing was copied from it. ## File map @@ -29,7 +29,9 @@ Change FormChem's 3D without breaking its promises: every energy and measurement | `frontend/src/canvas/render/model3d.ts` | the page object (snapshot, or a placeholder) | | `frontend/src/io/glb.ts`, `chem/elements3d.ts`, `chem/geom3d.ts`, `chem/conformer-mol.ts` | glTF writer, palette and radii, measurement maths, local molfile | | `frontend/src/app/view3d-commands.ts`, `app/menus.ts` | `VIEW3D_COMMAND_IDS`, the commands, `DISPLAY_3D`, `SURFACE_3D` | -| `docs/3D.md`, `docs/FORMAT.md` | the reference; `conformers`, `conformer` and `model3d`. HASHOUT backend 199 to 222, frontend 222 to 244 | +| `backend/app/services/xtb/` (0.12.0) | `__init__` (methods, levels, limits, settings keys), `solvents` (24 ALPB), `discovery` (`find`, `_locate`, `child_env`), `inputs` (start geometry in label order, `electrons_check`, argv), `runner` (`Process`, own process group, `stop_all`), `jobs` (one at a time, `_collect`, `_prune`), `parse`, `writeback` (`records`, `program`, `label`) | +| `routers/xtb.py`, `services/agent_xtb.py`, `frontend/src/app/xtb-commands.ts`, `ui/xtb-dialog.ts`, `ui/prefs/xtb.ts` | the xtb routes and `_applier` over `three_d.commit`; the two tools; the client and commands; the dialogs; the Preferences rows | +| `docs/3D.md`, `docs/FORMAT.md` | the reference; `conformers` (with the xtb `program` record), `conformer` and `model3d`. HASHOUT backend 199 to 222 and 270 to 275, frontend 222 to 244, 298 and 299 | ## Laws @@ -50,11 +52,19 @@ Change FormChem's 3D without breaking its promises: every energy and measurement ### A force field or method -Add it to `METHODS` and `forcefield.setup` with its own fallback reason, to `FORCE_FIELDS` in `three-api.ts`, the panel's select, `_FF` in `mcp.py`, and `docs/3D.md`. An external program (xtb) runs as a separate process found by a path the person sets, never bundled or linked, and its energy is stored under its own `method`. +Add it to `METHODS` and `forcefield.setup` with its own fallback reason, to `FORCE_FIELDS` in `three-api.ts`, the panel's select, `_FF` in `mcp.py`, and `docs/3D.md`. An external program runs as a separate process found by a path the person sets, never bundled or linked, and its energy is stored under its own `method`, as xtb does (below). + +### An xtb or CREST option (0.12.0) + +1. Constants first: `xtb/__init__.py` (`METHODS`, `OPT_LEVELS`, limits) or `solvents.ALPB` (only solvents xtb documents). +2. `jobs.options` validates it (422 with the reason), `inputs.xtb_argv` or `crest_argv` passes it; never build a shell string, always an argv list. +3. Output: a new value is read in `parse.py` from the documented file layout and checked on a hand-written file under `/tmp`; it travels in the job's `conformers` table and, when it belongs with the geometry, in `writeback.program` (then FORMAT.md, `model.ts` `ConformerProgram` and `model.py` in one change). +4. Expose it: the dialog field in `xtb-dialog.ts` (built once; polling patches text only), the command `params` in `xtb-commands.ts`, the tool schema and `KEYS` in `agent_xtb.py`, `docs/3D.md` and `docs/AGENTS.md`. +5. Laws that stay: one job at a time; a failed job keeps its folder until it is forgotten; results map back by element order or the job fails (502); write-back goes through `three_d.commit` with the stale signature, so an edit mid-run fails the job instead of storing stale conformers. Check with a stand-in program on a temporary PATH (a script printing `xtb version X` and writing `xtbopt.xyz` and the log lines), never only with a real installation. ### A structure file reader -A parser returning `Structure` (with `summary` working on it), a `detect` rule and rows in `EXTENSIONS` and `MIMES`, `readers.read`, `document.MODEL_FORMATS` and `importers.MODELS_3D`, `package.EXT_BY_MIME`, the window's `OPEN_EXTENSIONS` and `STRUCTURE_ACCEPT`, and `routers/files.py` `SUFFIXES` so the desktop save accepts it (that list still lacks `.glb`, `.cif`, `.mmcif` and `.ent` at 0.10.0). The bytes stay as media; never rewrite the file. +A parser returning `Structure` (with `summary` working on it), a `detect` rule and rows in `EXTENSIONS` and `MIMES`, `readers.read`, `document.MODEL_FORMATS` and `importers.MODELS_3D`, `package.EXT_BY_MIME`, the window's `OPEN_EXTENSIONS` and `STRUCTURE_ACCEPT`, and `routers/files.py` `SUFFIXES` so the desktop save accepts it. The bytes stay as media; never rewrite the file. ### A 3D MCP tool or route diff --git a/.docs/wiki/3D.md b/.docs/wiki/3D.md index e5d0e18a..a92bbf85 100644 --- a/.docs/wiki/3D.md +++ b/.docs/wiki/3D.md @@ -64,13 +64,22 @@ Select a PDB or mmCIF model and choose 3D > Extract Ligand.... With several liga 3D coordinates belong to the structure they were built from. Change an element, a charge, a bond or a wedge, or add or delete atoms, and the structure's conformers are removed in the same undo step; build again. Moving atoms and changing colours keep them, and Undo brings them back. +## xtb and CREST + +From 0.12.0 FormChem runs xtb and CREST when you have installed them; it never includes or downloads them (they are LGPL-3.0 programs of the Grimme group). Get them from https://github.com/grimme-lab/xtb and https://github.com/crest-lab/crest (or conda-forge), then check Preferences > 3D > Tight-Binding Programs: each row shows the version and path FormChem found, or where to get the program. Set a path there when the program is not on your PATH. + +- **3D > Optimise with xtb...**: GFN2-xTB or GFN-FF, charge, unpaired electrons, an ALPB solvent (water, DMSO, chloroform and 21 more) or the gas phase, and either an optimisation or a single point energy. The result replaces the structure's conformers, as one undo step, with the energy in hartree and kcal/mol, the HOMO-LUMO gap and a label such as "xtb 6.7.1, GFN2-xTB, ALPB (Water)". +- **3D > Conformer Search with CREST...**: the same settings plus the energy window (6 kcal/mol) and how many to keep (20). The ensemble replaces the conformers, lowest first, with populations; conformers whose stereo no longer matches the drawing are left out and counted. + +The dialog shows progress and the program's last lines, Cancel Job stops a run, and a failed run keeps its folder so you can read the program's own files. + ## Not yet -- xtb and CREST are not offered; every energy is a force-field energy. +- xtb and CREST were checked with stand-in programs, not real installations. - Surfaces on large proteins take a while and hold the window meanwhile. - Measurements on a structure without a 3D object on the page last only while the panel is open. - Atropisomers and allene axial chirality are not recognised. ## For agents -`build_3d`, `conformers_3d`, `minimise_3d`, `scan_dihedral` and `measure_3d` work on a structure's conformers, `open_3d_structure` opens PDB, mmCIF, SD and MOL files, `extract_ligand` takes a ligand out, and `export_3d` writes MOL, SD, PDB or XYZ. See [Agents](Agents). +`build_3d`, `conformers_3d`, `minimise_3d`, `scan_dihedral` and `measure_3d` work on a structure's conformers, `open_3d_structure` opens PDB, mmCIF, SD and MOL files, `extract_ligand` takes a ligand out, and `export_3d` writes MOL, SD, PDB or XYZ. From 0.12.0 `xtb_optimise` and `crest_conformers` run xtb and CREST when they are installed. See [Agents](Agents). diff --git a/.docs/wiki/Accessibility.md b/.docs/wiki/Accessibility.md new file mode 100644 index 00000000..b7481171 --- /dev/null +++ b/.docs/wiki/Accessibility.md @@ -0,0 +1,37 @@ +# Accessibility + +From 0.12.0 FormChem can be used from the keyboard alone, speaks what it focuses through your screen reader, describes a whole structure in words, and offers element colours that stay apart. The full guide is [`docs/ACCESSIBILITY.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/ACCESSIBILITY.md). + +## Keys + +`Mod` is Cmd on a Mac and Ctrl elsewhere. + +| Key | What it does | +| --- | --- | +| `Alt+Mod+A` | View > Focus Structure: the focus ring goes onto the drawing | +| Tab, Shift+Tab | next or previous atom, in reading order | +| an arrow | the bonded atom in that direction | +| Ctrl, Cmd or Alt with an arrow | the bond in that direction | +| Space | select or deselect the focused atom or bond | +| Enter, then an arrow | draw a new bond in that direction (Enter on an empty drawing adds a carbon) | +| O, N, Cl and the other hover keys | change the focused atom | +| `Alt+Mod+]`, `Alt+Mod+[` | View > Next Atom, Previous Atom | +| `Alt+Mod+S` | View > Describe Structure | + +## What you hear + +Each move is spoken, for example "Oxygen. 1 hydrogen. Single bond to Carbon. Not in a ring. Atom 3 of 3." Describe Structure speaks and shows the formula, the name, the charge, the ring systems (named when FormChem knows them: benzene, pyridine, piperidine and others), the functional groups and the stereocentres with their R or S labels, each with the method behind it; Copy copies the text. + +## Element colours + +Preferences > Interface > Element colours, or View > Element Colours: Standard, High contrast (every element colour at 7:1 or more on white) or Colour-blind safe (the Okabe-Ito blue, vermillion, bluish green and reddish purple). They apply when Colour atoms by element is on, also to pictures and copies. + +## Focus and targets + +Every dialog control shows a 2 pixel outline from the keyboard; colour swatches and tool buttons are at least 24 pixels. + +## Not yet + +- Checked by reading what FormChem says, not with VoiceOver, NVDA or Orca. +- On many European Windows keyboards Ctrl+Alt is AltGr, so `Ctrl+Alt+[` and `]` may not type; use the View menu or the command palette. +- The 3D View has no keyboard rotation yet. diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index 80316343..005d9bf2 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -1,6 +1,6 @@ # Agents -FormChem's engine is an MCP server (`backend/app/routers/mcp.py`), over HTTP at `http://127.0.0.1:8220/mcp` and over stdio with `./formchem mcp` (`setup/mcp_stdio.py`, which starts the engine when needed). An agent works in the same window you see. From 0.8.0 it draws there directly: it makes and opens drawings, draws structures and reaction schemes from SMILES or molfiles, edits them atom by atom by id, reads them back in machine form and checks its work with a picture drawn by the window's own renderer. From 0.9.0 it also draws from chemical names and names what is drawn, predicts 1H and 13C NMR spectra, and opens JCAMP-DX spectra, picks their peaks and integrates them. From 0.10.0 it builds structures in 3D, searches conformers, minimises, scans dihedrals and measures, opens PDB, mmCIF and 3D SD files, extracts ligands and writes 3D files. Every change is one undo step, every call is listed in [Agent Activity](Agent-Activity), and you can stop an agent from the title bar. +FormChem's engine is an MCP server (`backend/app/routers/mcp.py`), over HTTP at `http://127.0.0.1:8220/mcp` and over stdio with `./formchem mcp` (`setup/mcp_stdio.py`, which starts the engine when needed). An agent works in the same window you see. From 0.8.0 it draws there directly: it makes and opens drawings, draws structures and reaction schemes from SMILES or molfiles, edits them atom by atom by id, reads them back in machine form and checks its work with a picture drawn by the window's own renderer. From 0.9.0 it also draws from chemical names and names what is drawn, predicts 1H and 13C NMR spectra, and opens JCAMP-DX spectra, picks their peaks and integrates them. From 0.10.0 it builds structures in 3D, searches conformers, minimises, scans dihedrals and measures, opens PDB, mmCIF and 3D SD files, extracts ligands and writes 3D files. From 0.11.0 it creates and opens structure databases, imports into them, searches them, registers and updates records, exports them, and adds and finds lab notebook entries. From 0.12.0 it keeps structures in the shared structure library, hands out live structure objects for sibling Form apps, draws peptides and nucleic acids from HELM, and runs xtb and CREST when you have installed them. Every change is one undo step, every call is listed in [Agent Activity](Agent-Activity), and you can stop an agent from the title bar. The full reference, with every tool's arguments and result shape and the recorded examples, is [`docs/AGENTS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/AGENTS.md). @@ -20,7 +20,7 @@ The full reference, with every tool's arguments and result shape and the recorde ## Tools -60 tools. Reading never asks you; a tool that changes something asks you in the window the first time (Consent, below). +77 tools. Reading never asks you; a tool that changes something asks you in the window the first time (Consent, below). | Group | Tools | Kind | | --- | --- | --- | @@ -34,6 +34,11 @@ The full reference, with every tool's arguments and result shape and the recorde | NMR prediction (0.9.0) | `predict_nmr` (read); `predict_spectrum` (change) | | | Spectra (0.9.0) | `open_spectrum`, `spectrum_pick_peaks`, `spectrum_integrate` (change); `spectrum_data`, `spectrum_peaks`, `spectrum_export` (read) | | | 3D (0.10.0) | `build_3d`, `conformers_3d`, `minimise_3d`, `open_3d_structure`, `extract_ligand` (change); `measure_3d` (read); `scan_dihedral` (change only with `store`); `export_3d` (change only when it writes outside the temporary folder) | | +| Databases (0.11.0) | `db_create`, `db_open`, `db_add_record`, `db_update_record` (change); `db_list`, `db_search`, `db_get_record` (read); `db_import` (change unless `dry_run`); `db_export` (change only when it writes outside the temporary folder) | | +| Notebook (0.11.0) | `nb_add_entry` (change); `nb_search` (read) | | +| Library (0.12.0) | `library_add` (change); `library_list`, `live_structure_object` (read) | | +| HELM (0.12.0) | `draw_from_helm` | change | +| xtb and CREST (0.12.0) | `xtb_optimise`, `crest_conformers` (need the programs installed) | change | | Window and extensions | `list_commands`, `extensions_list` (read); `run_command`, `extension_command` (change) | | | Handoff | `handoff` | change with a state | | Reactions (0.5.0) | `perceive_reactions`, `map_reaction` (change); `export_reaction`, `reaction_stoichiometry` (read) | | @@ -78,6 +83,21 @@ The full reference, with every tool's arguments and result shape and the recorde | `open_3d_structure {path, doc?, as?, x?, y?}` | a PDB or mmCIF file as a 3D object (cartoon, ligand in focus, the file kept as it is), or SD and MOL records as structures with their file coordinates | | `extract_ligand {doc?, object?, ligand?}` | a ligand of a PDB or mmCIF model as a structure beside it, with its SMILES and whether its bond orders were inferred | | `export_3d {doc?, object?, format?, conformer?, output?}` | MOL, SD, PDB or XYZ text with every hydrogen, or a new file | +| `db_list`, `db_create {title, path?}`, `db_open {path}` | the open and known databases; make or open an `.fcdb` file and get its handle, record count, fields and whether it is read-only ([Databases](Databases)) | +| `db_import {path, db?, format?, mode?, key?, mapping?, dry_run?, wait?}` | SD, RD, SMILES, CSV, TSV or `.fchem` records as a job: added, updated and failed, with each failed record's number and reason | +| `db_search {db?, smiles?, mode?, threshold?, smarts?, query?, within?, name?, limit?}` | substructure, similarity (with scores), exact or a full query; the hit list with its first rows, which you also see in the window | +| `db_get_record {uid, db?}` | one record with its molfile, keys, field values and files | +| `db_add_record {smiles or molfile, db?, values?, on_duplicate?}` | registers a structure; a duplicate is refused with the matches until the agent chooses existing, batch or new | +| `db_update_record {uid, db?, smiles?, molfile?, values?}` | changes a record's structure or field values | +| `db_export {format, db?, path?, hitlist?, uids?, fields?, v3000?, structure_as?}` | SD, SMILES or CSV of a hit list, some records or the whole database | +| `nb_add_entry {db, title, template?, date?, author?, procedure?, observations?, tags?, products?, reaction? or doc?}` | an open (unsigned) notebook entry with its scheme and the stoichiometry computed from it ([Lab Notebook](Lab-Notebook)) | +| `nb_search {db, query?, substructure?, limit?}` | notebook entries by words or by a substructure of their scheme, newest first | +| `library_list {kind?}` | the shared structure library's items ([Live Structures](Live-Structures)) | +| `library_add {smiles or doc, ids?, name?, kinds?}` | adds a structure as a favourite, template, recent or live item, with pictures that keep the drawing inside | +| `live_structure_object {id}` | the JSON a sibling Form app stores for a live structure | +| `draw_from_helm {helm, doc?, x?, y?, name?}` | a peptide or nucleic acid from HELM as atoms, one undo step ([Biopolymers](Biopolymers)) | +| `xtb_optimise {object?, method?, charge?, uhf?, solvent?, single_point?, level?, limit?}` | an xtb optimisation or single point stored as the structure's conformer, with the energy in hartree and kcal/mol ([3D](3D)) | +| `crest_conformers {object?, method?, solvent?, ewin?, keep?, limit?}` | a CREST conformer ensemble with populations | | `list_commands`, `run_command` | the window's command catalogue, the same commands as the menus | | `extensions_list`, `extension_command` | Form extensions and their commands | | `handoff {state?, note?}` | working, ready or question, with a note the person sees | @@ -98,6 +118,10 @@ From 0.9.0: `draw_from_name {name: "ethyl ethanoate"}` draws a name exactly as ` From 0.10.0: `build_3d {object}` builds a conformer and says whether every drawn stereocentre was kept ("all 11 stereo labels kept" for Taxol), so an agent checks that line before using the geometry; `measure_3d {atoms: [C, O]}` then reads ethanol's C-O as 1.42 Å with the method. `conformers_3d`, `minimise_3d` and `scan_dihedral` give energies with their force field and engine version; a scan stores nothing unless `store` is true. `open_3d_structure {path}` opens a PDB or mmCIF file as a 3D object and lists its chains, ligands and waters, `extract_ligand` turns one ligand into a structure (saying when its bond orders were inferred), and `export_3d` returns MOL, SD, PDB or XYZ text. An edit to a structure's atoms or bonds removes its conformers, so build again after editing. Styles, surfaces and the PNG and glTF exports of the 3D View are window commands (`style-ballstick`, `surface-vdw`, `export-gltf` and the rest) for `run_command`. +From 0.11.0: `db_open {path}` (or `db_create {title}`) gives a database handle; with one database open the other `db_` tools can leave `db` out. `db_import {path, dry_run: true}` counts what would be added and failed before the real import, and a bad record never stops it. `db_search {smiles: "c1ccccc1"}` answers the hit list, its count, the time and the method, and the hit list appears in your window too. `db_add_record` refuses a duplicate and lists the matches until the agent chooses `on_duplicate`. `nb_add_entry` writes an open entry from reaction SMILES or a drawing; only you sign entries. Every write is recorded with the agent's name in the database's log and in Agent Activity. + +From 0.12.0: `library_add {smiles: "Oc1ccccc1", name: "Phenol"}` adds a structure to the shared library (asking you the first time), `library_list` lists it and `live_structure_object {id}` returns the object a sibling app stores. `draw_from_helm {helm: "PEPTIDE1{G.G}$$$$"}` draws glycylglycine; bad HELM is refused with the character where reading stopped. `xtb_optimise` and `crest_conformers` wait for xtb or CREST and store the result as conformers in one undo step; when the programs are not installed they say where to get them, because FormChem never includes or downloads them. + Which drawing: `doc` when given; else the only open drawing; else the drawing the window shows; else the tool asks for `doc`. Coordinates are points, x right and y down; the default bond length is 14.4 points. `get_context` lists every drawing open, oldest first, as text and in `structuredContent.documents`: @@ -153,4 +177,4 @@ Every tool call, from any transport or from the window's own chat, is logged by ## Skills -`formchem-harness` (using FormChem: drawing with the tools, checking with render and get_structure, names, NMR prediction and spectra, 3D, commands, reactions, analysis, handoff) and `formchem-skillset` (developing FormChem), in `.claude/skills` and mirrored to `.agents/skills`. The harness's `references/tools.md` is generated from the server and lists every argument. +`formchem-harness` (using FormChem: drawing with the tools, checking with render and get_structure, names, NMR prediction and spectra, 3D and xtb, databases and the notebook, the structure library and HELM, commands, reactions, analysis, handoff) and `formchem-skillset` (developing FormChem), in `.claude/skills` and mirrored to `.agents/skills`. The harness's `references/tools.md` is generated from the server and lists every argument of all 77 tools. diff --git a/.docs/wiki/Architecture.md b/.docs/wiki/Architecture.md index 2a1226aa..80f6d973 100644 --- a/.docs/wiki/Architecture.md +++ b/.docs/wiki/Architecture.md @@ -2,18 +2,27 @@ ``` frontend/ vanilla TypeScript and Vite: engine/ (model, ops, document client, session, reactions-api, names-api, nmr-api, spectra-api, - three-api, stale), chem/ (valence, rings, formula, stoich, spectrum-ops, elements3d, geom3d, conformer-mol), canvas/ (view, hit + three-api, stale, database-api), chem/ (valence, rings, formula, stoich, spectrum-ops, elements3d, geom3d, conformer-mol), canvas/ (view, hit testing, tools, spectrum-links, render/ with one module per object kind, spectrum and its data cache and model3d included), app/ (menus, shell, canvas, object and reaction commands, documents, window tools, agent-window, agent-calls, agent-activity, - name, nmr, spectrum and 3D commands), ui/ (shell, menus, Home, Preferences, tool rail, Analysis and Stoichiometry panels, + name, nmr, spectrum, 3D, database, live structure, HELM and xtb commands), canvas/a11y/ (keyboard focus, spoken atoms + and bonds, palettes), ui/ (shell, menus, Home, Preferences, tool rail, Analysis and Stoichiometry panels, Structure + Library, file changed bar, announcer, Structure Summary, HELM and xtb dialogs, template library, Agent activity panel, agent chip, name dialog, Spectrum editor, 3D View panel with its viewer, lazy 3Dmol.js - loader and dialogs), io/ (glb), dock/, extensions/, styles/ + loader and dialogs, database/ (the database workspace, table, gallery, form and dialogs), database-find/ (search, query + builder, hit lists, saved queries, import, export, plot), notebook/ (the notebook view and entry editor)), io/ (glb), dock/, + extensions/, styles/ backend/ FastAPI engine: core/ (config, guard, window key, seal, agent token), routers/ (system, live, library, commands, documents, chem, reactions, - templates, terminal, chat, extensions, mcp, agent_activity, names, nmr, spectra, three_d), services/ (model, ops, store, history, - package, importers, templates, agent_out, agent_draw, agent_edits, agent_convert, agent_log, chem/ on RDKit and Indigo, names/ (the - name engines), nmr/ (the increment predictor), spectra/ (the JCAMP-DX reader and spectrum service), three_d/ (3D building, - conformers, force fields, scans, PDB and mmCIF readers, ligands, the stale-conformer rule)), data/templates/, data/names/ -src-tauri/ the desktop shell; the frozen engine runs from a folder inside the app on macOS and as a sidecar elsewhere + templates, terminal, chat, extensions, mcp, agent_activity, names, nmr, spectra, three_d, databases, db_search, notebook, + structures, describe, helm, xtb), services/ (model, ops, store, history, package, importers, templates, agent_out, agent_draw, + agent_edits, agent_convert, agent_log, agent_db, agent_notebook, agent_library, agent_helm, agent_xtb, live_structures, + file_watch, describe, helm/ (HELM reader, writer, monomers), xtb/ (finding and running xtb and CREST), chem/ on RDKit and Indigo, names/ (the name engines), nmr/ (the increment predictor), + spectra/ (the JCAMP-DX reader and spectrum service), three_d/ (3D building, conformers, force fields, scans, PDB and mmCIF + readers, ligands, the stale-conformer rule), database/ (the .fcdb store, registration, fields, import, export, search, hit + lists, the command line), notebook/ (entries, the content hash, schemes, export)), data/templates/, data/names/, + data/helm_monomers.json +src-tauri/ the desktop shell; the frozen engine runs from a folder inside the app on macOS and as a sidecar elsewhere; the deep link + plugin registers formai:// ``` ## The engine owns the document @@ -64,6 +73,30 @@ From 0.10.0 the engine's `services/three_d/` (routes under `/api/documents/{id}/ - **Structure files stay as files.** A PDB or mmCIF file read by FormChem's own readers becomes a `model3d` object over the bytes kept as media, so saving, exporting and pasting carry the original file. 3D SD and MOL records become structures whose file coordinates are their conformer. - **The window shows, the engine computes.** The 3D View panel loads 3Dmol.js on first use (its own chunk, so startup is unaffected), reads a structure as a molfile with an atom map from the engine (or writes one locally from the stored conformer), and measures in the window with the engine's formulas. A `model3d` on the page is drawn as a PNG snapshot of the view; the panel writes a new snapshot, the camera and the style in one coalesced transaction after the person changes the view, and the renderer keeps the old picture until the new one has loaded, so the page never flashes. Exports and print use the snapshot and need no 3D renderer. +## Databases and the notebook + +From 0.11.0 the engine's `services/database/` and `services/notebook/` (routes under `/api/databases`) keep structure databases and lab notebook entries. They live beside the document store, not in it: a database is not a drawing, has no undo stack and is not sent as transactions. ([`docs/DATABASE.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/DATABASE.md), [`docs/DATABASES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/DATABASES.md)) + +- **One file, one connection, one lock.** Each open `.fcdb` is a handle (`g` and eight characters) with one SQLite connection and a lock; every write is one `BEGIN IMMEDIATE ... COMMIT` and one audit row, and reads take the same lock. A lock file beside the database makes a second FormChem or the command line open it read-only. +- **Chemistry enters through one function.** `database/chem.py` `register_values` computes the keys, formula, masses and both fingerprints of every stored structure and of every exact query, so they always agree. +- **Search screens in memory.** `database/search.py` keeps each database's fingerprints as numpy arrays, refreshed only when the record count, the newest id or the newest audit row moves; substructure hits are screened there and confirmed by an RDKit SubstructLibrary, similarity is computed for every row at once, and every query term is a mask. Every search is stored as a hit list. +- **Long work runs as jobs.** Imports and large exports run on worker threads in batches of 250 records, each its own transaction, with a report of failed records the window polls. +- **Everyone hears about it, after the commit.** Each write broadcasts `{t: "database", db, change, uids?}` on the live channel once committed. The window's workspace refetches only the rows or lists the message names; rows are paged in blocks of 100, pooled and keyed by uid, so a 10,000 record table never rebuilds. +- **The notebook reuses the chemistry.** An entry's scheme is a one-page FormChem document; its stoichiometry is computed on every read by the reaction services, and its content hash covers the scheme, text, products, tags and file hashes, so signing can tell when it changed. +- **Pictures have their own key.** Database reads need the window key; thumbnails and attachments, loaded by image and link tags, take a second view key that opens only those two routes. + +## Family integration + +From 0.12.0 FormChem shares structures with the other Form apps and runs outside programs, without changing the document flow. ([`docs/LIVE_STRUCTURES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/LIVE_STRUCTURES.md), [`docs/HELM.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/HELM.md), [`docs/3D.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/3D.md)) + +- **The library is plain files.** `services/live_structures.py` writes `Library/library.json` and an SVG, PNG and molfile per item, each through a temporary file and a rename, the index last, so sibling apps read it without FormChem running. +- **A live drawing is an ordinary drawing with a link.** Opening an item makes a normal session from the drawing inside its SVG and keeps `{id, rev, from}` beside it in memory; Save rewrites the item and raises its revision instead of writing a `.fchem`, and the engine broadcasts `live-structure`. Nothing is written into the drawing, so Save As copies are ordinary. +- **Three ways in.** The window's commands, `./formchem edit-live` (which posts with the agent token, the one thing that token may write outside `/mcp`) and the `formai://formchem/edit` deep link, which the desktop shell receives through tauri-plugin-deep-link and the main window alone handles. +- **The file watch polls.** Once a second the engine compares the size and time of each open drawing's file and broadcasts `file-changed` when another program moved it; FormChem's own saves are recognised by the `modified` time inside the file. +- **Accessibility sits in front of the canvas.** The keyboard route in `canvas/a11y/` is installed before the canvas's own key handler, moves the view's keyboard cursor, and speaks through one shared live region; `POST /api/describe` gives the summary with the method of each part. +- **HELM becomes atoms.** `services/helm/` reads HELM against FormChem's own monomer data and joins monomers into one RDKit molecule, which enters the drawing as an ordinary fragment through the template placement path, one transaction. +- **xtb and CREST run outside.** `services/xtb/` finds the programs the person installed, runs one job at a time as a separate process in its own folder, and writes the result back as one 3D transaction with the stale-conformer check, as the 0.10.0 3D routes do. + ## Guarding the engine The engine binds to 127.0.0.1. A local guard refuses requests whose Host or Origin is not local, and a window key made at each start lets only the FormChem window change settings, use the terminal dock or answer an agent's question. Saved agent choices are sealed with a key in the system keychain. From 0.8.0 the MCP endpoint also needs the agent token (`core/agent_token.py`, the file `agent-token` in the data folder), which the stdio relay and the agent configs send. diff --git a/.docs/wiki/Biopolymers.md b/.docs/wiki/Biopolymers.md new file mode 100644 index 00000000..35081f16 --- /dev/null +++ b/.docs/wiki/Biopolymers.md @@ -0,0 +1,27 @@ +# Biopolymers + +From 0.12.0 FormChem reads peptides and nucleic acids written in HELM and writes structures back to HELM. The full guide is [`docs/HELM.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/HELM.md). + +## From HELM + +Insert > Biopolymer from HELM... reads as you type: the structure, the number of monomers, the formula and the masses with their method, or the character where reading stopped. Insert places it as atoms, one undo step. + +| Try | What it is | +| --- | --- | +| `PEPTIDE1{G.G}$$$$` | glycylglycine | +| `PEPTIDE1{C.Y.I.Q.N.C.P.L.G.[am]}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$V2.0` | oxytocin with its disulfide | +| `RNA1{R(A)P.R(U)}$$$$` | the dinucleotide ApU | + +Read: PEPTIDE, RNA and CHEM simple polymers, RNA branches such as `R(A)P`, whole repeat counts, inline SMILES monomers and connections (disulfides, lactam bridges, rings). Refused, with the reason: mixtures, BLOBs, repeat ranges, hydrogen-bond pairs and unknown attachment points. + +## To HELM + +Edit > Copy As > Copy as HELM writes a peptide or nucleic acid drawn as atoms back to HELM, with its connections. FormChem copies it only when the HELM reads back to the same structure; otherwise it tells you which piece it could not match. + +## The monomers + +55 monomers written for FormChem from textbook structures: the 20 amino acids and their 19 D forms (`[dA]` and so on), Aib, Nle, Orn, Sar, Hyp and pyroglutamate (`[pE]`), the caps `[ac]` and `[am]`, ribose `R` and deoxyribose `[dR]`, phosphate `P`, and the bases A, C, G, U and T. No HELM monomer library was copied. Anything else can be written as inline SMILES. + +## Agents + +`draw_from_helm` draws a HELM string in a drawing as one undo step; see [Agents](Agents). diff --git a/.docs/wiki/Command-Line.md b/.docs/wiki/Command-Line.md index 90f45f8c..81857234 100644 --- a/.docs/wiki/Command-Line.md +++ b/.docs/wiki/Command-Line.md @@ -1,6 +1,6 @@ # Command Line -From 0.7.0 four commands work on whole files of structures without the window: convert between formats, convert a folder, write properties to a CSV file and draw every record as a picture. They run from the source tree with the engine's Python; the full reference with timings is [`docs/CLI.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/CLI.md). +From 0.7.0 four commands work on whole files of structures without the window (and from 0.11.0 `./formchem db` works on databases, and from 0.12.0 `./formchem edit-live` opens a live structure in the running FormChem, both below): convert between formats, convert a folder, write properties to a CSV file and draw every record as a picture. They run from the source tree with the engine's Python; the full reference with timings is [`docs/CLI.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/CLI.md). ## The four commands @@ -35,6 +35,44 @@ A record that cannot be read never stops the run. The first 20 failures are prin On a two-core machine, 10,000 SD records convert to SMILES in about 1.4 seconds, to InChIKey in about 4 seconds, and with standardising in about 22 seconds. `--jobs N` (0 for one per CPU) uses several processes for large files and folders, with the output always in input order. +## Databases + +From 0.11.0 `./formchem db` works on structure databases ([Databases](Databases)) without the window: + +| Command | What it does | +| --- | --- | +| `./formchem db create TITLE [--path FILE.fcdb]` | makes a database (in the `Databases` folder of the data folder unless `--path` says otherwise) | +| `./formchem db info DB` | title, record and entry counts, duplicate rules and fields | +| `./formchem db import DB FILE` | imports SD, RD, SMILES, CSV, TSV, `.fchem`, molfile or InChI files; `--mode` new, append or merge, `--key`, `--dry-run`, `--errors failed.csv` | +| `./formchem db search DB --substructure SMILES` | also `--similarity SMILES --threshold 0.7`, `--exact`, `--formula C6-8N1` or `--query JSON`; prints the first 20 hits (`--show N`) and keeps the hit list for the window | +| `./formchem db export DB OUT` | the whole database or `--hitlist ID` to SD (`--v3000`), SMILES or CSV (`--inchi`), `--fields a,b` | + +``` +./formchem db create Demo +./formchem db import ~/formchem/Databases/Demo.fcdb big.sdf --errors failed.csv +./formchem db search ~/formchem/Databases/Demo.fcdb --substructure c1ccccc1 +./formchem db export ~/formchem/Databases/Demo.fcdb hits.sdf --hitlist 1 +``` + +Every subcommand takes `--json`. The command ends with 0 on success, 1 when an import did not finish and 2 when it was refused. A database open in the app opens read-only here, and the other way round. + +## Editing a live structure + +From 0.12.0 `./formchem edit-live` asks the FormChem that is running to open a structure from the shared structure library for editing ([Live Structures](Live-Structures)). Sibling Form apps use it; so can a script. + +| Command | What it does | +| --- | --- | +| `./formchem edit-live ID` | opens library item `ID` (or the path of its `Library/items/ID.svg`) as a live drawing | +| `./formchem edit-live --object FILE` | opens the live structure object saved in `FILE`, adding it to the library first when it is new or newer | +| `--from APP` | names the app asking; the title bar shows "Live structure from APP" | + +``` +$ ./formchem edit-live s7jkf0w3t10 --from FormTxt +Opened Phenol for editing in FormChem (live structure s7jkf0w3t10, rev 1). +``` + +It ends with 0 when the structure opened, 1 when FormChem is not running or refused, and 2 when the argument could not be read. + ## Pictures from the command line `render` draws with RDKit, close to the journal style (14.4 pt bonds, 0.6 pt lines, 10 pt Arimo labels, black on white), not with the window's own drawing code, so labels, wedges and double bonds can sit a little differently. For pictures exactly as the window shows them, with the drawing kept inside, use File > Export ([Formats and Export](Formats-and-Export)). diff --git a/.docs/wiki/Databases.md b/.docs/wiki/Databases.md new file mode 100644 index 00000000..30ccdee6 --- /dev/null +++ b/.docs/wiki/Databases.md @@ -0,0 +1,59 @@ +# Databases + +From 0.11.0 FormChem keeps compounds in structure databases. A database is one `.fcdb` file (a SQLite file any SQLite browser opens), so copying the file copies everything: records, your fields, files, hit lists, saved queries, forms and the [lab notebook](Lab-Notebook). The full guide is [`docs/DATABASES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/DATABASES.md); the file and its routes are defined in [`docs/DATABASE.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/DATABASE.md). + +## A database in three steps + +1. File > New Database..., give it a title (it goes to the `Databases` folder of the data folder unless you choose one). +2. Database > Import Records..., pick an SD, SMILES, CSV or TSV file, check the column mapping, press Check to see the counts, then Import. +3. Click Structure beside the search bar with a ring drawn in a drawing, choose Substructure, and the hits appear as a hit list. Database > Export Records... writes them to SD. + +## The workspace + +| Part | What it does | +| --- | --- | +| Left column | open databases, hit lists (newest first, with counts) and saved queries in folders | +| Search bar | names, ids, formulas (`C6-8N1`) and SMILES; Structure searches with your drawing | +| Views | Table, Gallery, Form, Plot and Notebook, sharing one selection | +| Toolbar buttons | Import, Export, Add Structure, Advanced Search and the gear menu (settings, fields, Save Query, Combine Hit Lists, New Notebook Entry) | + +File > Databases (`Ctrl+Shift+D`, `Cmd+Shift+D` on a Mac) shows and hides the workspace; Home's Databases list opens one. In a browser window, File > Open of an `.fcdb` file or a drop on Home copies it into the Databases folder and opens it. + +## Records and fields + +- The table sorts by any column, resizes, hides and freezes columns, and edits a field in place (double-click; Enter saves, Escape cancels). It loads rows as you scroll, so 10,000 records scroll at once. +- Database > Fields... adds your own fields: text, numbers with units, dates, yes or no, choices, structures, files, links to other records, and computed descriptors (cLogP, TPSA and others) that follow the structure and name their method. +- Structure > Add to Database registers a structure from a drawing. The rules in Database > Database Settings... decide what a duplicate is (stereo matched or ignored, salts stripped or kept); a dialog then offers Open Existing, Add as New Batch or Add Anyway. Registration numbers are never reused. +- Enter on a record shows its details and files; Open in Drawing opens it as a drawing. + +## Searching + +| Search | How | +| --- | --- | +| Exact | the same compound, stereo, salts, charges and tautomers matched or ignored | +| Substructure | contains the drawn structure (or a SMARTS in Advanced Search) | +| Similarity | Tanimoto on Morgan fingerprints at or above a threshold (0.7), each hit with its score | +| Formula | element counts or ranges, `C6-8H*N1O0-2` | +| Fields | text, numbers, dates, choices, empty or not | + +Advanced Search... combines terms in All of, Any of and None of groups and can search within the current hit list. Every search becomes a hit list: keep it, rename it, export it, or combine two by union, intersection or difference. Save Query... keeps a query in a folder to run again. + +## Plot + +The Plot view draws a histogram of one field or a scatter of two with a least-squares line and R squared, coloured by a third field if you like. Drag a rectangle or lasso and choose Hit List from Selection. + +## Import and export + +Import reads SD (V2000 and V3000), RD, SMILES, CSV and TSV files and `.fchem` drawings, maps columns to fields (or new fields), and runs as new records, appended records or a merge that updates matching records. Check counts what would happen first. A bad record never stops an import; the report lists each one with its number and a plain reason. Export writes SD (every field as a data item), SMILES or CSV; an SD file exported and imported again keeps every InChIKey and field value. + +## When a database is read-only + +A database another FormChem (or the command line) has open opens read-only and says why; you can browse, search and export, but not change it. + +## Not yet + +- The desktop app's file choosers, Link File and dropping an `.fcdb` file on the desktop window were not tried for 0.11.0. +- The workspace covers the in-window menu bar while it is open; its toolbar and gear menu carry the commands. +- Record values, hit list names, saved query names and entry titles show as typed in every language; RDKit's own messages stay in English. + +See also [Lab Notebook](Lab-Notebook), [Command Line](Command-Line) for `./formchem db`, and [Agents](Agents) for the database tools. diff --git a/.docs/wiki/Getting-Started.md b/.docs/wiki/Getting-Started.md index f0961efa..64d6d0e6 100644 --- a/.docs/wiki/Getting-Started.md +++ b/.docs/wiki/Getting-Started.md @@ -26,6 +26,18 @@ Aspirin, with the mouse and a few keys: Faster: copy `CC(=O)Oc1ccccc1C(=O)O` and press `Ctrl+V` on the canvas, or use Insert > Structure from SMILES. Molfile, SDF, RXN, SMILES, InChI, CML, CDXML and CDX files open from File > Open or by dropping them on Home, PDB and mmCIF files open there as 3D objects, and Ctrl+3 shows a structure in 3D after 3D > Build 3D from 2D ([3D](3D)), and File > Export saves PNG, SVG, PDF and EPS pictures that open again as the drawing ([Formats and Export](Formats-and-Export)). The page is dark by default; View > Dark Page turns it off ([Grid and Page](Grid-and-Page)). [Drawing](Drawing) lists every tool and hover key, and how to draw with the keyboard alone. +## A database in three steps + +1. File > New Database..., type a title and press Create. The database workspace opens with the empty database (an `.fcdb` file in the `Databases` folder of the data folder). +2. Database > Import Records..., choose an SD, SMILES, CSV or TSV file, look over the column mapping, press Check for the counts, then Import. When it ends, the report lists any bad records with their reasons. +3. Draw a benzene ring in a drawing (File > Databases, `Ctrl+Shift+D`, switches back and forth), select it, then click Structure beside the search bar and choose Substructure. The hits become a hit list in the left column; Database > Export Records... writes them to an SD file. + +[Databases](Databases) covers fields, duplicates, the plot and saved queries, and [Lab Notebook](Lab-Notebook) the notebook entries that live in the same file. + +## Without a mouse + +`Alt+Ctrl+A` (`Option+Cmd+A` on macOS) puts the keyboard focus on the drawing. On an empty drawing press Enter for a carbon, then Enter and an arrow key for each new bond, and type `O` on an atom to make it oxygen; every step is spoken by your screen reader. `Alt+Ctrl+S` (`Option+Cmd+S`) describes the whole structure. [Accessibility](Accessibility) has the keys and the element colours. + ## Connect an agent Claude Code, Codex, Cursor, Antigravity or any MCP client can draw in the window you have open: @@ -49,6 +61,8 @@ An agent you connected to 0.7.0 over HTTP needs the token from 0.8.0 on: run `./ | `./formchem install-desktop`, `./formchem desktop dev`, `./formchem desktop build` | the Tauri desktop app | | `./formchem freeze` | freeze the engine for the desktop app (a folder in `src-tauri/engine` on macOS, a one-file sidecar elsewhere) | | `./formchem convert`, `batch`, `descriptors`, `render` | convert structure files and folders, write properties to CSV, draw every record ([Command Line](Command-Line)) | +| `./formchem db create`, `info`, `import`, `search`, `export` | structure databases without the window ([Command Line](Command-Line)) | +| `./formchem edit-live ID` | open a live structure from the shared library in the running FormChem ([Command Line](Command-Line)) | | `./formchem i18n check`, `scan`, `export`, `import` | the interface languages: gaps, new strings, CSV out and in | | `./formchem counts` | lines of code per language | | `./formchem doctor`, `./formchem clean` | checks, cleanup | @@ -61,4 +75,4 @@ Each command has a `formchem.bat` twin on Windows. ## Ports and folders -The engine listens on 127.0.0.1:8220 (`FORMCHEM_PORT`), the Vite app on localhost:5220. The desktop shell starts the engine on a free port and prefers 8221. The data folder is `~/formchem` (`FORMCHEM_DATA_DIR`); it holds `settings.json`, `library.json` (Home's lists), `commands-catalogue.json`, `agent-token` (0.8.0), the `Agent log` folder (0.8.0) and, while the engine runs, `engine.json`. +The engine listens on 127.0.0.1:8220 (`FORMCHEM_PORT`), the Vite app on localhost:5220. The desktop shell starts the engine on a free port and prefers 8221. The data folder is `~/formchem` (`FORMCHEM_DATA_DIR`); it holds `settings.json`, `library.json` (Home's lists), `commands-catalogue.json`, `agent-token` (0.8.0), the `Agent log` folder (0.8.0), the `Databases` folder (0.11.0; new databases, and the short-lived `.uploads` and `.exports` copies of a browser window), the `Library` folder (0.12.0; the shared structure library other Form apps read, [Live Structures](Live-Structures)) and, while the engine runs, `engine.json`. diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index 44d0170a..7025a9f0 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -2,7 +2,7 @@ FormChem is the chemical structure drawing suite of the FormAI family: local-first, no account, on macOS, Windows and Linux. It runs in the browser or as a Tauri desktop app, with a local engine that holds every document, and an MCP server so Claude Code, Codex, Cursor or Antigravity can work in the same window you see. -FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, window, desktop shell, CI) and 0.2.0 the family shell (title bar, menus, Home, Preferences, the terminal and agent dock, extensions, Help and updates). 0.3.0 added documents and the RDKit chemistry engine, 0.4.0 the drawing canvas, its tools and hover keys, and the Analysis panel, 0.5.0 reactions and annotations: arrows and the other drawn objects, reaction perception, atom mapping, balance and stoichiometry, the template library, Find and rulers, and 0.6.0 stereo, queries and analysis: CIP labels and enhanced stereo, abbreviations, query structures and R-groups, calculated properties with their methods, the structure check and the isotope pattern. 0.7.0 is formats and exchange: chemistry files in and out with a report of what each format loses, pictures (PNG, SVG, PDF, EPS) that open again as the drawing, printing, the clipboard, Standardise and a command line for whole files, plus what the first desktop test asked for: a fast start on macOS, a clearer 2D layout, the dark page, resizing on the sheet and grids. 0.8.0 is agents: 42 MCP tools with which an agent makes and opens drawings, draws structures and reaction schemes from SMILES or molfiles, edits them atom by atom by id, reads them back and checks its work with a picture from the window's own renderer, each change one undo step, plus Agent Activity with undo and Stop, and an agent token for the HTTP endpoint. 0.9.0 is names, predictions and spectra: chemical names read into structures and written for them, offline with FormChem's own dictionary, systematic parser and round-trip-checked namer; 1H and 13C NMR spectra predicted by FormChem's own increment method, each value with its method and version; JCAMP-DX spectra opened as spectrum objects with peaks, integrals and multiplets linked to atoms in the Spectrum editor; and ten more agent tools (52). 0.10.0 is 3D: structures built in 3D from the drawing with their stereo checked, conformer searches, minimisation and dihedral scans with the force field and version beside each energy, measurements, surfaces with ESP, a 3D View panel and 3D views placed on the page, PDB and mmCIF files opened as proteins with their ligands, ligands extracted as structures, PNG, glTF and 3D structure exports, and eight more agent tools (60). A structure database comes next. +FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, window, desktop shell, CI) and 0.2.0 the family shell (title bar, menus, Home, Preferences, the terminal and agent dock, extensions, Help and updates). 0.3.0 added documents and the RDKit chemistry engine, 0.4.0 the drawing canvas, its tools and hover keys, and the Analysis panel, 0.5.0 reactions and annotations: arrows and the other drawn objects, reaction perception, atom mapping, balance and stoichiometry, the template library, Find and rulers, and 0.6.0 stereo, queries and analysis: CIP labels and enhanced stereo, abbreviations, query structures and R-groups, calculated properties with their methods, the structure check and the isotope pattern. 0.7.0 is formats and exchange: chemistry files in and out with a report of what each format loses, pictures (PNG, SVG, PDF, EPS) that open again as the drawing, printing, the clipboard, Standardise and a command line for whole files, plus what the first desktop test asked for: a fast start on macOS, a clearer 2D layout, the dark page, resizing on the sheet and grids. 0.8.0 is agents: 42 MCP tools with which an agent makes and opens drawings, draws structures and reaction schemes from SMILES or molfiles, edits them atom by atom by id, reads them back and checks its work with a picture from the window's own renderer, each change one undo step, plus Agent Activity with undo and Stop, and an agent token for the HTTP endpoint. 0.9.0 is names, predictions and spectra: chemical names read into structures and written for them, offline with FormChem's own dictionary, systematic parser and round-trip-checked namer; 1H and 13C NMR spectra predicted by FormChem's own increment method, each value with its method and version; JCAMP-DX spectra opened as spectrum objects with peaks, integrals and multiplets linked to atoms in the Spectrum editor; and ten more agent tools (52). 0.10.0 is 3D: structures built in 3D from the drawing with their stereo checked, conformer searches, minimisation and dihedral scans with the force field and version beside each energy, measurements, surfaces with ESP, a 3D View panel and 3D views placed on the page, PDB and mmCIF files opened as proteins with their ligands, ligands extracted as structures, PNG, glTF and 3D structure exports, and eight more agent tools (60). 0.11.0 is databases and the lab notebook: structure databases in one `.fcdb` SQLite file with your own fields, registration with duplicate rules, exact, substructure, similarity, formula and field search, hit lists and saved queries, table, gallery, form and plot views, SD, SMILES and CSV import and export, notebook entries with schemes, stoichiometry, products and signing, `./formchem db`, eleven more agent tools (71), and a new app icon. 0.12.0 is family integration: live structures that keep their drawing inside when copied into other Form apps and come back editable, a shared structure library every Form app reads, a bar when a file changes on disk, keyboard and screen reader access with spoken atoms and a structure summary, high-contrast and colour-blind safe element colours, peptides and nucleic acids in HELM, xtb and CREST run when you have installed them, `./formchem edit-live`, and six more agent tools (77). Desktop builds, file associations, demos and the manual come next. | Page | What it covers | | --- | --- | @@ -15,11 +15,16 @@ FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, wi | [Analysis](Analysis) | Calculated properties with their methods, the isotope pattern, Copy Analysis and Check Structure | | [Names](Names) | Structure from Name, pasting a name, the Name section and Copy Name, what names are read and refused | | [Spectra and NMR](Spectra-and-NMR) | JCAMP-DX spectra, the Spectrum editor, peaks, integrals and links to atoms, predicted 1H and 13C NMR | -| [3D](3D) | The 3D View, Build 3D from 2D, conformers, minimising, dihedral scans, measuring, surfaces, 3D views on the page, PDB and mmCIF files, ligands and 3D exports | +| [3D](3D) | The 3D View, Build 3D from 2D, conformers, minimising, dihedral scans, measuring, surfaces, 3D views on the page, PDB and mmCIF files, ligands, 3D exports, and xtb and CREST | +| [Databases](Databases) | Structure databases: the workspace, fields, Add to Database and duplicates, search, hit lists, saved queries, the plot, import and export | +| [Lab Notebook](Lab-Notebook) | Notebook entries with scheme, stoichiometry, procedure, products and files; search, signing and export | +| [Biopolymers](Biopolymers) | Peptides and nucleic acids from HELM and back, and FormChem's own monomers | +| [Live Structures](Live-Structures) | Copy as Live Structure, the shared Structure Library, editing again from a sibling app, and the file changed bar | +| [Accessibility](Accessibility) | Keyboard focus on atoms and bonds, what is spoken, Describe Structure, element colours | | [Formats and Export](Formats-and-Export) | Opening chemistry files and the import report, File > Import, exporting pictures that keep the drawing inside, exporting chemistry files, printing | | [Clipboard](Clipboard) | Copy, Cut, Paste and Paste Special, Copy As, what goes on the clipboard and what each platform can do | -| [Command Line](Command-Line) | Converting files and folders, properties to CSV and pictures of every record, with standardising and the failure report | -| [Agents](Agents) | The MCP server and its 60 tools, drawing directly and from names, NMR, spectrum and 3D tools, agent configs, the agent token, skills, consent and Stop | +| [Command Line](Command-Line) | Converting files and folders, properties to CSV and pictures of every record, with standardising and the failure report, `./formchem db` for databases and `./formchem edit-live` | +| [Agents](Agents) | The MCP server and its 77 tools, drawing directly and from names and HELM, NMR, spectrum, 3D and xtb, database, notebook and library tools, agent configs, the agent token, skills, consent and Stop | | [Agent Activity](Agent-Activity) | Every call agents made with undo for the latest one, the editing chip with Stop, and the call log | | [Terminal](Terminal) | The terminal and agent dock | | [Extensions](Extensions) | Form extensions in FormChem | diff --git a/.docs/wiki/Lab-Notebook.md b/.docs/wiki/Lab-Notebook.md new file mode 100644 index 00000000..890af340 --- /dev/null +++ b/.docs/wiki/Lab-Notebook.md @@ -0,0 +1,42 @@ +# Lab Notebook + +From 0.11.0 every [database](Databases) holds a lab notebook: one entry per experiment, with its reaction scheme, stoichiometry, procedure, observations, products and files, kept in the same `.fcdb` file as the compounds. The full guide is [`docs/DATABASES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/DATABASES.md). + +## An entry in four steps + +1. Open a database and choose Database > Notebook > New Notebook Entry... (or New Entry in the Notebook view). Give a title, the experiment date and your name, and pick a template: Blank, Reaction, Analysis or Purification. +2. Draw the reaction in a drawing and press New Scheme from Drawing; the stoichiometry table fills in from the scheme. +3. Write the procedure and observations, add products with their sample id, mass, yield and purity, and link each to its record in the database. +4. Sign Notebook Entry... when the experiment is written up. + +## What an entry holds + +| Part | Notes | +| --- | --- | +| Scheme | the first page of a drawing; Edit Scheme opens it on the canvas with a Save to Entry bar | +| Stoichiometry | computed from the scheme every time (formula, MW, role, amount, equivalents) with its method; never typed | +| Procedure, Observations | paragraphs separated by blank lines, `- ` bullets, `**bold**` and `*italic*`, with a preview | +| Products | name, sample, mass, yield, purity, notes, and a link to the product's record | +| Tags | separated by commas | +| Files | stored up to 50 MB, or linked by path in the desktop app, each with its SHA-256 | + +Text saves a moment after you stop typing; other fields save when they change. + +## Finding entries + +The Notebook view lists entries newest first. The search box finds words in the title, procedure, observations, tags and sample ids (every word must appear); the substructure search finds entries whose scheme contains a structure, for example `NC=O` for amide couplings. + +## Signing + +Sign records your name, the time and a SHA-256 hash of the entry's content, including the hashes of its files, and keeps that content as a signed version. A change after signing marks the entry "Modified after signing"; the signed version stays as it was and opens read-only from the versions list. Sign Again records a new signed version. Agents can add entries but never sign them. + +## Exporting + +Export Notebook Entry... writes a self-contained HTML page (scheme picture, stoichiometry, text, products, files with their hashes, the signature and any "Modified after signing" banner; it needs no network and prints as shown) or JSON with the content, its hash and every version, so the hashes can be checked later. + +## Not yet + +- Entries hold no spectra or grid of their own; attach spectra as files. +- Printing the HTML export, Link File and the save dialog in the desktop app were not tried for 0.11.0. + +See also [Databases](Databases) and [Agents](Agents) (`nb_add_entry`, `nb_search`). diff --git a/.docs/wiki/Live-Structures.md b/.docs/wiki/Live-Structures.md new file mode 100644 index 00000000..7458ba26 --- /dev/null +++ b/.docs/wiki/Live-Structures.md @@ -0,0 +1,43 @@ +# Live Structures + +From 0.12.0 a structure you copy from FormChem into another Form app (FormDeck, FormTxt, form.md) stays a FormChem drawing: the picture carries the drawing inside, and FormChem opens it again for editing. The full guide is [`docs/LIVE-STRUCTURES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/LIVE-STRUCTURES.md); the contract sibling apps follow is [`docs/LIVE_STRUCTURES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/LIVE_STRUCTURES.md). + +## A live structure in three steps + +1. Select a structure and choose Edit > Copy As > Copy as Live Structure. +2. Paste it into the other Form app. It shows the picture. +3. To change it, the other app opens it in FormChem (a `formai://formchem/edit` link, `./formchem edit-live`, or opening its picture). Edit, then press `Mod+S`: the picture is rewritten with a higher revision and the other app shows the new one. + +## The Structure Library + +Window > Structure Library... shows every structure you starred, copied, saved as a template or placed as a live structure: + +| Tab | How a structure gets there | +| --- | --- | +| Favourites | Structure > Star Structure | +| Recent | Copy as Live Structure, or inserting from the library (newest 50 kept) | +| Templates | File > Save as Template to Library... | +| Live | Copy as Live Structure | + +Search by name, formula or SMILES; Insert, Open, Copy as Live Structure, Unstar and Delete work on the chosen tile. The library is plain files in `~/formchem/Library/` (a `library.json`, and an SVG, PNG and molfile per item), so other Form apps read it without FormChem running. + +## A live drawing + +- The title bar shows "Live structure from [app]". +- Save asks for no path; it saves to the library item. Closing with unsaved changes and choosing Save does the same. +- Save As makes an ordinary `.fchem` copy. +- A live structure from another computer joins your library with its own id; an older copy never overwrites a newer edit. + +## Dropping and pasting + +Drop a FormChem picture or a live structure on the canvas to insert it there; hold Alt, or drop with no drawing open, to open it as its own drawing. Pasting one inserts the drawing inside it. + +## When a file changes outside FormChem + +If the file of an open drawing changes on disk, a bar over the canvas offers Reload (undoable) or Keep Mine (your next save wins). FormChem's own saves never show it. + +## Not yet + +- No sibling app was run against this for 0.12.0; the files and the clipboard were checked against the contract. +- The desktop app's own clipboard and a real `formai://` link were not tried; from a browser window other apps get the HTML picture and the images. +- Dragging a structure out of FormChem does not carry a live structure yet. diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md index aef50456..868989a9 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -11,6 +11,11 @@ - [Names](Names) - [Spectra and NMR](Spectra-and-NMR) - [3D](3D) +- [Databases](Databases) +- [Lab Notebook](Lab-Notebook) +- [Biopolymers](Biopolymers) +- [Live Structures](Live-Structures) +- [Accessibility](Accessibility) - [Formats and Export](Formats-and-Export) - [Clipboard](Clipboard) - [Command Line](Command-Line) diff --git a/AGENTS.md b/AGENTS.md index 0bced17a..5f8fe7dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ FormChem exposes an MCP server at http://127.0.0.1:8220/mcp (stdio: `./formchem mcp`, which runs `setup/mcp_stdio.py`). Configs: .codex/config.toml, .cursor/mcp.json, .mcp.json, and for Antigravity ~/.gemini/config/mcp_config.json. Run `./formchem agents install` to install them and the skills for your home folder too. -HTTP requests need the agent token (`./formchem agents token`; `agents install` writes it into the configs; the stdio transport sends it itself). FormChem has 60 tools. Reading is open; changing tools make the window ask the person the first time, and the person can Stop an agent. Since 0.8.0 agents draw directly: get_context or list_open_documents first; draw_from_smiles and draw_from_molfile place a structure as one undo step and answer with ids, SMILES, InChIKey, formula and a picture; get_atoms names atoms and bonds for the edit tools (add_atom, add_bond, set_charge, set_atom, set_stereo, replace_substructure, delete, move, scale, align, clean_layout, add_arrow, add_text, add_reaction), one undo step each; render, get_structure and validate check the result; convert and batch_convert match the CLI. Since 0.9.0 draw_from_name and name_structure read and write names offline, predict_nmr and predict_spectrum predict 1H and 13C NMR, and the spectrum tools open, read, pick, integrate and export JCAMP-DX spectra. Since 0.10.0 build_3d builds a structure in 3D and reports whether every stereo label was kept, conformers_3d, minimise_3d, scan_dihedral and measure_3d work on its conformers with the force field and version beside each number, open_3d_structure opens PDB, mmCIF, SDF and MOL files, extract_ligand turns a bound ligand into a structure, and export_3d writes MOL, SDF, PDB or XYZ. Reaction and analysis tools, list_commands and run_command for the window's commands, Form extensions and handoff to the person (question when you need their input) are there too. The skill packs live in .agents/skills: formchem-harness (using FormChem) and formchem-skillset (developing FormChem). The document contract is docs/FORMAT.md. +HTTP requests need the agent token (`./formchem agents token`; `agents install` writes it into the configs; the stdio transport sends it itself). FormChem has 77 tools. Reading is open; changing tools make the window ask the person the first time, and the person can Stop an agent. Since 0.8.0 agents draw directly: get_context or list_open_documents first; draw_from_smiles and draw_from_molfile place a structure as one undo step and answer with ids, SMILES, InChIKey, formula and a picture; get_atoms names atoms and bonds for the edit tools (add_atom, add_bond, set_charge, set_atom, set_stereo, replace_substructure, delete, move, scale, align, clean_layout, add_arrow, add_text, add_reaction), one undo step each; render, get_structure and validate check the result; convert and batch_convert match the CLI. Since 0.9.0 draw_from_name and name_structure read and write names offline, predict_nmr and predict_spectrum predict 1H and 13C NMR, and the spectrum tools open, read, pick, integrate and export JCAMP-DX spectra. Since 0.10.0 build_3d builds a structure in 3D and reports whether every stereo label was kept, conformers_3d, minimise_3d, scan_dihedral and measure_3d work on its conformers with the force field and version beside each number, open_3d_structure opens PDB, mmCIF, SDF and MOL files, extract_ligand turns a bound ligand into a structure, and export_3d writes MOL, SDF, PDB or XYZ. Since 0.11.0 db_list, db_create and db_open reach structure databases (.fcdb files), db_import fills one (dry_run first; read the failed-record report), db_search searches by substructure, similarity (read each score), exact match or a query node and leaves a hit list the person sees, db_get_record, db_add_record (a duplicate is refused until you choose on_duplicate) and db_update_record work on records, db_export writes SD, SMILES or CSV, and nb_add_entry and nb_search keep lab notebook entries, which only the person signs. Since 0.12.0 library_list, library_add and live_structure_object reach the shared structure library every Form app reads, draw_from_helm draws a peptide or nucleic acid from HELM, and xtb_optimise and crest_conformers run xtb and CREST only when the person installed them (never shipped; quote program, version, method and solvent with each energy). Reaction and analysis tools, list_commands and run_command for the window's commands, Form extensions and handoff to the person (question when you need their input) are there too. The skill packs live in .agents/skills: formchem-harness (using FormChem) and formchem-skillset (developing FormChem). The document contract is docs/FORMAT.md; the database and notebook contract is docs/DATABASE.md; the structure library and live structure contract is docs/LIVE_STRUCTURES.md. Clean room (details in CLAUDE.md): FormChem is written only from the owner's clean-room specifications. Never open, run, decompile or read the private documentation of the commercial suite it replaces, and never copy its names, icons, templates or text. Vendor names appear only to name file formats. diff --git a/CHANGELOG.md b/CHANGELOG.md index d9da2bab..2b1de3a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,122 @@ Versions follow `v*.*.*` with dots. Dates are US Eastern. +## 0.12.0 · 2026-12-05 + +Family integration: a structure you copy out of FormChem into another Form app stays a FormChem drawing, and comes back editable. Copy as Live Structure puts the structure on the clipboard with its drawing inside and keeps it in a shared structure library that every Form app can read; a sibling app asks FormChem to edit it again with a `formai://formchem/edit` link or `./formchem edit-live`, and saving writes the new picture back for the sibling. FormChem can now be used from the keyboard alone, speaks every atom and bond it focuses, describes a whole structure in words, and offers high-contrast and colour-blind safe element colours. Peptides and nucleic acids written in HELM become structures and go back to HELM, and xtb and CREST run as programs you install yourself. Agents reach the library, HELM and xtb through six new MCP tools. + +### New + +- Edit > Copy As > Copy as Live Structure copies the selection (or the page) as a live structure: the clipboard holds the picture as SVG and PNG with the FormChem drawing inside, an HTML picture carrying the live structure object, the SMILES and FormChem's own drawing, and the structure joins the shared structure library with the Live and Recent kinds. Pasting it back into FormChem gives the editable structure. +- The shared structure library is a plain folder, `Library/` in FormChem's data folder (by default `~/formchem/Library/`), with `library.json`, an SVG, a PNG and a molfile per item, so other Form apps read it without FormChem running. Its layout, the live structure object and the clipboard flavour are written down for sibling app authors in `docs/LIVE_STRUCTURES.md`. +- Window > Structure Library... shows the library in four tabs (Favourites, Recent, Templates and Live) with a search box. Insert places an item on the page, Open opens it in its own drawing, and Unstar, Delete and Copy as Live Structure work on the item. Structure > Star Structure adds the selection to Favourites, and File > Save as Template to Library... adds it to Templates; a structure already in the library gains the new kind instead of a second copy. Recent keeps the newest 50. +- Editing a live structure: a sibling app opens it with the link `formai://formchem/edit?id=...` (the desktop app registers the `formai` scheme), with `./formchem edit-live ID`, or by opening the item's SVG. FormChem opens it in a drawing marked "Live structure from" the sibling beside the title. Save (`Mod+S`) asks for no path: it writes the item's picture and molfile and raises its revision, so the sibling can show the new picture. Save As makes an ordinary copy, and closing an unsaved live drawing saves the item. A live structure from another computer is added to the library with its own id and revision. +- Dropping a FormChem picture or a live structure onto the canvas inserts it at the drop point; with Alt held, or with no drawing open, it opens as a drawing of its own. +- When the file of an open drawing changes on disk outside FormChem, a bar over the canvas says so and offers Reload (one undoable step) or Keep Mine (the next save writes over the outside change). FormChem's own saves never show it, and the canvas does not move when it appears. +- Keyboard navigation: View > Focus Structure (`Alt+Mod+A`) puts the keyboard focus on the drawing. Tab and Shift+Tab walk the atoms in reading order, an arrow key moves along the bond nearest its direction, Ctrl, Cmd or Alt with an arrow walks bonds, Space selects, and Enter followed by an arrow draws a new bond, so a structure can be built without a mouse. View > Next Atom and Previous Atom (`Alt+Mod+]` and `Alt+Mod+[`) do the same from the menu. A ring around the focused atom or bond stays readable at any zoom. +- Every move is spoken through the screen reader: the element by name, its charge, hydrogens, isotope, bonds and neighbours, ring size, its R or S label and its place, for example "Oxygen. 1 hydrogen. Single bond to Carbon. Not in a ring. Atom 3 of 3." +- View > Describe Structure (`Alt+Mod+S`) speaks and shows a summary of the drawing: formula, name, charge, ring systems by name (benzene, pyridine, piperidine, purine and 47 others), functional groups from FormChem's own table of 42, and stereocentres with their R or S labels, each with the method that found it. Copy copies the summary. +- Element colours: Standard, High contrast (every element at 7.38:1 or more against white) and Colour-blind safe (Okabe-Ito blue, vermillion, bluish green and reddish purple), chosen in Preferences > Interface or under View > Element Colours. The choice applies before the first drawing appears and to pictures and the clipboard, and switching repaints only the atom colours. +- Insert > Biopolymer from HELM... reads HELM version 2 as you type, marks the character where reading stopped, and shows the structure, the number of monomers, the formula and the average and monoisotopic masses with their method; Insert places it as one undo step. Simple polymers, RNA branches such as `R(A)P`, whole repeat counts, inline SMILES monomers and connections (disulfides, lactam bridges, head-to-tail rings) are read. Oxytocin reads and is laid out in about a tenth of a second. +- Edit > Copy As > Copy as HELM writes peptides and nucleic acids drawn as atoms back to HELM, with their disulfide, lactam and ring connections. HELM is copied only when it reads back to the same structure; anything FormChem cannot match is refused with the reason and the piece's formula. +- HELM monomers are FormChem's own data, written from textbook structures: the 20 amino acids and 19 D forms, Aib, Nle, Orn, Sar, Hyp and pyroglutamate, the acetyl and amide caps, ribose, deoxyribose, phosphate and the five bases (55 in all). +- 3D > Optimise with xtb... and 3D > Conformer Search with CREST... run xtb and CREST on the selected structure when you have installed them: GFN2-xTB or GFN-FF, charge, unpaired electrons, an ALPB implicit solvent from 24, the optimisation level or the energy window, threads and a time limit, with progress, Cancel Job and the program's last lines when a run fails. Results become the structure's conformers as one undo step, with the energy in hartree and kcal/mol, the HOMO-LUMO gap and a label naming the program, its version, the method and the solvent; CREST conformers that lost the drawn stereo are dropped and counted. +- Preferences > 3D > Tight-Binding Programs sets where xtb and CREST are and how many threads they use, and shows what FormChem found: the version and path, a path that does not work, or where to get the program. +- `./formchem edit-live ID`, `--object FILE` and `--from APP` open a live structure in the running FormChem from a terminal or a sibling app. See `docs/CLI.md`. +- The MCP server has 77 tools, 6 of them new: `library_list`, `library_add` and `live_structure_object` for the shared library, `draw_from_helm` for biopolymers, and `xtb_optimise` and `crest_conformers` for tight-binding results. See `docs/AGENTS.md`. + +### Exit criteria + +Checked in the built window under 4x CPU throttling: + +- Aspirin, Copy as Live Structure: the library item (C9H8O4, 180.159) was on disk 0.59 s after the command, with the SVG and PNG flavours, the HTML picture and the live structure object on the clipboard. Pasted into a new drawing it came back as the same 13-atom structure, also when only the live structure flavour was on the clipboard. Opened from the Live tab it showed the Live structure badge; water added and `Mod+S` raised the revision from 1 to 2 in 0.47 s. Pass for FormChem's side; no sibling app was run (see Known issues). +- Keyboard only: ethanol built with Focus Structure, Enter and the arrow keys, every atom spoken, and Describe Structure read "Formula C2H6O. Name: ethanol. Neutral overall. No rings. Functional groups: alcohol. No stereocentres." Pass with the spoken text read from the window; no real screen reader was run. +- Oxytocin from HELM: C43H66N12O12S2, 1007.207 average and 1006.436458 monoisotopic, and Copy as HELM gave back the identical string with its disulfide. Eleven further HELM strings round-tripped to the same InChIKey. +- Zero flash: switching element colours changed only fills (no node added or removed, layout shift 0); the file changed bar left the canvas where it was (layout shift 0); the xtb dialog kept its height and its log in place on every progress update. + +### Changed + +- The Edit > Copy As submenu gains Copy as HELM and Copy as Live Structure; Insert gains Biopolymer from HELM...; File gains Save as Template to Library...; Structure gains Star Structure; Window gains Structure Library...; 3D gains the xtb and CREST rows; View gains Focus Structure, Describe Structure, Next Atom, Previous Atom and an Element Colours submenu. +- Dialog colour swatches and the custom accent button are 24 pixels, and every dialog control shows a 2 pixel focus outline from the keyboard. +- The engine watches the files of open drawings once a second from the moment it starts. +- The MCP instructions and the workflow describe the library, HELM and xtb tools. + +### Known issues + +- No sibling app was run: the clipboard, the library folder and the live structure object were checked against `docs/LIVE_STRUCTURES.md` only. Browsers write the live structure flavour under a `web ` prefix and drop the molfile flavour, so other apps read the HTML picture and the images; the desktop app's native clipboard was not tried. +- The `formai://` link was not opened on a real desktop: the deep link plugin was fetched and its code lines checked against its source, but the desktop shell was not compiled on this machine. +- Not verified with a real screen reader (VoiceOver, NVDA or Orca): only the spoken text was read back from the window. Alt with the square brackets may not be typeable where Ctrl+Alt is AltGr; the commands are also in View and the command palette. +- xtb and CREST were not run for real here: FormChem neither includes nor downloads them, and the dialogs, jobs and results were checked with stand-in programs writing the documented files. The Windows process stop and the Windows install folders were not tried. +- HELM: mixtures, BLOBs, hydrogen-bond pairs, repeat ranges and unknown attachment points are refused; inline SMILES in RNA and linker pieces are not written back; inputs near the 2,000 monomer and 20,000 atom limits were not timed. +- Not verified: dropping from Finder or another app onto the desktop window; reaction items in the library; the native menus for the new rows. + +### Under the hood + +- New engine services: `live_structures` (the library folder, items, pictures, live drawings and `edit-live`), `file_watch`, `describe` (with its ring and functional group tables), the `helm` package (parser, monomers, assembly, writer) and the `xtb` package (discovery, inputs, runner, jobs, output readers, write-back), with routes in `routers/structures.py`, `describe.py`, `helm.py` and `xtb.py`. The agent token may write to `/api/structures` and nothing else. +- The window gains the live structure client and drops, the Structure Library dialog, the file changed bar, the accessibility modules under `canvas/a11y/` with the shared announcer and the Structure Summary, the HELM dialog and commands, and the xtb and CREST dialogs and Preferences section. +- `docs/FORMAT.md` records the program that made an xtb or CREST conformer. New desktop dependency `tauri-plugin-deep-link` 2.6.3 (Apache-2.0 OR MIT) with the crates it brings, listed in `NOTICE.md` and `THIRD-PARTY-NOTICES.txt`. +- Translations of the new strings into all 25 languages. A translated pattern with more fixed words now wins over a more general one (`Could not read the HELM: ...` over `Could not read ...: ...`). +- `./formchem agents sync` reads the agent modules' tools by importing them with the engine's Python, so the generated tool reference and `agents/manifest.json` list all 77 tools. + +## 0.11.0 · 2026-12-05 + +Databases and the lab notebook: FormChem keeps your compounds in structure databases you can search by structure, formula, mass and your own fields, and keeps your experiments in a notebook beside them. A database is one `.fcdb` file (a SQLite file any SQLite browser opens), so moving the file moves everything. Import 10,000 SD records, find the benzene rings among them in a fraction of a second, plot two fields against each other, and export the hits back to SD. Notebook entries hold a reaction scheme with its stoichiometry, the procedure, products linked to their records and files, and can be signed. Agents reach all of it through eleven new MCP tools. FormChem also has a new app icon. + +### New + +- File > New Database and Open Database, and Home's Databases list, open a full-window database workspace (File > Databases or `Shift+Mod+D` shows and hides it). The left column lists the open databases, the hit lists and the saved queries; the toolbar holds the search bar and the views. +- Views: Table, Gallery, Form, Plot and Notebook, all showing the same records and the same selection. The table pages records in as you scroll, so a 10,000 record database scrolls without waiting; sort by any column, resize, hide and freeze columns, and edit a field value in place (double-click, Enter or Tab saves, Escape cancels). The gallery shows structure tiles with two captions you choose. The form view shows one record at a time on a form laid out for you (Generate Form: single column, two columns or cards). +- Fields are your own columns: text, rich text, whole and real numbers with a unit and significant figures, dates, yes or no, choices, structures, reactions, pictures, files, links to another record, and computed descriptors (cLogP, TPSA, hydrogen bond donors and acceptors, rotatable bonds, rings, fraction sp3 and others) that follow the structure and name their method. Database > Fields... adds, renames, orders, hides and deletes them. +- Structure > Add to Database registers the selected structure (or the page). Duplicates are found by the database's rules (stereo matched or ignored, salts stripped or kept): a dialog shows the matching records and lets you open one, add a new batch of it or register the structure anyway. Registration numbers are never reused. +- Search: type in the search bar for names, ids, formulas and SMILES, or use Structure to search with what you drew: exact (with stereo, salts, charges and tautomers matched or ignored), substructure, or similarity with a Tanimoto threshold (0.7 by default) and a score for every hit. Formula search reads ranges such as `C6-8H*N1O0-2`; mass, number, text, date, choice and empty searches work on every field. Advanced Search builds queries with All of, Any of and None of groups and can search within the current hit list. +- Hit lists: every search becomes a hit list in the left column, named from its query ("Substructure c1ccccc1 and mw <= 300"). Keep the ones you want (the newest 20 others are kept), rename them, export them, and combine two by union, intersection or difference. Saved queries live in folders, show their last count and run again with one click. +- Database > Import Records... reads SD (V2000 and V3000), RD, SMILES, CSV and TSV files (a SMILES or InChI column, found by its header or its contents) and `.fchem` drawings. You see the columns with their detected types, map each to a field or a new field, run a check that counts what would be added, updated and failed, then import as new records, appended records or a merge that updates matching records. A bad record never stops an import: the report lists each one with its number and a plain reason, and Copy Report copies it. Stop ends an import part way. +- Database > Export Records... writes the hit list, the selection or the whole database to SD (V2000 or V3000, every field as a data item), SMILES or CSV (structures as SMILES or InChI). An SD file exported and imported into a new database keeps every InChIKey and every field value. +- The Plot view draws a histogram of one field or a scatter of two, with a least-squares line and its R squared, colour by a third field, and a rectangle or lasso selection that becomes a hit list. +- Record details (Enter or a double-click) show the picture, the identifiers with copy buttons, every field and the record's files: attach files up to 50 MB, or link larger ones by path in the desktop app. Open in Drawing opens the record as a new drawing. +- Database > Database Settings... sets the title, the description and the duplicate rules. +- The lab notebook (Database > Notebook, or the Notebook view) lists entries with text search (title, procedure, observations, tags and sample ids) and substructure search over each entry's scheme. New Notebook Entry... starts from a blank, reaction, analysis or purification template. +- An entry holds a reaction scheme (New Scheme from Drawing, or Edit Scheme to change it on the canvas and Save to Entry), the stoichiometry computed from the scheme with its method, the procedure and observations in a simple markup (paragraphs, bullets, bold, italic) with a preview, products with their sample, mass, yield and purity and a link to the product's record, tags and files. +- Sign Notebook Entry... records the signer, the time and a SHA-256 hash of the entry's content. A change after signing marks the entry "Modified after signing" and keeps the signed version, which opens read-only from the versions list. +- Export Notebook Entry... writes a self-contained HTML file (scheme as a picture, stoichiometry, files listed with their hashes, ready to print) or JSON with the content, the hash and every version, so the hashes can be checked later. +- Databases open by File > Open (desktop and browser) or by dropping an `.fcdb` file on Home. A database another FormChem already has open opens read-only and says why. +- `./formchem db create`, `info`, `import`, `search` and `export` work on databases from the command line, with `--errors` writing the failed records of an import to a CSV file. See `docs/CLI.md`. +- The MCP server has 71 tools, 11 of them new: `db_list`, `db_create`, `db_open`, `db_import`, `db_search`, `db_get_record`, `db_add_record`, `db_update_record` and `db_export` for databases, and `nb_add_entry` and `nb_search` for the notebook. Every write by an agent is recorded with the agent's name, and agents never sign entries. See `docs/AGENTS.md` and `docs/DATABASES.md`. + +### Exit criteria + +Checked in the built window under 4x CPU throttling: + +- 10,000 SD records (3 of them deliberately broken) imported through Import Records... in 34.4 s: 9,997 added, records 1500, 5000 and 8500 reported with plain reasons. Pass. +- A benzene substructure search found 2,218 of the 9,997 records in 145 ms. Pass. +- The hit list exported to SD wrote 2,218 records, and imported into a new database gave 2,218 records. Pass. +- Zero flash: scrolling the table 16,000 pixels reused 25 pooled rows (layout shift 0.0001, from loading rows filling in), the gallery and a 9,997 point scatter plot showed no layout shift. Pass. +- On a 100,000 record database (measured in the engine): benzene substructure in 0.45 to 0.54 s once the structure cache is built (30,769 hits), a similarity search in 0.12 to 0.15 s, a formula range in 6 ms. + +### Changed + +- New app icon: the macOS, Windows and Linux icons, the title bar mark, Home, About, the favicon and the splash screen all show the new FormChem card. +- The File > Open dialogs and Home's Open list `.fcdb`. File gains New Database, Open Database and Databases; Structure gains Add to Database; a new Database menu holds search, import, export, the views, the notebook, fields and settings. Home's Databases page offers New and Open. +- The MCP instructions and the workflow describe the database and notebook tools. + +### Known issues + +- Record values, hit list names, saved query names and entry titles are shown as typed, never translated; the engine's value-format errors and RDKit's own messages stay in English. +- The notebook does not hold spectra or a grid yet; an entry carries spectra as attached files. +- Variable attachment and link nodes, moved to this phase, are not drawn yet. +- While the database workspace is open it covers the in-window menu bar; its toolbar and gear menu carry the commands instead. +- Two databases with the same title look alike in the Open Database list; the path shows in its tooltip. +- Not verified: the desktop app's folder and file choosers, Link File and dropping an `.fcdb` on the desktop window (the desktop app has no drop handler; Home's drop area in the browser works); the consent prompt for `db_add_record` and `nb_add_entry` with a window open; live updates between two windows; a read-only database held by a second engine, in the window; scrolling 100,000 records in the window; printing the HTML entry export. +- Search speeds were measured on a small shared machine and not on the reference laptop. + +### Under the hood + +- New engine packages `services/database/` (schema, store with one transaction per write, registration and keys, fields, forms, records, attachments, thumbnails, jobs, import, export, query, search, hit lists, saved queries, plot, command line) and `services/notebook/` (templates, content hash, scheme, products, entries, attachments, markup, export), with routes in `routers/databases.py`, `routers/db_search.py` and `routers/notebook.py`. +- The window gains the database workspace (`ui/database/`), search, hit lists, import, export and plot (`ui/database-find/`), the notebook (`ui/notebook/`) and one client for the database routes (`engine/database-api.ts`). +- Every database read needs the window key; pictures and files load with a separate view key that opens only those two routes. +- `docs/DATABASE.md` is the contract for the `.fcdb` file, the query language and the routes. The new icon set is sized from the owner's masters in `assets/icon_src/masters`, so `cairosvg` is no longer used. No new dependency. +- Translations of the new strings into all 25 languages. `./formchem agents sync` now lists the tools of the agent modules too, so the generated tool reference has 71 tools. + ## 0.10.0 · 2026-12-03 3D: a structure you drew becomes a molecule you can turn. Build 3D from 2D keeps every wedge and double bond as drawn, the 3D View shows it in five styles with surfaces and measurements, conformer searches, minimisation and dihedral scans report energies with their force field and version, and a 3D view placed on the page keeps its angle and style in the drawing. PDB and mmCIF files open as proteins in cartoon with the ligand in focus, and a ligand comes out as an editable structure. Agents reach all of it through eight new MCP tools. diff --git a/CLAUDE.md b/CLAUDE.md index 47e0cc49..e24f1cf5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,11 +4,11 @@ Two jobs happen in this repo: drawing chemistry with FormChem, and developing Fo ## Drawing with FormChem -The FormChem MCP server runs at http://127.0.0.1:8220/mcp, configured in .mcp.json; HTTP requests need the agent token (`./formchem agents token`; `./formchem agents install` writes it into the configs, and the stdio transport `./formchem mcp` sends it itself). Start the app with `./formchem` so changes appear live in the window. It has 60 tools. Changing tools make the window ask the person the first time unless you were started from FormChem's own dock, and the person can Stop an agent from the title bar. +The FormChem MCP server runs at http://127.0.0.1:8220/mcp, configured in .mcp.json; HTTP requests need the agent token (`./formchem agents token`; `./formchem agents install` writes it into the configs, and the stdio transport `./formchem mcp` sends it itself). Start the app with `./formchem` so changes appear live in the window. It has 77 tools. Changing tools make the window ask the person the first time unless you were started from FormChem's own dock, and the person can Stop an agent from the title bar. -Since 0.8.0 agents draw directly: `get_context` or `list_open_documents` first; `draw_from_smiles` (reaction SMILES draws a scheme) and `draw_from_molfile` place a structure in free space as one undo step and answer with ids, SMILES, InChIKey, formula and a picture; `get_atoms` names atoms and bonds by id for the edit tools (`add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text`, `add_reaction`), each one undo step; check your work with `render`, `get_structure` and `validate`; `convert` and `batch_convert` match `./formchem convert` and `batch`. Since 0.9.0 `draw_from_name` and `name_structure` read and write names offline, `predict_nmr` and `predict_spectrum` predict 1H and 13C NMR, and `open_spectrum`, `spectrum_data`, `spectrum_peaks`, `spectrum_pick_peaks`, `spectrum_integrate` and `spectrum_export` work with JCAMP-DX spectra. Since 0.10.0 `build_3d` builds a structure in 3D (check that its answer says every stereo label was kept), `conformers_3d`, `minimise_3d`, `scan_dihedral` and `measure_3d` work on its conformers with the force field and version beside each number, `open_3d_structure` opens PDB, mmCIF, SDF and MOL files, `extract_ligand` turns a bound ligand into a structure, and `export_3d` writes MOL, SDF, PDB or XYZ; an edit to a structure's atoms or bonds drops its conformers. Reaction tools, analysis tools, the window's own commands (`list_commands`, `run_command`), Form extensions and `handoff` (with `question` when you need the person's input) are there too. Every call shows in the window's Agent activity panel. +Since 0.8.0 agents draw directly: `get_context` or `list_open_documents` first; `draw_from_smiles` (reaction SMILES draws a scheme) and `draw_from_molfile` place a structure in free space as one undo step and answer with ids, SMILES, InChIKey, formula and a picture; `get_atoms` names atoms and bonds by id for the edit tools (`add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text`, `add_reaction`), each one undo step; check your work with `render`, `get_structure` and `validate`; `convert` and `batch_convert` match `./formchem convert` and `batch`. Since 0.9.0 `draw_from_name` and `name_structure` read and write names offline, `predict_nmr` and `predict_spectrum` predict 1H and 13C NMR, and `open_spectrum`, `spectrum_data`, `spectrum_peaks`, `spectrum_pick_peaks`, `spectrum_integrate` and `spectrum_export` work with JCAMP-DX spectra. Since 0.10.0 `build_3d` builds a structure in 3D (check that its answer says every stereo label was kept), `conformers_3d`, `minimise_3d`, `scan_dihedral` and `measure_3d` work on its conformers with the force field and version beside each number, `open_3d_structure` opens PDB, mmCIF, SDF and MOL files, `extract_ligand` turns a bound ligand into a structure, and `export_3d` writes MOL, SDF, PDB or XYZ; an edit to a structure's atoms or bonds drops its conformers. Since 0.11.0 `db_list`, `db_create` and `db_open` reach structure databases (`.fcdb` files), `db_import` fills one (try `dry_run` first and read the failed-record report), `db_search` searches by substructure, similarity (read each hit's score), exact match or a query node and leaves a hit list the person sees, `db_get_record`, `db_add_record` (a duplicate is refused until you choose `on_duplicate`) and `db_update_record` work on records, `db_export` writes SD, SMILES or CSV, and `nb_add_entry` and `nb_search` keep lab notebook entries, which only the person signs. Since 0.12.0 `library_list`, `library_add` and `live_structure_object` reach the shared structure library that every Form app reads, `draw_from_helm` draws a peptide or nucleic acid from HELM (bad HELM is refused with the character where reading stopped), and `xtb_optimise` and `crest_conformers` run xtb and CREST only when the person has installed them (FormChem never ships them; quote the program, version, method and solvent with every energy). Reaction tools, analysis tools, the window's own commands (`list_commands`, `run_command`), Form extensions and `handoff` (with `question` when you need the person's input) are there too. Every call shows in the window's Agent activity panel. -Load the skill `.claude/skills/formchem-harness` for using the app. For work on the codebase itself, load `.claude/skills/formchem-skillset`. The document format is `docs/FORMAT.md`. +Load the skill `.claude/skills/formchem-harness` for using the app. For work on the codebase itself, load `.claude/skills/formchem-skillset`. The document format is `docs/FORMAT.md`; the database and notebook contract is `docs/DATABASE.md`; the shared structure library and live structure contract for sibling apps is `docs/LIVE_STRUCTURES.md`. ## Developing FormChem diff --git a/NOTICE.md b/NOTICE.md index 5c681435..75d243a3 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -36,6 +36,8 @@ This file is the human list, with the reason each work is there. The full licenc | fontTools 4.69.1 (fonttools) | MIT | engine, embeds subsets of the label fonts in exported SVG and draws label outlines in PDF and EPS | | Other Python packages frozen into the engine | listed with their licences in `THIRD-PARTY-NOTICES.txt` | read from the installed metadata of `backend/requirements.txt` | | @tauri-apps/api 2.12.1; tauri, tauri-plugin-shell, tauri-plugin-dialog, tauri-plugin-updater, tauri-plugin-single-instance, serde, serde_json, regex | MIT or Apache-2.0 | desktop shell | +| tauri-plugin-deep-link 2.6.3 (from 0.12.0) | Apache-2.0 OR MIT | desktop shell, registers the `formai://` scheme so sibling apps open a live structure with `formai://formchem/edit` | +| rust-ini 0.21.3, ordered-multimap 0.7.3, crunchy 0.2.4; dlv-list 0.5.2, const-random 0.1.20, const-random-macro 0.1.18, hashbrown 0.14.5 | MIT; MIT OR Apache-2.0 | desktop shell, brought by tauri-plugin-deep-link through rust-ini, its INI file reader | | fontdb 0.24 | MIT | desktop shell, lists installed font families | | objc2-foundation 0.3 (macOS shell) | MIT | desktop shell, window geometry for the traffic-light placement | | Arimo (Copyright 2020-2026 The Arimo Project Authors; googlefonts/arimo 4a6255f, through google/fonts 659809e), variable weight, roman and italic | SIL OFL-1.1 | app, atom labels and captions standing in for Arial and Helvetica so output measures the same everywhere; `frontend/public/fonts/Arimo-*.ttf` with `Arimo-OFL.txt` beside them | @@ -61,6 +63,7 @@ Tauri links these crates unedited (no `[patch]` and no vendored copy): | ring | Apache-2.0 AND ISC | TLS for the updater (rustls) | | webpki-root-certs | CDLA-Permissive-2.0 | root certificates for the updater's TLS | | r-efi | MIT OR Apache-2.0 OR LGPL-2.1-or-later | used under MIT | +| tiny-keccak 2.0.2 | CC0-1.0 | hashing at build time for const-random, through tauri-plugin-deep-link (from 0.12.0) | The Linux AppImage also carries the build machine's WebKitGTK, GTK and GLib (LGPL-2.1-or-later) as separate shared libraries. This notice, `THIRD-PARTY-NOTICES.txt` and LICENSE ship inside every installer. @@ -69,15 +72,29 @@ The Linux AppImage also carries the build machine's WebKitGTK, GTK and GLib (LGP | Tool | License | | --- | --- | | TypeScript 7.0.2, Vite 8.3.5, @tauri-apps/cli | Apache-2.0, MIT, MIT or Apache-2.0 | -| cairosvg, Pillow (run by `assets/icon_src/build.py` in a throwaway environment to draw the icon set; the icons are shipped, the tools are not) | LGPL-3.0-or-later, MIT-CMU | +| Pillow (run by `assets/icon_src/build.py` in a throwaway environment to size the icon set from the owner's masters in `assets/icon_src/masters`; the icons are shipped, the tool is not) | MIT-CMU | | PyInstaller | GPL-2.0 with the bootloader exception, which permits distributing the frozen engine; the bootloader is inside the engine, so its licence text is in `THIRD-PARTY-NOTICES.txt` | +## Programs FormChem runs but never ships + +From 0.12.0 FormChem can run these programs when the person has installed them and set their path (or put them on PATH). They are separate programs under their own licences: FormChem does not include them, does not download them, does not link to them, and only starts them as separate processes and reads the files they write. + +| Program | License | What FormChem uses it for | +| --- | --- | --- | +| xtb (https://github.com/grimme-lab/xtb) | LGPL-3.0 | 3D > Optimise with xtb and the `xtb_optimise` agent tool: GFN2-xTB and GFN-FF optimisations and single points with ALPB implicit solvent | +| CREST (https://github.com/crest-lab/crest) | LGPL-3.0 | 3D > Conformer Search with CREST and the `crest_conformers` agent tool | + +The list of 24 ALPB solvent names in `backend/app/services/xtb/solvents.py` names the solvents xtb documents; no xtb code or parameter file is in FormChem. + ## FormChem's own data These ship with the engine and are FormChem's own work under Apache-2.0; no third-party database or list was copied to make them: - The names dictionary in `backend/app/data/names/` (common names with SMILES written for FormChem and InChIKeys computed with RDKit), read by the offline name engine. - The NMR increments in `backend/app/services/nmr/` (rounded base values and substituent terms of textbook additive methods), and the reference shifts in `backend/app/services/nmr/reference.py`, approximate typical values used only to measure the predictor's error. NMRShiftDB2 data is not used. +- The HELM monomer data in `backend/app/data/helm_monomers.json` (from 0.12.0): 55 monomers (the 20 amino acids, 19 D forms, six non-standard residues, two caps, two sugars, phosphate and five bases) written for FormChem from textbook structures. No HELM monomer library (including the Pistoia Alliance's) was consulted or copied; the file says so in its `source` fields. +- The functional group table (42 SMARTS patterns) and the ring system names (51 ring skeletons) in `backend/app/services/describe.py` (from 0.12.0), written for FormChem for the spoken Structure Summary. +- The high-contrast and colour-blind safe element palettes in `frontend/src/canvas/render/atom.ts` (from 0.12.0). The colour-blind palette uses four colour values of the Okabe-Ito palette (Okabe and Ito, Color Universal Design), a published colour recommendation; no code or file was copied. ## Trademarks diff --git a/README.md b/README.md index 05e62146..b8dade95 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

FormChem icon: a white hexagon with a ring inside it on an orange to violet rounded square

+

FormChem icon: benzene, an arrow and phenol in white above a row of spectrum peaks, on a blue to violet to orange card in a dark rounded square

FormChem

@@ -8,7 +8,7 @@ with an MCP server so an agent works in the same window you see. Local-first, no account.

- version 0.10.0 + version 0.12.0 TypeScript and Vite Python and FastAPI macOS, Windows, Linux @@ -28,7 +28,7 @@ ## Features -FormChem draws structures and reactions: draw on the canvas with the mouse or the keyboard, annotate with arrows, brackets, shapes, tables and TLC plates, and the chemistry engine checks every change, reads reaction schemes, maps their atoms, works out the amounts, labels stereochemistry and computes properties with the method behind each number. Drawings go out as chemistry files and as pictures that open again as the drawing, through the clipboard to other programs, and whole files convert on the command line. Names turn into structures and structures into names, offline; 1H and 13C NMR spectra are predicted with the method and version beside every number; and measured spectra open from JCAMP-DX files with their peaks linked to atoms. Structures turn in 3D: built from the drawing with their stereo checked, with conformers, minimisation, dihedral scans, measurements and surfaces, placed on the page as 3D views, and proteins open from PDB and mmCIF files with their ligands. Agents draw in the same window: they draw and edit structures and reactions, from names too, predict and read spectra and build in 3D through 60 MCP tools, check their work with a picture of what you see, and every call is one undo step you can review, undo or stop. +FormChem draws structures and reactions: draw on the canvas with the mouse or the keyboard, annotate with arrows, brackets, shapes, tables and TLC plates, and the chemistry engine checks every change, reads reaction schemes, maps their atoms, works out the amounts, labels stereochemistry and computes properties with the method behind each number. Drawings go out as chemistry files and as pictures that open again as the drawing, through the clipboard to other programs, and whole files convert on the command line. Names turn into structures and structures into names, offline; 1H and 13C NMR spectra are predicted with the method and version beside every number; and measured spectra open from JCAMP-DX files with their peaks linked to atoms. Structures turn in 3D: built from the drawing with their stereo checked, with conformers, minimisation, dihedral scans, measurements and surfaces, placed on the page as 3D views, and proteins open from PDB and mmCIF files with their ligands. Compounds live in structure databases (one `.fcdb` file each) that you search by structure, formula and your own fields, browse as a table, gallery, form or plot, and fill from or write to SD, SMILES and CSV files, with a lab notebook of signed experiment entries beside them. A structure copied into another Form app stays a FormChem drawing and comes back editable, through a shared structure library every Form app reads. Everything can be drawn and read from the keyboard, with each atom spoken and the whole structure summarised, in element colours that stay apart for low vision and colour blindness. Peptides and nucleic acids come in and go out as HELM, and xtb and CREST run when you have installed them. Agents draw in the same window: they draw and edit structures and reactions, from names and HELM too, predict and read spectra, build in 3D, run xtb, search and fill databases and keep the structure library through 77 MCP tools, check their work with a picture of what you see, and every call is one undo step you can review, undo or stop. @@ -57,7 +57,7 @@ FormChem draws structures and reactions: draw on the canvas with the mouse or th - + @@ -72,7 +72,22 @@ FormChem draws structures and reactions: draw on the canvas with the mouse or th - + + + + + + + + + + + + + + + + @@ -80,12 +95,13 @@ FormChem draws structures and reactions: draw on the canvas with the mouse or th ### Coming next -- A local structure database: records with fields, exact, substructure, similarity and formula search, saved queries, SD import and export, and table and gallery views with structure columns -- A notebook view: experiment entries with schemes, tables, spectra and text, searchable across entries +- Desktop builds checked end to end, with the engine's self check on every platform, and file associations so `.fchem` (and open-with for `.mol`, `.sdf`, `.rxn`, `.cdxml` and `.cdx`) opens with a double-click +- Three offline browser demos (drawing, reactions, 3D), the manual and the full wiki, and a parity score row by row against the specifications +- Then a parity pass: closing the gaps that score marks as partial, a performance pass on large documents and a polish pass on every dialog and menu ## Built for agents -Claude Code, Codex, Cursor, Antigravity or any MCP client draws in the window you have open. `draw_from_smiles {"smiles": "CC(=O)Oc1ccccc1C(=O)O"}` lays aspirin out in free space on the page and answers with its ids, SMILES, InChIKey, formula and a picture drawn by the window's own renderer; `render`, `get_structure` and `validate` check the work; `get_atoms` and 14 edit tools (`add_atom`, `add_bond`, `set_charge`, `set_stereo`, `replace_substructure`, `move`, `scale`, `add_arrow`, `add_reaction` and more) build and change structures by id; `new_document`, `open_document`, `save_document` and `close_document` handle drawings; `convert` and `batch_convert` give the command line's exact output. From 0.9.0 `draw_from_name {"name": "caffeine"}` draws a name and says how it was read, `name_structure` names what is drawn, `predict_nmr` and `predict_spectrum` give predicted 1H and 13C NMR with their method and version, and `open_spectrum`, `spectrum_data`, `spectrum_peaks`, `spectrum_pick_peaks`, `spectrum_integrate` and `spectrum_export` work on JCAMP-DX spectra. From 0.10.0 `build_3d` builds a structure in 3D and says whether every stereo label was kept, `conformers_3d`, `minimise_3d`, `scan_dihedral` and `measure_3d` give energies and geometry with their force field and version, `open_3d_structure` opens PDB, mmCIF, SDF and MOL files, `extract_ligand` turns a bound ligand into a structure, and `export_3d` writes MOL, SDF, PDB or XYZ. The window's commands (`list_commands`, `run_command`), Form extensions, handoffs and the reaction and analysis tools are there as before. +Claude Code, Codex, Cursor, Antigravity or any MCP client draws in the window you have open. `draw_from_smiles {"smiles": "CC(=O)Oc1ccccc1C(=O)O"}` lays aspirin out in free space on the page and answers with its ids, SMILES, InChIKey, formula and a picture drawn by the window's own renderer; `render`, `get_structure` and `validate` check the work; `get_atoms` and 14 edit tools (`add_atom`, `add_bond`, `set_charge`, `set_stereo`, `replace_substructure`, `move`, `scale`, `add_arrow`, `add_reaction` and more) build and change structures by id; `new_document`, `open_document`, `save_document` and `close_document` handle drawings; `convert` and `batch_convert` give the command line's exact output. From 0.9.0 `draw_from_name {"name": "caffeine"}` draws a name and says how it was read, `name_structure` names what is drawn, `predict_nmr` and `predict_spectrum` give predicted 1H and 13C NMR with their method and version, and `open_spectrum`, `spectrum_data`, `spectrum_peaks`, `spectrum_pick_peaks`, `spectrum_integrate` and `spectrum_export` work on JCAMP-DX spectra. From 0.10.0 `build_3d` builds a structure in 3D and says whether every stereo label was kept, `conformers_3d`, `minimise_3d`, `scan_dihedral` and `measure_3d` give energies and geometry with their force field and version, `open_3d_structure` opens PDB, mmCIF, SDF and MOL files, `extract_ligand` turns a bound ligand into a structure, and `export_3d` writes MOL, SDF, PDB or XYZ. From 0.11.0 `db_list`, `db_create` and `db_open` reach structure databases, `db_import` fills one and reports every bad record, `db_search {"smiles": "c1ccccc1"}` answers a hit list you see in the window too, `db_get_record`, `db_add_record` (which refuses a duplicate until the agent chooses) and `db_update_record` work on records, `db_export` writes SD, SMILES or CSV, and `nb_add_entry` and `nb_search` keep lab notebook entries, which only you sign. From 0.12.0 `library_list`, `library_add` and `live_structure_object` reach the shared structure library and the object a sibling app keeps, `draw_from_helm {"helm": "PEPTIDE1{G.G}$$$$"}` draws a peptide or nucleic acid, and `xtb_optimise` and `crest_conformers` run xtb and CREST when you have installed them. The window's commands (`list_commands`, `run_command`), Form extensions, handoffs and the reaction and analysis tools are there as before. Every change is one undo step, labelled with the tool in Edit > Undo. Reading is always open; the window asks before an outside agent changes anything, the title bar shows which agent is editing with a Stop button, and Window > Agent Activity lists every call with undo for the latest one. The HTTP endpoint needs the agent token, which `./formchem agents install` writes into the agent configs; stdio clients send it themselves. An agent set up for 0.7.0 over HTTP needs `./formchem agents install` once more. @@ -111,6 +127,8 @@ FormChem hosts Form extensions (Form Extension Contract, API 1): FormPortal inst - **Agents:** the drawing and edit tools build JSON ops in the engine and apply them as one transaction, so they work with or without a window; pictures for agents come from the window's own renderer over the live channel, with an RDKit fallback when no window is open. One function logs every call for Agent Activity. - **Names and spectra:** FormChem's own offline name engine, NMR increment predictor and JCAMP-DX reader, each behind a registry so that OPSIN or a data-backed predictor can be added later without changing the window or the tools. No name or shift database is copied; spectrum points are computed on request and never stored in the drawing. - **3D:** RDKit's ETKDGv3, MMFF94 and UFF in the engine, FormChem's own PDB and mmCIF readers and glTF writer, and 3Dmol.js in the window, loaded only when a 3D view first opens. Conformers live in the drawing and drop in the same undo step when the structure they were built from changes, in the engine and in the window alike. +- **Databases:** one SQLite file per database with plain-English tables, specified in [`docs/DATABASE.md`](docs/DATABASE.md). Searches screen fingerprints held in memory as numpy arrays before RDKit confirms a match, imports and exports run as background jobs in batches, and the window pages records in blocks of 100 into pooled rows, so large tables never rebuild. +- **Family integration:** the shared structure library is plain files written atomically, specified for sibling apps in [`docs/LIVE_STRUCTURES.md`](docs/LIVE_STRUCTURES.md); a live drawing is an ordinary drawing linked to its library item, and the desktop shell registers `formai://` with tauri-plugin-deep-link. HELM is read and written by FormChem's own parser and monomer data, and xtb and CREST (LGPL-3.0) run only as separate programs you install. - **Format:** `.fchem` is a zip package around `document.json`, specified in [`docs/FORMAT.md`](docs/FORMAT.md), which both the engine and the window implement. ## Run it from source @@ -120,7 +138,7 @@ Prefer it in your browser, or want to contribute? Run the web UI straight from t **Requires:** Python 3.12+ and Node 20.19+. ```sh -git clone git@github.com:nodemode-dev/formchem.git +git clone https://github.com/nodemode-dev/formchem.git cd formchem ./formchem install # backend venv and frontend packages ./formchem # web UI at http://localhost:5220 @@ -129,7 +147,7 @@ cd formchem `./formchem desktop dev` opens the desktop window instead. On Windows use `formchem.bat install` and `formchem.bat`. The engine listens on `127.0.0.1:8220` (MCP at `/mcp`); `FORMCHEM_DATA_DIR` moves the data folder from `~/formchem`. > [!IMPORTANT] -> **Status:** in development, and the repository is private until the first release. This version draws, checks and analyses structures and reactions, with stereochemistry, query structures and calculated properties, from 0.7.0 reads and writes the common chemistry files, exports pictures, prints, copies and pastes, and converts files on the command line, from 0.8.0 lets agents draw, edit, check and convert directly, from 0.9.0 reads and writes chemical names, predicts NMR spectra and opens JCAMP-DX spectra, and from 0.10.0 builds structures in 3D, searches conformers, opens PDB and mmCIF files and extracts their ligands; a structure database comes next. The 0.7.0 to 0.10.0 desktop apps have not been run on a Mac yet, 0.8.0's agent tools were checked over stdio and HTTP and 0.9.0's and 0.10.0's in process, not yet with a real Claude Code or Codex client, the NMR accuracy figures rest on approximate reference shifts, the 3D View ran on software WebGL only, and xtb and CREST are not offered. Nothing is built or released for download yet. +> **Status:** in development, in a public repository since 5 December 2026. This version draws, checks and analyses structures and reactions, with stereochemistry, query structures and calculated properties, from 0.7.0 reads and writes the common chemistry files, exports pictures, prints, copies and pastes, and converts files on the command line, from 0.8.0 lets agents draw, edit, check and convert directly, from 0.9.0 reads and writes chemical names, predicts NMR spectra and opens JCAMP-DX spectra, from 0.10.0 builds structures in 3D, searches conformers, opens PDB and mmCIF files and extracts their ligands, from 0.11.0 keeps structure databases and a lab notebook, and from 0.12.0 shares live structures and a structure library with the other Form apps, works from the keyboard with spoken atoms, reads and writes HELM, and runs xtb and CREST you install; desktop builds, file associations, demos and the manual come next. The 0.7.0 to 0.12.0 desktop apps have not been run on a Mac yet, 0.8.0's agent tools were checked over stdio and HTTP, 0.9.0's and 0.10.0's in process and 0.11.0's and 0.12.0's over HTTP, not yet with a real Claude Code or Codex client, the NMR accuracy figures rest on approximate reference shifts, the 3D View ran on software WebGL only, no sibling app has opened a live structure yet, no real screen reader has been run, and xtb and CREST were checked with stand-in programs only. Nothing is built or released for download yet. **Contributing:** branch from `main`, keep changes to source here, and leave packaging and releases to FormCompiler. See [`CONTRIBUTING.md`](CONTRIBUTING.md), [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md), [`.docs/BRANCHING.md`](.docs/BRANCHING.md) and [`AGENTS.md`](AGENTS.md). Report security issues privately as [`SECURITY.md`](SECURITY.md) describes. @@ -137,12 +155,12 @@ cd formchem | Path | What it is | |---|---| -| `backend/` | FastAPI engine: documents, chemistry, reactions and analysis, names, NMR prediction and spectra, 3D (conformers, force fields, PDB and mmCIF), file formats and pictures, the conversion command line, templates, live channel, terminal dock, extensions, MCP and the agent tools, the agent call log | -| `frontend/` | Vanilla TypeScript and Vite window: the drawing canvas and tools, spectra and the Spectrum editor, the 3D View, export, print and clipboard, shell, menus, Home, Preferences, dock | +| `backend/` | FastAPI engine: documents, chemistry, reactions and analysis, names, NMR prediction and spectra, 3D (conformers, force fields, PDB and mmCIF), structure databases and the lab notebook, the shared structure library and live structures, the file watch, the structure description, HELM, xtb and CREST jobs, file formats and pictures, the conversion command line and edit-live, templates, live channel, terminal dock, extensions, MCP and the agent tools, the agent call log | +| `frontend/` | Vanilla TypeScript and Vite window: the drawing canvas and tools, spectra and the Spectrum editor, the 3D View, the database workspace and the notebook, the Structure Library, keyboard focus and the screen reader announcer, the HELM and xtb dialogs, export, print and clipboard, shell, menus, Home, Preferences, dock | | `setup/` | Install, boot, build, freeze, convert and agent setup scripts | -| `src-tauri/` | Desktop shell; it starts the engine folder on macOS and the engine sidecar elsewhere | +| `src-tauri/` | Desktop shell; it starts the engine folder on macOS and the engine sidecar elsewhere, and registers the `formai://` link | -Docs: [`.docs/wiki`](.docs/wiki) · Formats: [`docs/FORMATS.md`](docs/FORMATS.md) · Names: [`docs/NAMES.md`](docs/NAMES.md) · Spectra and NMR: [`docs/SPECTRA.md`](docs/SPECTRA.md) · 3D: [`docs/3D.md`](docs/3D.md) · Command line: [`docs/CLI.md`](docs/CLI.md) · Agent tools: [`docs/AGENTS.md`](docs/AGENTS.md) · Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md) · Contributing: [`.docs/BRANCHING.md`](.docs/BRANCHING.md) +Docs: [`.docs/wiki`](.docs/wiki) · Formats: [`docs/FORMATS.md`](docs/FORMATS.md) · Names: [`docs/NAMES.md`](docs/NAMES.md) · Spectra and NMR: [`docs/SPECTRA.md`](docs/SPECTRA.md) · 3D: [`docs/3D.md`](docs/3D.md) · Databases: [`docs/DATABASES.md`](docs/DATABASES.md) and the contract [`docs/DATABASE.md`](docs/DATABASE.md) · Live structures: [`docs/LIVE-STRUCTURES.md`](docs/LIVE-STRUCTURES.md) and the contract [`docs/LIVE_STRUCTURES.md`](docs/LIVE_STRUCTURES.md) · Accessibility: [`docs/ACCESSIBILITY.md`](docs/ACCESSIBILITY.md) · HELM: [`docs/HELM.md`](docs/HELM.md) · Command line: [`docs/CLI.md`](docs/CLI.md) · Agent tools: [`docs/AGENTS.md`](docs/AGENTS.md) · Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md) · Contributing: [`.docs/BRANCHING.md`](.docs/BRANCHING.md)
diff --git a/SECURITY.md b/SECURITY.md index 5bb31bd9..57a477a3 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -7,7 +7,7 @@ check whether the problem is still there. | Version | Supported | | --- | --- | -| 0.10.x (in development, not yet released) | Yes | +| 0.12.x (in development, not yet released) | Yes | | Anything older | No | ## Reporting a vulnerability @@ -62,6 +62,55 @@ something outside it could get in: SMILES, file paths and tool names. Anything that lets an agent act after Stop, undo or change someone else's work through the call log, or skip the log, counts. +- **Databases and notebook entries** (from 0.11.0): records, field values, + files and notebook entries are private data, so every database route, reads + included, needs the window key; agents reach databases only through the MCP + tools, behind the agent token. Thumbnails and + attachments, which the window loads through image and link tags that + cannot send a header, also take a separate view key in the query; it is + random per engine start, opens only those two picture routes, and the + window key itself never goes into a URL or a log. Agents' database writes + ask the person like drawing changes do and are recorded under the agent's + name in the database's audit table. A browser window's uploads and one-time + downloads stay in the Databases folder and are deleted after a day (a + download as soon as it is sent), and only an `.fcdb` that was just uploaded + can be adopted into that folder. Anything that lets a request without the + window key (or an MCP call without the agent token) read records or entries, lets the view key open + any other route, or lets an upload, download or adopted file reach a path + outside the Databases folder, counts. A notebook signature is a SHA-256 + hash of the entry's content with a name and time, recorded by FormChem; + it is not a cryptographic signature tied to a person's key. +- **The structure library and the agent token's one write path** (from + 0.12.0): the shared library is the folder `Library` in the data folder, + readable by any program running as the person, by design, so that sibling + Form apps can read it; it holds pictures, molfiles and SMILES, nothing + else. Its routes (`/api/structures` and the paths under it) take the window + key or the agent token, reads included, so that `./formchem edit-live` and + sibling apps can ask FormChem to open a structure. That is the only place + outside `/mcp` where the agent token may change anything; every other + changing route still needs the window key. The item picture route is the + exception that takes no key, because an image tag cannot send one, and like + every route it answers local origins only. Anything that lets the agent + token write outside `/api/structures`, or lets a library write leave the + `Library` folder, counts. +- **The `formai://` link** (from 0.12.0): the desktop app registers the + `formai` scheme. A `formai://formchem/edit?id=...&from=...` link can only + ask the running FormChem to open a library item, which it already has, + as a live drawing in the main window; the `from` name is shown in the + title bar after it is cleaned to letters, digits, spaces, dots and dashes. + A link cannot open a file path, run a command, change a setting or save + anything, and other `formai` hosts are passed on, not acted on. Anything + that lets a link do more counts. +- **xtb and CREST** (from 0.12.0): FormChem never ships or downloads them. It + runs the program at the path the person set in Preferences > 3D, or the + one it finds on PATH or in the usual install folders, as a separate + process with its own temporary folder, and only after the person asks for + a calculation (or allows an agent's). The path is a setting only the window + key can change. A program put at that path or on PATH by someone else runs + as the person, as any program on PATH would; that is outside what FormChem + can guard. Anything that makes FormChem run a program the person did not + choose, pass it arguments other than its own, or leave its process running + after a cancel, a time limit or the engine's exit, counts. - **Files**: opening or importing documents, structure files, media or archives in a way that writes outside where it should. diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index e8c471a3..aef40479 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -476,15 +476,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [[ end file click-8.5.1.dist-info/licenses/LICENSE.txt ]] ============================================================================== -python: cryptography 51.0.0 +python: cryptography 51.0.1 Licence: Apache-2.0 OR BSD-3-Clause Source: https://cryptography.io/en/latest/changelog/ -[[ begin file cryptography-51.0.0.dist-info/licenses/LICENSE ]] +[[ begin file cryptography-51.0.1.dist-info/licenses/LICENSE ]] This software is made available under the terms of *either* of the licenses found in LICENSE.APACHE or LICENSE.BSD. Contributions to cryptography are made under the terms of *both* these licenses. -[[ end file cryptography-51.0.0.dist-info/licenses/LICENSE ]] -[[ begin file cryptography-51.0.0.dist-info/licenses/LICENSE.APACHE ]] +[[ end file cryptography-51.0.1.dist-info/licenses/LICENSE ]] +[[ begin file cryptography-51.0.1.dist-info/licenses/LICENSE.APACHE ]] Apache License Version 2.0, January 2004 @@ -687,8 +687,8 @@ under the terms of *both* these licenses. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -[[ end file cryptography-51.0.0.dist-info/licenses/LICENSE.APACHE ]] -[[ begin file cryptography-51.0.0.dist-info/licenses/LICENSE.BSD ]] +[[ end file cryptography-51.0.1.dist-info/licenses/LICENSE.APACHE ]] +[[ begin file cryptography-51.0.1.dist-info/licenses/LICENSE.BSD ]] Copyright (c) Individual contributors. All rights reserved. @@ -716,7 +716,7 @@ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -[[ end file cryptography-51.0.0.dist-info/licenses/LICENSE.BSD ]] +[[ end file cryptography-51.0.1.dist-info/licenses/LICENSE.BSD ]] ============================================================================== python: epam-indigo 1.49.0 @@ -1326,10 +1326,10 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND [[ end file httpx-0.28.1.dist-info/licenses/LICENSE.md ]] ============================================================================== -python: idna 3.20 +python: idna 3.21 Licence: BSD-3-Clause Source: https://github.com/kjd/idna/blob/master/HISTORY.md -[[ begin file idna-3.20.dist-info/licenses/LICENSE.md ]] +[[ begin file idna-3.21.dist-info/licenses/LICENSE.md ]] BSD 3-Clause License Copyright (c) 2013-2026, Kim Davies and contributors. @@ -1361,7 +1361,7 @@ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -[[ end file idna-3.20.dist-info/licenses/LICENSE.md ]] +[[ end file idna-3.21.dist-info/licenses/LICENSE.md ]] ============================================================================== python: jaraco-classes 3.4.0 @@ -8702,12 +8702,26 @@ Source: https://github.com/RustCrypto/formats [[ file LICENSE-APACHE: shared text T20 ]] [[ file LICENSE-MIT: shared text T24 ]] +============================================================================== +crate: const-random 0.1.20 +Licence: MIT OR Apache-2.0 +Source: https://github.com/tkaitchuck/constrandom +[[ file LICENSE-APACHE: shared text T13 ]] +[[ file LICENSE-MIT: shared text T25 ]] + +============================================================================== +crate: const-random-macro 0.1.18 +Licence: MIT OR Apache-2.0 +Source: https://github.com/tkaitchuck/constrandom +[[ file LICENSE-APACHE: shared text T13 ]] +[[ file LICENSE-MIT: shared text T25 ]] + ============================================================================== crate: constant_time_eq 0.6.2 Licence: CC0-1.0 OR MIT-0 OR Apache-2.0 Source: https://codeberg.org/cesarb/constant_time_eq [[ file LICENSE-APACHE: shared text T12 ]] -[[ file LICENSE-CC0: shared text T25 ]] +[[ file LICENSE-CC0: shared text T26 ]] [[ begin file LICENSE-MIT0 ]] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -8967,21 +8981,21 @@ crate: core-foundation 0.10.1 Licence: MIT OR Apache-2.0 Source: https://github.com/servo/core-foundation-rs [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T26 ]] +[[ file LICENSE-MIT: shared text T27 ]] ============================================================================== crate: core-foundation 0.9.4 Licence: MIT OR Apache-2.0 Source: https://github.com/servo/core-foundation-rs [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T26 ]] +[[ file LICENSE-MIT: shared text T27 ]] ============================================================================== crate: core-foundation-sys 0.8.7 Licence: MIT OR Apache-2.0 Source: https://github.com/servo/core-foundation-rs [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T26 ]] +[[ file LICENSE-MIT: shared text T27 ]] ============================================================================== crate: core-graphics 0.25.0 @@ -8995,14 +9009,14 @@ option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. [[ end file COPYRIGHT ]] [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T26 ]] +[[ file LICENSE-MIT: shared text T27 ]] ============================================================================== crate: core-graphics-types 0.2.0 Licence: MIT OR Apache-2.0 Source: https://github.com/servo/core-foundation-rs [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T26 ]] +[[ file LICENSE-MIT: shared text T27 ]] ============================================================================== crate: core_detect 1.0.0 @@ -9081,7 +9095,7 @@ Source: https://github.com/RustCrypto/utils crate: crc32fast 1.5.6 Licence: MIT OR Apache-2.0 Source: https://github.com/srijs/rust-crc32fast -[[ file LICENSE-APACHE: shared text T27 ]] +[[ file LICENSE-APACHE: shared text T28 ]] [[ begin file LICENSE-MIT ]] MIT License @@ -9111,7 +9125,7 @@ crate: crossbeam-channel 0.5.17 Licence: MIT OR Apache-2.0 Source: https://github.com/crossbeam-rs/crossbeam [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T28 ]] +[[ file LICENSE-MIT: shared text T29 ]] [[ begin file LICENSE-THIRD-PARTY ]] =============================================================================== @@ -9713,7 +9727,35 @@ crate: crossbeam-utils 0.8.23 Licence: MIT OR Apache-2.0 Source: https://github.com/crossbeam-rs/crossbeam [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T28 ]] +[[ file LICENSE-MIT: shared text T29 ]] + +============================================================================== +crate: crunchy 0.2.4 +Licence: MIT +Source: https://github.com/eira-fransham/crunchy +[[ begin file LICENSE ]] +The MIT License (MIT) + +Copyright 2017-2023 Eira Fransham. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +[[ end file LICENSE ]] ============================================================================== crate: crypto-common 0.1.7 @@ -9785,51 +9827,51 @@ DEALINGS IN THE SOFTWARE. crate: cssparser 0.37.0 Licence: MPL-2.0 Source: https://github.com/servo/rust-cssparser -[[ file LICENSE: shared text T29 ]] +[[ file LICENSE: shared text T30 ]] ============================================================================== crate: cssparser 0.38.0 Licence: MPL-2.0 Source: https://github.com/servo/rust-cssparser -[[ file LICENSE: shared text T29 ]] +[[ file LICENSE: shared text T30 ]] ============================================================================== crate: cssparser-macros 0.7.1 Licence: MPL-2.0 Source: https://github.com/servo/rust-cssparser -[[ file LICENSE: shared text T29 ]] +[[ file LICENSE: shared text T30 ]] ============================================================================== crate: ctor 1.0.14 Licence: Apache-2.0 OR MIT Source: https://github.com/mmastrac/linktime -[[ file LICENSE-APACHE: shared text T30 ]] -[[ file LICENSE-MIT: shared text T31 ]] +[[ file LICENSE-APACHE: shared text T31 ]] +[[ file LICENSE-MIT: shared text T32 ]] ============================================================================== crate: darling 0.24.1 Licence: MIT Source: https://github.com/TedDriggs/darling -[[ file LICENSE: shared text T32 ]] +[[ file LICENSE: shared text T33 ]] ============================================================================== crate: darling_core 0.24.1 Licence: MIT Source: https://github.com/TedDriggs/darling -[[ file LICENSE: shared text T32 ]] +[[ file LICENSE: shared text T33 ]] ============================================================================== crate: darling_macro 0.24.1 Licence: MIT Source: https://github.com/TedDriggs/darling -[[ file LICENSE: shared text T32 ]] +[[ file LICENSE: shared text T33 ]] ============================================================================== crate: dbus 0.9.12 Licence: Apache-2.0/MIT Source: https://github.com/diwic/dbus-rs -[[ file LICENSE-APACHE: shared text T33 ]] -[[ file LICENSE-MIT: shared text T34 ]] +[[ file LICENSE-APACHE: shared text T34 ]] +[[ file LICENSE-MIT: shared text T35 ]] ============================================================================== crate: deranged 0.5.9 @@ -10065,13 +10107,13 @@ SOFTWARE. crate: derive_more 2.1.1 Licence: MIT Source: https://github.com/JelteF/derive_more -[[ file LICENSE: shared text T35 ]] +[[ file LICENSE: shared text T36 ]] ============================================================================== crate: derive_more-impl 2.1.1 Licence: MIT Source: https://github.com/JelteF/derive_more -[[ file LICENSE: shared text T35 ]] +[[ file LICENSE: shared text T36 ]] ============================================================================== crate: digest 0.10.7 @@ -10144,15 +10186,15 @@ DEALINGS IN THE SOFTWARE. crate: dirs 7.0.0 Licence: MIT OR Apache-2.0 Source: https://codeberg.org/dirs/dirs-rs -[[ file LICENSE-APACHE: shared text T36 ]] -[[ file LICENSE-MIT: shared text T37 ]] +[[ file LICENSE-APACHE: shared text T37 ]] +[[ file LICENSE-MIT: shared text T38 ]] ============================================================================== crate: dirs-sys 0.5.0 Licence: MIT OR Apache-2.0 Source: https://github.com/dirs-dev/dirs-sys-rs -[[ file LICENSE-APACHE: shared text T36 ]] -[[ file LICENSE-MIT: shared text T37 ]] +[[ file LICENSE-APACHE: shared text T37 ]] +[[ file LICENSE-MIT: shared text T38 ]] ============================================================================== crate: dispatch2 0.3.1 @@ -10179,23 +10221,52 @@ Licence: MIT Source: https://github.com/OpenByteDev/dlopen2 Note: The published crate carries no licence file; its SPDX licence and repository are given above. +============================================================================== +crate: dlv-list 0.5.2 +Licence: MIT OR Apache-2.0 +Source: https://github.com/sgodwincs/dlv-list-rs +[[ file LICENSE-APACHE: shared text T12 ]] +[[ begin file LICENSE-MIT ]] +MIT License + +Copyright (c) 2022 Scott Godwin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +[[ end file LICENSE-MIT ]] + ============================================================================== crate: dom_query 0.28.0 Licence: MIT Source: https://github.com/niklak/dom_query -[[ file LICENSE: shared text T38 ]] +[[ file LICENSE: shared text T39 ]] ============================================================================== crate: dom_query 0.30.0 Licence: MIT Source: https://github.com/niklak/dom_query -[[ file LICENSE: shared text T38 ]] +[[ file LICENSE: shared text T39 ]] ============================================================================== crate: dpi 0.1.2 Licence: Apache-2.0 AND MIT Source: https://github.com/rust-windowing/winit -[[ file LICENSE: shared text T30 ]] +[[ file LICENSE: shared text T31 ]] [[ begin file LICENSE-LIBM-MIT ]] rust-lang/libm as a whole is available for use under the MIT license: @@ -10641,7 +10712,7 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice crate: dunce 1.0.5 Licence: CC0-1.0 OR MIT-0 OR Apache-2.0 Source: https://gitlab.com/kornelski/dunce -[[ file LICENSE: shared text T25 ]] +[[ file LICENSE: shared text T26 ]] ============================================================================== crate: dyn-clone 1.0.20 @@ -10731,7 +10802,7 @@ Test code within encoding_rs is dedicated to the Public Domain when so designated (see the individual files for PD/CC0-dedicated sections). [[ end file COPYRIGHT ]] [[ file LICENSE-APACHE: shared text T2 ]] -[[ file LICENSE-MIT: shared text T39 ]] +[[ file LICENSE-MIT: shared text T40 ]] [[ begin file LICENSE-WHATWG ]] Copyright © WHATWG (Apple, Google, Mozilla, Microsoft). @@ -11470,22 +11541,22 @@ SOFTWARE. crate: foreign-types 0.5.0 Licence: MIT/Apache-2.0 Source: https://github.com/sfackler/foreign-types -[[ file LICENSE-APACHE: shared text T27 ]] -[[ file LICENSE-MIT: shared text T40 ]] +[[ file LICENSE-APACHE: shared text T28 ]] +[[ file LICENSE-MIT: shared text T41 ]] ============================================================================== crate: foreign-types-macros 0.2.4 Licence: MIT/Apache-2.0 Source: https://github.com/sfackler/foreign-types -[[ file LICENSE-APACHE: shared text T27 ]] -[[ file LICENSE-MIT: shared text T40 ]] +[[ file LICENSE-APACHE: shared text T28 ]] +[[ file LICENSE-MIT: shared text T41 ]] ============================================================================== crate: foreign-types-shared 0.3.1 Licence: MIT/Apache-2.0 Source: https://github.com/sfackler/foreign-types -[[ file LICENSE-APACHE: shared text T27 ]] -[[ file LICENSE-MIT: shared text T40 ]] +[[ file LICENSE-APACHE: shared text T28 ]] +[[ file LICENSE-MIT: shared text T41 ]] ============================================================================== crate: form_urlencoded 1.2.3 @@ -11524,29 +11595,29 @@ DEALINGS IN THE SOFTWARE. crate: futures-channel 0.3.34 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-lang/futures-rs -[[ file LICENSE-APACHE: shared text T41 ]] -[[ file LICENSE-MIT: shared text T42 ]] +[[ file LICENSE-APACHE: shared text T42 ]] +[[ file LICENSE-MIT: shared text T43 ]] ============================================================================== crate: futures-core 0.3.34 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-lang/futures-rs -[[ file LICENSE-APACHE: shared text T41 ]] -[[ file LICENSE-MIT: shared text T42 ]] +[[ file LICENSE-APACHE: shared text T42 ]] +[[ file LICENSE-MIT: shared text T43 ]] ============================================================================== crate: futures-executor 0.3.34 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-lang/futures-rs -[[ file LICENSE-APACHE: shared text T41 ]] -[[ file LICENSE-MIT: shared text T42 ]] +[[ file LICENSE-APACHE: shared text T42 ]] +[[ file LICENSE-MIT: shared text T43 ]] ============================================================================== crate: futures-io 0.3.34 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-lang/futures-rs -[[ file LICENSE-APACHE: shared text T41 ]] -[[ file LICENSE-MIT: shared text T42 ]] +[[ file LICENSE-APACHE: shared text T42 ]] +[[ file LICENSE-MIT: shared text T43 ]] ============================================================================== crate: futures-lite 2.6.1 @@ -11560,29 +11631,29 @@ Source: https://github.com/smol-rs/futures-lite crate: futures-macro 0.3.34 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-lang/futures-rs -[[ file LICENSE-APACHE: shared text T41 ]] -[[ file LICENSE-MIT: shared text T42 ]] +[[ file LICENSE-APACHE: shared text T42 ]] +[[ file LICENSE-MIT: shared text T43 ]] ============================================================================== crate: futures-sink 0.3.34 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-lang/futures-rs -[[ file LICENSE-APACHE: shared text T41 ]] -[[ file LICENSE-MIT: shared text T42 ]] +[[ file LICENSE-APACHE: shared text T42 ]] +[[ file LICENSE-MIT: shared text T43 ]] ============================================================================== crate: futures-task 0.3.34 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-lang/futures-rs -[[ file LICENSE-APACHE: shared text T41 ]] -[[ file LICENSE-MIT: shared text T42 ]] +[[ file LICENSE-APACHE: shared text T42 ]] +[[ file LICENSE-MIT: shared text T43 ]] ============================================================================== crate: futures-util 0.3.34 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-lang/futures-rs -[[ file LICENSE-APACHE: shared text T41 ]] -[[ file LICENSE-MIT: shared text T42 ]] +[[ file LICENSE-APACHE: shared text T42 ]] +[[ file LICENSE-MIT: shared text T43 ]] ============================================================================== crate: gdk 0.18.2 @@ -11661,7 +11732,7 @@ SOFTWARE. crate: getrandom 0.2.17 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-random/getrandom -[[ file LICENSE-APACHE: shared text T43 ]] +[[ file LICENSE-APACHE: shared text T44 ]] [[ begin file LICENSE-MIT ]] Copyright (c) 2018-2024 The rust-random Project Developers Copyright (c) 2014 The Rust Project Developers @@ -11695,7 +11766,7 @@ DEALINGS IN THE SOFTWARE. crate: getrandom 0.3.4 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-random/getrandom -[[ file LICENSE-APACHE: shared text T43 ]] +[[ file LICENSE-APACHE: shared text T44 ]] [[ begin file LICENSE-MIT ]] Copyright (c) 2018-2025 The rust-random Project Developers Copyright (c) 2014 The Rust Project Developers @@ -11729,7 +11800,7 @@ DEALINGS IN THE SOFTWARE. crate: getrandom 0.4.3 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-random/getrandom -[[ file LICENSE-APACHE: shared text T43 ]] +[[ file LICENSE-APACHE: shared text T44 ]] [[ begin file LICENSE-MIT ]] Copyright (c) 2018-2026 The rust-random Project Developers Copyright (c) 2014 The Rust Project Developers @@ -11830,14 +11901,21 @@ crate: hashbrown 0.12.3 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-lang/hashbrown [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T44 ]] +[[ file LICENSE-MIT: shared text T25 ]] + +============================================================================== +crate: hashbrown 0.14.5 +Licence: MIT OR Apache-2.0 +Source: https://github.com/rust-lang/hashbrown +[[ file LICENSE-APACHE: shared text T13 ]] +[[ file LICENSE-MIT: shared text T25 ]] ============================================================================== crate: hashbrown 0.17.2 Licence: MIT OR Apache-2.0 Source: https://github.com/rust-lang/hashbrown [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T44 ]] +[[ file LICENSE-MIT: shared text T25 ]] ============================================================================== crate: heck 0.4.1 @@ -11864,7 +11942,7 @@ Source: https://github.com/hermit-os/hermit-rs crate: hex 0.4.3 Licence: MIT OR Apache-2.0 Source: https://github.com/KokaKiwi/rust-hex -[[ file LICENSE-APACHE: shared text T27 ]] +[[ file LICENSE-APACHE: shared text T28 ]] [[ begin file LICENSE-MIT ]] Copyright (c) 2013-2014 The Rust Project Developers. Copyright (c) 2015-2020 The rust-hex Developers @@ -12837,14 +12915,14 @@ Note: The published crate carries no licence file; its SPDX licence and reposito crate: jni-sys 0.3.1 Licence: MIT OR Apache-2.0 Source: https://github.com/jni-rs/jni-sys -[[ file LICENSE-APACHE: shared text T27 ]] +[[ file LICENSE-APACHE: shared text T28 ]] [[ file LICENSE-MIT: shared text T58 ]] ============================================================================== crate: jni-sys 0.4.1 Licence: MIT OR Apache-2.0 Source: https://github.com/jni-rs/jni-sys -[[ file LICENSE-APACHE: shared text T27 ]] +[[ file LICENSE-APACHE: shared text T28 ]] [[ file LICENSE-MIT: shared text T58 ]] ============================================================================== @@ -12864,7 +12942,7 @@ Source: https://github.com/wasm-bindgen/wasm-bindgen/tree/master/crates/js-sys crate: json-patch 4.2.0 Licence: MIT/Apache-2.0 Source: https://github.com/idubrov/json-patch -[[ file LICENSE-APACHE: shared text T27 ]] +[[ file LICENSE-APACHE: shared text T28 ]] [[ begin file LICENSE-MIT ]] MIT License @@ -13220,8 +13298,8 @@ DEALINGS IN THE SOFTWARE. crate: libdbus-sys 0.2.7 Licence: Apache-2.0/MIT Source: https://github.com/diwic/dbus-rs -[[ file LICENSE-APACHE: shared text T33 ]] -[[ file LICENSE-MIT: shared text T34 ]] +[[ file LICENSE-APACHE: shared text T34 ]] +[[ file LICENSE-MIT: shared text T35 ]] ============================================================================== crate: libloading 0.7.4 @@ -13274,8 +13352,8 @@ SOFTWARE. crate: link-section 0.19.4 Licence: Apache-2.0 OR MIT Source: https://github.com/mmastrac/linktime -[[ file LICENSE-APACHE: shared text T30 ]] -[[ file LICENSE-MIT: shared text T31 ]] +[[ file LICENSE-APACHE: shared text T31 ]] +[[ file LICENSE-MIT: shared text T32 ]] ============================================================================== crate: linux-raw-sys 0.12.1 @@ -13807,7 +13885,7 @@ See the Licenses for the specific language governing permissions and limitations under the Licenses. [[ end file COPYRIGHT ]] [[ file LICENSE-APACHE: shared text T2 ]] -[[ file LICENSE-MIT: shared text T39 ]] +[[ file LICENSE-MIT: shared text T40 ]] ============================================================================== crate: ndk 0.9.0 @@ -14471,6 +14549,34 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice defined by the Mozilla Public License, v. 2.0. [[ end file LICENSE.txt ]] +============================================================================== +crate: ordered-multimap 0.7.3 +Licence: MIT +Source: https://github.com/sgodwincs/ordered-multimap-rs +[[ begin file LICENSE ]] +MIT License + +Copyright (c) 2018 sgodwincs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +[[ end file LICENSE ]] + ============================================================================== crate: ordered-stream 0.2.0 Licence: MIT OR Apache-2.0 @@ -15961,6 +16067,22 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [[ end file LICENSE-MIT ]] +============================================================================== +crate: rust-ini 0.21.3 +Licence: MIT +Source: https://github.com/zonyitoo/rust-ini +[[ begin file LICENSE ]] +The MIT License (MIT) + +Copyright (c) 2014 Y. T. CHUNG + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +[[ end file LICENSE ]] + ============================================================================== crate: rustc-hash 2.1.3 Licence: Apache-2.0 OR MIT @@ -16509,7 +16631,7 @@ Source: https://github.com/dtolnay/serde-repr crate: serde_spanned 0.6.9 Licence: MIT OR Apache-2.0 Source: https://github.com/toml-rs/toml -[[ file LICENSE-APACHE: shared text T27 ]] +[[ file LICENSE-APACHE: shared text T28 ]] [[ file LICENSE-MIT: shared text T74 ]] ============================================================================== @@ -17182,28 +17304,28 @@ crate: string_cache 0.11.0 Licence: MIT OR Apache-2.0 Source: https://github.com/servo/string-cache [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T26 ]] +[[ file LICENSE-MIT: shared text T27 ]] ============================================================================== crate: string_cache 0.9.0 Licence: MIT OR Apache-2.0 Source: https://github.com/servo/string-cache [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T26 ]] +[[ file LICENSE-MIT: shared text T27 ]] ============================================================================== crate: string_cache_codegen 0.11.2 Licence: MIT OR Apache-2.0 Source: https://github.com/servo/string-cache [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T26 ]] +[[ file LICENSE-MIT: shared text T27 ]] ============================================================================== crate: string_cache_codegen 0.6.1 Licence: MIT OR Apache-2.0 Source: https://github.com/servo/string-cache [[ file LICENSE-APACHE: shared text T13 ]] -[[ file LICENSE-MIT: shared text T26 ]] +[[ file LICENSE-MIT: shared text T27 ]] ============================================================================== crate: strsim 0.11.1 @@ -17566,7 +17688,7 @@ Source: https://github.com/gdesmott/system-deps crate: tao 0.37.3 Licence: Apache-2.0 Source: https://github.com/tauri-apps/tao -[[ file LICENSE: shared text T30 ]] +[[ file LICENSE: shared text T31 ]] [[ begin file LICENSE.spdx ]] SPDXVersion: SPDX-2.1 DataLicense: CC0-1.0 @@ -17711,6 +17833,14 @@ Licence: Apache-2.0 OR MIT Source: https://github.com/tauri-apps/tauri Note: The published crate carries no licence file; its SPDX licence and repository are given above. +============================================================================== +crate: tauri-plugin-deep-link 2.6.3 +Licence: Apache-2.0 OR MIT +Source: https://github.com/tauri-apps/plugins-workspace +[[ file LICENSE.spdx: shared text T79 ]] +[[ file LICENSE_APACHE-2.0: shared text T3 ]] +[[ file LICENSE_MIT: shared text T4 ]] + ============================================================================== crate: tauri-plugin-dialog 2.8.4 Licence: Apache-2.0 OR MIT @@ -17918,6 +18048,12 @@ Source: https://github.com/time-rs/time [[ file LICENSE-Apache: shared text T3 ]] [[ file LICENSE-MIT: shared text T81 ]] +============================================================================== +crate: tiny-keccak 2.0.2 +Licence: CC0-1.0 +Source: https://crates.io/crates/tiny-keccak/2.0.2 +[[ file LICENSE: shared text T26 ]] + ============================================================================== crate: tinystr 0.8.5 Licence: Unicode-3.0 @@ -17929,7 +18065,7 @@ crate: tinyvec 1.13.3 Licence: Zlib OR Apache-2.0 OR MIT Source: https://github.com/Lokathor/tinyvec [[ file LICENSE-APACHE.md: shared text T2 ]] -[[ file LICENSE-MIT.md: shared text T31 ]] +[[ file LICENSE-MIT.md: shared text T32 ]] [[ file LICENSE-ZLIB.md: shared text T22 ]] ============================================================================== @@ -18183,7 +18319,7 @@ Source: https://github.com/tokio-rs/tokio crate: toml 0.8.2 Licence: MIT OR Apache-2.0 Source: https://github.com/toml-rs/toml -[[ file LICENSE-APACHE: shared text T27 ]] +[[ file LICENSE-APACHE: shared text T28 ]] [[ file LICENSE-MIT: shared text T74 ]] ============================================================================== @@ -18211,14 +18347,14 @@ Source: https://github.com/toml-rs/toml crate: toml_edit 0.19.15 Licence: MIT OR Apache-2.0 Source: https://github.com/toml-rs/toml -[[ file LICENSE-APACHE: shared text T27 ]] +[[ file LICENSE-APACHE: shared text T28 ]] [[ file LICENSE-MIT: shared text T74 ]] ============================================================================== crate: toml_edit 0.20.2 Licence: MIT OR Apache-2.0 Source: https://github.com/toml-rs/toml -[[ file LICENSE-APACHE: shared text T27 ]] +[[ file LICENSE-APACHE: shared text T28 ]] [[ file LICENSE-MIT: shared text T74 ]] ============================================================================== @@ -18809,7 +18945,7 @@ licensed under the Apache License, Version 2.0 or or , at your option. [[ end file COPYRIGHT ]] [[ file LICENSE-APACHE: shared text T2 ]] -[[ file LICENSE-MIT: shared text T39 ]] +[[ file LICENSE-MIT: shared text T40 ]] ============================================================================== crate: utf_types 1.0.0 @@ -18838,7 +18974,7 @@ Test code is dedicated to the Public Domain when so designated (see the individual files for PD/CC0-dedicated sections). [[ end file COPYRIGHT ]] [[ file LICENSE-APACHE: shared text T2 ]] -[[ file LICENSE-MIT: shared text T39 ]] +[[ file LICENSE-MIT: shared text T40 ]] ============================================================================== crate: uuid 1.29.3 @@ -19425,7 +19561,7 @@ Note: The published crate carries no licence file; its SPDX licence and reposito crate: winapi 0.3.9 Licence: MIT/Apache-2.0 Source: https://github.com/retep998/winapi-rs -[[ file LICENSE-APACHE: shared text T27 ]] +[[ file LICENSE-APACHE: shared text T28 ]] [[ begin file LICENSE-MIT ]] Copyright (c) 2015-2018 The winapi-rs Developers @@ -22219,6 +22355,34 @@ DEALINGS IN THE SOFTWARE. [[ end shared text T24 ]] [[ begin shared text T25 ]] +Copyright (c) 2016 Amanieu d'Antras + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +[[ end shared text T25 ]] + +[[ begin shared text T26 ]] Creative Commons Legal Code CC0 1.0 Universal @@ -22340,9 +22504,9 @@ express Statement of Purpose. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. -[[ end shared text T25 ]] +[[ end shared text T26 ]] -[[ begin shared text T26 ]] +[[ begin shared text T27 ]] Copyright (c) 2012-2013 Mozilla Foundation Permission is hereby granted, free of charge, to any @@ -22368,9 +22532,9 @@ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -[[ end shared text T26 ]] +[[ end shared text T27 ]] -[[ begin shared text T27 ]] +[[ begin shared text T28 ]] Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -22572,9 +22736,9 @@ DEALINGS IN THE SOFTWARE. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -[[ end shared text T27 ]] +[[ end shared text T28 ]] -[[ begin shared text T28 ]] +[[ begin shared text T29 ]] The MIT License (MIT) Copyright (c) 2019 The Crossbeam Project Developers @@ -22602,9 +22766,9 @@ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -[[ end shared text T28 ]] +[[ end shared text T29 ]] -[[ begin shared text T29 ]] +[[ begin shared text T30 ]] Mozilla Public License Version 2.0 ================================== @@ -22978,9 +23142,9 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. -[[ end shared text T29 ]] +[[ end shared text T30 ]] -[[ begin shared text T30 ]] +[[ begin shared text T31 ]] Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -23182,17 +23346,17 @@ Apache License WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -[[ end shared text T30 ]] +[[ end shared text T31 ]] -[[ begin shared text T31 ]] +[[ begin shared text T32 ]] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -[[ end shared text T31 ]] +[[ end shared text T32 ]] -[[ begin shared text T32 ]] +[[ begin shared text T33 ]] MIT License Copyright (c) 2017 Ted Driggs @@ -23214,9 +23378,9 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -[[ end shared text T32 ]] +[[ end shared text T33 ]] -[[ begin shared text T33 ]] +[[ begin shared text T34 ]] Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -23418,9 +23582,9 @@ Apache License WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -[[ end shared text T33 ]] +[[ end shared text T34 ]] -[[ begin shared text T34 ]] +[[ begin shared text T35 ]] Copyright (c) 2014-2018 David Henningsson and other contributors Permission is hereby granted, free of charge, to any person obtaining a copy @@ -23440,9 +23604,9 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -[[ end shared text T34 ]] +[[ end shared text T35 ]] -[[ begin shared text T35 ]] +[[ begin shared text T36 ]] The MIT License (MIT) Copyright (c) 2016 Jelte Fennema @@ -23464,9 +23628,9 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -[[ end shared text T35 ]] +[[ end shared text T36 ]] -[[ begin shared text T36 ]] +[[ begin shared text T37 ]] Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -23641,9 +23805,9 @@ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. -[[ end shared text T36 ]] +[[ end shared text T37 ]] -[[ begin shared text T37 ]] +[[ begin shared text T38 ]] Copyright (c) 2018-2019 dirs-rs contributors Permission is hereby granted, free of charge, to any person obtaining a copy @@ -23663,9 +23827,9 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -[[ end shared text T37 ]] +[[ end shared text T38 ]] -[[ begin shared text T38 ]] +[[ begin shared text T39 ]] MIT License Copyright (c) 2023 Mykola Humanov @@ -23693,9 +23857,9 @@ SOFTWARE. This project contains portions of code and architectural concepts originally derived from the "nipper" project (https://github.com/importcjj/nipper), developed by Chen Jiaju, licensed under the MIT License and the Apache License 2.0 (dual licensed). -[[ end shared text T38 ]] +[[ end shared text T39 ]] -[[ begin shared text T39 ]] +[[ begin shared text T40 ]] Copyright Mozilla Foundation Permission is hereby granted, free of charge, to any @@ -23721,9 +23885,9 @@ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -[[ end shared text T39 ]] +[[ end shared text T40 ]] -[[ begin shared text T40 ]] +[[ begin shared text T41 ]] Copyright (c) 2017 The foreign-types Developers Permission is hereby granted, free of charge, to any person obtaining a copy @@ -23743,9 +23907,9 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -[[ end shared text T40 ]] +[[ end shared text T41 ]] -[[ begin shared text T41 ]] +[[ begin shared text T42 ]] Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -23948,9 +24112,9 @@ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -[[ end shared text T41 ]] +[[ end shared text T42 ]] -[[ begin shared text T42 ]] +[[ begin shared text T43 ]] Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors @@ -23977,9 +24141,9 @@ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -[[ end shared text T42 ]] +[[ end shared text T43 ]] -[[ begin shared text T43 ]] +[[ begin shared text T44 ]] Apache License Version 2.0, January 2004 https://www.apache.org/licenses/ @@ -24181,34 +24345,6 @@ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -[[ end shared text T43 ]] - -[[ begin shared text T44 ]] -Copyright (c) 2016 Amanieu d'Antras - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. [[ end shared text T44 ]] [[ begin shared text T45 ]] diff --git a/agents/manifest.json b/agents/manifest.json index b65c08b7..5b989407 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -63,7 +63,24 @@ "measure_3d", "open_3d_structure", "extract_ligand", - "export_3d" + "export_3d", + "db_list", + "db_create", + "db_open", + "db_import", + "db_search", + "db_get_record", + "db_add_record", + "db_update_record", + "db_export", + "nb_add_entry", + "nb_search", + "library_list", + "library_add", + "live_structure_object", + "draw_from_helm", + "xtb_optimise", + "crest_conformers" ], "read_only": [ "get_context", @@ -86,7 +103,13 @@ "stereo", "substructure", "get_atoms", - "measure_3d" + "measure_3d", + "db_list", + "db_search", + "db_get_record", + "nb_search", + "library_list", + "live_structure_object" ], "approval_gated": [ "draw_from_smiles", @@ -127,7 +150,18 @@ "scan_dihedral", "open_3d_structure", "extract_ligand", - "export_3d" + "export_3d", + "db_create", + "db_open", + "db_import", + "db_add_record", + "db_update_record", + "db_export", + "nb_add_entry", + "library_add", + "draw_from_helm", + "xtb_optimise", + "crest_conformers" ], "transports": [ "stdio", @@ -138,10 +172,12 @@ { "name": "formchem-harness", "sub_skills": [ + "databases", "drawing", "edit-by-id", "extension-drawings", "handoff", + "library-and-biopolymers", "names-and-spectra", "reactions", "session-and-connection", @@ -161,11 +197,13 @@ "clean-room", "clipboard", "command-line", + "databases", "desktop", "dock", "document-format", "engine", "extensions", + "family-integration", "formats-and-export", "menus", "names-and-spectra", diff --git a/assets/app-icon/formchem-256.png b/assets/app-icon/formchem-256.png index f1ea8acd..834d4fce 100644 Binary files a/assets/app-icon/formchem-256.png and b/assets/app-icon/formchem-256.png differ diff --git a/assets/formchem_folder_icon.png b/assets/formchem_folder_icon.png index 279b87da..e84530a3 100644 Binary files a/assets/formchem_folder_icon.png and b/assets/formchem_folder_icon.png differ diff --git a/assets/formchem_icon.png b/assets/formchem_icon.png index dadc4ff1..0611a66a 100644 Binary files a/assets/formchem_icon.png and b/assets/formchem_icon.png differ diff --git a/assets/formchem_icon_macos.png b/assets/formchem_icon_macos.png index db57bd60..0611a66a 100644 Binary files a/assets/formchem_icon_macos.png and b/assets/formchem_icon_macos.png differ diff --git a/assets/formchem_mark.svg b/assets/formchem_mark.svg index 35fefd44..8b2e9981 100644 --- a/assets/formchem_mark.svg +++ b/assets/formchem_mark.svg @@ -1 +1 @@ - + diff --git a/assets/icon_src/build.py b/assets/icon_src/build.py index a18b88d0..28c38769 100644 --- a/assets/icon_src/build.py +++ b/assets/icon_src/build.py @@ -3,41 +3,34 @@ import struct from pathlib import Path -import cairosvg -from PIL import Image, ImageFilter +from PIL import Image ROOT = Path(__file__).resolve().parents[2] -MARK = ROOT / "assets" / "formchem_mark.svg" -CANVAS = 1024 -MAC_TILE = 824 -MAC_MARGIN = (CANVAS - MAC_TILE) // 2 -SHADOW_DY = 12 -SHADOW_BLUR = 14 -SHADOW_ALPHA = 0.5 +MASTERS = ROOT / "assets" / "icon_src" / "masters" +APP = MASTERS / "formchem_icon_dark.png" +CARD = MASTERS / "formchem_dark_transparent_noshadow.png" +SMALL = 48 ICNS_TYPES = [("icp4", 16), ("icp5", 32), ("icp6", 64), ("ic07", 128), ("ic08", 256), ("ic09", 512), ("ic10", 1024), ("ic11", 32), ("ic12", 64), ("ic13", 256), ("ic14", 512)] ICO_SIZES = [16, 24, 32, 48, 64, 128, 256] FAVICON_SIZES = [16, 32, 48] -def render(svg: str, size: int) -> Image.Image: - data = cairosvg.svg2png(bytestring=svg.encode(), output_width=size, output_height=size) - return Image.open(io.BytesIO(data)).convert("RGBA") +def load(path: Path) -> Image.Image: + return Image.open(path).convert("RGBA") -def full(svg: str, size: int) -> Image.Image: - return render(svg, size) +def card_square(card: Image.Image) -> Image.Image: + box = card.getbbox() or (0, 0, card.width, card.height) + piece = card.crop(box) + side = max(piece.size) + square = Image.new("RGBA", (side, side), (0, 0, 0, 0)) + square.alpha_composite(piece, ((side - piece.width) // 2, (side - piece.height) // 2)) + return square -def mac_master(svg: str) -> Image.Image: - tile = render(svg.replace('viewBox="0 0 64 64"', 'viewBox="4 4 56 56"'), MAC_TILE) - shadow = Image.new("RGBA", (CANVAS, CANVAS), (0, 0, 0, 0)) - alpha = tile.getchannel("A").point(lambda a: int(a * SHADOW_ALPHA)) - dark = Image.new("RGBA", tile.size, (0, 0, 0, 255)) - dark.putalpha(alpha) - shadow.alpha_composite(dark, (MAC_MARGIN, MAC_MARGIN + SHADOW_DY)) - shadow = shadow.filter(ImageFilter.GaussianBlur(SHADOW_BLUR)) - shadow.alpha_composite(tile, (MAC_MARGIN, MAC_MARGIN)) - return shadow +def sized(app: Image.Image, card: Image.Image, size: int) -> Image.Image: + source = card if size <= SMALL else app + return source.resize((size, size), Image.LANCZOS) def png_bytes(image: Image.Image) -> bytes: @@ -79,32 +72,32 @@ def write(data: bytes, relative: str) -> None: def main() -> None: - parser = argparse.ArgumentParser(description="Regenerate the FormChem raster icons from assets/formchem_mark.svg.") + parser = argparse.ArgumentParser(description="Regenerate the FormChem raster icons from the owner's masters in assets/icon_src/masters.") parser.add_argument("--web", action="store_true", help="also write the favicon and web app icons into frontend/public") args = parser.parse_args() - svg = MARK.read_text(encoding="utf-8") - mac = mac_master(svg) + app = load(APP) + card = card_square(load(CARD)) - save(full(svg, 256), "assets/app-icon/formchem-256.png") - save(full(svg, 1024), "assets/formchem_icon.png") - save(mac, "assets/formchem_icon_macos.png") - save(full(svg, 512), "assets/formchem_folder_icon.png") + save(sized(app, card, 256), "assets/app-icon/formchem-256.png") + save(app, "assets/formchem_icon.png") + save(app, "assets/formchem_icon_macos.png") + save(sized(app, card, 512), "assets/formchem_folder_icon.png") - save(full(svg, 32), "src-tauri/icons/32x32.png") - save(full(svg, 128), "src-tauri/icons/128x128.png") - save(full(svg, 256), "src-tauri/icons/128x128@2x.png") - save(full(svg, 1024), "src-tauri/icons/icon.png") - write(ico([(n, png_bytes(full(svg, n))) for n in ICO_SIZES]), "src-tauri/icons/icon.ico") - write(icns(mac), "src-tauri/icons/icon.icns") + save(sized(app, card, 32), "src-tauri/icons/32x32.png") + save(sized(app, card, 128), "src-tauri/icons/128x128.png") + save(sized(app, card, 256), "src-tauri/icons/128x128@2x.png") + save(app, "src-tauri/icons/icon.png") + write(ico([(n, png_bytes(sized(app, card, n))) for n in ICO_SIZES]), "src-tauri/icons/icon.ico") + write(icns(app), "src-tauri/icons/icon.icns") if args.web: - save(full(svg, 192), "frontend/public/icon-192.png") - save(full(svg, 512), "frontend/public/icon-512.png") - save(full(svg, 64), "frontend/public/favicon.png") + save(sized(app, card, 192), "frontend/public/icon-192.png") + save(sized(app, card, 512), "frontend/public/icon-512.png") + save(sized(app, card, 64), "frontend/public/favicon.png") touch = Image.new("RGBA", (180, 180), (16, 15, 20, 255)) - touch.alpha_composite(full(svg, 180)) + touch.alpha_composite(sized(app, card, 180)) save(touch.convert("RGB"), "frontend/public/apple-touch-icon.png") - write(ico([(n, png_bytes(full(svg, n))) for n in FAVICON_SIZES]), "frontend/public/favicon.ico") + write(ico([(n, png_bytes(sized(app, card, n))) for n in FAVICON_SIZES]), "frontend/public/favicon.ico") if __name__ == "__main__": diff --git a/assets/icon_src/masters/formchem_dark_transparent_noshadow.png b/assets/icon_src/masters/formchem_dark_transparent_noshadow.png new file mode 100644 index 00000000..29899f58 Binary files /dev/null and b/assets/icon_src/masters/formchem_dark_transparent_noshadow.png differ diff --git a/assets/icon_src/masters/formchem_dark_transparent_shadow.png b/assets/icon_src/masters/formchem_dark_transparent_shadow.png new file mode 100644 index 00000000..3b4466b0 Binary files /dev/null and b/assets/icon_src/masters/formchem_dark_transparent_shadow.png differ diff --git a/assets/icon_src/masters/formchem_icon_dark.png b/assets/icon_src/masters/formchem_icon_dark.png new file mode 100644 index 00000000..1bd76452 Binary files /dev/null and b/assets/icon_src/masters/formchem_icon_dark.png differ diff --git a/assets/icon_src/masters/formchem_icon_light.png b/assets/icon_src/masters/formchem_icon_light.png new file mode 100644 index 00000000..9671e3b3 Binary files /dev/null and b/assets/icon_src/masters/formchem_icon_light.png differ diff --git a/assets/icon_src/masters/formchem_light_transparent_noshadow.png b/assets/icon_src/masters/formchem_light_transparent_noshadow.png new file mode 100644 index 00000000..29899f58 Binary files /dev/null and b/assets/icon_src/masters/formchem_light_transparent_noshadow.png differ diff --git a/assets/icon_src/masters/formchem_light_transparent_shadow.png b/assets/icon_src/masters/formchem_light_transparent_shadow.png new file mode 100644 index 00000000..172e386b Binary files /dev/null and b/assets/icon_src/masters/formchem_light_transparent_shadow.png differ diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 601b7360..fcd726f8 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # backend HASHOUT_LOG -Living log for the FormChem engine and its setup scripts, _v0.1.0 to _v0.10.0. It follows the family template (formdeck's engine) for 0.1.0 and 0.2.0, from 0.3.0 it records the chemistry engine, the document store and the file format, from 0.5.0 the reaction services (perception, mapping, balance, stoichiometry, reaction exchange), the template library and media, and from 0.6.0 the analysis services (stereo and enhanced stereo, wedges, abbreviations, hydrogens, queries and SMARTS, V3000 query molfiles, Markush, properties, the structure check, the isotope pattern), the analysis router and tools, and the desktop build fixes, and from 0.7.0 the one-folder macOS engine, the scored 2D layout, the formats table with its readers, writers and report items, the stream reader, picture export with its own PDF and EPS writer, the embedded source, the file write route, standardisation, the batch command line and the quick command state mirror, and from 0.8.0 the agent tools (drawing, checking, documents, conversion and edits by id), the shared write result and the render bridge, the agent call log with its undo and Stop, and the agent token, and from 0.9.0 the offline name engine (dictionary, systematic parser, round-trip-checked namer), FormChem's own NMR increment predictor, the JCAMP-DX reader and the spectra service, and the ten agent tools over them, and from 0.10.0 the 3D package (building from 2D with the stereo check, force fields, conformer searches, minimisation, relaxed scans, measurements and charges, 3D export), FormChem's own PDB and mmCIF readers with ligand extraction, 3D SD records, the stale-conformer rule inside the store, the 3D routes and the eight agent tools over them, so many reasons here are about what was kept, what was dropped, and why. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. +Living log for the FormChem engine and its setup scripts, _v0.1.0 to _v0.12.0. It follows the family template (formdeck's engine) for 0.1.0 and 0.2.0, from 0.3.0 it records the chemistry engine, the document store and the file format, from 0.5.0 the reaction services (perception, mapping, balance, stoichiometry, reaction exchange), the template library and media, and from 0.6.0 the analysis services (stereo and enhanced stereo, wedges, abbreviations, hydrogens, queries and SMARTS, V3000 query molfiles, Markush, properties, the structure check, the isotope pattern), the analysis router and tools, and the desktop build fixes, and from 0.7.0 the one-folder macOS engine, the scored 2D layout, the formats table with its readers, writers and report items, the stream reader, picture export with its own PDF and EPS writer, the embedded source, the file write route, standardisation, the batch command line and the quick command state mirror, and from 0.8.0 the agent tools (drawing, checking, documents, conversion and edits by id), the shared write result and the render bridge, the agent call log with its undo and Stop, and the agent token, and from 0.9.0 the offline name engine (dictionary, systematic parser, round-trip-checked namer), FormChem's own NMR increment predictor, the JCAMP-DX reader and the spectra service, and the ten agent tools over them, and from 0.10.0 the 3D package (building from 2D with the stereo check, force fields, conformer searches, minimisation, relaxed scans, measurements and charges, 3D export), FormChem's own PDB and mmCIF readers with ligand extraction, 3D SD records, the stale-conformer rule inside the store, the 3D routes and the eight agent tools over them, and from 0.11.0 the structure database (one `.fcdb` SQLite file with its store, registration and keys, fields, forms, import and export jobs, the query language, the fingerprint screening cache, hit lists, saved queries and the plot), the lab notebook (entries, the content hash and signing, schemes, products, the HTML and JSON export), the view key, `./formchem db` and the eleven agent tools over them, and from 0.12.0 the shared structure library and live structures (the Library folder, items, pictures with the source inside, live drawings, adoption, `edit-live` and the agent token's one write path), the file watch, the structure description behind the spoken summary, the HELM reader and writer over FormChem's own monomer data, xtb and CREST run as programs the person installs (discovery, the runner, jobs and the write-back), the deep link in the desktop shell and the six agent tools over them, so many reasons here are about what was kept, what was dropped, and why. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. ## Org navi map @@ -48,6 +48,27 @@ backend/app/services/three_d/ molecule (atom labels), forcefield, build, verify backend/app/routers/three_d.py /api/documents/{id}/3d/... (build, conformers, active, minimise, scan, measure, charges, molblock, open, structure, extract-ligand) and /api/3d/parse (0.10.0) docs/3D.md building, conformers, scans, measurements, surfaces, structure files, exports and limits (0.10.0) +backend/app/services/database/ schema, store (handles, locks, transactions, audit, live notify), chem (register_values), + computed, fields, forms, records, attachments, thumbs, jobs, imports, exports, uploads, info, + query, search (the screening cache), hitlists, saved, plot, dbcli (./formchem db) (0.11.0) +backend/app/services/notebook/ templates, content (canonical JSON and hash), scheme, products, entries, attachments, + markup, export (0.11.0) +backend/app/services/ also agent_db.py (nine db_ tools) and agent_notebook.py (nb_add_entry, nb_search), 0.11.0 +backend/app/routers/ also databases (files, fields, records, pictures, import, export, forms), db_search (search, + hit lists, saved queries, plot) and notebook (/api/databases/{db}/entries) (0.11.0) +docs/DATABASE.md the .fcdb contract: tables, query language, signing, locking, routes (0.11.0) +docs/DATABASES.md databases and the notebook for the person using them (0.11.0) +assets/icon_src/ build.py sizes every shipped icon from the owner's masters/ (0.11.0) +backend/app/services/ also live_structures.py (the shared Library folder, items, pictures, live drawings, edit-live), + file_watch.py (outside changes to open drawings), describe.py (the spoken structure summary), + agent_library.py, agent_helm.py, agent_xtb.py (0.12.0) +backend/app/services/helm/ parser, monomers, assemble, writer; data/helm_monomers.json holds the 55 monomers (0.12.0) +backend/app/services/xtb/ constants, solvents, discovery, parse, inputs, runner, jobs, writeback (0.12.0) +backend/app/routers/ also structures (/api/structures and /api/files/watch), describe, helm, xtb (0.12.0) +backend/app/core/window_key.py AGENT_WRITES: the agent token may write to /api/structures only (0.12.0) +src-tauri/ tauri-plugin-deep-link 2.6.3 registers the formai scheme (0.12.0) +docs/LIVE_STRUCTURES.md the contract for sibling apps: library folder, object, clipboard flavour, editing (0.12.0) +docs/LIVE-STRUCTURES.md, docs/ACCESSIBILITY.md, docs/HELM.md the same for the person using them (0.12.0) docs/AGENTS.md every agent tool with arguments and results, consent, Stop, the token and the call log (0.8.0) docs/NAMES.md, docs/SPECTRA.md how names are read and written; JCAMP-DX, the spectrum object and NMR prediction (0.9.0) docs/FORMATS.md every format, what it loses, the report codes and the exchange routes (0.7.0) @@ -288,6 +309,62 @@ build_app, build_app.bat desktop bundle build, teed to build_app.log 220. The eight agent tools of 0.10.0 · routers/mcp.py 221. The notices read nested npm packages by their lock path · setup/notices.py 222. Engine 3D texts the window shows are keys; some stay agent text · setup/i18n_tool.py NOT_TEXT, part15 +223. A database is one SQLite file with a DELETE journal · services/database/schema.py +224. One transaction per write, reads under the same lock · services/database/store.py writing, reading, next_number +225. A lock file beside the database, read-only for the second engine · services/database/store.py _take_lock, _alive +226. Chemistry columns come only from register_values · services/database/chem.py +227. Computed fields are the analysis panel's descriptors · services/database/computed.py DESCRIPTORS +228. Fields, typed values and the readable records view · services/database/fields.py +229. Forms on a 600 point grid, generated ones follow the fields · services/database/forms.py +230. Duplicates follow the rules; numbers never come back · services/database/records.py +231. Thumbnails are drawn once and inked when served · services/database/thumbs.py +232. Records and entries share one attachments table · services/database/attachments.py +233. Jobs live in memory on worker threads · services/database/jobs.py +234. Import streams, commits in batches and never stops on a record · services/database/imports.py +235. Export round-trips the fields; downloads are served once · services/database/exports.py, uploads.py +236. One normaliser for every query, and names from the query · services/database/query.py +237. The screening cache and its freshness gate · services/database/search.py Screen, _gate, advance +238. Substructure: numpy screen, then a SubstructLibrary · services/database/search.py _substructure +239. Similarity from popcounts, exact on the chosen key · services/database/search.py _similarity, _exact +240. Queries are masks, cheap terms first · services/database/search.py _evaluate +241. Hit lists in one transaction; temp tables when read-only · services/database/hitlists.py +242. Saved queries and plot points · services/database/saved.py, plot.py +243. The database routes are thin; a duplicate is a 409 with its rows · routers/databases.py, db_search.py +244. Database reads need the window key; pictures take a view key · core/window_key.py VIEW, require_view +245. Browser windows upload, adopt and download · services/database/uploads.py adopt, exports.py download +246. library.json keeps the databases list · services/library.py remember_database, databases +247. ./formchem db · services/database/dbcli.py, cli.py +248. The nine database tools · services/agent_db.py; routers/mcp.py AGENT_MODULES +249. The entry hash covers eleven keys · services/notebook/content.py +250. Signing, and the version kept when a signed entry changes · services/notebook/entries.py sign, after_change +251. Entry search, schemes and stoichiometry · services/notebook/entries.py listing; scheme.py +252. Products link entries to records · services/notebook/products.py +253. Entries export as HTML or JSON · services/notebook/export.py, markup.py +254. The notebook routes and its two tools · routers/notebook.py; services/agent_notebook.py +255. The icon set is sized from the owner's masters · assets/icon_src/build.py +256. The Library folder is its own, written atomically with the index last · services/live_structures.py folder, write_index +257. One item per structure and kind; recent is capped by use · services/live_structures.py add, prune +258. Items are described by the analysis services; the engine draws pictures without a window · services/live_structures.py describe, engine_pictures +259. A live drawing is an ordinary drawing plus a link · services/live_structures.py open_live, save_live, LINKS +260. An object from another computer keeps its id and the higher rev · services/live_structures.py adopt +261. edit-live posts to the running engine with the agent token · services/live_structures.py edit_live; app/cli.py +262. The agent token writes to /api/structures and nothing else · core/window_key.py AGENT_WRITES; routers/structures.py +263. The file watch polls once a second and knows FormChem's own saves · services/file_watch.py +264. The structure description runs FormChem's own groups and ring names · services/describe.py; routers/describe.py +265. HELM monomers are FormChem's own data, checked when they load · data/helm_monomers.json; services/helm/monomers.py +266. The HELM reader refuses with the character where it stopped · services/helm/parser.py +267. Monomers are joined by zipping attachment points · services/helm/assemble.py +268. Writing HELM cuts known bonds and is offered only when it reads back · services/helm/writer.py; helm/__init__.py from_mol +269. The HELM routes answer a syntax error as data · routers/helm.py +270. xtb and CREST are found where the person put them, never shipped · services/xtb/discovery.py +271. Inputs keep the 3D label order and check the electrons · services/xtb/inputs.py +272. A program runs in its own process group with its log in a file · services/xtb/runner.py +273. One job at a time; a folder is kept only when a job fails · services/xtb/jobs.py +274. Results go back as one 3D transaction with a program record · services/xtb/writeback.py; routers/xtb.py _applier +275. The xtb routes and the three settings keys · routers/xtb.py; services/xtb/discovery.py save +276. The six agent tools join AGENT_MODULES · services/agent_library.py, agent_helm.py, agent_xtb.py; routers/mcp.py +277. The deep link plugin and the formai scheme · src-tauri/Cargo.toml, src/main.rs, tauri.conf.json +278. The notices cover the deep link crates · NOTICE.md, THIRD-PARTY-NOTICES.txt ## 1. Ports and the data folder are FormChem's own · _v0.1.0 (app/core/config.py) @@ -1177,6 +1254,230 @@ The MCP tools call the route functions in process rather than repeating them. To The engine's build and minimise warnings, route errors, file reading errors, import report items and ligand errors that reach the window are keyed in part15 as they render, with nested pattern keys (`Universal force field used: {0}.` wraps `no {0} parameters for {1}`). Left English on purpose: the ligand warnings and charge warnings the window does not show, the measure route's errors (the window measures itself), validation errors of fields the window always sends right, and every MCP text, which agents read. `NOT_TEXT` gained the save filter names, method ids, glTF accessor types, water residue names, unit readouts and the command results that only go back to agents. Two dead keys stay where they are (part01:8, the 0.10.0 placeholder text, and part13:187, the 0.9.0 media refusal), because removing them would shift indices in 25 languages. +## 223. A database is one SQLite file with a DELETE journal · _v0.11.0 (services/database/schema.py FORMAT, FORMAT_VERSION, APPLICATION_ID, TABLES, connect, version_of, create, check, migrate) + +docs/DATABASE.md was written first (1b9bc84) so the engine and window built against one contract. A database is one `.fcdb` file so moving or backing up one file moves everything, records, fields, hit lists, forms, entries and the audit. The journal is DELETE, not WAL, so a closed database is never split into `-wal` and `-shm` files that a person could leave behind when copying. `application_id` 0x46434442 ("FCDB") and `user_version` 1 identify the file; `check` reports a newer version so the store can open it read-only instead of refusing it. Foreign keys are on for every connection, so field values, hit list items and entry links cascade. + +## 224. One transaction per write, reads under the same lock · _v0.11.0 (services/database/store.py Database, writing, reading, next_number, audit, notify, bind; _open_file) + +Every write is `BEGIN IMMEDIATE ... COMMIT` inside `writing(db)`, under `db.lock`, and every write calls `audit`; the search cache relies on that (entry 237). Reads take the same lock because one connection is shared by route threads and the import worker. `next_number` keeps `meta.last_number`, so a deleted top number is never handed out again. `_open_file` sets `busy_timeout` to 5000 ms: with the DELETE journal a second engine or the command line could otherwise get "database is locked" while the writer commits (a read waited 1.03 s for a lock held 1 s). `notify` broadcasts the `database` live message only after the commit, from any thread, through the loop `bind` records; routers/databases.py binds it on first use so it works before main.py's lifespan has. + +## 225. A lock file beside the database, read-only for the second engine · _v0.11.0 (services/database/store.py _lockfile, _alive, _take_lock, open_path, close, close_all; app/main.py lifespan) + +`[file].lock` holds pid, host, app and time. A second engine finding a live lock opens the file read-only with a sentence naming the other FormChem; a lock whose process is gone on the same host is taken over. Every write route answers 423 on a read-only handle. `close_all` runs when the engine stops, so a clean exit leaves no lock; a crash leaves one that the next open takes over. + +## 226. Chemistry columns come only from register_values · _v0.11.0 (services/database/chem.py register_values, mol_from, query_from, parent, element_counts, similarity_fp, screen_fp, to_bytes, from_bytes, screen_passes, FP_METHOD, SCREEN_METHOD) + +Canonical SMILES, InChI, InChIKey, skeleton, parent key, Hill formula, masses, element counts and both fingerprints are computed in one function from a molfile or SMILES, so a stored row and a query are keyed by the same code (exact search runs the query through it too). The parent is the standardised largest fragment, neutralised, so aspirin sodium chloride has aspirin's InChIKey as its parent key. Fingerprints are Morgan radius 2 and RDKit pattern, 2048 bits each, packed little-endian; the byte form and the screen test are shared with search.py. + +## 227. Computed fields are the analysis panel's descriptors · _v0.11.0 (services/database/computed.py DESCRIPTORS, method, values, fill, computed_fields) + +A computed field reuses `chem/props.measure`, the code behind the properties route, so a cLogP in a table equals the one in the Analysis panel. The contract's keys map onto props keys (`rotatable` to `rotatable_bonds`, `fsp3` to `fraction_csp3`, `charge` to `formal_charge`). A computed Field carries `method` (the props method plus the RDKit version), a key the window's Field type does not declare. A computed field added without a label is named after its descriptor (80ea55e). Persons cannot write a computed value (422). + +## 228. Fields, typed values and the readable records view · _v0.11.0 (services/database/fields.py rebuild_view, ensure_view, create, change, delete, coerce, detect, NAME_RE, VIEW_BUILTINS) + +The `records` view is recreated on every field change and on every open, with dates as `datetime(num, 'unixepoch')` and integers cast, so a generic SQLite browser shows `2024-07-14 00:00:00` and `28`, not epoch seconds and `28.0` (ba6d88f). Labels that clash with a built-in or another label get ` (name)` appended in the view. `change` accepts `type` as well as the documented keys, because the Fields dialog changes it; values convert between number and text storage and are dropped to or from computed. `coerce(..., text=True)` is the import path (strings, grouped digits, yes and no). + +## 229. Forms on a 600 point grid, generated ones follow the fields · _v0.11.0 (services/database/forms.py layout, overlaps, generate, refresh, drop_field, listing, STYLES) + +Items sit on a 600 point grid; every field gets a `label` item with the same `field` key so deleting the field removes both. Single, double and card forms are generated and regenerated on every field add, delete, hide, move or rename; a form saved as `custom` is never regenerated and only loses items of a deleted field. 0, 1, 5, 12 and 40 fields in all three styles gave no overlaps and nothing past x 580. A writable database with no form gets a default single-column one on first listing. + +## 230. Duplicates follow the rules; numbers never come back · _v0.11.0 (services/database/records.py duplicate_ids, add, update, delete, page, register, DuplicateError, SORTS, MAX_LIMIT) + +`duplicate_ids` compares `parent_key` with salts stripped, else `inchikey`; with stereo ignored it compares the first InChIKey block, and for the parent it does so by an index-friendly range (`>= 'BLOCK-' AND < 'BLOCK.'`). `on_duplicate: existing` answers the existing record with `existing: true`; `batch` keeps the number and sets `parent`. `page` orders a hit list by rank by default; `sort=score` and `rank` need a hit list; field sorts put empty values last; at most 500 rows a page. records.py is the engine API search and the notebook call. + +## 231. Thumbnails are drawn once and inked when served · _v0.11.0 (services/database/thumbs.py render, themed, svg, THEMES, _PALETTES) + +The `thumbs` cache key is (compound, size), so one RDKit drawing is stored with placeholder colours per element group and a transparent background, and `themed` swaps in the dark or light ink when it is served. The window sends `theme` from the body class actually painted, and `v` (the record's modified time) so a changed structure gets a new URL. First draw about 3 ms, cached under 1 ms. + +## 232. Records and entries share one attachments table · _v0.11.0 (services/database/attachments.py store_bytes, link, read, LIMIT; services/notebook/attachments.py add_bytes, add_link) + +A uid starting `c` or `n` picks the owner column. Stored files up to 50 MB keep their SHA-256 (413 above, with a hint to link by path); linked files are hashed once when linked. The hashes are what an entry's content hash covers (entry 249). The attachments route serves rows of either owner. + +## 233. Jobs live in memory on worker threads · _v0.11.0 (services/database/jobs.py Job, start, get, cancel, wait, KEEP, REPORT_CAP) + +Imports and large exports must not block the engine, so they run on daemon threads with counts, state and the failed-record report the window polls. The newest 50 finished jobs are kept; a report is capped at 5,000 rows (`report_truncated`). The Job adds `total`, `skipped`, `notes`, `seconds`, `created_fields` and `error` to the documented shape. Jobs end with the engine. + +## 234. Import streams, commits in batches and never stops on a record · _v0.11.0 (services/database/imports.py preview, start, default_mapping, plain, PLAIN_REASONS, _structure_column, _Plan, _flush, BATCH) + +SD, RD, SMILES, InChI, molfile and `.fchem` go through the 0.7.0 streaming readers (chem/records.py, gzip aware); the SD connection table is kept as the stored molfile. CSV and TSV find their structure column by header or by 80 percent of sampled values parsing, and the SD title becomes a `name` column when any record has one. Records are registered outside the lock and written in batches of 250, each its own transaction, so a 10,000 record import never holds the database; a record that cannot be stored rolls back to a savepoint and goes to the report. Dry runs track the keys seen earlier in the file, so their counts equal the real run's (505 records merged: 3 added, 501 updated, 1 failed both times). `plain` leads RDKit's messages with a plain reason and keeps RDKit's words in brackets (31e9f84). `.fchem` imports fragments only, because a compound row holds one molecule. + +## 235. Export round-trips the fields; downloads are served once · _v0.11.0 (services/database/exports.py export, download, sweep, NON_SCALAR, KEEP_SECONDS; services/database/uploads.py save, sweep) + +SD records get an empty title line and every scalar field as a data item under its label, so importing the file into a new database rebuilds the same fields (100 records: same InChIKeys, no value different). V2000 export reuses the stored molfile. Without a path the file goes to `Databases/.exports/` with a name without spaces (a space cut the URL, cccb9e6), is deleted after one download, and anything older than 24 hours is swept. Browser uploads go to `Databases/.uploads/` (1 GB cap, swept after a day). + +## 236. One normaliser for every query, and names from the query · _v0.11.0 (services/database/query.py normalise, parse_formula, name_of, structure_text, QueryError, MAX_DEPTH, MAX_TERMS) + +Searches, saved queries, the command line and agents all pass through `normalise`, which fills defaults (`charges: match`, `tautomers: ignore`, threshold 0.7) and names the bad key in a 422. The formula grammar reads `C6-8H*N1O0-2`. `name_of` turns the query into the hit list's name in plain words ("Substructure c1ccccc1 and mw <= 300"), molfile queries named by their SMILES, so the sidebar reads without opening the query. + +## 237. The screening cache and its freshness gate · _v0.11.0 (services/database/search.py Screen, screen, _load, _gate, _backfill, audit_head, advance, forget, LOAD_PAGE, BACKFILL_BATCH) + +Per database handle, numpy arrays hold ids, numbers, batches, both fingerprints as (N, 32) uint64 words with popcounts, SMILES and element counts, read in pages of 5,000 ids so the lock is released between pages (100,000 rows in 630 ms). Freshness is checked by compound count, newest id and newest audit row (3 to 6 ms); only when one moves is `max(modified)` scanned (133 ms on 100,000 rows, it reads every wide row). That depends on every compound write calling `store.audit`. Hit list and saved query writes advance the cached audit head inside their own transaction, so a search does not invalidate its own cache. Rows lacking a fingerprint are recomputed and written back in batches of 400, as the contract asks of readers. + +## 238. Substructure: numpy screen, then a SubstructLibrary · _v0.11.0 (services/database/search.py _substructure, substructure_library, query_mol, BINARY_FROM, THREADS) + +The pattern screen `(sfp & q) == q` runs on the cached words, and only candidates go to RDKit's `SubstructLibrary.GetMatches` restricted with `SetSearchOrder`, on 2 threads, with chirality as the term asks. A `CachedTrustedSmilesMolHolder` answers at once; from 5,000 records a worker thread builds a `CachedMolHolder` of pickles and swaps it in, because parsing SMILES during each match cost about 2 s per 100,000 rows (benzene: 1.4 s first, then 0.45 to 0.54 s, 30,769 hits). On 2,000 records the hits equal a brute-force `HasSubstructMatch` (546, no mismatch). + +## 239. Similarity from popcounts, exact on the chosen key · _v0.11.0 (services/database/search.py _similarity, _exact, _neutral, _canonical, SIMILARITY_METHOD) + +Tanimoto is computed for every row at once from popcounts; a hit is a score at or above the threshold (less 1e-9), so raising the threshold can only drop hits; scores agree with RDKit to 5e-7. Exact search keys on `inchikey` (stereo match, salts keep), `skeleton` (stereo ignore), `parent_key` (salts strip) or its first block (both ignored, a scan), with the database rules as defaults. Charges ignored compares uncharged canonical SMILES of the skeleton candidates; tautomers default to ignore (standard InChI), and `match` adds a canonical SMILES comparison. + +## 240. Queries are masks, cheap terms first · _v0.11.0 (services/database/search.py _evaluate, _cost, _formula, _element, _text, _number, _date, _choice, _empty, run, matching_ids, methods_for, EQUAL_TOLERANCE) + +Every term is a boolean mask over the cached rows. `and` narrows term by term with structure terms last, so a substructure screens only what the cheaper terms left; `or` evaluates only rows not yet matched; `not` is the complement within the universe (the database or `within`). Formula ranges test per-element count arrays built once per cache (C6-8N1 on 100,000 rows: 5.7 ms, 235 ms before 3543d5b). Text is matched in Python (casefold, whole word by lookarounds, regex), the same on every platform. `run` answers `took_ms` for the search alone, `screened`, `candidates` and the methods with the RDKit version; a search within a hit list is stored as `and [hitlist, query]`. + +## 241. Hit lists in one transaction; temp tables when read-only · _v0.11.0 (services/database/hitlists.py create, combine, from_selection, update, delete, own_write, _scratch, _prune, KEEP_UNSAVED) + +A hit list, its items and the prune of older unsaved lists (20 kept) are one transaction: a half-written hit list would be wrong, and 30,769 items stay well inside the lock budget. Ranks start at 1. Combining keeps the first list's order, drops scores and stores the result as hitlist terms so it can be re-run. On a read-only database `_scratch` creates TEMP tables that shadow the file's (SQLite resolves unqualified names to temp first) and copies the saved lists in, so search, combine, selection, plot and paging work there; renames and saves answer 423. + +## 242. Saved queries and plot points · _v0.11.0 (services/database/saved.py create, run, _folder; services/database/plot.py points, _axis, TEXT_BUILTINS) + +A saved query stores the normalised node and a folder cleaned of empty segments; running it names the hit list after it and writes `last_run` and `last_count` (not on a read-only file). `points` gives `[uid, x, y]` (or `[uid, x]`) in hit list rank or registration order for rows that have every asked value, counts the rest as `missing`, and names the method of built-in masses and computed fields. A text built-in such as `smiles` answers 422 with the reason, not 404 (28b35c9). + +## 243. The database routes are thin; a duplicate is a 409 with its rows · _v0.11.0 (routers/databases.py GUARD, VIEW_GUARD, _bind; routers/db_search.py GUARD; frontend engine/database-api.ts DuplicateError) + +Routes call the services on a worker thread and turn `DatabaseError` into its status. The jobs, uploads and downloads routes are declared before `/{db}` so they do not read as handles. A duplicate answers 409 `{detail, duplicates}` at the top level; the window's `DuplicateError` and `db_add_record`'s `structuredContent` read the same keys (1c9086a), so there is one shape everywhere. + +## 244. Database reads need the window key; pictures take a view key · _v0.11.0 (core/window_key.py VIEW, VIEW_PARAM, require_view; routers/system.py GET /api/window/view-key; routers/databases.py VIEW_GUARD) + +Records hold private data, so every database GET needs the window key, not only the middleware (46fcd1e). Thumbnails and attachments load through img and a tags that cannot send a header, so they also accept a second random key in the query (`k`) that opens only those two routes; the full window key never enters a URL or the access log. The window fetches the view key once, right after the window key and before the app mounts, so building a picture URL is synchronous. + +## 245. Browser windows upload, adopt and download · _v0.11.0 (services/database/uploads.py adopt; routers/databases.py open; services/database/exports.py download) + +A browser window has no file paths. Imports go through an uploaded copy; exports without a path come back as a one-time download. A dropped or chosen `.fcdb` is uploaded, then `POST /api/databases/open {path, adopt: true}` moves it out of the swept uploads folder into `Databases/` under a free name and opens it. Only a file directly in `.uploads/` with the `.fcdb` suffix is accepted (422 otherwise, `/etc/passwd` included). + +## 246. library.json keeps the databases list · _v0.11.0 (services/library.py remember_database, databases; services/database/info.py remember, create_database, open_database, known) + +Home lists databases from the `databases` list of `library.json`: `{id, path, name, opened, count}`, capped at 50. An open moves the database to the top; a count update keeps the order. `open_database` is the one place the routes and the command line open a file, so it always makes sure the records view exists and remembers the database. + +## 247. ./formchem db · _v0.11.0 (services/database/dbcli.py USAGE, add_parser, run, create, describe, import_file, search, export, _errors_csv; app/cli.py; formchem, formchem.bat) + +The command line opens a database through the same services as the routes, so it takes the lock and a running engine sees the file read-only while it works. `db` goes through the same launcher as `convert` in both dispatchers. Ctrl+C cancels an import job and waits for it to end. `--errors` writes every failed record to a CSV file; `--json` prints the service answer. Exit code 0, 1 for an import that did not finish `done`, 2 for a refused call. + +## 248. The nine database tools · _v0.11.0 (services/agent_db.py TOOLS, NAMES, MUTATING, mutating, call; routers/mcp.py AGENT_MODULES, INSTRUCTIONS, WORKFLOW) + +Agent modules define tools in the `_tool` shape, frozen `NAMES` and `mutating(name, args)`, and mcp.py walks one `AGENT_MODULES` tuple for the list, the gate and dispatch, so a later module adds one name (562bb07). `db_create`, `db_open`, `db_add_record` and `db_update_record` always ask; `db_import` unless `dry_run`; `db_export` only with a path outside the temporary folder. `db_search` is read-only although it adds an unsaved hit list, which is search history the person sees, pruned at 20. A duplicate without `on_duplicate` is an error listing the duplicates and the three choices. Calls run on a worker thread and write as `agent:[name]`. 60 tools became 69 here and 71 with the notebook. + +## 249. The entry hash covers eleven keys · _v0.11.0 (services/notebook/content.py KEYS, HASH_METHOD, canonical, digest, attachment_hashes, of_row) + +The hash is SHA-256 over canonical JSON (sorted keys, no spaces, UTF-8) of exactly the eleven keys of DATABASE.md, attachments as their sorted hashes. `of_row` always reads from SQLite, so `date` is a float (a REAL column) in every hash and export; a verifier must hash the JSON export's values as written. + +## 250. Signing, and the version kept when a signed entry changes · _v0.11.0 (services/notebook/entries.py sign, after_change, update, version, versions_of) + +Signing always records a new `signed` version, also when the entry was already signed and unchanged. The `edited-after-signing` row copies the newest signed version's content and hash (the content as it was signed, not the content just before the edit) and is written only while the status is `signed`, so once per signing. A patch that leaves the hash unchanged is not a change; going back to the signed text keeps `modified`. Attaching a file runs the same rule, because attachment hashes are content. + +## 251. Entry search, schemes and stoichiometry · _v0.11.0 (services/notebook/entries.py listing, _haystack, count; services/notebook/scheme.py checked, molecules, cached_molecules, stoichiometry, from_reaction, one_page, fchem, pictures, STOICH_METHOD) + +Text search casefolds and needs every word, over title, procedure, observations, tags and product sample ids; newest entry first. Substructure takes SMILES, else SMARTS; each scheme fragment goes through `derive.derive_fragment` to SMILES, and molecules are cached per (database, entry, modified) so an unchanged scheme is never read again (0e0525c). A scheme must pass `package.check` and have one page. Stoichiometry is computed on every read by `reactions.perceive_page` and `stoich.compute`, named with FormChem's and RDKit's versions, never stored. Agents give reaction SMILES or RXN (`from_reaction`) or an open drawing cut to one page (`one_page`). + +## 252. Products link entries to records · _v0.11.0 (services/notebook/products.py normalise, resolve, link, entries_for) + +Products are normalised to the documented shape, and every product with a compound uid becomes an `entry_compounds` row with its sample ids, cleared when the products are emptied. An unknown uid is refused before anything is written. `entries_for` lists the entries that made a record. + +## 253. Entries export as HTML or JSON · _v0.11.0 (services/notebook/export.py to_html, to_json, export, render, _clean_svg, INLINE_LIMIT; services/notebook/markup.py blocks, inline, to_html) + +The HTML file is self-contained: the scheme as inline SVG (the window's picture when sent, cleaned of scripts, foreignObject, event attributes and javascript links; otherwise RDKit depictions), the stoichiometry with its method, image attachments up to 4 MB as data URIs, print rules. The markup renderer escapes every character first and knows paragraphs, dash bullets, bold and italic only. JSON is `formchem-entry` version 1 with content, hash, status and every version with its content, so each hash can be recomputed. Without a path the file goes to `Databases/.exports/`. + +## 254. The notebook routes and its two tools · _v0.11.0 (routers/notebook.py; services/agent_notebook.py TOOLS, NAMES, MUTATING, mutating, call) + +Thin routes under `/api/databases/{db}/entries` with the window key, plus a download route for the browser (a POST, so it can carry the picture) and `scheme.fchem` for Edit Scheme; both added to the contract (c2c1cb7). `nb_add_entry` validates products and record uids before creating, so a refused call writes nothing; it always asks; entries from agents are never signed, because signing is a person's statement. `nb_search` never asks. + +## 255. The icon set is sized from the owner's masters · _v0.11.0 (assets/icon_src/build.py, assets/icon_src/masters/; src-tauri/icons; frontend/src/ui/brand.ts, public/favicon.svg, public/splash.html) + +The owner supplied six 1024 pixel masters on 5 December 2026 (app icon on dark and light, the card alone with and without shadow). The app master feeds the macOS, Windows and Linux sizes from 64 pixels; the card alone, cropped square, feeds 48 pixels and below so the structure stays readable. The in-app mark, favicon and splash are a vector redraw of the card. Nothing is drawn from SVG any more, so `cairosvg` and its NOTICE row went. + +## 256. The Library folder is its own, written atomically with the index last · _v0.12.0 (services/live_structures.py LIBRARY, ITEMS, INDEX, folder, index_path, read_index, write_file, write_index, present, drop_files, delete) + +`FORMCHEM_DATA_DIR/Library/library.json` is a different file from `FORMCHEM_DATA_DIR/library.json` (recent drawings and databases, services/library.py); the names follow LIVE_STRUCTURES.md. Every file goes through `core/files.write_atomic` (temporary file in the same folder, fsync, rename): item files first, `library.json` last, so a sibling reading the index never finds an item whose files are half written. Delete writes the index first, then removes the files, and readers skip items whose files are missing (`present`). + +## 257. One item per structure and kind; recent is capped by use · _v0.12.0 (services/live_structures.py add, update, prune, kinds_of, clean_kinds, _used, RECENT_CAP, KINDS, new_id, ID_PATTERN) + +A non-live add whose canonical SMILES matches a non-live item merges the kinds instead of adding a copy, so starring twice or starring a template gives one item. Live adds are always a new item: two sibling documents must never share an id by accident. Recent is capped at 50 by an extra `used` time (set on add, insert and adopt; falls back to `modified`), and an item that loses its last kind is deleted with its files in the same write. Ids are `s` plus 10 lower-case letters or digits, drawn until unused. + +## 258. Items are described by the analysis services; the engine draws pictures without a window · _v0.12.0 (services/live_structures.py describe, chem_fields, source_svg, source_png, engine_pictures, store_files, svg_size, png_bytes, PNG_WIDTH) + +SMILES, InChIKey, formula and mass come from `perceive.prepare`, `ids` and `mass.average_mass`, not RDKit descriptors, so the numbers match the Analysis panel; items carry an extra `method` naming them. A reaction is stored as `kind: reaction` with its RXN file (`writers.export_document(doc, "rxn")`) and reaction SMILES, and no formula or mass. The window sends the pictures it drew (SVG with the source embedded and subset fonts, PNG 512 pixels wide with the source in iTXt) as extra fields of the POST; agents and adopted objects without a PNG get RDKit pictures from depict.py with the source embedded in the same carriers, so every reader of embedded drawings finds it. + +## 259. A live drawing is an ordinary drawing plus a link · _v0.12.0 (services/live_structures.py open_live, save_live, rewrite, LINKS, links, sibling_name, _drawing; routers/structures.py live_links, save_structure) + +A live drawing is a normal session with `LINKS[doc_id] = {id, rev, from, name}` beside it; nothing is written into the drawing, so a Save As copy carries no live mark. `open_live` builds the drawing from the item SVG's embedded source with a new document id and the item name as title, then broadcasts `opened` and `live-open`; an item already open is brought forward by broadcasting `live-open` again (660b55f). `save_live` describes the whole page again, rewrites the files, raises rev, marks the session saved (`saved` with `path: null`) and broadcasts `live-structure`. The sibling's name is cleaned to letters, digits, spaces, dots and dashes before it reaches the title. + +## 260. An object from another computer keeps its id and the higher rev · _v0.12.0 (services/live_structures.py adopt, object_source, live_object, _rev, OBJECT_FORMAT, FORMAT_VERSION) + +An object whose id is unknown, or whose rev is higher than the library's, is written from the object's SVG source keeping its id and rev; a lower or equal rev keeps the library item. So a document carried to another computer reopens the structure it holds, and an older copy never overwrites a newer edit. + +## 261. edit-live posts to the running engine with the agent token · _v0.12.0 (services/live_structures.py open_request, edit_live; app/cli.py edit-live; formchem, formchem.bat) + +`./formchem edit-live` takes a library id, a path to `items/[id].svg` (read as the id) or a JSON object file, reads the port from `engine.json` and posts to `/api/structures/open` with the agent token, so it works from any terminal without the window key. Exit 0 when opened, 1 when FormChem is not running or refuses (the engine's reason is printed), 2 when the argument cannot be read. The dispatchers route `edit-live` through setup/convert like `convert` and `db` (b3b5f87). + +## 262. The agent token writes to /api/structures and nothing else · _v0.12.0 (core/window_key.py AGENT_WRITES, agent_may_write, WindowKeyGuard; routers/structures.py _guard, GUARD, structure_picture) + +The global guard refuses every non-GET without the window key, which stopped agents and `edit-live`. A valid bearer token now passes it for `/api/structures` and paths under `/api/structures/` only (exact prefix plus slash, so `/api/structuresX` stays 403; checked with curl, 98febea). The routes themselves take the window key or the token, reads included. The picture route is unguarded like the media route, because an `img` element cannot send a header; LocalGuard still keeps it to local origins. + +## 263. The file watch polls once a second and knows FormChem's own saves · _v0.12.0 (services/file_watch.py POLL_SECONDS, ensure_started, stop, check, stamp, disk_modified, reload, keep, pending; app/main.py lifespan; routers/structures.py watched_files, resolve_file_change) + +An asyncio loop compares `os.stat` (mtime_ns and size) of each open drawing with a path once a second, with no file-system notification library. FormChem's own saves write `modified` into document.json, so on a change the watcher reads only that value from the zip and stays quiet when it equals the session's. A missing file broadcasts `missing: true`. Reload applies the disk document as one undoable transaction, the way Restore Version does, then marks the drawing saved; Keep Mine marks it unsaved so the next save writes over the outside change. The lifespan starts and stops the loop (c6a97ca), so nothing waits for the first window call. + +## 264. The structure description runs FormChem's own groups and ring names · _v0.12.0 (services/describe.py GROUPS, RING_NAMES, functional_groups, ring_systems, ring_name, _skeleton_key, _join_kind, stereo, _name, describe, from_fragments, from_smiles; routers/describe.py run, _source, _from_doc) + +The 42 functional group SMARTS and the 51 ring skeletons were written for FormChem. Each SMARTS marks its core atoms with map numbers; groups run in priority order and a match is skipped when a core atom is already claimed, so an ester's O is not also an ether and urea's N is not an amide; carbonyl patterns use `#6X3`, `#7X3` and `#8X2` so aromatic carbonyls (caffeine) match. A ring system is named by writing its ring atoms alone as SMILES with hydrogens and charges cleared and comparing canonical forms, so substituents do not matter but bond orders do (testosterone's unsaturated nucleus is not called gonane). Every part names its method. The route takes fragments, a SMILES or an open drawing behind the window key, up to 1,000 atoms and 200 fragments. + +## 265. HELM monomers are FormChem's own data, checked when they load · _v0.12.0 (data/helm_monomers.json; services/helm/monomers.py Monomer, Library, _monomer, build, library, cap, attachment_labels, canonical, inline, LEAVING) + +No monomer library had a licence cleared, so the 55 monomers were written from textbook structures (20 L amino acids, 19 D forms, Aib, Nle, Orn, Sar, Hyp, pE, the caps ac and am, R, dR, P, A, C, G, U, T) and the file says so in `source`. Each carries its attachment SMILES with `[*:n]`, its capped form and the leaving group of each point. The loader caps every attachment SMILES itself and refuses the file if the result differs from `capped`, so a typo cannot ship. R3 sits on C, K, D, E and Orn (and their D forms), the points disulfide and lactam bridges use. Inline SMILES monomers take H at every point. + +## 266. The HELM reader refuses with the character where it stopped · _v0.12.0 (services/helm/parser.py parse, _sections, _split, _Reader, _units, _polymers, _connections, HelmError, MAX_TEXT, MAX_MONOMERS, MAX_REPEAT) + +Sections split on `$` outside brackets, braces and quotes; one section or four or five are accepted, the fifth empty or `V2.x`. Refused with a position: BLOB, mixtures, repeat ranges, hydrogen-bond pairs, `?` attachment points and polymer groups. Whole repeat counts expand the dot unit; monomer numbers count branch monomers in order (`R(A)P` is 1, 2, 3) as HELM does. Annotations are kept as text with a note. Limits: 100,000 characters, 2,000 monomers, 500 repeats. + +## 267. Monomers are joined by zipping attachment points · _v0.12.0 (services/helm/assemble.py assemble, _resolve, _links, _check, _combine, Placed, Link, Assembly, MAX_ATOMS) + +Each bond's two dummies get one shared atom map number and `Chem.molzip` joins them, which keeps every tetrahedral centre (checked on adenosine and thymidine keys before the writer existed). Unused points become their leaving atom. Combining is a pairwise tree, so 2,000 monomers are not quadratic; 20,000 atoms is the limit. The package exports the function as `build_molecule` so it does not hide the `assemble` submodule (03fb9cc). + +## 268. Writing HELM cuts known bonds and is offered only when it reads back · _v0.12.0 (services/helm/writer.py CUTS, PATTERNS, PARTNER, write, pieces_of, _cuts, _pieces, _match, _labels, _assign, _topology, _branch; services/helm/__init__.py from_mol, _same, read, method) + +The writer cuts alpha-carbonyl amides, acetyl amides, S-S, the ester O-P and the sugar C1' to base N, and side-chain lactams (4449a9e), caps each side with the leaving group of its cut, and matches the piece by canonical isomeric SMILES. Which R label sits on each cut atom comes from a substructure match against the monomer's labelled capped form; phosphate's two labels on one atom are resolved from the partner. Backbone runs R2 to R1, a base on sugar R3 is a branch, everything else is a connection. A piece with no stereo drawn matches the first (L, D-sugar) monomer with a `stereo_assumed` note. The HELM written is parsed and built again and compared by InChIKey (flat SMILES when stereo was assumed); a mismatch is refused, never offered. `read` names the reader, the monomer data version and count, RDKit, the mass source and the layout candidate the scorer chose (9c5f98a). + +## 269. The HELM routes answer a syntax error as data · _v0.12.0 (routers/helm.py parse, from_structure, monomer_list, _guard, _structure, _bond_length) + +All three routes need the window key. A syntax error is a 200 with `ok: false` and `error {text, position}`, so the dialog validates on every key without treating a half-typed string as a failure. + +## 270. xtb and CREST are found where the person put them, never shipped · _v0.12.0 (services/xtb/__init__.py XTB_HOME, CREST_HOME, LICENCE; services/xtb/discovery.py PROGRAMS, find, _locate, _candidates, folders, version_of, _checked, usable, status, child_env, LIFE, VERSION_WAIT) + +Plan question Q9 is unanswered, so its default (b) applies: the LGPL-3.0 programs run only as separate processes the person installed, and FormChem neither includes nor downloads them. The lookup is the setting (a file, or a folder holding it), then PATH, then conda and mamba prefixes and the usual bin folders; `--version` runs with a 15 s limit. Only a program that runs is cached, for 30 s, so an install made while FormChem is open is seen the next time (7531c12). Children get `OMP_NUM_THREADS=n,1`, `OMP_MAX_ACTIVE_LEVELS=1`, the MKL and OpenBLAS thread counts and `OMP_STACKSIZE=1G` when unset (xtb's own advice); CREST gets xtb's folder first on PATH because it calls the xtb program. + +## 271. Inputs keep the 3D label order and check the electrons · _v0.12.0 (services/xtb/inputs.py Start, start, electrons_check, xyz, xtb_argv, crest_argv, MAX_CHARGE, MAX_UHF) + +Jobs start from the stored conformers, or from a fresh ETKDGv3+MMFF94 build, written in `molecule.prepare`'s label order (heavy atoms, then hydrogens), so results map back by index. Charge defaults to the sum of formal charges and unpaired electrons to RDKit's radical count; their parity is checked against the electron count before anything starts, with the reason in plain words. + +## 272. A program runs in its own process group with its log in a file · _v0.12.0 (services/xtb/runner.py Process, Outcome, stop_all, POLL, GRACE, LOG) + +Output goes to `output.log` in the job folder and is read line by line, so no pipe can fill and block. Each program gets its own process group (`start_new_session`; on Windows `CREATE_NEW_PROCESS_GROUP` and `taskkill /T`), and cancel or the time limit sends SIGTERM, waits 3 s, then SIGKILL; `atexit` stops running programs when the engine exits. Checked with stand-in programs only. + +## 273. One job at a time; a folder is kept only when a job fails · _v0.12.0 (services/xtb/jobs.py Job, Options, options, submit, get, listing, cancel, _prune, _collect, _on_line, _argv, MAX_RUNNING, KEEP_JOBS, FORGET_AFTER, MAX_KEEP; services/xtb/parse.py) + +xtb and CREST use every thread given, so one job runs at a time and the time limit covers the whole job (600 s for xtb and 3,600 s for CREST by default, a week at most). The folder is deleted on success, cancel and timeout, kept on failure so the person can read the program's files, and deleted when the job is forgotten after an hour (259a9d8). Energies come from the last TOTAL ENERGY line, else the `xtbopt.xyz` comment; convergence from the log, else `.xtboptok`. CREST energies come from the comment lines of `crest_conformers.xyz`, `crest.energies` only when a comment has none, and the ensemble is cut to `keep` in file order. The parsers were checked on files written by hand from the documented formats, not on real output. + +## 274. Results go back as one 3D transaction with a program record · _v0.12.0 (services/xtb/writeback.py records, program, label, Result, CONFORMER_METHOD; routers/xtb.py _applier, start_job, LABELS; docs/FORMAT.md conformers) + +A result must have the input's element order, else the job fails with 502. Conformers go through `molecule.add_conformer` and `molecule.record` with method `xtb` and energy in kcal/mol (Eh times 627.509474), and a `program` record (name, version, method, solvent, charge, uhf, energy in hartree, gap) that FORMAT.md, model.ts and model.py describe (c8aedcd). Stereo is checked with `verify.stereo`: CREST conformers that lost it are dropped and counted, an xtb result is kept with `stereo_changed`. The write-back replaces the fragment's conformers through `three_d.commit` and `_replace_ops` with the stale signature, so an edit during a run fails the job with the 3D 409 text and leaves the drawing alone; an optimisation keeps only its own conformer, so MMFF94 and xtb energies never sit side by side. + +## 275. The xtb routes and the three settings keys · _v0.12.0 (routers/xtb.py xtb_status, xtb_settings, xtb_optimise, xtb_single, xtb_crest, xtb_jobs, xtb_job, xtb_cancel, _guard; services/xtb/discovery.py save, settings, threads, SETTING_XTB, SETTING_CREST, SETTING_THREADS; services/xtb/solvents.py ALPB, ALIASES, solvent_of) + +Every route needs the window key. A missing program is a 424 naming the project address, bad input a 422 (the parity reason included), an unknown drawing or object a 404. `xtbPath`, `crestPath` and `xtbThreads` are written through `config.write_settings` by the settings route, so `SETTINGS_KEYS` in system.py is not touched; threads default to the smaller of 4 and the CPU count. The 24 ALPB solvents are the ones xtb documents, with a few aliases (dcm, chloroform). + +## 276. The six agent tools join AGENT_MODULES · _v0.12.0 (services/agent_library.py TOOLS, NAMES, MUTATING, mutating, call; services/agent_helm.py TOOL, TOOLS, NAMES, mutating, call, t_draw_from_helm; services/agent_xtb.py TOOLS, NAMES, body, call, NOT_SHIPPED; routers/mcp.py AGENT_MODULES, INSTRUCTIONS, WORKFLOW) + +The three modules took the agent module shape (ed5029a) and `AGENT_MODULES` now holds five modules, so tools/list has 77. `library_add`, `draw_from_helm`, `xtb_optimise` and `crest_conformers` ask the person the first time; `library_list` and `live_structure_object` are read-only. HELM and xtb build their `Agent` from the name, because `_draw`, `_apply` and `_three_d` read only `a.name`. The xtb tools wait for the job and answer with hartree and kcal/mol, the gap, convergence and the program label, and every description says the programs are not shipped. Workflow lines 7c and 7d name them. `setup/agents.py` reads these modules' TOOLS by AST and cannot read `{**_KIND, ...}`, the `[*...]` solvent list, f-strings over imported limits or the `TOOLS = [TOOL]` shape, so `./formchem agents sync` stops at 0.12.0 until the reader learns them or the modules spell them out. + +## 277. The deep link plugin and the formai scheme · _v0.12.0 (src-tauri/Cargo.toml, Cargo.lock, src/main.rs, tauri.conf.json plugins.deep-link, capabilities/default.json) + +`tauri-plugin-deep-link` 2.6.3 (Apache-2.0 OR MIT) matches tauri 2.12; single-instance gets its `deep-link` feature so a second launch forwards the `formai://` argument on Linux and Windows, and `register_all()` in setup registers the scheme for the AppImage. The capability `deep-link:default` allows `get_current`. The existing `RunEvent::Opened` handler keeps only file URLs, so `formai://` links reach the window only through the plugin. `cargo check` stopped at gdk-sys (no GTK headers on the build machine), so these lines were checked against the plugin's source, not compiled. + +## 278. The notices cover the deep link crates · _v0.12.0 (NOTICE.md; THIRD-PARTY-NOTICES.txt; setup/notices.py) + +The plugin brought rust-ini 0.21.3, ordered-multimap 0.7.3, dlv-list 0.5.2, const-random 0.1.20, const-random-macro 0.1.18, crunchy 0.2.4, hashbrown 0.14.5 and tiny-keccak 2.0.2 (CC0-1.0). THIRD-PARTY-NOTICES.txt was regenerated with the engine's own virtual environment and `packaging` added on PYTHONPATH from a scratch folder: the system Python holds other versions of numpy, click and fonttools and would list the wrong ones. That run also moved cryptography to 51.0.1 and idna to 3.21, the versions installed in the engine's environment. + ## Not verified at 0.7.0 No macOS build was made: the one-folder freeze with Python 3.14 (in particular that `fc_flatten_engine` finds and replaces `Python.framework` and that `otool` finds nothing still linking it), the signed and notarized build, the launch time against the old 30 seconds, and multiprocessing under the frozen engine. At a2c81f6 `build_app`'s own freeze step does not pass `--collect-submodules fontTools`, which `setup/freeze_backend` does; a desktop app built with `./build_app` may lack fontTools' table modules, which would turn the font subsets off. EPS was not rendered (no Ghostscript). CDXML and CDX files made by the reference suite itself were never read; only Indigo-written files were. `formchem.bat` and `setup/convert.bat` were not run (no Windows here). @@ -1192,3 +1493,11 @@ No macOS build: the frozen engine carrying `data/names/` and the spectra and NMR ## Not verified at 0.10.0 No macOS build: the frozen engine with the `three_d` package (RDKit's force fields and ETKDG were already frozen, but nobody ran a 3D build in the app). The MCP tools ran in process as an in-app agent, not through a real client, so the consent prompt for the five always-gated tools was reasoned about, not clicked. MMFF94s and UFF ran (UFF on a stannane and on ethanol) but were not compared with reference energies. mmCIF was read from hand-written files and the engine path only; a large real mmCIF entry was not tried. `as=file` exports were checked for SDF and PDB; XYZ and V3000 only through the service and the MCP tool. A 14-membered lactone gave 10 conformers from 47 embedded; macrocycle timing was not measured. Large PDB files through File > Import (base64 to the window and back, under the 64 MB read and 50 MB upload limits) were not tried. The race in entry 211 was reasoned about, not provoked. The ligand template table was written from knowledge; the templates exercised (BEN, ACT, FOL) matched their ligands, the others were not compared with a reference. 1DRF in the engine's corpus was copied from a local test folder of another project (the PDB data file only, wwPDB data, CC0); it lives outside the repository. + +## Not verified at 0.11.0 + +No macOS build: the frozen engine with the `database` and `notebook` packages (numpy and RDKit's SubstructLibrary were already frozen, but nobody opened a database in the app). The MCP tools ran over curl with the agent token and in scratch merges, not through `setup/mcp_stdio.py` or a real client; the consent prompt for `db_add_record` and `nb_add_entry` with a window open was not clicked. The 1 million record size of the plan was not tried; 100,000 records were searched in the engine only, on this 2-CPU machine shared with other agents, not on the reference laptop. A read-only second engine was checked through a TestClient process, not against a window. The live `database` broadcast was checked in one window; two windows on one database were not. Lock removal on a crash was reasoned about (stale takeover), not provoked on a second host. The HTML entry export was not printed. `formchem.bat db` was not run (no Windows here). The new icons were checked as files (icns at 1024, ico 16 to 256), not in a built desktop app. + +## Not verified at 0.12.0 + +No real xtb or CREST: discovery, the runner, cancel, the time limit, the parsers, the routes and the two agent tools ran against stand-in programs writing the documented files, so real output layouts (for example CREST 3's `crest.energies` columns), real timings and CREST's atom order on a real run are unseen; the Windows process-group stop and the Windows install folders were not tried. The deep link lines in src-tauri were not compiled (gdk-sys stopped `cargo check`) and no `formai://` link was opened on a desktop. No sibling app (FormDeck, FormTxt, form.md) read the Library folder or an object; both were checked field by field against LIVE_STRUCTURES.md only. Reaction items in the library have a code path (RXN, reaction SMILES) that no run copied. HELM inputs near 2,000 monomers and 20,000 atoms were not timed (20 residues at most), inline SMILES in RNA and CHEM pieces are not written back, and mixed peptide and nucleic acid conjugates are written only when the joining bond is one of the cut kinds. The describe route ran on 25 SMILES and through a TestClient, with no real screen reader at the other end. `./formchem agents sync` stops on the new modules (entry 276), so `references/tools.md` and `agents/manifest.json` still list 71 tools. `formchem.bat edit-live` was not run (no Windows here). diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 61fb31ca..ea370a8e 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.10.0" +__version__ = "0.12.0" diff --git a/backend/app/cli.py b/backend/app/cli.py index 3a3c1673..a21c205b 100644 --- a/backend/app/cli.py +++ b/backend/app/cli.py @@ -8,7 +8,9 @@ ./formchem batch DIR --to FMT [--out DIR] [--jobs N] [--standardise [STEPS]] [--recursive] [--errors report.csv] ./formchem descriptors IN --csv OUT [--props LIST] [--standardise [STEPS]] [--jobs N] [--errors report.csv] ./formchem render IN --out DIR [--format svg|png] [--size W[xH]] [--transparent] [--standardise [STEPS]] [--jobs N] -./formchem convert --formats | --steps ./formchem descriptors --list""" +./formchem convert --formats | --steps ./formchem descriptors --list +./formchem db create|info|import|search|export ... (./formchem db --help) +./formchem edit-live ID | --object FILE [--from APP]""" SHOWN = 20 @@ -71,6 +73,12 @@ def parser() -> argparse.ArgumentParser: r.add_argument("--size", metavar="W[xH]", help="fit each drawing into this many pixels (default: the journal scale, 14.4 pt bonds; PNG at 300 dpi)") r.add_argument("--transparent", action="store_true", help="no white background") _common(r) + e = sub.add_parser("edit-live", usage=USAGE.splitlines()[6], help="open a live structure from the shared library for editing") + e.add_argument("id", nargs="?") + e.add_argument("--object", metavar="FILE", help="a live structure object (JSON) saved by a sibling app") + e.add_argument("--from", dest="sibling", metavar="APP", help="the sibling app asking, shown in the title bar") + from app.services.database import dbcli + dbcli.add_parser(sub) return top @@ -151,6 +159,12 @@ def _list_columns() -> int: def run(args) -> int: + if args.command == "db": + from app.services.database import dbcli + return dbcli.run(args) + if args.command == "edit-live": + from app.services.live_structures import edit_live + return edit_live(_path(args.object) if args.object else (args.id or ""), args.sibling) from app.services import batch from app.services.chem import depict quiet = args.quiet diff --git a/backend/app/core/window_key.py b/backend/app/core/window_key.py index ee33262e..24f44278 100644 --- a/backend/app/core/window_key.py +++ b/backend/app/core/window_key.py @@ -6,6 +6,8 @@ from fastapi import HTTPException, Request +from app.core import agent_token + HEADER = "x-formchem-window-key" STDOUT_ENV = "FORMCHEM_WINDOW_KEY_STDOUT" LINE = "formchem-window-key: " @@ -14,6 +16,8 @@ READS = ("GET", "HEAD", "OPTIONS") OPEN = ("/mcp", "/api/window/key") KEY = secrets.token_urlsafe(32) +VIEW = secrets.token_urlsafe(24) +VIEW_PARAM = "k" STATE = {"claimed": False, "secondClaim": False} TICKETS: dict[str, float] = {} @@ -31,10 +35,29 @@ def require(request: Request) -> None: raise HTTPException(403, REFUSED) +def require_view(request: Request) -> None: + if valid(request.headers.get(HEADER)): + return + given = request.query_params.get(VIEW_PARAM, "") + if not (given and hmac.compare_digest(given.encode("utf-8"), VIEW.encode("utf-8"))): + raise HTTPException(403, REFUSED) + + def is_open(path: str) -> bool: return path in OPEN +AGENT_WRITES = "/api/structures" + + +def agent_may_write(scope) -> bool: + path = str(scope.get("path", "")) + if path != AGENT_WRITES and not path.startswith(AGENT_WRITES + "/"): + return False + bearer = next((v.decode("latin-1") for k, v in scope.get("headers", []) if k.decode("latin-1").lower() == "authorization"), None) + return agent_token.valid(bearer) + + def claim() -> str | None: if STATE["claimed"]: STATE["secondClaim"] = True @@ -68,7 +91,7 @@ async def __call__(self, scope, receive, send) -> None: await self.app(scope, receive, send) return given = next((v.decode("latin-1") for k, v in scope.get("headers", []) if k.decode("latin-1").lower() == HEADER), None) - if valid(given): + if valid(given) or agent_may_write(scope): await self.app(scope, receive, send) return body = json.dumps({"detail": REFUSED}).encode("utf-8") diff --git a/backend/app/data/helm_monomers.json b/backend/app/data/helm_monomers.json new file mode 100644 index 00000000..2de58687 --- /dev/null +++ b/backend/app/data/helm_monomers.json @@ -0,0 +1,66 @@ +{ + "format": "formchem-helm-monomers", + "version": "1.0", + "source": "Written for FormChem from textbook structures of the amino acids and nucleosides. No monomer library was consulted or copied.", + "leaving_groups": {"H": "hydrogen", "OH": "hydroxy"}, + "monomers": [ + {"symbol": "A", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-alanine", "natural": "A", "smiles": "[*:1]N[C@@H](C)C(=O)[*:2]", "capped": "N[C@@H](C)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-alanine."}, + {"symbol": "R", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-arginine", "natural": "R", "smiles": "[*:1]N[C@@H](CCCNC(=N)N)C(=O)[*:2]", "capped": "N[C@@H](CCCNC(=N)N)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-arginine."}, + {"symbol": "N", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-asparagine", "natural": "N", "smiles": "[*:1]N[C@@H](CC(N)=O)C(=O)[*:2]", "capped": "N[C@@H](CC(N)=O)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-asparagine."}, + {"symbol": "D", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-aspartic acid", "natural": "D", "smiles": "[*:1]N[C@@H](CC(=O)[*:3])C(=O)[*:2]", "capped": "N[C@@H](CC(=O)O)C(=O)O", "attachments": {"R1": "H", "R2": "OH", "R3": "OH"}, "source": "Written for FormChem from the structure of L-aspartic acid."}, + {"symbol": "C", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-cysteine", "natural": "C", "smiles": "[*:1]N[C@@H](CS[*:3])C(=O)[*:2]", "capped": "N[C@@H](CS)C(=O)O", "attachments": {"R1": "H", "R2": "OH", "R3": "H"}, "source": "Written for FormChem from the structure of L-cysteine."}, + {"symbol": "E", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-glutamic acid", "natural": "E", "smiles": "[*:1]N[C@@H](CCC(=O)[*:3])C(=O)[*:2]", "capped": "N[C@@H](CCC(=O)O)C(=O)O", "attachments": {"R1": "H", "R2": "OH", "R3": "OH"}, "source": "Written for FormChem from the structure of L-glutamic acid."}, + {"symbol": "Q", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-glutamine", "natural": "Q", "smiles": "[*:1]N[C@@H](CCC(N)=O)C(=O)[*:2]", "capped": "N[C@@H](CCC(N)=O)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-glutamine."}, + {"symbol": "G", "polymer": "PEPTIDE", "role": "amino acid", "name": "glycine", "natural": "G", "smiles": "[*:1]NCC(=O)[*:2]", "capped": "NCC(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of glycine."}, + {"symbol": "H", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-histidine", "natural": "H", "smiles": "[*:1]N[C@@H](Cc1c[nH]cn1)C(=O)[*:2]", "capped": "N[C@@H](Cc1c[nH]cn1)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-histidine."}, + {"symbol": "I", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-isoleucine", "natural": "I", "smiles": "[*:1]N[C@@H]([C@@H](C)CC)C(=O)[*:2]", "capped": "N[C@@H]([C@@H](C)CC)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-isoleucine (2S,3S)."}, + {"symbol": "L", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-leucine", "natural": "L", "smiles": "[*:1]N[C@@H](CC(C)C)C(=O)[*:2]", "capped": "N[C@@H](CC(C)C)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-leucine."}, + {"symbol": "K", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-lysine", "natural": "K", "smiles": "[*:1]N[C@@H](CCCCN[*:3])C(=O)[*:2]", "capped": "N[C@@H](CCCCN)C(=O)O", "attachments": {"R1": "H", "R2": "OH", "R3": "H"}, "source": "Written for FormChem from the structure of L-lysine."}, + {"symbol": "M", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-methionine", "natural": "M", "smiles": "[*:1]N[C@@H](CCSC)C(=O)[*:2]", "capped": "N[C@@H](CCSC)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-methionine."}, + {"symbol": "F", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-phenylalanine", "natural": "F", "smiles": "[*:1]N[C@@H](Cc1ccccc1)C(=O)[*:2]", "capped": "N[C@@H](Cc1ccccc1)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-phenylalanine."}, + {"symbol": "P", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-proline", "natural": "P", "smiles": "[*:1]N1CCC[C@H]1C(=O)[*:2]", "capped": "N1CCC[C@H]1C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-proline."}, + {"symbol": "S", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-serine", "natural": "S", "smiles": "[*:1]N[C@@H](CO)C(=O)[*:2]", "capped": "N[C@@H](CO)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-serine."}, + {"symbol": "T", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-threonine", "natural": "T", "smiles": "[*:1]N[C@@H]([C@@H](C)O)C(=O)[*:2]", "capped": "N[C@@H]([C@@H](C)O)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-threonine (2S,3R)."}, + {"symbol": "W", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-tryptophan", "natural": "W", "smiles": "[*:1]N[C@@H](Cc1c[nH]c2ccccc12)C(=O)[*:2]", "capped": "N[C@@H](Cc1c[nH]c2ccccc12)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-tryptophan."}, + {"symbol": "Y", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-tyrosine", "natural": "Y", "smiles": "[*:1]N[C@@H](Cc1ccc(O)cc1)C(=O)[*:2]", "capped": "N[C@@H](Cc1ccc(O)cc1)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-tyrosine."}, + {"symbol": "V", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-valine", "natural": "V", "smiles": "[*:1]N[C@@H](C(C)C)C(=O)[*:2]", "capped": "N[C@@H](C(C)C)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-valine."}, + + {"symbol": "dA", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-alanine", "natural": "A", "smiles": "[*:1]N[C@H](C)C(=O)[*:2]", "capped": "N[C@H](C)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-alanine."}, + {"symbol": "dR", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-arginine", "natural": "R", "smiles": "[*:1]N[C@H](CCCNC(=N)N)C(=O)[*:2]", "capped": "N[C@H](CCCNC(=N)N)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-arginine."}, + {"symbol": "dN", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-asparagine", "natural": "N", "smiles": "[*:1]N[C@H](CC(N)=O)C(=O)[*:2]", "capped": "N[C@H](CC(N)=O)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-asparagine."}, + {"symbol": "dD", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-aspartic acid", "natural": "D", "smiles": "[*:1]N[C@H](CC(=O)[*:3])C(=O)[*:2]", "capped": "N[C@H](CC(=O)O)C(=O)O", "attachments": {"R1": "H", "R2": "OH", "R3": "OH"}, "source": "Written for FormChem from the structure of D-aspartic acid."}, + {"symbol": "dC", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-cysteine", "natural": "C", "smiles": "[*:1]N[C@H](CS[*:3])C(=O)[*:2]", "capped": "N[C@H](CS)C(=O)O", "attachments": {"R1": "H", "R2": "OH", "R3": "H"}, "source": "Written for FormChem from the structure of D-cysteine."}, + {"symbol": "dE", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-glutamic acid", "natural": "E", "smiles": "[*:1]N[C@H](CCC(=O)[*:3])C(=O)[*:2]", "capped": "N[C@H](CCC(=O)O)C(=O)O", "attachments": {"R1": "H", "R2": "OH", "R3": "OH"}, "source": "Written for FormChem from the structure of D-glutamic acid."}, + {"symbol": "dQ", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-glutamine", "natural": "Q", "smiles": "[*:1]N[C@H](CCC(N)=O)C(=O)[*:2]", "capped": "N[C@H](CCC(N)=O)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-glutamine."}, + {"symbol": "dH", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-histidine", "natural": "H", "smiles": "[*:1]N[C@H](Cc1c[nH]cn1)C(=O)[*:2]", "capped": "N[C@H](Cc1c[nH]cn1)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-histidine."}, + {"symbol": "dI", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-isoleucine", "natural": "I", "smiles": "[*:1]N[C@H]([C@H](C)CC)C(=O)[*:2]", "capped": "N[C@H]([C@H](C)CC)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-isoleucine (2R,3R), the mirror image of L-isoleucine."}, + {"symbol": "dL", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-leucine", "natural": "L", "smiles": "[*:1]N[C@H](CC(C)C)C(=O)[*:2]", "capped": "N[C@H](CC(C)C)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-leucine."}, + {"symbol": "dK", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-lysine", "natural": "K", "smiles": "[*:1]N[C@H](CCCCN[*:3])C(=O)[*:2]", "capped": "N[C@H](CCCCN)C(=O)O", "attachments": {"R1": "H", "R2": "OH", "R3": "H"}, "source": "Written for FormChem from the structure of D-lysine."}, + {"symbol": "dM", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-methionine", "natural": "M", "smiles": "[*:1]N[C@H](CCSC)C(=O)[*:2]", "capped": "N[C@H](CCSC)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-methionine."}, + {"symbol": "dF", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-phenylalanine", "natural": "F", "smiles": "[*:1]N[C@H](Cc1ccccc1)C(=O)[*:2]", "capped": "N[C@H](Cc1ccccc1)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-phenylalanine."}, + {"symbol": "dP", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-proline", "natural": "P", "smiles": "[*:1]N1CCC[C@@H]1C(=O)[*:2]", "capped": "N1CCC[C@@H]1C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-proline."}, + {"symbol": "dS", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-serine", "natural": "S", "smiles": "[*:1]N[C@H](CO)C(=O)[*:2]", "capped": "N[C@H](CO)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-serine."}, + {"symbol": "dT", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-threonine", "natural": "T", "smiles": "[*:1]N[C@H]([C@H](C)O)C(=O)[*:2]", "capped": "N[C@H]([C@H](C)O)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-threonine (2R,3S), the mirror image of L-threonine."}, + {"symbol": "dW", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-tryptophan", "natural": "W", "smiles": "[*:1]N[C@H](Cc1c[nH]c2ccccc12)C(=O)[*:2]", "capped": "N[C@H](Cc1c[nH]c2ccccc12)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-tryptophan."}, + {"symbol": "dY", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-tyrosine", "natural": "Y", "smiles": "[*:1]N[C@H](Cc1ccc(O)cc1)C(=O)[*:2]", "capped": "N[C@H](Cc1ccc(O)cc1)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-tyrosine."}, + {"symbol": "dV", "polymer": "PEPTIDE", "role": "amino acid", "name": "D-valine", "natural": "V", "smiles": "[*:1]N[C@H](C(C)C)C(=O)[*:2]", "capped": "N[C@H](C(C)C)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of D-valine."}, + + {"symbol": "Aib", "polymer": "PEPTIDE", "role": "amino acid", "name": "2-aminoisobutyric acid (2-methylalanine)", "natural": "A", "smiles": "[*:1]NC(C)(C)C(=O)[*:2]", "capped": "NC(C)(C)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of 2-aminoisobutyric acid."}, + {"symbol": "Nle", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-norleucine", "natural": "L", "smiles": "[*:1]N[C@@H](CCCC)C(=O)[*:2]", "capped": "N[C@@H](CCCC)C(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of L-norleucine."}, + {"symbol": "Orn", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-ornithine", "natural": "K", "smiles": "[*:1]N[C@@H](CCCN[*:3])C(=O)[*:2]", "capped": "N[C@@H](CCCN)C(=O)O", "attachments": {"R1": "H", "R2": "OH", "R3": "H"}, "source": "Written for FormChem from the structure of L-ornithine."}, + {"symbol": "Sar", "polymer": "PEPTIDE", "role": "amino acid", "name": "sarcosine (N-methylglycine)", "natural": "G", "smiles": "[*:1]N(C)CC(=O)[*:2]", "capped": "CNCC(=O)O", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of sarcosine."}, + {"symbol": "Hyp", "polymer": "PEPTIDE", "role": "amino acid", "name": "trans-4-hydroxy-L-proline", "natural": "P", "smiles": "O[C@@H]1C[C@@H](C(=O)[*:2])N([*:1])C1", "capped": "O[C@@H]1C[C@@H](C(=O)O)NC1", "attachments": {"R1": "H", "R2": "OH"}, "source": "Written for FormChem from the structure of trans-4-hydroxy-L-proline (2S,4R)."}, + {"symbol": "pE", "polymer": "PEPTIDE", "role": "amino acid", "name": "L-pyroglutamic acid (5-oxo-L-proline)", "natural": "E", "smiles": "O=C1CC[C@H](N1)C(=O)[*:2]", "capped": "O=C1CC[C@H](N1)C(=O)O", "attachments": {"R2": "OH"}, "source": "Written for FormChem from the structure of L-pyroglutamic acid; it has no R1 because its ring nitrogen is a lactam, so it starts a chain."}, + {"symbol": "ac", "polymer": "PEPTIDE", "role": "cap", "name": "N-acetyl cap", "natural": null, "smiles": "CC(=O)[*:2]", "capped": "CC(=O)O", "attachments": {"R2": "OH"}, "source": "Written for FormChem from the acetyl group; it caps the N-terminus."}, + {"symbol": "am", "polymer": "PEPTIDE", "role": "cap", "name": "C-terminal amide cap", "natural": null, "smiles": "N[*:1]", "capped": "N", "attachments": {"R1": "H"}, "source": "Written for FormChem from the amide nitrogen; it caps the C-terminus as a carboxamide."}, + + {"symbol": "R", "polymer": "RNA", "role": "sugar", "name": "beta-D-ribofuranose (ribose)", "natural": "R", "smiles": "[*:3][C@@H]1O[C@H](CO[*:1])[C@@H](O[*:2])[C@H]1O", "capped": "O[C@@H]1O[C@H](CO)[C@@H](O)[C@H]1O", "attachments": {"R1": "H", "R2": "H", "R3": "OH"}, "source": "Written for FormChem from the sugar of adenosine: R1 is the 5'-oxygen, R2 the 3'-oxygen, R3 the anomeric carbon that carries the base."}, + {"symbol": "dR", "polymer": "RNA", "role": "sugar", "name": "2-deoxy-beta-D-ribofuranose (deoxyribose)", "natural": "R", "smiles": "[*:3][C@H]1C[C@H](O[*:2])[C@@H](CO[*:1])O1", "capped": "O[C@H]1C[C@H](O)[C@@H](CO)O1", "attachments": {"R1": "H", "R2": "H", "R3": "OH"}, "source": "Written for FormChem from the sugar of thymidine: R1 is the 5'-oxygen, R2 the 3'-oxygen, R3 the anomeric carbon that carries the base."}, + {"symbol": "P", "polymer": "RNA", "role": "phosphate", "name": "phosphate", "natural": "P", "smiles": "[*:1]P(=O)(O)[*:2]", "capped": "OP(=O)(O)O", "attachments": {"R1": "OH", "R2": "OH"}, "source": "Written for FormChem from phosphoric acid; it links the 3'-oxygen of one sugar to the 5'-oxygen of the next."}, + {"symbol": "A", "polymer": "RNA", "role": "base", "name": "adenine", "natural": "A", "smiles": "[*:1]n1cnc2c(N)ncnc21", "capped": "Nc1ncnc2[nH]cnc12", "attachments": {"R1": "H"}, "source": "Written for FormChem from the structure of adenine, attached at N9."}, + {"symbol": "C", "polymer": "RNA", "role": "base", "name": "cytosine", "natural": "C", "smiles": "[*:1]n1ccc(N)nc1=O", "capped": "Nc1cc[nH]c(=O)n1", "attachments": {"R1": "H"}, "source": "Written for FormChem from the structure of cytosine, attached at N1."}, + {"symbol": "G", "polymer": "RNA", "role": "base", "name": "guanine", "natural": "G", "smiles": "[*:1]n1cnc2c1nc(N)[nH]c2=O", "capped": "Nc1nc2[nH]cnc2c(=O)[nH]1", "attachments": {"R1": "H"}, "source": "Written for FormChem from the structure of guanine, attached at N9."}, + {"symbol": "U", "polymer": "RNA", "role": "base", "name": "uracil", "natural": "U", "smiles": "[*:1]n1ccc(=O)[nH]c1=O", "capped": "O=c1cc[nH]c(=O)[nH]1", "attachments": {"R1": "H"}, "source": "Written for FormChem from the structure of uracil, attached at N1."}, + {"symbol": "T", "polymer": "RNA", "role": "base", "name": "thymine", "natural": "T", "smiles": "[*:1]n1cc(C)c(=O)[nH]c1=O", "capped": "Cc1c[nH]c(=O)[nH]c1=O", "attachments": {"R1": "H"}, "source": "Written for FormChem from the structure of thymine, attached at N1."} + ] +} diff --git a/backend/app/main.py b/backend/app/main.py index d76f625f..5bcdeffa 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -21,6 +21,15 @@ from app.routers import pictures from app.routers import agent_activity from app.routers import names +from app.routers import databases as database_routes +from app.routers import db_search +from app.routers import notebook as notebook_routes +from app.services.database import store as database_store +from app.routers import structures +from app.routers import describe as describe_routes +from app.routers import helm as helm_routes +from app.routers import xtb as xtb_routes +from app.services import file_watch mimetypes.add_type("text/javascript", ".js") mimetypes.add_type("text/javascript", ".mjs") @@ -50,10 +59,14 @@ async def lifespan(this: FastAPI): agent_token.value() claude_code.sweep() terminals.bind(asyncio.get_running_loop()) + database_store.bind(asyncio.get_running_loop()) history.start() + file_watch.ensure_started() yield + file_watch.stop() await chat_engine.stop_all() terminals.close_all() + database_store.close_all() claude_code.revoke_all() await history.stop() _clear_discovery() @@ -83,6 +96,13 @@ async def lifespan(this: FastAPI): app.include_router(pictures.router) app.include_router(names.router) app.include_router(three_d.router) +app.include_router(database_routes.router) +app.include_router(db_search.router) +app.include_router(notebook_routes.router) +app.include_router(structures.router) +app.include_router(describe_routes.router) +app.include_router(helm_routes.router) +app.include_router(xtb_routes.router) _dist = config.dist_dir() if _dist is not None: diff --git a/backend/app/routers/databases.py b/backend/app/routers/databases.py new file mode 100644 index 00000000..a5f277b3 --- /dev/null +++ b/backend/app/routers/databases.py @@ -0,0 +1,301 @@ +import asyncio +from contextlib import contextmanager +from pathlib import Path +from typing import Iterator +from urllib.parse import quote + +from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response +from fastapi.responses import FileResponse, JSONResponse +from starlette.background import BackgroundTask +from starlette.datastructures import UploadFile as StarletteUpload + +from app.core import window_key +from app.services.database import attachments, exports, forms, imports +from app.services.database import fields as fieldsmod +from app.services.database import info, records, store, thumbs, uploads +from app.services.database.store import DatabaseError + +BASE = "/api/databases" + + +async def _bind() -> None: + store.bind(asyncio.get_running_loop()) + + +def _guard(request: Request) -> None: + window_key.require(request) + + +def _view_guard(request: Request) -> None: + window_key.require_view(request) + + +router = APIRouter(dependencies=[Depends(_bind)]) +GUARD = [Depends(_guard)] +VIEW_GUARD = [Depends(_view_guard)] + + +@router.get(BASE + "/jobs/{job}", dependencies=GUARD) +def get_job(job: str) -> dict: + with _errors(): + return imports.job(job) + + +@router.post(BASE + "/jobs/{job}/cancel", dependencies=GUARD) +def cancel_job(job: str) -> dict: + with _errors(): + return imports.cancel(job) + + +@router.post(BASE + "/uploads", dependencies=GUARD) +async def upload(request: Request) -> dict: + form = await request.form() + found = [v for key in ("file", "files") for v in form.getlist(key) if isinstance(v, StarletteUpload)] + if not found: + raise HTTPException(422, "Send the file as a multipart field named file.") + with _errors(): + saved = await asyncio.to_thread(uploads.save, found[0].filename or "upload", found[0].file) + return {"path": str(saved)} + + +@router.get(BASE + "/downloads/{name}", dependencies=GUARD) +def download(name: str) -> FileResponse: + with _errors(): + target = exports.download(name) + return FileResponse(target, filename=name, background=BackgroundTask(target.unlink, missing_ok=True)) + + +@contextmanager +def _errors() -> Iterator[None]: + try: + yield + except records.DuplicateError: + raise + except DatabaseError as exc: + raise HTTPException(exc.status, str(exc)) + + +def _db(handle: str) -> store.Database: + with _errors(): + return store.get(handle) + + +def _body(body: object) -> dict: + if not isinstance(body, dict): + raise HTTPException(422, "Send a JSON object.") + return body + + +@router.get(BASE, dependencies=GUARD) +def list_databases() -> dict: + opened = [] + for db in store.all_open(): + try: + opened.append(info.describe(db)) + except DatabaseError: + continue + return {"open": opened, "known": info.known()} + + +@router.post(BASE, dependencies=GUARD) +def create_database(body: dict = Body(default={})) -> dict: + body = _body(body) + title = body.get("title") if isinstance(body.get("title"), str) else "" + path = body.get("path") if isinstance(body.get("path"), str) and body.get("path").strip() else None + with _errors(): + return info.describe(info.create_database(title, path)) + + +@router.post(f"{BASE}/open", dependencies=GUARD) +def open_database(body: dict = Body(...)) -> dict: + body = _body(body) + with _errors(): + path = str(uploads.adopt(body.get("path"))) if body.get("adopt") is True else body.get("path") + return info.describe(info.open_database(path)) + + +@router.post(BASE + "/{db}/close", dependencies=GUARD) +def close_database(db: str) -> dict: + with _errors(): + info.close_database(db) + return {"closed": True} + + +@router.get(BASE + "/{db}", dependencies=GUARD) +def describe(db: str) -> dict: + with _errors(): + return info.describe(_db(db)) + + +@router.patch(BASE + "/{db}", dependencies=GUARD) +def update(db: str, body: dict = Body(...)) -> dict: + with _errors(): + return info.update(_db(db), _body(body)) + + +@router.post(BASE + "/{db}/fields", dependencies=GUARD) +def add_field(db: str, body: dict = Body(...)) -> dict: + with _errors(): + return fieldsmod.add(_db(db), _body(body)) + + +@router.patch(BASE + "/{db}/fields/{name}", dependencies=GUARD) +def change_field(db: str, name: str, body: dict = Body(...)) -> dict: + with _errors(): + return fieldsmod.change(_db(db), name, _body(body)) + + +@router.delete(BASE + "/{db}/fields/{name}", dependencies=GUARD) +def delete_field(db: str, name: str) -> dict: + with _errors(): + return {"deleted": fieldsmod.delete(_db(db), name)} + + +def _int(value: str | None, what: str, default: int | None = None) -> int | None: + if value is None or value == "": + return default + try: + return int(value) + except ValueError: + raise HTTPException(422, f"{what} must be a whole number.") + + +@router.get(BASE + "/{db}/records", dependencies=GUARD) +def list_records(db: str, request: Request) -> dict: + q = request.query_params + with _errors(): + return records.page(_db(db), _int(q.get("hitlist"), "hitlist"), _int(q.get("offset"), "offset", 0), _int(q.get("limit"), "limit", 100), + q.get("sort") or None, q.get("desc") in ("1", "true", "yes")) + + +@router.get(BASE + "/{db}/records/{uid}", dependencies=GUARD) +def get_record(db: str, uid: str) -> dict: + with _errors(): + return records.get(_db(db), uid) + + +def _duplicates(exc: records.DuplicateError) -> JSONResponse: + return JSONResponse({"detail": str(exc), "duplicates": exc.duplicates}, status_code=409) + + +@router.post(BASE + "/{db}/records", dependencies=GUARD) +def add_record(db: str, body: dict = Body(...)): + body = _body(body) + try: + with _errors(): + return records.add(_db(db), body.get("structure"), body.get("values"), body.get("on_duplicate")) + except records.DuplicateError as exc: + return _duplicates(exc) + + +@router.patch(BASE + "/{db}/records/{uid}", dependencies=GUARD) +def update_record(db: str, uid: str, body: dict = Body(...)) -> dict: + body = _body(body) + with _errors(): + return records.update(_db(db), uid, body.get("structure"), body.get("values")) + + +@router.post(BASE + "/{db}/records/delete", dependencies=GUARD) +def delete_records(db: str, body: dict = Body(...)) -> dict: + with _errors(): + return {"deleted": records.delete(_db(db), _body(body).get("uids"))} + + +@router.get(BASE + "/{db}/records/{uid}/thumb.svg", dependencies=VIEW_GUARD) +def thumb(db: str, uid: str, request: Request) -> Response: + q = request.query_params + size = _int(q.get("size"), "size", 128) + if not thumbs.MIN_SIZE <= size <= thumbs.MAX_SIZE: + raise HTTPException(422, f"size must be from {thumbs.MIN_SIZE} to {thumbs.MAX_SIZE}.") + theme = q.get("theme") or "dark" + if theme not in thumbs.THEMES: + raise HTTPException(422, "theme must be dark or light.") + with _errors(): + svg = thumbs.svg(_db(db), uid, size, theme) + cache = "private, max-age=86400" if q.get("v") else "no-cache" + return Response(svg, media_type="image/svg+xml", headers={"cache-control": cache, "x-formchem-method": thumbs.METHOD}) + + +@router.post(BASE + "/{db}/records/{uid}/attachments", dependencies=GUARD) +async def add_attachment(db: str, uid: str, request: Request) -> dict: + target = _db(db) + if request.headers.get("content-type", "").startswith("multipart/"): + form = await request.form() + found = [v for key in ("file", "files") for v in form.getlist(key) if isinstance(v, StarletteUpload)] + if not found: + raise HTTPException(422, "Send the file as a multipart field named file.") + upload = found[0] + data = await upload.read(attachments.LIMIT + 1) + with _errors(): + return await asyncio.to_thread(attachments.store_bytes, target, uid, upload.filename or "attachment", data, upload.content_type) + try: + body = await request.json() + except ValueError: + raise HTTPException(422, "Send a file, or {path, link: true}.") + body = _body(body) + if body.get("link") is not True: + raise HTTPException(422, "Send a file, or {path, link: true} to link a file by its path.") + with _errors(): + return await asyncio.to_thread(attachments.link, target, uid, body.get("path")) + + +@router.get(BASE + "/{db}/attachments/{attachment}", dependencies=VIEW_GUARD) +def get_attachment(db: str, attachment: int) -> Response: + with _errors(): + found, data = attachments.read(_db(db), attachment) + disposition = f"inline; filename*=UTF-8''{quote(found['name'])}" + if isinstance(data, Path): + return FileResponse(data, media_type=found["mime"] or "application/octet-stream", headers={"content-disposition": disposition}) + return Response(data, media_type=found["mime"] or "application/octet-stream", headers={"content-disposition": disposition}) + + +def _text(body: dict, key: str) -> str | None: + value = body.get(key) + if value is not None and not isinstance(value, str): + raise HTTPException(422, f"{key} must be text.") + return value or None + + +@router.post(BASE + "/{db}/import/preview", dependencies=GUARD) +def import_preview(db: str, body: dict = Body(...)) -> dict: + body = _body(body) + with _errors(): + return imports.preview(_db(db), body.get("path"), _text(body, "format")) + + +@router.post(BASE + "/{db}/import", dependencies=GUARD) +def import_start(db: str, body: dict = Body(...)) -> dict: + body = _body(body) + with _errors(): + return imports.start(_db(db), body.get("path"), _text(body, "format"), body.get("mode") or "new", _text(body, "key"), + body.get("mapping"), body.get("dry_run") is True) + + +@router.post(BASE + "/{db}/export", dependencies=GUARD) +def export(db: str, body: dict = Body(...)) -> dict: + body = _body(body) + hitlist = body.get("hitlist") + if hitlist is not None and (not isinstance(hitlist, int) or isinstance(hitlist, bool)): + raise HTTPException(422, "hitlist must be a hit list id.") + with _errors(): + return exports.export(_db(db), body.get("format") or "sdf", _text(body, "path"), hitlist, body.get("uids"), body.get("fields"), + body.get("v3000") is True, body.get("structure_as") or "smiles") + + +@router.get(BASE + "/{db}/forms", dependencies=GUARD) +def list_forms(db: str) -> list: + with _errors(): + return forms.listing(_db(db)) + + +@router.put(BASE + "/{db}/forms/{form}", dependencies=GUARD) +def put_form(db: str, form: int, body: dict = Body(...)) -> dict: + with _errors(): + return forms.put(_db(db), form, _body(body)) + + +@router.post(BASE + "/{db}/forms/generate", dependencies=GUARD) +def generate_form(db: str, body: dict = Body(default={})) -> dict: + body = _body(body) + with _errors(): + return forms.generate(_db(db), body.get("style") or "single", _text(body, "name")) diff --git a/backend/app/routers/db_search.py b/backend/app/routers/db_search.py new file mode 100644 index 00000000..03238baf --- /dev/null +++ b/backend/app/routers/db_search.py @@ -0,0 +1,128 @@ +import asyncio + +from fastapi import APIRouter, Body, Depends, HTTPException, Request + +from app.core import window_key +from app.services.database import hitlists, plot, saved, search, store +from app.services.database.store import DatabaseError + +router = APIRouter() +BASE = "/api/databases/{db}" + + +def _guard(request: Request) -> None: + window_key.require(request) + + +GUARD = [Depends(_guard)] + + +async def _call(fn, *args, **kwargs): + try: + return await asyncio.to_thread(fn, *args, **kwargs) + except DatabaseError as exc: + raise HTTPException(exc.status, str(exc)) + + +def _db(handle: str): + try: + return store.get(handle) + except DatabaseError as exc: + raise HTTPException(exc.status, str(exc)) + + +def _int(v, what: str, required: bool = False) -> int | None: + if v is None or v == "": + if required: + raise HTTPException(422, f"{what} is required") + return None + if isinstance(v, bool) or not str(v).strip().lstrip("-").isdigit(): + raise HTTPException(422, f"{what} must be a whole number") + return int(v) + + +def _object(body) -> dict: + if not isinstance(body, dict): + raise HTTPException(422, "The body must be a JSON object") + return body + + +@router.post(f"{BASE}/search", dependencies=GUARD) +async def run_search(db: str, body: dict = Body(...)) -> dict: + body = _object(body) + if not isinstance(body.get("query"), dict): + raise HTTPException(422, "query is required: a group {op, terms} or a term {kind, ...}") + name = body.get("name") if isinstance(body.get("name"), str) and body.get("name").strip() else None + return await _call(search.run, _db(db), body["query"], _int(body.get("within"), "within"), name) + + +@router.get(f"{BASE}/hitlists", dependencies=GUARD) +async def list_hitlists(db: str) -> list[dict]: + return await _call(hitlists.all_of, _db(db)) + + +@router.post(f"{BASE}/hitlists/combine", dependencies=GUARD) +async def combine_hitlists(db: str, body: dict = Body(...)) -> dict: + body = _object(body) + return await _call(hitlists.combine, _db(db), _int(body.get("a"), "a", True), _int(body.get("b"), "b", True), str(body.get("op") or ""), + body.get("name") if isinstance(body.get("name"), str) else None) + + +@router.post(f"{BASE}/hitlists/from-selection", dependencies=GUARD) +async def hitlist_from_selection(db: str, body: dict = Body(...)) -> dict: + body = _object(body) + return await _call(hitlists.from_selection, _db(db), body.get("uids"), body.get("name") if isinstance(body.get("name"), str) else None) + + +@router.patch(f"{BASE}/hitlists/{{hid}}", dependencies=GUARD) +async def update_hitlist(db: str, hid: int, body: dict = Body(...)) -> dict: + body = _object(body) + name = body.get("name") + if name is not None and not isinstance(name, str): + raise HTTPException(422, "name must be text") + keep = body.get("saved") + if keep is not None and not isinstance(keep, bool): + raise HTTPException(422, "saved must be true or false") + return await _call(hitlists.update, _db(db), hid, name, keep) + + +@router.delete(f"{BASE}/hitlists/{{hid}}", dependencies=GUARD) +async def delete_hitlist(db: str, hid: int) -> dict: + return await _call(hitlists.delete, _db(db), hid) + + +@router.get(f"{BASE}/queries", dependencies=GUARD) +async def list_queries(db: str) -> list[dict]: + return await _call(saved.all_of, _db(db)) + + +@router.post(f"{BASE}/queries", dependencies=GUARD) +async def save_query(db: str, body: dict = Body(...)) -> dict: + body = _object(body) + if not isinstance(body.get("query"), dict): + raise HTTPException(422, "query is required") + return await _call(saved.create, _db(db), body.get("name"), body.get("folder") or "", body["query"]) + + +@router.patch(f"{BASE}/queries/{{qid}}", dependencies=GUARD) +async def update_query(db: str, qid: int, body: dict = Body(...)) -> dict: + body = _object(body) + if body.get("query") is not None and not isinstance(body.get("query"), dict): + raise HTTPException(422, "query must be a query object") + return await _call(saved.update, _db(db), qid, body.get("name"), body.get("folder"), body.get("query")) + + +@router.delete(f"{BASE}/queries/{{qid}}", dependencies=GUARD) +async def delete_query(db: str, qid: int) -> dict: + return await _call(saved.delete, _db(db), qid) + + +@router.post(f"{BASE}/queries/{{qid}}/run", dependencies=GUARD) +async def run_query(db: str, qid: int, body: dict | None = Body(None)) -> dict: + body = _object(body or {}) + return await _call(saved.run, _db(db), qid, _int(body.get("within"), "within")) + + +@router.get(f"{BASE}/plot", dependencies=GUARD) +async def plot_points(db: str, x: str, y: str | None = None, hitlist: str | None = None) -> dict: + return await _call(plot.points, _db(db), x, y or None, _int(hitlist, "hitlist")) diff --git a/backend/app/routers/describe.py b/backend/app/routers/describe.py new file mode 100644 index 00000000..525f58b5 --- /dev/null +++ b/backend/app/routers/describe.py @@ -0,0 +1,86 @@ +import asyncio +import copy + +from fastapi import APIRouter, Body, Depends, HTTPException, Request + +from app.core import window_key +from app.services import describe as service +from app.services.store import STORE + +router = APIRouter() +MAX_ATOMS = 1000 +MAX_FRAGMENTS = 200 +MAX_SMILES = 20000 + + +def _guard(request: Request) -> None: + window_key.require(request) + + +GUARD = [Depends(_guard)] + + +def _checked(frag) -> dict: + from app.routers.chem import _fragment + return _fragment({"fragment": frag}) + + +def _from_doc(body: dict) -> tuple[list[dict], dict | None]: + doc_id = body.get("doc") + try: + s = STORE.get(doc_id) + except KeyError: + raise HTTPException(404, f"No open drawing has the id {doc_id}.") + with s.lock: + doc = copy.deepcopy(s.doc) + objects = doc.get("objects") or {} + wanted = body.get("objects") + if wanted is None: + ids = [k for k, o in objects.items() if isinstance(o, dict) and o.get("kind") == "fragment"] + elif isinstance(wanted, list) and all(isinstance(i, str) for i in wanted): + ids = wanted + else: + raise HTTPException(422, "objects must be a list of fragment ids") + frags = [] + for i in ids: + o = objects.get(i) + if not isinstance(o, dict) or o.get("kind") != "fragment": + raise HTTPException(404, f"{i} is not a fragment of {doc_id}.") + frags.append(o) + return frags, doc.get("expansions") if isinstance(doc.get("expansions"), dict) else None + + +def _source(body: dict) -> service.Source: + smiles = body.get("smiles") + if isinstance(smiles, str) and smiles.strip(): + if len(smiles) > MAX_SMILES: + raise HTTPException(413, "smiles is too long") + return service.from_smiles(smiles.strip()) + expansions = body.get("expansions") if isinstance(body.get("expansions"), dict) else None + if body.get("doc") is not None: + frags, expansions = _from_doc(body) + elif isinstance(body.get("fragments"), list): + frags = body["fragments"] + elif isinstance(body.get("fragment"), dict): + frags = [body["fragment"]] + else: + raise HTTPException(422, "give fragments, fragment, smiles or doc") + if len(frags) > MAX_FRAGMENTS: + raise HTTPException(422, f"more than {MAX_FRAGMENTS} fragments") + checked = [_checked(f) for f in frags] + if sum(len(f["atoms"]) for f in checked) > MAX_ATOMS: + raise HTTPException(422, f"structures over {MAX_ATOMS} atoms are not described") + return service.from_fragments(checked, expansions) + + +def run(body: dict) -> dict: + try: + src = _source(body) + return service.describe(src, want_name=body.get("name", True) is not False) + except service.DescribeError as exc: + raise HTTPException(422, str(exc)) + + +@router.post("/api/describe", dependencies=GUARD) +async def describe(body: dict = Body(...)) -> dict: + return await asyncio.to_thread(run, body) diff --git a/backend/app/routers/helm.py b/backend/app/routers/helm.py new file mode 100644 index 00000000..b74f8c83 --- /dev/null +++ b/backend/app/routers/helm.py @@ -0,0 +1,97 @@ +import asyncio +import math + +from fastapi import APIRouter, Body, Depends, HTTPException, Request +from rdkit import Chem + +from app.core import window_key +from app.services import helm +from app.services.chem import DEFAULT_BOND_LENGTH, ids, perceive + +router = APIRouter() +MAX_HELM = 100_000 +MAX_SMILES = 50_000 +MAX_MOLFILE = 5_000_000 +MAX_ATOMS = 5000 + + +def _guard(request: Request) -> None: + window_key.require(request) + + +GUARD = [Depends(_guard)] + + +def _num(v) -> bool: + return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) + + +def _bond_length(body: dict) -> float: + value = body.get("bond_length") + if value is None: + return DEFAULT_BOND_LENGTH + if not _num(value) or not 1 <= value <= 500: + raise HTTPException(422, "bond_length must be a number of points from 1 to 500") + return float(value) + + +def _coord(body: dict, key: str) -> float: + v = body.get(key) + if v is None: + return 0.0 + if not _num(v) or not -100_000 <= v <= 100_000: + raise HTTPException(422, f"{key} must be a number of points from -100000 to 100000") + return float(v) + + +def _structure(body: dict) -> tuple[Chem.Mol | None, str | None]: + smiles, block, frag = body.get("smiles"), body.get("molfile"), body.get("fragment") + if isinstance(smiles, str) and smiles.strip(): + if len(smiles) > MAX_SMILES: + raise HTTPException(413, "smiles is too long") + mol = Chem.MolFromSmiles(smiles.strip()) + return mol, None if mol is not None else "smiles is not a valid SMILES." + if isinstance(block, str) and block.strip(): + if len(block) > MAX_MOLFILE: + raise HTTPException(413, "molfile is too long") + mol = Chem.MolFromMolBlock(block) + return mol, None if mol is not None else "molfile could not be read as a molecule." + if isinstance(frag, dict): + from app.routers.chem import _fragment + checked = _fragment({"fragment": frag}) + if len(checked["atoms"]) > MAX_ATOMS: + raise HTTPException(422, f"fragments over {MAX_ATOMS} atoms are not written as HELM") + expansions = body.get("expansions") if isinstance(body.get("expansions"), dict) else None + conv = perceive.prepare(checked, expansions) + if any(a.GetAtomicNum() == 0 for a in conv.mol.GetAtoms()): + return None, "The structure holds labels, R-groups or any-atoms, which have no HELM monomer." + text = ids.smiles(ids.identifier_mol(conv.mol)) + mol = Chem.MolFromSmiles(text) if text else None + return mol, None if mol is not None else "The structure could not be read as a molecule (check valences)." + raise HTTPException(422, "give fragment, smiles or molfile") + + +@router.post("/api/helm/parse", dependencies=GUARD) +async def parse(body: dict = Body(...)) -> dict: + text = body.get("helm") + if not isinstance(text, str): + raise HTTPException(422, "helm is required") + if len(text) > MAX_HELM: + raise HTTPException(413, f"helm is longer than {MAX_HELM:,} characters") + draw = body.get("draw") is not False + return await asyncio.to_thread(helm.read, text, _bond_length(body), (_coord(body, "x"), _coord(body, "y")), draw) + + +@router.post("/api/helm/from-structure", dependencies=GUARD) +async def from_structure(body: dict = Body(...)) -> dict: + mol, why = await asyncio.to_thread(_structure, body) + if mol is None: + return {"ok": False, "helm": None, "method": helm.method(), "warnings": [], "reason": why} + return await asyncio.to_thread(helm.from_mol, mol) + + +@router.get("/api/helm/monomers", dependencies=GUARD) +def monomer_list() -> dict: + lib = helm.monomers.library() + rows = [m.as_dict() for kind in lib.by_polymer.values() for m in kind.values()] + return {"version": lib.version, "source": lib.source, "count": len(rows), "monomers": rows, "method": helm.method()} diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index 271319c6..11134781 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -11,7 +11,7 @@ from app.core import config from app.routers import live from app.routers.live import local_origin -from app.services import bridge +from app.services import agent_db, agent_helm, agent_library, agent_notebook, agent_xtb, bridge from app.services.hub import HUB, Client router = APIRouter() @@ -37,6 +37,12 @@ "set_stereo, replace_substructure, delete, move, scale, align, clean_layout, add_arrow, add_text and add_reaction. " "3D tools work on a structure's stored conformers: build_3d, conformers_3d, minimise_3d, scan_dihedral and measure_3d; open_3d_structure opens PDB, mmCIF, SDF and MOL files, " "extract_ligand turns a bound ligand into a structure, export_3d writes MOL, SDF, PDB or XYZ. " + "Structure databases (.fcdb files): db_list, db_create, db_open, db_import, db_search (substructure, similarity, exact, formula or a query node; answers the hit list and its first rows), " + "db_get_record, db_add_record, db_update_record and db_export. " + "Lab notebook entries live in the same database: nb_add_entry adds an open (unsigned) entry with a scheme from reaction SMILES or a drawing, nb_search finds entries by words or substructure. " + "draw_from_helm {helm} draws a peptide or nucleic acid written in HELM 2 (PEPTIDE1{A.G.C}, RNA1{R(A)P.R(U)}, connections for disulfides) as atoms, one undo step. " + "The shared structure library every Form app reads: library_list, library_add (favourite, template, recent or live) and live_structure_object (the JSON a sibling app stores). " + "xtb_optimise and crest_conformers run xtb and CREST when the person installed them, and store the result as the structure's conformers. " "Tools that change what the person sees ask the person in the window to allow agents the first time. Details: resource formchem://guide.") WORKFLOW = [ "1. get_context -> window open or not, agents allowed or not, open drawings, catalogue size, your last handoff", @@ -47,6 +53,10 @@ "5. reactions: perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry; analysis: compute_properties, stereo, substructure, name_structure, predict_nmr; files: convert, batch_convert", "6. spectra: predict_spectrum, open_spectrum, spectrum_data, spectrum_peaks, spectrum_pick_peaks, spectrum_integrate, spectrum_export", "7. 3D: build_3d {object} -> a conformer with energy and the stereo check; conformers_3d, minimise_3d, scan_dihedral, measure_3d; open_3d_structure {path}, extract_ligand, export_3d", + "7a. databases: db_list -> open and known .fcdb files; db_open {path} or db_create {title}; db_search {db, smiles, mode} -> hit list and rows; db_get_record, db_add_record, db_update_record, db_import, db_export", + "7b. notebook: nb_add_entry {db, title, template, reaction or doc, products} -> entry number, hash and stoichiometry (never signed); nb_search {db, query, substructure} -> entries newest first", + "7c. biopolymers: draw_from_helm {helm} -> new ids, formula, masses with method, InChIKey; library: library_list {kind}, library_add {doc or smiles, kinds}, live_structure_object {id}", + "7d. xtb: xtb_optimise {object, method, solvent, single_point} -> energy in Eh and kcal/mol, gap, converged; crest_conformers {object, ewin, keep} -> ensemble with populations (both need the programs installed)", "8. list_commands {text} and run_command {id} for the window's own menu commands; extensions_list and extension_command for Form extensions", "9. handoff {state: ready, note} when you are done; state question when you need the person's input", ] @@ -428,6 +438,9 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = "conformer": {"type": "string", "description": "Conformer id, or all; default all for sdf, else the shown one"}, "output": {"type": "string", "description": "Absolute path of a new file to write; left out, the text comes back"}}), ] +AGENT_MODULES = (agent_db, agent_notebook, agent_library, agent_helm, agent_xtb) +for _module in AGENT_MODULES: + TOOLS += _module.TOOLS NAMES = {t["name"] for t in TOOLS} MUTATING = {"run_command", "extension_command", "perceive_reactions", "map_reaction", "new_document", "open_document", "save_document", "close_document", "draw_from_smiles", "draw_from_molfile", "draw_from_name", "add_atom", "add_bond", "set_charge", "set_atom", "set_stereo", "replace_substructure", @@ -452,7 +465,14 @@ def _clip(s: str, n: int) -> str: return s if len(s) <= n else s[: n - 1] + "…" +def _module_of(name: str): + return next((m for m in AGENT_MODULES if name in m.NAMES), None) + + def _mutating(name: str, args: dict) -> bool: + module = _module_of(name) + if module is not None: + return module.mutating(name, args) if name in MUTATING: return True if name == "handoff": @@ -1907,6 +1927,9 @@ async def _dispatch(a: Agent, name: str, args: dict) -> dict: if refused: return {**_fail(refused), "_refused": True} try: + module = _module_of(name) + if module is not None: + return await module.call(name, args, a.name) return await HANDLERS[name](a, args) except ToolError as exc: return _fail(str(exc)) diff --git a/backend/app/routers/notebook.py b/backend/app/routers/notebook.py new file mode 100644 index 00000000..2dc17e2a --- /dev/null +++ b/backend/app/routers/notebook.py @@ -0,0 +1,115 @@ +import asyncio +from urllib.parse import quote + +from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response +from starlette.datastructures import UploadFile + +from app.core import window_key +from app.services import package +from app.services.database import store +from app.services.database.store import DatabaseError +from app.services.notebook import attachments, entries, export, scheme + +router = APIRouter() +BASE = "/api/databases/{db}/entries" +ENTRY = BASE + "/{uid}" + + +def _guard(request: Request) -> None: + window_key.require(request) + + +GUARD = [Depends(_guard)] + + +def _db(handle: str) -> store.Database: + try: + return store.get(handle) + except DatabaseError as exc: + raise HTTPException(exc.status, str(exc)) + + +def _run(fn, *args, **kwargs): + try: + return fn(*args, **kwargs) + except DatabaseError as exc: + raise HTTPException(exc.status, str(exc)) + + +def _download(name: str, mime: str, data: bytes) -> Response: + plain = name.encode("ascii", "replace").decode("ascii").replace('"', "") + headers = {"content-disposition": f"attachment; filename=\"{plain}\"; filename*=UTF-8''{quote(name)}", "x-formchem-filename": quote(name), + "access-control-expose-headers": "x-formchem-filename, content-disposition", "x-content-type-options": "nosniff", "cache-control": "no-store"} + return Response(data, media_type=f"{mime}; charset=utf-8" if mime.startswith(("text/", "application/json")) else mime, headers=headers) + + +@router.get(BASE, dependencies=GUARD) +def list_entries(db: str, q: str | None = None, substructure: str | None = None, offset: int = 0, limit: int = 100) -> dict: + return _run(entries.listing, _db(db), q, substructure, offset, limit) + + +@router.post(BASE, dependencies=GUARD) +def create_entry(db: str, body: dict = Body(...)) -> dict: + return _run(entries.create, _db(db), body.get("title"), body.get("template"), body.get("author"), body.get("date")) + + +@router.get(ENTRY, dependencies=GUARD) +def get_entry(db: str, uid: str) -> dict: + return _run(entries.get, _db(db), uid) + + +@router.patch(ENTRY, dependencies=GUARD) +def update_entry(db: str, uid: str, body: dict = Body(...)) -> dict: + return _run(entries.update, _db(db), uid, body) + + +@router.post(ENTRY + "/sign", dependencies=GUARD) +def sign_entry(db: str, uid: str, body: dict = Body(...)) -> dict: + return _run(entries.sign, _db(db), uid, body.get("by")) + + +@router.get(ENTRY + "/versions/{version_id}", dependencies=GUARD) +def entry_version(db: str, uid: str, version_id: int) -> dict: + return _run(entries.version, _db(db), uid, version_id) + + +@router.post(ENTRY + "/attachments", dependencies=GUARD) +async def attach(db: str, uid: str, request: Request) -> dict: + d = _db(db) + kind = request.headers.get("content-type", "") + if kind.startswith("multipart/"): + form = await request.form() + found = [v for v in form.getlist("file") if isinstance(v, UploadFile)] + if not found: + raise HTTPException(400, "Send the file as a multipart field named file.") + upload = found[0] + data = await upload.read(attachments.STORED_LIMIT + 1) + return await asyncio.to_thread(_run, attachments.add_bytes, d, uid, upload.filename or "Attachment", data, upload.content_type) + try: + body = await request.json() + except ValueError: + raise HTTPException(400, "Send a file, or {path, link: true} to link a file by its path.") + if not isinstance(body, dict) or not body.get("link"): + raise HTTPException(400, "Send a file, or {path, link: true} to link a file by its path.") + return await asyncio.to_thread(_run, attachments.add_link, d, uid, body.get("path")) + + +@router.post(ENTRY + "/export", dependencies=GUARD) +def export_entry(db: str, uid: str, body: dict = Body(...)) -> dict: + path = body.get("path") + return _run(export.export, _db(db), uid, str(body.get("format") or ""), path if isinstance(path, str) and path.strip() else None, body.get("picture")) + + +@router.post(ENTRY + "/export/download", dependencies=GUARD) +def download_entry_with_picture(db: str, uid: str, body: dict = Body(...)) -> Response: + name, mime, data = _run(export.render, _db(db), uid, str(body.get("format") or ""), body.get("picture")) + return _download(name, mime, data) + + +@router.get(ENTRY + "/scheme.fchem", dependencies=GUARD) +def scheme_package(db: str, uid: str) -> Response: + entry = _run(entries.get, _db(db), uid, False) + if not entry.get("scheme"): + raise HTTPException(404, f"Entry {entry['number']} has no scheme yet.") + name = f"Entry {entry['number']} scheme" + return _download(f"{name}{package.EXT}", package.MIMETYPE, scheme.fchem(entry["scheme"], name)) diff --git a/backend/app/routers/structures.py b/backend/app/routers/structures.py new file mode 100644 index 00000000..58eaf113 --- /dev/null +++ b/backend/app/routers/structures.py @@ -0,0 +1,115 @@ +import asyncio + +from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response + +from app.core import agent_token, window_key +from app.services import file_watch +from app.services import live_structures as lib + +router = APIRouter() + + +def _guard(request: Request) -> None: + if not (window_key.valid(request.headers.get(window_key.HEADER)) or agent_token.valid(request.headers.get("authorization"))): + raise HTTPException(403, window_key.REFUSED) + + +GUARD = [Depends(_guard)] + + +def _failed(exc: Exception) -> HTTPException: + return HTTPException(getattr(exc, "status", 400), str(exc)) + + +async def _run(fn, *args, **kwargs): + try: + return await asyncio.to_thread(fn, *args, **kwargs) + except lib.LibraryError as exc: + raise _failed(exc) from None + + +@router.get("/api/structures", dependencies=GUARD) +async def list_structures(kind: str | None = None) -> dict: + file_watch.ensure_started() + return await _run(lib.listing, kind) + + +@router.post("/api/structures", dependencies=GUARD) +async def add_structure(body: dict = Body(...)) -> dict: + return await _run(lib.add, body.get("source"), body.get("name"), body.get("kinds", ["favourite"]), body.get("svg"), body.get("png"), + body.get("width"), body.get("height"), body.get("tags")) + + +@router.get("/api/structures/links", dependencies=GUARD) +async def live_links() -> dict: + file_watch.ensure_started() + return {"links": lib.links()} + + +@router.post("/api/structures/open", dependencies=GUARD) +async def open_structure(body: dict = Body(...)) -> dict: + try: + return await lib.open_live(body.get("id"), body.get("object"), body.get("from")) + except lib.LibraryError as exc: + raise _failed(exc) from None + + +@router.patch("/api/structures/{item_id}", dependencies=GUARD) +async def change_structure(item_id: str, body: dict = Body(...)) -> dict: + return await _run(lib.update, item_id, body.get("name"), body.get("kinds"), body.get("tags"), body.get("used") is True) + + +@router.delete("/api/structures/{item_id}", dependencies=GUARD) +async def delete_structure(item_id: str) -> dict: + return await _run(lib.delete, item_id) + + +@router.get("/api/structures/{item_id}/object", dependencies=GUARD) +async def structure_object(item_id: str) -> dict: + return await _run(lib.live_object, item_id) + + +@router.post("/api/structures/{item_id}/save", dependencies=GUARD) +async def save_structure(item_id: str, body: dict = Body(...)) -> dict: + doc_id = body.get("doc") + link = lib.LINKS.get(doc_id) if isinstance(doc_id, str) else None + if link is None: + raise HTTPException(409, "That drawing is not open as a live structure.") + if link["id"] != item_id: + raise HTTPException(409, f"That drawing edits {link['id']}, not {item_id}.") + try: + return await lib.save_live(doc_id, body.get("svg"), body.get("png"), body.get("width"), body.get("height")) + except lib.LibraryError as exc: + raise _failed(exc) from None + + +@router.get("/api/files/watch", dependencies=GUARD) +async def watched_files() -> dict: + file_watch.ensure_started() + return {"pending": file_watch.pending(), "poll_seconds": file_watch.POLL_SECONDS} + + +@router.post("/api/files/watch/{doc_id}/{choice}", dependencies=GUARD) +async def resolve_file_change(doc_id: str, choice: str) -> dict: + file_watch.ensure_started() + if choice not in ("reload", "keep"): + raise HTTPException(404, "Choose reload or keep.") + try: + return await (file_watch.reload(doc_id) if choice == "reload" else file_watch.keep(doc_id)) + except file_watch.WatchError as exc: + raise _failed(exc) from None + + +@router.get("/api/structures/{item_id}/picture.{ext}") +async def structure_picture(item_id: str, ext: str) -> Response: + if ext not in ("svg", "png"): + raise HTTPException(404, "Pictures are svg or png.") + item = await _run(lib.get_item, item_id) + rel = item.get(ext) + if not isinstance(rel, str): + raise HTTPException(404, f"{item_id} has no {ext.upper()} picture.") + try: + data = await asyncio.to_thread(lib.item_path(rel).read_bytes) + except OSError: + raise HTTPException(404, f"{item_id} has no {ext.upper()} picture.") from None + return Response(data, media_type="image/svg+xml" if ext == "svg" else "image/png", headers={"cache-control": "no-cache"}) diff --git a/backend/app/routers/system.py b/backend/app/routers/system.py index 71998d71..b8d89e44 100644 --- a/backend/app/routers/system.py +++ b/backend/app/routers/system.py @@ -78,6 +78,12 @@ def window_ticket(request: Request) -> dict: return {"ticket": window_key.ticket()} +@router.get("/window/view-key") +def window_view_key(request: Request) -> dict: + window_key.require(request) + return {"key": window_key.VIEW, "param": window_key.VIEW_PARAM} + + @router.get("/health") def health() -> dict: return {"ok": True, "app": config.APP_NAME, "version": config.VERSION} diff --git a/backend/app/routers/xtb.py b/backend/app/routers/xtb.py new file mode 100644 index 00000000..9b65228b --- /dev/null +++ b/backend/app/routers/xtb.py @@ -0,0 +1,109 @@ +import asyncio + +from fastapi import APIRouter, Body, Depends, HTTPException, Request + +from app.core import window_key +from app.routers import three_d +from app.services.three_d import molecule, stale +from app.services.xtb import CREST_LIMIT, MAX_LIMIT, METHODS, OPT_LEVELS, XTB_LIMIT, XtbError, discovery, inputs, jobs, solvents + +router = APIRouter() +LABELS = {"optimise": "xtb optimisation", "single": "xtb single point", "crest": "CREST conformers"} + + +def _guard(request: Request) -> None: + window_key.require(request) + + +GUARD = [Depends(_guard)] + + +def _failed(exc: XtbError) -> HTTPException: + return HTTPException(exc.status, str(exc)) + + +def _status(fresh: bool = False) -> dict: + return {**discovery.status(fresh), "settings": discovery.settings(), "solvents": solvents.listing(), + "methods": [{"id": k, "label": v} for k, v in METHODS.items()], "levels": list(OPT_LEVELS), + "limits": {"xtb": XTB_LIMIT, "crest": CREST_LIMIT, "max": MAX_LIMIT}} + + +@router.get("/api/xtb/status", dependencies=GUARD) +async def xtb_status(fresh: bool = False) -> dict: + return await asyncio.to_thread(_status, fresh) + + +@router.post("/api/xtb/settings", dependencies=GUARD) +async def xtb_settings(body: dict = Body(...)) -> dict: + try: + await asyncio.to_thread(discovery.save, body) + except ValueError as exc: + raise HTTPException(422, str(exc)) + return await asyncio.to_thread(_status, True) + + +def _applier(doc_id: str, kind: str, fid: str, signature: tuple, body: dict, rev: int): + async def apply(records: list[dict], active: str | None) -> dict: + try: + done = await three_d.commit(doc_id, LABELS[kind], three_d._replace_ops(fid, records, active), body, rev, (fid, signature)) + except HTTPException as exc: + detail = exc.detail.get("message") if isinstance(exc.detail, dict) else exc.detail + raise XtbError(str(detail), exc.status_code) + return {"changed": done["changed"], "rev": done["rev"]} + return apply + + +async def start_job(doc_id: str, kind: str, body: dict) -> dict: + s, doc = three_d._snapshot(doc_id) + frag = three_d._fragment(doc, body.get("object")) + scope = body.get("scope") or ("all" if kind == "single" else "shown") + if scope not in ("shown", "all"): + raise HTTPException(422, "scope must be shown or all") + cid = body.get("conformer") if isinstance(body.get("conformer"), str) else None + try: + found = await asyncio.to_thread(discovery.usable, jobs.KINDS[kind]) + start = await asyncio.to_thread(inputs.start, frag, molecule.expansions_of(doc), "shown" if kind == "crest" else scope, cid) + opts = jobs.options(kind, body, start) + except XtbError as exc: + raise _failed(exc) + agent = three_d._agent(body) + job = jobs.submit(kind, doc_id, frag["id"], start, opts, found, _applier(doc_id, kind, frag["id"], stale.signature(frag), body, s.rev), agent) + if body.get("wait") is True: + await jobs.wait(job) + return job.public() + + +@router.post("/api/documents/{doc_id}/xtb/optimise", dependencies=GUARD) +async def xtb_optimise(doc_id: str, body: dict = Body(...)) -> dict: + return await start_job(doc_id, "optimise", body) + + +@router.post("/api/documents/{doc_id}/xtb/single", dependencies=GUARD) +async def xtb_single(doc_id: str, body: dict = Body(...)) -> dict: + return await start_job(doc_id, "single", body) + + +@router.post("/api/documents/{doc_id}/xtb/crest", dependencies=GUARD) +async def xtb_crest(doc_id: str, body: dict = Body(...)) -> dict: + return await start_job(doc_id, "crest", body) + + +@router.get("/api/xtb/jobs", dependencies=GUARD) +def xtb_jobs() -> dict: + return {"jobs": jobs.listing()} + + +@router.get("/api/xtb/jobs/{job_id}", dependencies=GUARD) +def xtb_job(job_id: str) -> dict: + try: + return jobs.get(job_id).public() + except XtbError as exc: + raise _failed(exc) + + +@router.post("/api/xtb/jobs/{job_id}/cancel", dependencies=GUARD) +def xtb_cancel(job_id: str) -> dict: + try: + return jobs.cancel(job_id).public() + except XtbError as exc: + raise _failed(exc) diff --git a/backend/app/services/agent_db.py b/backend/app/services/agent_db.py new file mode 100644 index 00000000..2aa65966 --- /dev/null +++ b/backend/app/services/agent_db.py @@ -0,0 +1,333 @@ +import asyncio + +ROWS_DEFAULT = 20 +ROWS_MAX = 100 +WAIT_DEFAULT = 60.0 +WAIT_MAX = 600.0 +REPORT_LINES = 10 + + +class ToolError(Exception): + pass + + +def _tool(name: str, description: str, props: dict, required: list[str] | None = None, read: bool = False, destructive: bool = False) -> dict: + return {"name": name, "description": description, "inputSchema": {"type": "object", "properties": props, "required": required or []}, + "annotations": {"readOnlyHint": read, "destructiveHint": destructive, "openWorldHint": False}} + + +_S = {"type": "string"} +_DB = {"type": "string", "description": "Database handle (g plus 8 characters) from db_list, db_create or db_open; may be left out when one database is open"} +_STRUCTURE = {"type": "object", "description": "{smiles} or {molfile}; for a substructure term also {smarts}", + "properties": {"smiles": _S, "molfile": _S, "smarts": _S}} +_VALUES = {"type": "object", "description": "Field values by field name (see the fields of db_list or db_open), for example {\"mp\": 121.5, \"supplier\": \"Acme\"}"} +_QUERY = {"type": "object", "description": "A query node of docs/DATABASE.md: a term {kind, ...} with kind exact, substructure, similarity, formula, mass, text, number, date, " + "choice, empty or hitlist, or a group {op: and | or | not, terms: [...]}"} + +TOOLS = [ + _tool("db_list", "The structure databases open in FormChem (handle, title, path, record count, read-only or not, fields) and the databases FormChem knows from earlier " + "(path, name, count, whether the file still exists). Open one with db_open, make one with db_create.", {}, read=True), + _tool("db_create", "Makes a new FormChem structure database (.fcdb, one SQLite file) and opens it. Without path it goes to the Databases folder of FormChem's data folder. " + "Answers with its handle and info.", {"title": _S, "path": {"type": "string", "description": "Absolute path of the new .fcdb file (optional)"}}, ["title"]), + _tool("db_open", "Opens a FormChem database file (.fcdb) and answers with its handle, title, record count, fields and whether it opened read-only " + "(it does when another FormChem holds it).", {"path": {"type": "string", "description": "Absolute path of the .fcdb file"}}, ["path"]), + _tool("db_import", "Imports structures from an SD, RD, SMILES, CSV or TSV (SMILES or InChI column) or .fchem file into a database as a job, and waits up to wait seconds " + "(default 60) for it. Bad records never stop the import: the answer lists each failed record number and reason. dry_run counts what would be added, updated and failed " + "without writing. mode new or append adds every good record; merge updates records that match on key (structure, or a field name) and adds the rest.", + {"db": _DB, "path": {"type": "string", "description": "Absolute path of the file to import"}, "format": {"type": "string", "enum": ["sdf", "rdf", "smiles", "csv", "tsv", "fchem"]}, + "mode": {"type": "string", "enum": ["new", "append", "merge"]}, "key": {"type": "string", "description": "Merge key: structure (default) or a field name"}, + "mapping": {"type": "object", "description": "Source column or SD tag to field name, \"\" to skip, or \"+Label\" to make a new field; left out, the detected mapping is used"}, + "dry_run": {"type": "boolean"}, "wait": {"type": "number", "description": "Seconds to wait for the job (0 to 600, default 60); a job still running is reported with its id"}}, + ["path"]), + _tool("db_search", "Searches a database and answers with the hit list (id, name, count, took_ms, methods) and its first rows (uid, number, SMILES, formula, mw, field values, " + "and score for similarity). Give smiles with mode (substructure, the default, similarity with threshold 0 to 1, or exact), or a full query node. within limits the " + "search to an earlier hit list. Every search becomes a hit list the person sees in the window.", + {"db": _DB, "smiles": {"type": "string", "description": "Structure to search with (or a SMARTS with mode substructure and smarts true)"}, + "smarts": {"type": "boolean", "description": "Read smiles as SMARTS (substructure only)"}, + "mode": {"type": "string", "enum": ["substructure", "similarity", "exact"]}, "threshold": {"type": "number", "description": "Similarity threshold, 0 to 1 (default 0.7)"}, + "query": _QUERY, "within": {"type": "integer", "description": "Hit list id to search within"}, "name": {"type": "string", "description": "Name for the hit list"}, + "limit": {"type": "integer", "description": "Rows to return (default 20, at most 100); the hit list holds them all"}}, read=True), + _tool("db_get_record", "One record of a database by uid: number, batch, SMILES, InChIKey, formula, masses, molfile, field values and attachments.", + {"db": _DB, "uid": {"type": "string", "description": "Record uid (c plus 10 characters)"}}, ["uid"], read=True), + _tool("db_add_record", "Registers a structure in a database with optional field values. When the structure is already there (by the database's duplicate rules) and " + "on_duplicate is not given, nothing is added and the answer lists the duplicates: call again with on_duplicate existing (use the existing record), batch (a new batch " + "of it) or new (register anyway).", + {"db": _DB, "smiles": _S, "molfile": _S, "values": _VALUES, "on_duplicate": {"type": "string", "enum": ["ask", "existing", "batch", "new"]}}), + _tool("db_update_record", "Changes a record's structure, field values or both; computed fields follow the new structure.", + {"db": _DB, "uid": {"type": "string", "description": "Record uid"}, "smiles": _S, "molfile": _S, "values": _VALUES}, ["uid"]), + _tool("db_export", "Writes records to an SD file (V2000, or V3000 when asked; every scalar field as a data item), a SMILES file or CSV: a hit list, a list of uids or the " + "whole database. Without path the file goes to FormChem's export folder and the answer gives its path.", + {"db": _DB, "format": {"type": "string", "enum": ["sdf", "smiles", "csv"]}, "path": {"type": "string", "description": "Absolute path of the file to write (optional)"}, + "hitlist": {"type": "integer"}, "uids": {"type": "array", "items": _S}, "fields": {"type": "array", "items": _S, "description": "Field names to include (default all)"}, + "v3000": {"type": "boolean"}, "structure_as": {"type": "string", "enum": ["smiles", "inchi"], "description": "Structure column of a CSV"}}, ["format"]), +] +NAMES = frozenset(t["name"] for t in TOOLS) +MUTATING = frozenset({"db_create", "db_open", "db_add_record", "db_update_record"}) + + +def mutating(name: str, args: dict) -> bool: + if name in MUTATING: + return True + if name == "db_import": + return args.get("dry_run") is not True + if name == "db_export": + path = args.get("path") + if not isinstance(path, str) or not path.strip(): + return False + from app.services import agent_convert + return not agent_convert.in_temp(path.strip()) + return False + + +def _ok(text: str, data: dict | None = None) -> dict: + out = {"content": [{"type": "text", "text": text}]} + if data is not None: + out["structuredContent"] = data + return out + + +def _fail(text: str) -> dict: + return {"content": [{"type": "text", "text": text}], "isError": True} + + +def _clip(s, n: int) -> str: + s = " ".join(str(s).split()) + return s if len(s) <= n else s[: n - 1] + "..." + + +def _db(args: dict): + from app.services.database import store + wanted = str(args.get("db") or "").strip() + if wanted: + for d in store.all_open(): + if d.handle == wanted or str(d.path) == wanted: + return d + raise ToolError(f"No open database has the handle {_clip(wanted, 40)}. db_list gives the open ones; db_open {{path}} opens a file.") + found = store.all_open() + if len(found) == 1: + return found[0] + if not found: + raise ToolError("No database is open. db_open {path} opens one; db_create {title} makes one.") + raise ToolError("Several databases are open; give db, a handle from db_list.") + + +def _structure(args: dict, required: bool = True) -> dict | None: + if isinstance(args.get("molfile"), str) and args["molfile"].strip(): + return {"molfile": args["molfile"]} + if isinstance(args.get("smiles"), str) and args["smiles"].strip(): + return {"smiles": args["smiles"].strip()} + if required: + raise ToolError("Give smiles or molfile.") + return None + + +def _info_line(i: dict) -> str: + ro = f" read-only ({i.get('readonly_reason') or 'held elsewhere'})" if i.get("readonly") else "" + fields = ", ".join(f"{f['name']} ({f['type']})" for f in i.get("fields") or []) or "no fields" + return f"{i['db']} \"{_clip(i.get('title') or '', 60)}\": {i.get('count', 0)} records, {fields}; {i.get('path')}{ro}" + + +def _row_line(r: dict) -> str: + score = f" score {r['score']:.3f}" if isinstance(r.get("score"), (int, float)) else "" + vals = "; ".join(f"{k} {_clip(v, 30)}" for k, v in (r.get("values") or {}).items() if v not in (None, "", [])) + return f"- {r['uid']} #{r['number']}" + (f".{r['batch']}" if (r.get("batch") or 1) > 1 else "") + f" {r.get('formula') or ''} {_clip(r.get('smiles') or '', 80)}{score}" + (f" [{vals}]" if vals else "") + + +def db_list(args: dict, agent: str) -> dict: + from app.services.database import info, store + opened = [info.describe(d) for d in store.all_open()] + known = info.known() + lines = [_info_line(i) for i in opened] or ["No database is open."] + paths = {i["path"] for i in opened} + rest = [k for k in known if k.get("path") not in paths] + if rest: + lines.append("Known: " + "; ".join(f"{_clip(k.get('name') or '', 40)} ({k.get('count') if k.get('count') is not None else '?'} records) {k.get('path')}" + + ("" if k.get("exists", True) else " (missing)") for k in rest[:20])) + return _ok("\n".join(lines), {"open": opened, "known": known}) + + +def db_create(args: dict, agent: str) -> dict: + from app.services.database import info + title = str(args.get("title") or "").strip() + if not title: + raise ToolError("Give title, the database's name.") + path = str(args.get("path") or "").strip() or None + d = info.create_database(title, path) + i = info.describe(d) + return _ok(f"Created and opened {_info_line(i)}", i) + + +def db_open(args: dict, agent: str) -> dict: + from app.services.database import info + path = str(args.get("path") or "").strip() + if not path: + raise ToolError("Give path, the absolute path of a .fcdb file.") + i = info.describe(info.open_database(path)) + return _ok(f"Opened {_info_line(i)}", i) + + +def _job_text(j: dict) -> str: + head = (f"Import job {j['job']} {j['state']}{' (dry run)' if j.get('dry_run') else ''}: read {j.get('read', 0)}, " + f"{'would add' if j.get('dry_run') else 'added'} {j.get('added', 0)}, updated {j.get('updated', 0)}, failed {j.get('failed', 0)}") + if j.get("seconds") is not None: + head += f" in {j['seconds']} s" + lines = [head + "."] + for item in (j.get("report") or [])[:REPORT_LINES]: + lines.append(f"- record {item.get('record')}: {_clip(item.get('reason'), 160)}") + more = (j.get("failed") or 0) - min(len(j.get("report") or []), REPORT_LINES) + if more > 0: + lines.append(f"- and {more} more in the job's report") + if j.get("error"): + lines.append(f"Error: {_clip(j['error'], 300)}") + if j["state"] == "running": + lines.append("Still running; the person sees its progress in the window.") + return "\n".join(lines) + + +def db_import(args: dict, agent: str) -> dict: + from app.services.database import imports + d = _db(args) + path = str(args.get("path") or "").strip() + if not path: + raise ToolError("Give path, the absolute path of the file to import.") + mapping = args.get("mapping") + if mapping is not None and not isinstance(mapping, dict): + raise ToolError("mapping is an object of source column to field name.") + if mapping is None: + mapping = imports.preview(d, path, args.get("format") or None).get("mapping") + wait = args.get("wait") + wait = WAIT_DEFAULT if not isinstance(wait, (int, float)) or isinstance(wait, bool) else max(0.0, min(WAIT_MAX, float(wait))) + j = imports.start(d, path, args.get("format") or None, str(args.get("mode") or "new"), args.get("key") or None, mapping, + args.get("dry_run") is True, actor=f"agent:{agent}") + if wait > 0: + j = imports.wait(j["job"], wait) + return _ok(_job_text(j), j) + + +def _query(args: dict) -> dict: + q = args.get("query") + if isinstance(q, dict): + return q + s = args.get("smiles") + if not isinstance(s, str) or not s.strip(): + raise ToolError("Give smiles (with mode) or query.") + mode = str(args.get("mode") or "substructure") + if mode not in ("substructure", "similarity", "exact"): + raise ToolError("mode is substructure, similarity or exact.") + if args.get("smarts") is True: + if mode != "substructure": + raise ToolError("smarts works only with mode substructure.") + return {"kind": "substructure", "structure": {"smarts": s.strip()}} + term = {"kind": mode, "structure": {"smiles": s.strip()}} + if mode == "similarity" and args.get("threshold") is not None: + term["threshold"] = args["threshold"] + return term + + +def db_search(args: dict, agent: str) -> dict: + from app.services.database import records, search + d = _db(args) + within = args.get("within") + if within is not None and (isinstance(within, bool) or not str(within).strip().isdigit()): + raise ToolError("within is a hit list id.") + limit = args.get("limit") + limit = ROWS_DEFAULT if not isinstance(limit, int) or isinstance(limit, bool) else max(0, min(ROWS_MAX, limit)) + name = args.get("name") if isinstance(args.get("name"), str) and args.get("name").strip() else None + result = search.run(d, _query(args), int(within) if within is not None else None, name, actor=f"agent:{agent}") + ids, scores = search.hitlist_ids(d, result["id"])[:limit], None + if result.get("scored") and ids: + with d.lock: + scores = {r[0]: r[1] for r in d.conn.execute(f"SELECT compound, score FROM hitlist_items WHERE hitlist = ? AND compound IN ({','.join('?' * len(ids))})", + [result["id"], *ids]).fetchall()} + rows = records.rows(d, ids, scores) if ids else [] + methods = "; ".join(f"{k}: {v}" for k, v in (result.get("methods") or {}).items()) + head = (f"Hit list {result['id']} \"{_clip(result['name'], 80)}\": {result['count']} record{'' if result['count'] == 1 else 's'} in {result['took_ms']} ms" + + (f", {result['screened']} screened" if result.get("screened") is not None else "") + "." + + (f" Methods: {methods}." if methods else "")) + tail = f"\nShowing {len(rows)} of {result['count']}; db_export {{hitlist: {result['id']}}} writes them all." if result["count"] > len(rows) else "" + return _ok("\n".join([head, *[_row_line(r) for r in rows]]) + tail, {**result, "rows": rows}) + + +def db_get_record(args: dict, agent: str) -> dict: + from app.services.database import records + d = _db(args) + uid = str(args.get("uid") or "").strip() + if not uid: + raise ToolError("Give uid, a record uid from db_search.") + r = records.get(d, uid) + atts = ", ".join(f"{a.get('name')} ({a.get('size') or 0} bytes)" for a in r.get("attachments") or []) + text = (_row_line(r)[2:] + f"\nInChIKey {r.get('inchikey') or 'none'}, MW {r.get('mw')}, exact mass {r.get('exact_mass')}" + + (f"\nAttachments: {atts}" if atts else "") + f"\nMolfile: {len((r.get('molfile') or '').splitlines())} lines in structuredContent.") + return _ok(text, r) + + +def db_add_record(args: dict, agent: str) -> dict: + from app.services.database import records + d = _db(args) + values = args.get("values") + if values is not None and not isinstance(values, dict): + raise ToolError("values is an object of field name to value.") + on_dup = args.get("on_duplicate") or None + try: + r = records.add(d, _structure(args), values, on_dup, actor=f"agent:{agent}") + except records.DuplicateError as exc: + found = "\n".join(_row_line(x) for x in exc.duplicates[:10]) + refused = _fail(f"This structure is already registered; nothing was added:\n{found}\nCall db_add_record again with on_duplicate existing (use that record), " + "batch (a new batch of it) or new (register anyway).") + return {**refused, "structuredContent": {"detail": str(exc), "duplicates": exc.duplicates}} + return _ok(f"Registered as {_row_line(r)[2:]}", r) + + +def db_update_record(args: dict, agent: str) -> dict: + from app.services.database import records + d = _db(args) + uid = str(args.get("uid") or "").strip() + if not uid: + raise ToolError("Give uid, the record to change.") + values = args.get("values") + if values is not None and not isinstance(values, dict): + raise ToolError("values is an object of field name to value.") + structure = _structure(args, required=False) + if structure is None and not values: + raise ToolError("Give smiles, molfile or values to change.") + r = records.update(d, uid, structure, values, actor=f"agent:{agent}") + return _ok(f"Updated {_row_line(r)[2:]}", r) + + +def db_export(args: dict, agent: str) -> dict: + from app.services.database import exports + d = _db(args) + fmt = str(args.get("format") or "").strip() + uids = args.get("uids") + if uids is not None and (not isinstance(uids, list) or not all(isinstance(u, str) for u in uids)): + raise ToolError("uids is a list of record uids.") + fields = args.get("fields") + if fields is not None and (not isinstance(fields, list) or not all(isinstance(f, str) for f in fields)): + raise ToolError("fields is a list of field names.") + hitlist = args.get("hitlist") + out = exports.export(d, fmt, str(args.get("path") or "").strip() or None, int(hitlist) if isinstance(hitlist, int) and not isinstance(hitlist, bool) else None, + uids, fields, args.get("v3000") is True, str(args.get("structure_as") or "smiles"), actor=f"agent:{agent}") + out = {k: v for k, v in out.items() if k != "url"} + skipped = f", {out.get('skipped')} skipped" if out.get("skipped") else "" + return _ok(f"Wrote {out.get('written', 0)} records to {out.get('path')}{skipped}.", out) + + +HANDLERS = {"db_list": db_list, "db_create": db_create, "db_open": db_open, "db_import": db_import, "db_search": db_search, + "db_get_record": db_get_record, "db_add_record": db_add_record, "db_update_record": db_update_record, "db_export": db_export} + + +async def call(name: str, args: dict, agent_name: str) -> dict: + from app.services.database.store import DatabaseError + fn = HANDLERS.get(name) + if fn is None: + return _fail(f"There is no database tool {name}.") + try: + return await asyncio.to_thread(fn, args if isinstance(args, dict) else {}, agent_name or "agent") + except ToolError as exc: + return _fail(str(exc)) + except DatabaseError as exc: + return _fail(str(exc)) + except (ValueError, TypeError, KeyError) as exc: + return _fail(f"{name}: bad arguments ({type(exc).__name__}: {_clip(exc, 200)}).") + except Exception as exc: + return _fail(f"{name} failed: {type(exc).__name__}: {_clip(exc, 300)}") diff --git a/backend/app/services/agent_helm.py b/backend/app/services/agent_helm.py new file mode 100644 index 00000000..7d5ddba4 --- /dev/null +++ b/backend/app/services/agent_helm.py @@ -0,0 +1,83 @@ +import asyncio + +from app.services import helm +from app.services.chem import DEFAULT_BOND_LENGTH + +MAX_HELM = 100_000 +TOOL = { + "name": "draw_from_helm", + "description": "Draws a peptide, nucleic acid or linker written in HELM version 2 notation in a drawing, as atoms, with FormChem's scored 2D layout, placed in free space as one undo step. " + "Reads simple polymers such as PEPTIDE1{A.G.C}, RNA1{R(A)P.R(U)} and CHEM1{[[*:1]CCO[*:2]]}, connections such as PEPTIDE1,PEPTIDE1,1:R3-6:R3 (disulfides, cyclisation) " + "and empty group and annotation sections, against FormChem's own monomer data: the 20 amino acids and their D forms ([dA] and so on), [Aib], [Nle], [Orn], [Sar], [Hyp], [pE], " + "the caps [ac] and [am], the sugars R and [dR], phosphate P and the bases A, C, G, U and T. With no drawing open it makes one. " + "Returns the new ids, SMILES, InChIKey, formula, average and monoisotopic mass with their method and version, and a picture; text it cannot read is refused with the character where reading stopped.", + "inputSchema": {"type": "object", "properties": { + "helm": {"type": "string", "description": "HELM text, such as PEPTIDE1{C.Y.I.Q.N.C.P.L.G.[am]}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$V2.0"}, + "doc": {"type": "string", "description": "Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one"}, + "x": {"type": "number", "description": "Left edge in points; left out: free space"}, + "y": {"type": "number", "description": "Top edge in points; left out: free space"}, + "name": {"type": "string", "description": "Name given to the new structure; left out, the HELM text (shortened) is used"}, + }, "required": ["helm"]}, + "annotations": {"readOnlyHint": False, "destructiveHint": False, "openWorldHint": False}, +} +LABEL = "Draw from HELM" +TOOLS = [TOOL] +NAMES = frozenset({TOOL["name"]}) + + +def mutating(name: str, args: dict) -> bool: + return name in NAMES + + +class HelmToolError(ValueError): + pass + + +def _short(text: str, n: int = 80) -> str: + one = " ".join(text.split()) + return one if len(one) <= n else one[: n - 3] + "..." + + +def prepare(args: dict) -> dict: + text = str(args.get("helm") or "").strip() + if not text: + raise HelmToolError("Give helm, such as PEPTIDE1{G.G}$$$$V2.0.") + if len(text) > MAX_HELM: + raise HelmToolError(f"HELM text is limited to {MAX_HELM:,} characters.") + found = helm.read(text, DEFAULT_BOND_LENGTH, (0.0, 0.0), True) + if not found["ok"]: + err = found["error"] or {} + pos = int(err.get("position") or 0) + near = text[max(0, pos - 12): pos + 12] + raise HelmToolError(f"Could not read the HELM at character {pos + 1} (near \"{near}\"): {err.get('text', 'not HELM')} Fix it and retry.") + return found + + +def summary(found: dict) -> str: + chains = ", ".join(f"{p['id']} ({p['monomers']} monomers)" for p in found["polymers"]) + m = found["method"] + return (f"Read {chains}" + (f" with {found['connections']} connection{'' if found['connections'] == 1 else 's'}" if found["connections"] else "") + + f" by {m['reader']} with {m['monomers']}: {found['formula']}, average mass {found['average_mass']:.2f}, monoisotopic mass {found['exact_mass']:.4f} " + + f"({m['mass']}), InChIKey {found['inchikey'] or 'none'}. " + "".join(f"Note: {w['text']} " for w in found["warnings"][:4])) + + +async def call(name: str, args: dict, agent_name: str) -> dict: + from app.routers import mcp + if name not in NAMES: + return {"content": [{"type": "text", "text": f"Unknown tool {name}."}], "isError": True} + return await t_draw_from_helm(mcp.Agent("", agent_name), args if isinstance(args, dict) else {}) + + +async def t_draw_from_helm(a, args: dict) -> dict: + from app.routers import mcp + try: + found = await asyncio.to_thread(prepare, args) + except HelmToolError as exc: + raise mcp.ToolError(str(exc)) from None + name = str(args.get("name") or "").strip()[:200] or _short(str(args.get("helm"))) + out = await mcp._draw(a, {**args, "name": name}, found["molfile"], "molfile", LABEL, "biopolymer") + if not out.get("isError"): + out["content"][0]["text"] = summary(found) + out["content"][0]["text"] + out.setdefault("structuredContent", {})["helm"] = {k: found.get(k) for k in ("helm", "smiles", "inchikey", "formula", "average_mass", "exact_mass", + "polymers", "connections", "heavy_atoms", "layout", "method", "warnings")} + return out diff --git a/backend/app/services/agent_library.py b/backend/app/services/agent_library.py new file mode 100644 index 00000000..fd7e2d4b --- /dev/null +++ b/backend/app/services/agent_library.py @@ -0,0 +1,123 @@ +import asyncio +import copy + +from app.services import live_structures as lib + +_KIND = {"type": "string", "enum": list(lib.KINDS)} + + +def _tool(name: str, description: str, props: dict, required: list[str] | None = None, read: bool = False, destructive: bool = False) -> dict: + return {"name": name, "description": description, "inputSchema": {"type": "object", "properties": props, "required": required or []}, + "annotations": {"readOnlyHint": read, "destructiveHint": destructive, "openWorldHint": False}} + + +def _ok(text: str, data: dict | None = None) -> dict: + out = {"content": [{"type": "text", "text": text}]} + if data is not None: + out["structuredContent"] = data + return out + + +def _fail(text: str) -> dict: + return {"content": [{"type": "text", "text": text}], "isError": True} + + +TOOLS = [ + _tool("library_list", "The shared structure library that every Form app reads (FORMCHEM_DATA_DIR/Library): items with id, name, kinds " + "(favourite, recent, template, live), SMILES, InChIKey, formula, average mass, rev and file paths. Filter by kind.", + {"kind": {**_KIND, "description": "Only items of this kind"}}, read=True), + _tool("library_add", "Add a structure to the shared structure library as a favourite, template, recent or live item. Give a drawing " + "(doc, optionally object ids) or a SMILES. Pictures are drawn by the engine with the FormChem drawing embedded. A structure already " + "in the library gets the new kind instead of a copy (live items are always new).", + {"doc": {"type": "string", "description": "Drawing id from list_open_documents; left out with smiles, or when one drawing is open"}, + "ids": {"type": "array", "items": {"type": "string"}, "description": "Object ids on the drawing's page to keep; default the whole first page"}, + "smiles": {"type": "string", "description": "A SMILES to add instead of a drawing"}, + "name": {"type": "string"}, + "kinds": {"type": "array", "items": _KIND, "description": "Default [\"favourite\"]"}}), + _tool("live_structure_object", "The live structure object for a library item, the JSON a sibling Form app stores in its document " + "(format formai-structure): id, rev, name, SMILES, InChIKey, the SVG picture with the FormChem drawing inside, the molfile and the size in points.", + {"id": {"type": "string", "description": "Library item id (s and 10 letters or digits)"}}, ["id"], read=True), +] +NAMES = frozenset(t["name"] for t in TOOLS) +MUTATING = frozenset({"library_add"}) + + +def mutating(name: str, args: dict) -> bool: + return name in MUTATING + + +def _page_doc(doc: dict, ids: list[str] | None) -> dict: + out = copy.deepcopy(doc) + page = out["pages"][0] if out.get("pages") else None + if page is None: + raise lib.LibraryError("The drawing has no page.", 422) + out["pages"] = [page] + if ids: + missing = [i for i in ids if i not in (out.get("objects") or {})] + if missing: + raise lib.LibraryError(f"{missing[0]} is not an object of this drawing.", 422) + page["order"] = [i for i in ids if i in page.get("order", [])] or list(ids) + page["reactions"] = [] + return out + + +def _source(args: dict) -> dict: + from app.services import model + from app.services.store import STORE + smiles = args.get("smiles") + if isinstance(smiles, str) and smiles.strip(): + from rdkit import Chem + from app.services.chem import convert + mol = Chem.MolFromSmiles(smiles.strip()) + if mol is None or not mol.GetNumAtoms(): + raise lib.LibraryError(f"Could not read the SMILES {smiles.strip()}.", 422) + doc = model.empty_document(str(args.get("name") or "Structure")) + frag = convert.from_mol(mol) + doc["objects"][frag["id"]] = frag + doc["pages"][0]["order"].append(frag["id"]) + return doc + doc_id = args.get("doc") + if not doc_id: + if len(STORE.sessions) != 1: + raise lib.LibraryError("Name the drawing with doc (see list_open_documents) or give a SMILES.", 422) + doc_id = next(iter(STORE.sessions)) + try: + s = STORE.get(str(doc_id)) + except KeyError: + raise lib.LibraryError(f"No open drawing has the id {doc_id}.", 404) from None + with s.lock: + snap = copy.deepcopy(s.doc) + ids = args.get("ids") if isinstance(args.get("ids"), list) else None + return _page_doc(snap, [str(i) for i in ids] if ids else None) + + +def _row(it: dict) -> dict: + return {k: it.get(k) for k in ("id", "name", "kinds", "kind", "smiles", "inchikey", "formula", "mw", "rev", "svg", "mol", "png", "modified")} + + +def _line(it: dict) -> str: + mw = f", {it['mw']:.3f} g/mol" if isinstance(it.get("mw"), (int, float)) else "" + return f"{it['id']} {it.get('name') or ''} [{', '.join(it.get('kinds') or [])}] {it.get('formula') or it.get('smiles') or ''}{mw} rev {it.get('rev', 1)}" + + +async def call(name: str, args: dict, agent_name: str) -> dict: + args = args if isinstance(args, dict) else {} + try: + if name == "library_list": + found = await asyncio.to_thread(lib.listing, args.get("kind") or None) + rows = [_row(it) for it in found["items"]] + head = f"{len(rows)} item{'' if len(rows) == 1 else 's'} in the structure library at {lib.folder()}" + text = head + (":\n" + "\n".join(_line(r) for r in rows[:40]) + (f"\n... and {len(rows) - 40} more" if len(rows) > 40 else "") if rows else ".") + return _ok(text, {"folder": str(lib.folder()), "items": rows, "method": "mass: FormChem mass.average_mass with RDKit"}) + if name == "library_add": + source = _source(args) + kinds = args.get("kinds") if isinstance(args.get("kinds"), list) and args.get("kinds") else ["favourite"] + item = await asyncio.to_thread(lib.add, source, args.get("name"), kinds) + return _ok(f"Added to the structure library for {agent_name or 'the agent'}: {_line(item)}. Average mass by {item.get('method')}.", {"item": _row(item)}) + if name == "live_structure_object": + obj = await asyncio.to_thread(lib.live_object, str(args.get("id") or "")) + return _ok(f"Live structure object {obj['id']} rev {obj['rev']} ({obj.get('name') or obj.get('smiles')}): {len(obj['svg']):,} characters of SVG " + f"with the drawing inside and a {len(obj['molfile'].splitlines())}-line molfile.", obj) + except lib.LibraryError as exc: + return _fail(str(exc)) + return _fail(f"Unknown tool {name}.") diff --git a/backend/app/services/agent_notebook.py b/backend/app/services/agent_notebook.py new file mode 100644 index 00000000..372ded5f --- /dev/null +++ b/backend/app/services/agent_notebook.py @@ -0,0 +1,181 @@ +import asyncio +import copy +from datetime import datetime, timezone + +SHOWN = 20 +_S = {"type": "string"} +_DB = {"type": "string", "description": "Database handle (g plus 8 characters) from db_list, db_create or db_open"} + + +def _tool(name: str, description: str, props: dict, required: list[str] | None = None, read: bool = False, destructive: bool = False) -> dict: + return {"name": name, "description": description, "inputSchema": {"type": "object", "properties": props, "required": required or []}, + "annotations": {"readOnlyHint": read, "destructiveHint": destructive, "openWorldHint": False}} + + +_PRODUCT = {"type": "object", "properties": { + "compound": {"type": "string", "description": "uid of the product's record in the database (c plus 10 characters), or leave out"}, + "name": _S, "sample": {"type": "string", "description": "Sample or batch id, for example AB-012-3"}, + "mass_g": {"type": "number"}, "yield_pct": {"type": "number"}, "purity_pct": {"type": "number"}, "notes": _S}} + +TOOLS = [ + _tool("nb_add_entry", "Add a lab notebook entry to an open FormChem database. Give a title and, as known, the template (blank, reaction, analysis, purification), " + "the experiment date (YYYY-MM-DD), author, procedure and observations in the notebook's plain markup (paragraphs separated by blank lines, '- ' bullets, " + "**bold**, *italic*), tags, products, and the scheme as reaction SMILES or RXN text (reaction) or an open drawing id (doc). " + "Answers the new entry's number and uid, its content hash and the stoichiometry computed from the scheme. The entry is open (not signed): only a person signs.", + {"db": _DB, "title": _S, "template": {"type": "string", "enum": ["blank", "reaction", "analysis", "purification"]}, + "date": {"type": "string", "description": "Experiment date YYYY-MM-DD (default today)"}, "author": _S, + "procedure": {"type": "string", "description": "Replaces the template's headings when given"}, "observations": _S, + "tags": {"type": "array", "items": _S}, "products": {"type": "array", "items": _PRODUCT}, + "reaction": {"type": "string", "description": "Reaction SMILES (A.B>>C) or RXN text for the scheme"}, + "doc": {"type": "string", "description": "Open drawing id whose first page becomes the scheme, instead of reaction"}}, + ["db", "title"]), + _tool("nb_search", "Search the lab notebook entries of an open FormChem database by text (title, procedure, observations, tags, sample ids; every word must appear) " + "and by substructure (SMILES or SMARTS matched by RDKit against every structure in each entry's scheme). Give either or both; with neither, lists the newest entries. " + f"Answers the total and up to {SHOWN} rows (number, uid, title, date, status, tags), newest first.", + {"db": _DB, "query": {"type": "string", "description": "Words to find"}, "substructure": {"type": "string", "description": "SMILES or SMARTS"}, + "limit": {"type": "integer", "minimum": 1, "maximum": 200, "description": f"Rows to return (default {SHOWN})"}}, + ["db"], read=True), +] +MUTATING = frozenset({"nb_add_entry"}) +NAMES = frozenset(t["name"] for t in TOOLS) + + +def mutating(name: str, args: dict) -> bool: + return name in MUTATING + + +def _ok(text: str, data: dict | None = None) -> dict: + out = {"content": [{"type": "text", "text": text}]} + if data is not None: + out["structuredContent"] = data + return out + + +def _fail(text: str) -> dict: + return {"content": [{"type": "text", "text": text}], "isError": True} + + +class _Refused(Exception): + pass + + +def _date(value: object) -> float | None: + if value in (None, ""): + return None + if not isinstance(value, str): + raise _Refused("date is YYYY-MM-DD.") + try: + d = datetime.strptime(value.strip()[:10], "%Y-%m-%d").replace(tzinfo=timezone.utc) + except ValueError: + raise _Refused(f"date {value!r} is not YYYY-MM-DD.") from None + return d.timestamp() + + +def _day(t: float | None) -> str: + return datetime.fromtimestamp(t, timezone.utc).strftime("%Y-%m-%d") if t else "no date" + + +def _scheme(args: dict, title: str) -> dict | None: + from app.services.notebook import scheme + reaction, doc_id = args.get("reaction"), args.get("doc") + if reaction and doc_id: + raise _Refused("Give the scheme as reaction or as doc, not both.") + try: + if isinstance(reaction, str) and reaction.strip(): + return scheme.from_reaction(reaction.strip(), title) + if isinstance(doc_id, str) and doc_id.strip(): + from app.services.store import STORE + try: + snap = STORE.snapshot(doc_id.strip()) + except KeyError: + raise _Refused(f"No open drawing has the id {doc_id}; list_open_documents names them.") from None + return scheme.one_page(copy.deepcopy(snap["doc"])) + except scheme.SchemeError as exc: + raise _Refused(str(exc)) from None + return None + + +def _add(args: dict, actor: str) -> dict: + from app.services.database import store + from app.services.notebook import entries + from app.services.notebook import products + db = store.get(str(args.get("db") or "")) + title = str(args.get("title") or "") + try: + prods = products.normalise(args.get("products")) + with db.lock: + products.resolve(db.conn, prods) + except products.ProductError as exc: + raise _Refused(str(exc)) from None + doc = _scheme(args, title or "Scheme") + entry = entries.create(db, title, args.get("template"), args.get("author"), _date(args.get("date")), actor=actor) + patch = {k: args[k] for k in ("procedure", "observations", "tags", "products") if args.get(k) is not None} + if doc is not None: + patch["scheme"] = doc + if patch: + entry = entries.update(db, entry["uid"], patch, actor=actor) + return entry + + +def _stoich_lines(st: dict | None) -> list[str]: + lines = [] + for step in (st or {}).get("steps") or []: + for r in step.get("rows") or []: + role = {"agent": "reagent"}.get(r.get("role"), r.get("role")) + mw = f"MW {r['mw']:g}" if r.get("mw") else "no MW" + label = r.get("label") or "?" + formula = r.get("formula") + name = label if not formula or formula == label else f"{label} ({formula})" + lines.append(f" {name}, {role}, {mw}{', limiting' if r.get('limiting') else ''}") + if lines: + lines.append(f" [{st['method']}]") + return lines + + +async def _nb_add_entry(args: dict, agent_name: str) -> dict: + entry = await asyncio.to_thread(_add, args, f"agent:{agent_name}") + head = f"Added notebook entry {entry['number']} ({entry['uid']}): {entry['title']}, {_day(entry['date'])}, status open, hash {entry['hash'][:12]}." + lines = [head] + st = entry.get("stoichiometry") + if st and st.get("steps"): + lines.append("Stoichiometry from the scheme:") + lines += _stoich_lines(st) + elif entry.get("scheme") is None: + lines.append("No scheme was given.") + data = {k: entry[k] for k in ("uid", "number", "title", "author", "date", "status", "tags", "hash", "template", "products")} + data["stoichiometry"] = st + return _ok("\n".join(lines), data) + + +async def _nb_search(args: dict, agent_name: str) -> dict: + from app.services.database import store + from app.services.notebook import entries + db = store.get(str(args.get("db") or "")) + limit = args.get("limit") if isinstance(args.get("limit"), int) and not isinstance(args.get("limit"), bool) else SHOWN + limit = max(1, min(limit, 200)) + q = args.get("query") if isinstance(args.get("query"), str) else None + sub = args.get("substructure") if isinstance(args.get("substructure"), str) else None + found = await asyncio.to_thread(entries.listing, db, q, sub, 0, limit) + what = " and ".join(x for x in ((f"text {q!r}" if q and q.strip() else ""), (f"substructure {sub}" if sub and sub.strip() else "")) if x) or "all entries" + lines = [f"{found['total']} notebook entr{'y matches' if found['total'] == 1 else 'ies match'} {what}" + (f"; showing {len(found['rows'])}." if found["total"] > len(found["rows"]) else ".")] + for r in found["rows"]: + tags = f" [{', '.join(r['tags'])}]" if r["tags"] else "" + lines.append(f" {r['number']}. {r['title']} ({r['uid']}), {_day(r['date'])}, {r['status']}{tags}") + if found.get("method"): + lines.append(f"[{found['method']}]") + return _ok("\n".join(lines), found) + + +async def call(name: str, args: dict, agent_name: str) -> dict: + from app.services.database.store import DatabaseError + if name not in NAMES: + return _fail(f"There is no notebook tool named {name}.") + args = args if isinstance(args, dict) else {} + try: + if name == "nb_add_entry": + return await _nb_add_entry(args, agent_name) + return await _nb_search(args, agent_name) + except DatabaseError as exc: + return _fail(str(exc)) + except _Refused as exc: + return _fail(str(exc)) diff --git a/backend/app/services/agent_xtb.py b/backend/app/services/agent_xtb.py new file mode 100644 index 00000000..8b6a739f --- /dev/null +++ b/backend/app/services/agent_xtb.py @@ -0,0 +1,114 @@ +from fastapi import HTTPException + +from app.services.xtb import CREST_LIMIT, MAX_LIMIT, OPT_LEVELS, XTB_LIMIT, solvents + +_DOC = {"type": "string", "description": "Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one"} +_FRAG = {"type": "string", "description": "Fragment id (or a 3D object bound to one); may be left out when the drawing has one structure"} +_METHOD = {"type": "string", "enum": ["gfn2", "gfnff"], "description": "gfn2 (GFN2-xTB, default) or gfnff (GFN-FF force field)"} +_CHARGE = {"type": "integer", "description": "Total charge; default the sum of the drawn formal charges"} +_UHF = {"type": "integer", "description": "Unpaired electrons; default the drawn radicals"} +_SOLVENT = {"type": "string", "enum": ["none", *[k for k, _ in solvents.ALPB]], "description": "Implicit solvent (ALPB); default none, the gas phase"} +_LIMIT = {"type": "number", "description": f"Time limit in seconds (default {XTB_LIMIT} for xtb, {CREST_LIMIT} for CREST, at most {MAX_LIMIT})"} +_THREADS = {"type": "integer", "description": "Threads; default the Preferences setting"} +NOT_SHIPPED = ("xtb and CREST are LGPL programs FormChem does not include or download: they run only when the person has installed them " + "(on PATH or at the path set in Preferences > 3D); otherwise the tool says where to get them.") + + +def _tool(name: str, description: str, props: dict) -> dict: + return {"name": name, "description": description, "inputSchema": {"type": "object", "properties": props, "required": []}, + "annotations": {"readOnlyHint": False, "destructiveHint": False, "openWorldHint": False}} + + +TOOLS = [ + _tool("xtb_optimise", "Optimises the shown conformer of a structure with the xtb program (GFN2-xTB or GFN-FF, optional ALPB implicit solvent), or with " + "single_point computes the energy without moving atoms, then stores the result as the structure's conformers as one undo step. A structure " + "without 3D coordinates is built first (ETKDGv3+MMFF94). Answers with the total energy in hartree and kcal/mol, the HOMO-LUMO gap, whether the " + "optimisation converged, and the program, version, method and solvent. Waits until xtb finishes or the time limit stops it. " + NOT_SHIPPED, + {"doc": _DOC, "object": _FRAG, "method": _METHOD, "charge": _CHARGE, "uhf": _UHF, "solvent": _SOLVENT, + "single_point": {"type": "boolean", "description": "Energy only, no optimisation (default false)"}, + "scope": {"type": "string", "enum": ["shown", "all"], "description": "The shown conformer (default for optimisation) or every stored conformer (default for single_point)"}, + "level": {"type": "string", "enum": list(OPT_LEVELS), "description": "Optimisation convergence level (default normal)"}, + "conformer": {"type": "string", "description": "Conformer id (c...) to start from; default the shown one"}, "threads": _THREADS, "limit": _LIMIT}), + _tool("crest_conformers", "Searches conformers of a structure with the CREST program (metadynamics with GFN2-xTB or GFN-FF, optional ALPB solvent) and " + "replaces the structure's conformers with the ensemble within ewin kcal/mol, at most keep, as one undo step; the lowest becomes the shown one. " + "Answers with relative energies and Boltzmann populations at 298.15 K, and the program, version, method and solvent. CREST can take minutes to hours; " + "the tool waits until it finishes or the time limit stops it. " + NOT_SHIPPED, + {"doc": _DOC, "object": _FRAG, "method": _METHOD, "charge": _CHARGE, "uhf": _UHF, "solvent": _SOLVENT, + "ewin": {"type": "number", "description": "Energy window in kcal/mol (default 6)"}, "keep": {"type": "integer", "description": "Most conformers kept, 1 to 200 (default 20)"}, + "threads": _THREADS, "limit": _LIMIT}), +] +NAMES = frozenset(t["name"] for t in TOOLS) +KEYS = ("method", "charge", "uhf", "solvent", "scope", "level", "conformer", "threads", "limit", "ewin", "keep", "single_point") + + +def body(args: dict, fid: str) -> dict: + return {"object": fid, **{k: args[k] for k in KEYS if args.get(k) is not None}, "wait": True} + + +def _energy(c: dict) -> str: + eh, kcal = c.get("energy_eh"), c.get("energy") + if not isinstance(eh, (int, float)): + return "no energy" + return f"{eh:.8f} Eh ({kcal:.2f} kcal/mol)" if isinstance(kcal, (int, float)) else f"{eh:.8f} Eh" + + +def _ended(job: dict) -> None: + if job.get("state") == "done": + return + tail = "\n".join(job.get("tail") or []) + raise HTTPException(422, f"{job.get('title')} {job.get('state')}: {job.get('error')}" + (f"\nLast lines:\n{tail}" if tail else "")) + + +def _notes(job: dict) -> str: + return "".join(f" Note: {w.get('text')}" for w in (job.get("report") or {}).get("warnings", [])[:5] if isinstance(w, dict) and w.get("text")) + + +async def optimise(doc_id: str, payload: dict) -> dict: + from app.routers import xtb as routes + + single = payload.pop("single_point", False) is True + job = await routes.start_job(doc_id, "single" if single else "optimise", payload) + _ended(job) + rows = job.get("conformers") or [] + head = (f"{job['title']} of {job['object']} with {job['label']} done in {job['elapsed']} s; " + f"{len(rows)} conformer{'' if len(rows) == 1 else 's'} stored, shown {rows[0]['id'] if rows else None}. One undo step (rev {job.get('rev')}).") + lines = [head + _notes(job)] + for c in rows[:20]: + conv = "" if c.get("converged") is None else ", converged" if c.get("converged") else ", NOT converged" + gap = f", HOMO-LUMO gap {c['gap_ev']:.3f} eV" if isinstance(c.get("gap_ev"), (int, float)) else "" + lines.append(f"- {c['id']}: {_energy(c)}{gap}{conv}") + return {"text": "\n".join(lines), "data": job} + + +async def crest(doc_id: str, payload: dict) -> dict: + from app.routers import xtb as routes + + job = await routes.start_job(doc_id, "crest", payload) + _ended(job) + rows = job.get("conformers") or [] + rep = job.get("report") or {} + lines = [f"CREST kept {len(rows)} of {rep.get('found')} conformers of {job['object']} with {job['label']} in {job['elapsed']} s; " + f"shown: {rows[0]['id'] if rows else None}. One undo step (rev {job.get('rev')})." + _notes(job)] + for c in rows[:20]: + rel = c.get("relative") + pop = c.get("population") + lines.append(f"- {c['id']}: +{rel:.2f} kcal/mol" + (f", population {100 * pop:.1f}%" if isinstance(pop, (int, float)) else "") + f", {_energy(c)}" + if isinstance(rel, (int, float)) else f"- {c['id']}: {_energy(c)}") + return {"text": "\n".join(lines), "data": job} + + +def mutating(name: str, args: dict) -> bool: + return name in NAMES + + +async def call(name: str, args: dict, agent_name: str) -> dict: + from app.routers import mcp + + args = args if isinstance(args, dict) else {} + run = {"xtb_optimise": optimise, "crest_conformers": crest}.get(name) + if run is None: + return mcp._fail(f"Unknown tool {name}.") + doc_id, _ = await mcp._doc_id(args) + _, doc = mcp._drawing({"doc": doc_id}) + out = await mcp._three_d(mcp.Agent("", agent_name), run, doc_id, body(args, mcp._fragment_of(doc, args))) + return mcp._ok(out["text"], out["data"]) diff --git a/backend/app/services/database/__init__.py b/backend/app/services/database/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/backend/app/services/database/attachments.py b/backend/app/services/database/attachments.py new file mode 100644 index 00000000..e2e511c6 --- /dev/null +++ b/backend/app/services/database/attachments.py @@ -0,0 +1,103 @@ +import hashlib +import mimetypes +import sqlite3 +import time +from pathlib import Path + +from app.services.database import store +from app.services.database.store import DatabaseError + +LIMIT = 50 * 1024 * 1024 +CHUNK = 1024 * 1024 + + +def as_dict(row: sqlite3.Row) -> dict: + return {"id": row["id"], "name": row["name"], "mime": row["mime"], "size": row["size"], "sha256": row["sha256"], + "linked": row["path"] is not None, "path": row["path"], "created": row["created"]} + + +def listing(conn: sqlite3.Connection, compound: int | None = None, entry: int | None = None) -> list[dict]: + if compound is not None: + rows = conn.execute("SELECT id, name, mime, size, sha256, path, created FROM attachments WHERE compound = ? ORDER BY id", (compound,)) + else: + rows = conn.execute("SELECT id, name, mime, size, sha256, path, created FROM attachments WHERE entry = ? ORDER BY id", (entry,)) + return [as_dict(r) for r in rows] + + +def _owner(conn: sqlite3.Connection, uid: str) -> tuple[str, int]: + table, column = ("compounds", "compound") if uid.startswith("c") else ("entries", "entry") + row = conn.execute(f"SELECT id FROM {table} WHERE uid = ?", (uid,)).fetchone() + if row is None: + raise DatabaseError(f"There is no record {uid}." if column == "compound" else f"There is no entry {uid}.", 404) + return column, row["id"] + + +def _mime(name: str, given: str | None) -> str: + if given and given != "application/octet-stream": + return given + return mimetypes.guess_type(name)[0] or "application/octet-stream" + + +def store_bytes(db: store.Database, uid: str, name: str, data: bytes, mime: str | None = None, actor: str = "person") -> dict: + if len(data) > LIMIT: + raise DatabaseError(f"{name} is larger than {LIMIT // (1024 * 1024)} MB; link it by its path instead.", 413) + name = Path(name or "attachment").name or "attachment" + digest = hashlib.sha256(data).hexdigest() + with store.writing(db) as conn: + column, owner = _owner(conn, uid) + cur = conn.execute(f"INSERT INTO attachments ({column}, name, mime, size, sha256, data, created) VALUES (?, ?, ?, ?, ?, ?, ?)", + (owner, name, _mime(name, mime), len(data), digest, sqlite3.Binary(data), time.time())) + if column == "compound": + conn.execute("UPDATE compounds SET modified = ? WHERE id = ?", (time.time(), owner)) + store.audit(db, actor, "attachment-add", uid, {"name": name, "size": len(data), "sha256": digest}) + made = as_dict(conn.execute("SELECT id, name, mime, size, sha256, path, created FROM attachments WHERE id = ?", (cur.lastrowid,)).fetchone()) + store.notify(db, "records" if column == "compound" else "entries", [uid]) + return made + + +def _hash_file(path: Path) -> tuple[str, int]: + h = hashlib.sha256() + size = 0 + with open(path, "rb") as fh: + while chunk := fh.read(CHUNK): + h.update(chunk) + size += len(chunk) + return h.hexdigest(), size + + +def link(db: store.Database, uid: str, path: str, actor: str = "person") -> dict: + if not isinstance(path, str) or not path.strip(): + raise DatabaseError("Give the absolute path of the file to link.", 422) + target = Path(path.strip()).expanduser() + if not target.is_absolute(): + raise DatabaseError("Give the absolute path of the file to link.", 422) + if not target.is_file(): + raise DatabaseError(f"No file at {target}.", 404) + try: + digest, size = _hash_file(target) + except OSError as exc: + raise DatabaseError(f"{target.name} could not be read: {exc.strerror or exc}", 400) + with store.writing(db) as conn: + column, owner = _owner(conn, uid) + cur = conn.execute(f"INSERT INTO attachments ({column}, name, mime, size, sha256, path, created) VALUES (?, ?, ?, ?, ?, ?, ?)", + (owner, target.name, _mime(target.name, None), size, digest, str(target), time.time())) + if column == "compound": + conn.execute("UPDATE compounds SET modified = ? WHERE id = ?", (time.time(), owner)) + store.audit(db, actor, "attachment-link", uid, {"path": str(target), "sha256": digest}) + made = as_dict(conn.execute("SELECT id, name, mime, size, sha256, path, created FROM attachments WHERE id = ?", (cur.lastrowid,)).fetchone()) + store.notify(db, "records" if column == "compound" else "entries", [uid]) + return made + + +def read(db: store.Database, attachment_id: int) -> tuple[dict, bytes | Path]: + with store.reading(db): + row = db.conn.execute("SELECT * FROM attachments WHERE id = ?", (attachment_id,)).fetchone() + if row is None: + raise DatabaseError(f"There is no attachment {attachment_id}.", 404) + info = as_dict(row) + if row["path"] is not None: + target = Path(row["path"]) + if not target.is_file(): + raise DatabaseError(f"The linked file {target} is missing.", 410) + return info, target + return info, bytes(row["data"] or b"") diff --git a/backend/app/services/database/chem.py b/backend/app/services/database/chem.py new file mode 100644 index 00000000..f11da5fb --- /dev/null +++ b/backend/app/services/database/chem.py @@ -0,0 +1,134 @@ +import json +from collections import Counter + +from rdkit import Chem, DataStructs, RDLogger +from rdkit.Chem import rdMolDescriptors, rdFingerprintGenerator +from rdkit.Chem.MolStandardize import rdMolStandardize + +from app.services.chem import mass + +RDLogger.DisableLog("rdApp.*") + +FP_BITS = 2048 +FP_METHOD = "Morgan radius 2, 2048 bits (RDKit)" +SCREEN_METHOD = "RDKit pattern fingerprint, 2048 bits" +_MORGAN = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=FP_BITS) +_PARENT_STEPS = ("cleanup", "salts", "largest", "neutralise") + + +class StructureError(ValueError): + pass + + +def mol_from(structure: dict | str) -> Chem.Mol: + if isinstance(structure, str): + structure = {"molfile": structure} if "\n" in structure else {"smiles": structure} + if not isinstance(structure, dict): + raise StructureError("A structure is a SMILES string or a molfile.") + mol = None + if isinstance(structure.get("molfile"), str): + mol = Chem.MolFromMolBlock(structure["molfile"], sanitize=True, removeHs=False) + elif isinstance(structure.get("smiles"), str): + mol = Chem.MolFromSmiles(structure["smiles"].strip()) + else: + raise StructureError("Give the structure as smiles or molfile.") + if mol is None or mol.GetNumAtoms() == 0: + raise StructureError("RDKit could not read this structure (check valences and the molfile).") + return mol + + +def query_from(structure: dict) -> Chem.Mol: + if isinstance(structure.get("smarts"), str): + q = Chem.MolFromSmarts(structure["smarts"].strip()) + if q is None: + raise StructureError("RDKit could not read this SMARTS.") + return q + return mol_from(structure) + + +def to_bytes(bv: DataStructs.ExplicitBitVect) -> bytes: + out = bytearray(FP_BITS // 8) + for i in bv.GetOnBits(): + out[i >> 3] |= 1 << (i & 7) + return bytes(out) + + +def from_bytes(raw: bytes) -> DataStructs.ExplicitBitVect: + bv = DataStructs.ExplicitBitVect(FP_BITS) + on = [i * 8 + b for i, byte in enumerate(raw) if byte for b in range(8) if byte >> b & 1] + bv.SetBitsFromList(on) + return bv + + +def similarity_fp(mol: Chem.Mol) -> DataStructs.ExplicitBitVect: + return _MORGAN.GetFingerprint(mol) + + +def screen_fp(mol: Chem.Mol) -> DataStructs.ExplicitBitVect: + return Chem.PatternFingerprint(mol, fpSize=FP_BITS) + + +def screen_passes(query_raw: bytes, target_raw: bytes) -> bool: + return all((q & t) == q for q, t in zip(query_raw, target_raw)) + + +def parent(mol: Chem.Mol) -> Chem.Mol: + out = Chem.Mol(mol) + try: + out = rdMolStandardize.Cleanup(out) + out = rdMolStandardize.FragmentParent(out) + out = rdMolStandardize.Uncharger().uncharge(out) + except Exception: + return Chem.Mol(mol) + return out + + +def _key(mol: Chem.Mol) -> str: + try: + return Chem.MolToInchiKey(mol) or "" + except Exception: + return "" + + +def element_counts(mol: Chem.Mol) -> dict[str, int]: + withh = Chem.AddHs(mol) + found = Counter(a.GetSymbol() for a in withh.GetAtoms()) + return dict(sorted(found.items())) + + +def molblock(mol: Chem.Mol) -> str: + v3000 = mol.GetNumAtoms() > 999 or mol.GetNumBonds() > 999 or bool(mol.GetStereoGroups()) + return Chem.MolToV3KMolBlock(mol) if v3000 else Chem.MolToMolBlock(mol) + + +def register_values(structure: dict | str) -> dict: + mol = mol_from(structure) + if isinstance(structure, dict) and isinstance(structure.get("molfile"), str): + block = structure["molfile"] + else: + from rdkit.Chem import rdDepictor + drawn = Chem.Mol(mol) + rdDepictor.Compute2DCoords(drawn) + block = molblock(drawn) + plain = Chem.RemoveHs(mol) + try: + inchi = Chem.MolToInchi(mol) or "" + except Exception: + inchi = "" + key = _key(mol) + par = parent(mol) + return { + "molfile": block, + "smiles": Chem.MolToSmiles(plain), + "inchi": inchi, + "inchikey": key, + "skeleton": key.split("-")[0] if key else "", + "parent_key": _key(par) or key, + "formula": rdMolDescriptors.CalcMolFormula(mol), + "mw": round(mass.average_mass(mol), 4), + "exact_mass": round(mass.exact_mass(mol), 6), + "heavy_atoms": mol.GetNumHeavyAtoms(), + "fp": to_bytes(similarity_fp(plain)), + "sfp": to_bytes(screen_fp(plain)), + "counts": json.dumps(element_counts(mol), separators=(",", ":")), + } diff --git a/backend/app/services/database/computed.py b/backend/app/services/database/computed.py new file mode 100644 index 00000000..f00c66ab --- /dev/null +++ b/backend/app/services/database/computed.py @@ -0,0 +1,95 @@ +from rdkit import rdBase + +from app.services.chem import props +from app.services.database import store +from app.services.database.chem import mol_from + +DESCRIPTORS = { + "clogp": "clogp", + "tpsa": "tpsa", + "hbd": "hbd", + "hba": "hba", + "rotatable": "rotatable_bonds", + "rings": "rings", + "aromatic_rings": "aromatic_rings", + "fsp3": "fraction_csp3", + "mr": "mr", + "charge": "formal_charge", +} +_ROWS = {row[0]: row for row in props.ROWS} +BATCH = 300 + + +def label(key: str) -> str: + return _ROWS[DESCRIPTORS[key]][1] + + +def unit(key: str) -> str: + return _ROWS[DESCRIPTORS[key]][2] + + +def method(key: str) -> str: + row = _ROWS[DESCRIPTORS[key]] + return f"{row[3]}, {row[4]} (RDKit {rdBase.rdkitVersion})" + + +def catalogue() -> list[dict]: + return [{"key": k, "label": label(k), "unit": unit(k), "method": method(k)} for k in DESCRIPTORS] + + +def values(molfile: str, keys: list[str]) -> dict[str, float | None]: + wanted = [k for k in keys if k in DESCRIPTORS] + if not wanted: + return {} + try: + measured, _notes = props.measure(mol_from({"molfile": molfile})) + except Exception: + return {k: None for k in wanted} + out: dict[str, float | None] = {} + for k in wanted: + v = measured.get(DESCRIPTORS[k]) + out[k] = float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None + return out + + +def computed_fields(conn) -> list[tuple[int, str]]: + return [(r["id"], r["computed"]) for r in conn.execute("SELECT id, computed FROM fields WHERE type = 'computed' AND computed IS NOT NULL")] + + +def write(conn, compound: int, molfile: str, fields: list[tuple[int, str]]) -> None: + if not fields: + return + found = values(molfile, [key for _, key in fields]) + for fid, key in fields: + v = found.get(key) + if v is None: + conn.execute("DELETE FROM field_values WHERE compound = ? AND field = ?", (compound, fid)) + else: + conn.execute("INSERT OR REPLACE INTO field_values (compound, field, num, txt) VALUES (?, ?, ?, NULL)", (compound, fid, v)) + + +def fill(db: store.Database, field_ids: list[int] | None = None) -> int: + with store.reading(db): + fields = [f for f in computed_fields(db.conn) if field_ids is None or f[0] in field_ids] + if not fields: + return 0 + last, done = 0, 0 + while True: + with store.reading(db): + rows = db.conn.execute("SELECT id, molfile FROM compounds WHERE id > ? ORDER BY id LIMIT ?", (last, BATCH)).fetchall() + if not rows: + break + found = [(r["id"], values(r["molfile"], [key for _, key in fields])) for r in rows] + with store.writing(db) as conn: + for cid, vals in found: + for fid, key in fields: + v = vals.get(key) + if v is None: + conn.execute("DELETE FROM field_values WHERE compound = ? AND field = ?", (cid, fid)) + else: + conn.execute("INSERT OR REPLACE INTO field_values (compound, field, num, txt) VALUES (?, ?, ?, NULL)", (cid, fid, v)) + done += len(rows) + last = rows[-1]["id"] + if done: + store.notify(db, "records") + return done diff --git a/backend/app/services/database/dbcli.py b/backend/app/services/database/dbcli.py new file mode 100644 index 00000000..2841c794 --- /dev/null +++ b/backend/app/services/database/dbcli.py @@ -0,0 +1,241 @@ +import argparse +import json +import os +import sys +import time +from pathlib import Path + +USAGE = """./formchem db create TITLE [--path FILE.fcdb] +./formchem db info DB +./formchem db import DB FILE [--format FMT] [--mode new|append|merge] [--key structure|FIELD] [--dry-run] [--errors report.csv] +./formchem db search DB (--substructure SMILES | --similarity SMILES [--threshold T] | --exact SMILES | --formula F | --query JSON) [--show N] +./formchem db export DB OUT [--format sdf|smiles|csv] [--hitlist ID] [--fields a,b] [--v3000] [--inchi]""" +SHOWN = 20 + + +def _path(p: str) -> str: + q = Path(p).expanduser() + if not q.is_absolute(): + q = Path(os.environ.get("FORMCHEM_CALLER_DIR") or os.getcwd()) / q + return str(q) + + +def _open(path: str): + from app.services.database import info + return info.open_database(_path(path)) + + +def _close(db) -> None: + from app.services.database import info + info.close_database(db.handle) + + +def create(title: str, path: str | None = None) -> dict: + from app.services.database import info + db = info.create_database(title, _path(path) if path else None) + try: + return info.describe(db) + finally: + _close(db) + + +def describe(path: str) -> dict: + from app.services.database import info + db = _open(path) + try: + return info.describe(db) + finally: + _close(db) + + +def import_file(path: str, source: str, fmt: str | None = None, mode: str = "new", key: str | None = None, dry_run: bool = False, + progress=None) -> dict: + from app.services.database import imports + db = _open(path) + try: + job = imports.start(db, _path(source), fmt, mode, key, None, dry_run, actor="import") + while True: + found = imports.wait(job["job"], 1.0) + if progress is not None: + progress(found) + if found["state"] != "running": + return found + except KeyboardInterrupt: + imports.cancel(job["job"]) + return imports.wait(job["job"], 30) + finally: + _close(db) + + +def _query(args) -> dict: + if args.query: + try: + found = json.loads(args.query) + except ValueError as exc: + raise ValueError(f"--query is not JSON: {exc}") + return found + if args.substructure: + return {"kind": "substructure", "structure": {"smiles": args.substructure}} + if args.similarity: + return {"kind": "similarity", "structure": {"smiles": args.similarity}, "threshold": args.threshold} + if args.exact: + return {"kind": "exact", "structure": {"smiles": args.exact}} + if args.formula: + return {"kind": "formula", "formula": args.formula, "mode": "contains"} + raise ValueError("give a query: --substructure, --similarity, --exact, --formula or --query") + + +def search(path: str, query: dict, show: int = SHOWN) -> dict: + from app.services.database import records + from app.services.database import search as searching + db = _open(path) + try: + result = searching.run(db, query, actor="person") + rows = records.page(db, hitlist=result["id"], limit=max(1, min(show, records.MAX_LIMIT)))["rows"] if show else [] + return {**result, "rows": rows} + finally: + _close(db) + + +def export(path: str, out: str, fmt: str | None = None, hitlist: int | None = None, fields: list[str] | None = None, v3000: bool = False, + structure_as: str = "smiles") -> dict: + from app.services.database import exports + target = _path(out) + kind = fmt or {".sdf": "sdf", ".sd": "sdf", ".smi": "smiles", ".smiles": "smiles", ".csv": "csv"}.get(Path(target).suffix.lower(), "sdf") + db = _open(path) + try: + return exports.export(db, kind, target, hitlist, None, fields, v3000, structure_as) + finally: + _close(db) + + +def add_parser(sub) -> argparse.ArgumentParser: + d = sub.add_parser("db", usage=USAGE, help="structure databases (.fcdb): create, info, import, search, export") + dsub = d.add_subparsers(dest="db_command", required=True) + c = dsub.add_parser("create", usage=USAGE.splitlines()[0]) + c.add_argument("title") + c.add_argument("--path", help="where the .fcdb file goes (default: the Databases folder)") + i = dsub.add_parser("info", usage=USAGE.splitlines()[1]) + i.add_argument("db") + m = dsub.add_parser("import", usage=USAGE.splitlines()[2]) + m.add_argument("db") + m.add_argument("file") + m.add_argument("--format", help="sdf, rdf, smiles, csv, tsv, fchem, molfile or inchi when the extension does not say it") + m.add_argument("--mode", choices=("new", "append", "merge"), default="new") + m.add_argument("--key", help="merge key: structure (the duplicate rules) or a field name") + m.add_argument("--dry-run", action="store_true", help="count what would be added, updated and failed without writing") + m.add_argument("--errors", metavar="FILE", help="write every failed record (record number, reason) to this CSV file") + s = dsub.add_parser("search", usage=USAGE.splitlines()[3]) + s.add_argument("db") + s.add_argument("--substructure", metavar="SMILES") + s.add_argument("--similarity", metavar="SMILES") + s.add_argument("--threshold", type=float, default=0.7) + s.add_argument("--exact", metavar="SMILES") + s.add_argument("--formula", metavar="F", help="element counts or ranges, such as C6-8N1") + s.add_argument("--query", metavar="JSON", help="a query node as in docs/DATABASE.md") + s.add_argument("--show", type=int, default=SHOWN, help="how many hits to print (default 20)") + e = dsub.add_parser("export", usage=USAGE.splitlines()[4]) + e.add_argument("db") + e.add_argument("out") + e.add_argument("--format", choices=("sdf", "smiles", "csv")) + e.add_argument("--hitlist", type=int) + e.add_argument("--fields", help="comma-separated field names (default: every scalar field)") + e.add_argument("--v3000", action="store_true") + e.add_argument("--inchi", action="store_true", help="CSV structures as InChI instead of SMILES") + for p in (c, i, m, s, e): + p.add_argument("--json", action="store_true", help="print the result as JSON") + return d + + +def _print_info(found: dict) -> None: + print(f"{found['title']}: {found['count']:,} records, {found['entries']:,} notebook entries" + (" (read-only)" if found["readonly"] else "")) + print(f" file {found['path']}") + rules = found["rules"] + print(f" rules stereo {rules['stereo']}, salts {rules['salts']}, on duplicate {rules['on_duplicate']}") + for f in found["fields"]: + extra = f" ({f['unit']})" if f.get("unit") else "" + method = f", {f['method']}" if f.get("method") else "" + print(f" field {f['name']:<20} {f['type']:<11} {f['label']}{extra}{method}") + + +def _errors_csv(target: str, report: list[dict]) -> None: + import csv + with open(_path(target), "w", encoding="utf-8", newline="") as fh: + w = csv.writer(fh) + w.writerow(["record", "reason"]) + for r in report: + w.writerow([r["record"], r["reason"]]) + + +def run(args) -> int: + from app.services.database.store import DatabaseError + as_json = getattr(args, "json", False) + try: + if args.db_command == "create": + found = create(args.title, args.path) + print(json.dumps(found, indent=2) if as_json else f"created {found['path']}") + return 0 + if args.db_command == "info": + found = describe(args.db) + if as_json: + print(json.dumps(found, indent=2)) + else: + _print_info(found) + return 0 + if args.db_command == "import": + started = time.perf_counter() + + def progress(job: dict) -> None: + if not as_json and sys.stderr.isatty() and job.get("total"): + print(f"\r {job['read']:,} of {job['total']:,} records", end="", file=sys.stderr) + + job = import_file(args.db, args.file, args.format, args.mode, args.key, args.dry_run, progress) + if not as_json and sys.stderr.isatty(): + print(file=sys.stderr) + if args.errors: + _errors_csv(args.errors, job["report"]) + if as_json: + print(json.dumps(job, indent=2)) + else: + verb = "would add" if job["dry_run"] else "added" + print(f"{job['state']}: read {job['read']:,}, {verb} {job['added']:,}, updated {job['updated']:,}, failed {job['failed']:,}" + f" in {time.perf_counter() - started:.1f} s") + for r in job["report"][:SHOWN]: + print(f" record {r['record']}: {r['reason']}") + if len(job["report"]) > SHOWN and not args.errors: + print(f" ... {len(job['report']) - SHOWN} more; give --errors FILE to list them all") + if job.get("error"): + print(f" {job['error']}", file=sys.stderr) + return 0 if job["state"] == "done" else 1 + if args.db_command == "search": + found = search(args.db, _query(args), args.show) + if as_json: + print(json.dumps(found, indent=2)) + else: + print(f"{found['name']}: {found['count']:,} hits in {found.get('took_ms', 0):,.0f} ms (hit list {found['id']})") + for r in found["rows"]: + score = f" {r['score']:.3f}" if r.get("score") is not None else "" + print(f" {r['number']:>7}-{r['batch']} {r['uid']} {r['formula']:<14} {r['smiles']}{score}") + return 0 + found = export(args.db, args.out, args.format, args.hitlist, args.fields.split(",") if args.fields else None, args.v3000, + "inchi" if args.inchi else "smiles") + print(json.dumps(found, indent=2) if as_json else f"wrote {found['written']:,} records to {found['path']}" + + (f"; {found['skipped']:,} skipped" if found["skipped"] else "")) + return 0 + except (DatabaseError, ValueError) as exc: + print(f"formchem db {args.db_command}: {exc}", file=sys.stderr) + return 2 + except ImportError as exc: + print(f"formchem db {args.db_command}: this FormChem has no database search yet ({exc})", file=sys.stderr) + return 2 + + +def main(argv: list[str] | None = None) -> int: + top = argparse.ArgumentParser(prog="./formchem") + add_parser(top.add_subparsers(dest="command", required=True)) + args = top.parse_args(["db", *(sys.argv[1:] if argv is None else argv)]) + return run(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/backend/app/services/database/exports.py b/backend/app/services/database/exports.py new file mode 100644 index 00000000..83ddf22a --- /dev/null +++ b/backend/app/services/database/exports.py @@ -0,0 +1,204 @@ +import csv +import os +import re +import secrets +import time +from datetime import datetime, timezone +from pathlib import Path + +from rdkit import Chem + +from app.services.database import fields as fieldsmod +from app.services.database import store +from app.services.database.store import DatabaseError + +FORMATS = {"sdf": ".sdf", "smiles": ".smi", "csv": ".csv"} +NON_SCALAR = frozenset({"structure", "reaction", "image", "file"}) +BUILTIN_COLUMNS = ("number", "batch", "uid", "formula", "mw", "exact_mass", "inchikey", "smiles", "inchi", "created", "modified") +CHUNK = 500 +EXPORTS = ".exports" +KEEP_SECONDS = 24 * 3600 + + +def exports_dir() -> Path: + target = store.databases_dir() / EXPORTS + target.mkdir(parents=True, exist_ok=True) + return target + + +def sweep() -> None: + now = time.time() + for p in exports_dir().iterdir(): + try: + if p.is_file() and now - p.stat().st_mtime > KEEP_SECONDS: + p.unlink() + except OSError: + pass + + +def text_of(ftype: str, value) -> str: + if value is None: + return "" + if ftype == "boolean": + return "true" if value else "false" + if ftype == "datetime" and isinstance(value, (int, float)): + return datetime.fromtimestamp(value, timezone.utc).isoformat() + if ftype == "multichoice" and isinstance(value, list): + return "; ".join(value) + if isinstance(value, float): + return str(int(value)) if ftype == "integer" else format(value, ".15g") + return str(value) + + +def _selection(conn, hitlist: int | None, uids: list[str] | None) -> list[int]: + if uids is not None: + if not isinstance(uids, list) or not all(isinstance(u, str) for u in uids): + raise DatabaseError("uids must be a list of record ids.", 422) + out = [] + for k in range(0, len(uids), CHUNK): + part = uids[k:k + CHUNK] + marks = ",".join("?" * len(part)) + found = {r["uid"]: r["id"] for r in conn.execute(f"SELECT id, uid FROM compounds WHERE uid IN ({marks})", part)} + out.extend(found[u] for u in part if u in found) + return out + if hitlist is not None: + if conn.execute("SELECT 1 FROM hitlists WHERE id = ?", (hitlist,)).fetchone() is None: + raise DatabaseError(f"There is no hit list {hitlist}.", 404) + return [r[0] for r in conn.execute("SELECT compound FROM hitlist_items WHERE hitlist = ? ORDER BY rank", (hitlist,))] + return [r[0] for r in conn.execute("SELECT id FROM compounds ORDER BY number, batch")] + + +def _columns(conn, wanted: list[str] | None, fmt: str) -> list[dict]: + all_fields = fieldsmod.all_fields(conn) + if wanted is None: + return [f for f in all_fields if f["type"] not in NON_SCALAR] + if not isinstance(wanted, list) or not all(isinstance(w, str) for w in wanted): + raise DatabaseError("fields must be a list of field names.", 422) + by_name = {f["name"]: f for f in all_fields} + out = [] + for name in wanted: + if name in by_name: + out.append(by_name[name]) + elif name in BUILTIN_COLUMNS and fmt == "csv": + out.append({"name": name, "label": name, "type": "builtin", "id": None}) + elif name not in BUILTIN_COLUMNS: + raise DatabaseError(f"This database has no field named {name}.", 404) + return out + + +def _tag(label: str) -> str: + return re.sub(r"[<>\r\n]", " ", label).strip() or "field" + + +def _sd_record(row, values: dict, columns: list[dict], v3000: bool) -> str: + stored = row["molfile"] + if not v3000 and "V3000" not in stored.split("M END")[0][:400]: + block = stored if stored.endswith("\n") else stored + "\n" + lines = block.split("\n") + lines[0] = "" + block = "\n".join(lines) + else: + mol = Chem.MolFromMolBlock(stored, sanitize=False, removeHs=False, strictParsing=False) + if mol is None: + raise ValueError("the stored structure could not be read") + mol.SetProp("_Name", "") + big = mol.GetNumAtoms() > 999 or mol.GetNumBonds() > 999 + block = Chem.MolToV3KMolBlock(mol) if v3000 or big else Chem.MolToMolBlock(mol) + items = [] + for f in columns: + value = values.get(f["name"]) + if value is None or value == "" or value == []: + continue + text = text_of(f["type"], value).replace("\r\n", "\n").strip("\n") + text = "\n".join(line if line.strip() else " " for line in text.split("\n")) + items.append(f"> <{_tag(f['label'])}>\n{text}\n\n") + return block + "".join(items) + "$$$$\n" + + +def _write(fh, conn, fmt: str, ids: list[int], columns: list[dict], v3000: bool, structure_as: str, counts: dict, db: store.Database) -> None: + from app.services.database import records + writer = csv.writer(fh, lineterminator="\n") if fmt == "csv" else None + if writer is not None: + writer.writerow(["InChI" if structure_as == "inchi" else "SMILES", "number", *[f["label"] for f in columns]]) + for k in range(0, len(ids), CHUNK): + part = ids[k:k + CHUNK] + with store.reading(db): + marks = ",".join("?" * len(part)) + raw = {r["id"]: r for r in conn.execute(f"SELECT id, uid, number, batch, molfile, smiles, inchi, inchikey, formula, mw, exact_mass, created, modified " + f"FROM compounds WHERE id IN ({marks})", part)} + rows = {r["uid"]: r for r in records.rows_in(conn, part)} + for cid in part: + r = raw.get(cid) + if r is None: + continue + values = rows[r["uid"]]["values"] + try: + if fmt == "sdf": + fh.write(_sd_record(r, values, columns, v3000)) + elif fmt == "smiles": + if not r["smiles"]: + raise ValueError("no SMILES") + fh.write(f"{r['smiles']}\t{r['number']}\n") + else: + structure = r["inchi"] if structure_as == "inchi" else r["smiles"] + if not structure: + raise ValueError("no structure text") + cells = [] + for f in columns: + if f["type"] == "builtin": + v = r[f["name"]] + cells.append("" if v is None else format(v, ".15g") if isinstance(v, float) else str(v)) + else: + cells.append(text_of(f["type"], values.get(f["name"]))) + writer.writerow([structure, r["number"], *cells]) + counts["written"] += 1 + except ValueError: + counts["skipped"] += 1 + + +def export(db: store.Database, fmt: str, path: str | None = None, hitlist: int | None = None, uids: list[str] | None = None, + fields: list[str] | None = None, v3000: bool = False, structure_as: str = "smiles", actor: str = "person") -> dict: + if fmt not in FORMATS: + raise DatabaseError(f"format must be one of {', '.join(FORMATS)}.", 422) + if structure_as not in ("smiles", "inchi"): + raise DatabaseError("structure_as must be smiles or inchi.", 422) + with store.reading(db): + ids = _selection(db.conn, hitlist, uids) + columns = _columns(db.conn, fields, fmt) + title = db.meta("title") or db.path.stem + url = None + if path: + target = Path(path).expanduser() + if not target.is_absolute(): + raise DatabaseError("Give the absolute path to export to.", 422) + if not target.parent.is_dir(): + raise DatabaseError(f"The folder {target.parent} does not exist.", 404) + else: + sweep() + safe = re.sub(r"[^A-Za-z0-9_-]+", "_", title).strip("_") or "Database" + name = f"{safe}-{secrets.token_hex(4)}{FORMATS[fmt]}" + target = exports_dir() / name + url = f"/api/databases/downloads/{name}" + tmp = target.with_name(f".{target.name}.{os.getpid()}.tmp") + counts = {"written": 0, "skipped": 0} + try: + with open(tmp, "w", encoding="utf-8", newline="") as fh: + _write(fh, db.conn, fmt, ids, columns, bool(v3000), structure_as, counts, db) + os.replace(tmp, target) + except OSError as exc: + raise DatabaseError(f"Could not write {target.name}: {exc.strerror or exc}", 400) + finally: + tmp.unlink(missing_ok=True) + if not db.readonly: + with store.writing(db): + store.audit(db, actor, "export", None, {"format": fmt, "path": str(target) if path else None, **counts}) + return {"path": str(target), "written": counts["written"], "skipped": counts["skipped"], "url": url, "format": fmt} + + +def download(name: str) -> Path: + if not re.fullmatch(r"[A-Za-z0-9_.-]+", name or "") or name.startswith("."): + raise DatabaseError("There is no such download.", 404) + target = exports_dir() / name + if not target.is_file(): + raise DatabaseError("That download was already taken or has expired.", 404) + return target diff --git a/backend/app/services/database/fields.py b/backend/app/services/database/fields.py new file mode 100644 index 00000000..1f3a5216 --- /dev/null +++ b/backend/app/services/database/fields.py @@ -0,0 +1,379 @@ +import json +import re +import sqlite3 +from datetime import datetime, timezone + +from app.services.database import computed, schema, store +from app.services.database.store import DatabaseError + +NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") +TEXT_TYPES = frozenset({"text", "richtext", "choice", "multichoice", "structure", "reaction", "link"}) +VIEW_BUILTINS = ("uid", "number", "batch", "smiles", "formula", "mw") +EDITABLE = ("label", "unit", "digits", "choices", "position", "width", "hidden", "type", "computed") +_TRUE = {"true", "yes", "y", "1", "t", "on"} +_FALSE = {"false", "no", "n", "0", "f", "off"} + + +def stores_text(ftype: str) -> bool: + return ftype in TEXT_TYPES + + +def as_dict(row: sqlite3.Row) -> dict: + out = { + "id": row["id"], + "name": row["name"], + "label": row["label"], + "type": row["type"], + "unit": row["unit"], + "digits": row["digits"], + "choices": json.loads(row["choices"]) if row["choices"] else None, + "computed": row["computed"], + "position": row["position"], + "width": row["width"], + "hidden": bool(row["hidden"]), + } + if row["type"] == "computed" and row["computed"] in computed.DESCRIPTORS: + out["method"] = computed.method(row["computed"]) + return out + + +def all_fields(conn: sqlite3.Connection) -> list[dict]: + return [as_dict(r) for r in conn.execute("SELECT * FROM fields ORDER BY position, id")] + + +def find(conn: sqlite3.Connection, name: str) -> dict: + row = conn.execute("SELECT * FROM fields WHERE name = ?", (name,)).fetchone() + if row is None: + raise DatabaseError(f"This database has no field named {name}.", 404) + return as_dict(row) + + +def slug(label: str, taken: set[str]) -> str: + base = re.sub(r"[^a-z0-9]+", "_", label.lower()).strip("_") + if not base or not base[0].isalpha(): + base = f"f_{base}" if base else "field" + base = base[:56] + name, n = base, 2 + while name in taken or name in schema.RESERVED: + name = f"{base}_{n}" + n += 1 + return name + + +def _choices(value: object) -> list[str] | None: + if value is None: + return None + if not isinstance(value, list) or not all(isinstance(c, str) for c in value): + raise DatabaseError("choices must be a list of text values.", 422) + seen = list(dict.fromkeys(c.strip() for c in value if c.strip())) + return seen or None + + +def _check_spec(spec: dict, ftype: str) -> None: + if ftype not in schema.FIELD_TYPES: + raise DatabaseError(f"type must be one of {', '.join(schema.FIELD_TYPES)}.", 422) + if ftype == "computed" and spec.get("computed") not in computed.DESCRIPTORS: + raise DatabaseError(f"A computed field names its descriptor: one of {', '.join(computed.DESCRIPTORS)}.", 422) + if ftype in ("choice", "multichoice") and not spec.get("choices"): + raise DatabaseError("A choice field needs its list of choices.", 422) + digits = spec.get("digits") + if digits is not None and (not isinstance(digits, int) or isinstance(digits, bool) or not 1 <= digits <= 15): + raise DatabaseError("digits must be a whole number from 1 to 15.", 422) + width = spec.get("width") + if width is not None and (not isinstance(width, (int, float)) or isinstance(width, bool) or not 16 <= width <= 2000): + raise DatabaseError("width must be a number of pixels from 16 to 2000.", 422) + + +def renumber(conn: sqlite3.Connection, moved: int | None = None, to: int | None = None) -> None: + ids = [r[0] for r in conn.execute("SELECT id FROM fields ORDER BY position, id")] + if moved is not None and moved in ids: + ids.remove(moved) + ids.insert(max(0, min(len(ids), to if to is not None else len(ids))), moved) + for pos, fid in enumerate(ids): + conn.execute("UPDATE fields SET position = ? WHERE id = ?", (pos, fid)) + + +def _quoted(name: str) -> str: + return '"' + name.replace('"', '""') + '"' + + +def rebuild_view(conn: sqlite3.Connection) -> None: + used = {b.lower() for b in VIEW_BUILTINS} + cols = [f"c.{b} AS {b}" for b in VIEW_BUILTINS] + for f in conn.execute("SELECT id, name, label, type FROM fields ORDER BY position, id").fetchall(): + label = (f["label"] or f["name"]).strip() or f["name"] + if label.lower() in used: + label = f"{label} ({f['name']})" + used.add(label.lower()) + col = "v.txt" if stores_text(f["type"]) else "v.num" + if f["type"] == "datetime": + col = "datetime(v.num, 'unixepoch')" + elif f["type"] in ("integer", "boolean", "image", "file"): + col = "CAST(v.num AS INTEGER)" + cols.append(f"(SELECT {col} FROM field_values v WHERE v.compound = c.id AND v.field = {int(f['id'])}) AS {_quoted(label)}") + conn.execute("DROP VIEW IF EXISTS records") + conn.execute(f"CREATE VIEW records AS SELECT {', '.join(cols)} FROM compounds c ORDER BY c.number, c.batch") + + +def ensure_view(db: store.Database) -> None: + if db.readonly: + return + with store.writing(db) as conn: + rebuild_view(conn) + + +def create(conn: sqlite3.Connection, spec: dict) -> dict: + label = spec.get("label") if isinstance(spec.get("label"), str) else "" + name = spec.get("name") if isinstance(spec.get("name"), str) else "" + taken = {r[0] for r in conn.execute("SELECT name FROM fields")} + if not name and not label.strip() and spec.get("type") == "computed" and spec.get("computed") in computed.DESCRIPTORS: + label = computed.label(spec["computed"]) + if not name: + if not label.strip(): + raise DatabaseError("A new field needs a label or a name.", 422) + name = slug(label, taken) + if not NAME_RE.match(name): + raise DatabaseError("A field name starts with a lower-case letter and has only a-z, 0-9 and _ (64 at most).", 422) + if name in schema.RESERVED: + raise DatabaseError(f"{name} is a built-in column, so it cannot be a field name.", 422) + if name in taken: + raise DatabaseError(f"There is already a field named {name}.", 409) + ftype = spec.get("type") or "text" + spec = {**spec, "choices": _choices(spec.get("choices"))} + _check_spec(spec, ftype) + unit = spec.get("unit") + if ftype == "computed" and not unit: + unit = computed.unit(spec["computed"]) or None + if not label.strip(): + label = computed.label(spec["computed"]) if ftype == "computed" else name + count = conn.execute("SELECT count(*) FROM fields").fetchone()[0] + position = spec.get("position") + cur = conn.execute( + "INSERT INTO fields (name, label, type, unit, digits, choices, computed, position, width, hidden) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + (name, label.strip(), ftype, unit if isinstance(unit, str) and unit else None, spec.get("digits"), + json.dumps(spec["choices"]) if spec["choices"] else None, spec.get("computed") if ftype == "computed" else None, + count, spec.get("width"), 1 if spec.get("hidden") else 0)) + fid = cur.lastrowid + if isinstance(position, int) and not isinstance(position, bool): + renumber(conn, fid, position) + return as_dict(conn.execute("SELECT * FROM fields WHERE id = ?", (fid,)).fetchone()) + + +def add(db: store.Database, spec: dict, actor: str = "person") -> dict: + if not isinstance(spec, dict): + raise DatabaseError("Send the field as an object.", 422) + with store.writing(db) as conn: + made = create(conn, spec) + rebuild_view(conn) + _relayout(db, conn) + store.audit(db, actor, "field-add", None, {"field": made["name"], "type": made["type"]}) + if made["type"] == "computed": + computed.fill(db, [made["id"]]) + store.notify(db, "fields") + store.notify(db, "forms") + return made + + +def _relayout(db: store.Database, conn: sqlite3.Connection) -> None: + from app.services.database import forms + forms.refresh(conn, db.meta("title") or "") + + +def _convert_values(conn: sqlite3.Connection, fid: int, old: str, new: str) -> None: + if stores_text(old) == stores_text(new): + return + if stores_text(new): + conn.execute("UPDATE field_values SET txt = CASE WHEN num = CAST(num AS INTEGER) THEN CAST(CAST(num AS INTEGER) AS TEXT) ELSE CAST(num AS TEXT) END, num = NULL WHERE field = ?", (fid,)) + return + for row in conn.execute("SELECT compound, txt FROM field_values WHERE field = ?", (fid,)).fetchall(): + try: + num, _ = coerce({"type": new, "name": "", "label": "", "choices": None}, row["txt"], text=True) + except DatabaseError: + num = None + if num is None: + conn.execute("DELETE FROM field_values WHERE compound = ? AND field = ?", (row["compound"], fid)) + else: + conn.execute("UPDATE field_values SET num = ?, txt = NULL WHERE compound = ? AND field = ?", (num, row["compound"], fid)) + + +def change(db: store.Database, name: str, patch: dict, actor: str = "person") -> dict: + if not isinstance(patch, dict): + raise DatabaseError("Send the changes as an object.", 422) + unknown = [k for k in patch if k not in EDITABLE and k not in ("id", "name")] + if unknown: + raise DatabaseError(f"{unknown[0]} cannot be changed; a field's name never changes.", 422) + refill = False + with store.writing(db) as conn: + old = find(conn, name) + merged = {**old, **{k: v for k, v in patch.items() if k in EDITABLE}} + if "choices" in patch: + merged["choices"] = _choices(patch["choices"]) + _check_spec(merged, merged["type"]) + label = merged["label"].strip() if isinstance(merged["label"], str) and merged["label"].strip() else old["label"] + if merged["type"] != old["type"]: + if old["type"] == "computed" or merged["type"] == "computed": + conn.execute("DELETE FROM field_values WHERE field = ?", (old["id"],)) + else: + _convert_values(conn, old["id"], old["type"], merged["type"]) + refill = merged["type"] == "computed" and (old["type"] != "computed" or merged["computed"] != old["computed"]) + conn.execute( + "UPDATE fields SET label = ?, type = ?, unit = ?, digits = ?, choices = ?, computed = ?, width = ?, hidden = ? WHERE id = ?", + (label, merged["type"], merged["unit"] or None, merged["digits"], json.dumps(merged["choices"]) if merged["choices"] else None, + merged["computed"] if merged["type"] == "computed" else None, merged["width"], 1 if merged["hidden"] else 0, old["id"])) + if "position" in patch and isinstance(patch["position"], int) and not isinstance(patch["position"], bool): + renumber(conn, old["id"], patch["position"]) + rebuild_view(conn) + relaid = bool(set(patch) & {"label", "position", "hidden", "type"}) + if relaid: + _relayout(db, conn) + store.audit(db, actor, "field-change", None, {"field": name, "changed": sorted(k for k in patch if k in EDITABLE)}) + made = find(conn, name) + if refill: + computed.fill(db, [made["id"]]) + store.notify(db, "fields") + if relaid: + store.notify(db, "forms") + return made + + +def delete(db: store.Database, name: str, actor: str = "person") -> str: + from app.services.database import forms + with store.writing(db) as conn: + old = find(conn, name) + conn.execute("DELETE FROM fields WHERE id = ?", (old["id"],)) + renumber(conn) + forms.drop_field(conn, name) + rebuild_view(conn) + _relayout(db, conn) + store.audit(db, actor, "field-delete", None, {"field": name}) + store.notify(db, "fields") + store.notify(db, "forms") + return name + + +def _number(value: object, text: bool) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, (int, float)): + return float(value) + if isinstance(value, str) and value.strip(): + s = value.strip().replace(",", "") if text else value.strip() + return float(s) + raise ValueError("not a number") + + +def _when(value: object) -> float: + if isinstance(value, (int, float)) and not isinstance(value, bool): + return float(value) + if isinstance(value, str) and value.strip(): + s = value.strip() + try: + return float(s) + except ValueError: + pass + dt = datetime.fromisoformat(s.replace("Z", "+00:00")) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.timestamp() + raise ValueError("not a date") + + +def coerce(field: dict, value: object, text: bool = False) -> tuple[float | None, str | None]: + ftype, label = field["type"], field.get("label") or field.get("name") + if value is None or (isinstance(value, str) and not value.strip() and ftype not in ("text", "richtext")): + return None, None + try: + if ftype == "integer": + n = _number(value, text) + if n != int(n): + raise ValueError("not whole") + return float(int(n)), None + if ftype in ("real", "computed"): + if ftype == "computed" and not text: + raise DatabaseError(f"{label} is computed from the structure, so it cannot be written.", 422) + return _number(value, text), None + if ftype == "datetime": + return _when(value), None + if ftype == "boolean": + if isinstance(value, str): + s = value.strip().lower() + if s in _TRUE: + return 1.0, None + if s in _FALSE: + return 0.0, None + raise ValueError("not yes or no") + return (1.0 if bool(value) else 0.0), None + if ftype in ("image", "file"): + n = _number(value, text) + if n != int(n): + raise ValueError("not an attachment id") + return float(int(n)), None + if ftype == "choice": + s = str(value).strip() + if field.get("choices") and s not in field["choices"]: + raise ValueError(f"not one of {', '.join(field['choices'])}") + return None, s + if ftype == "multichoice": + items = value + if isinstance(value, str): + s = value.strip() + items = json.loads(s) if s.startswith("[") else [p.strip() for p in re.split(r"[;,\n]", s) if p.strip()] + if not isinstance(items, list) or not all(isinstance(i, str) for i in items): + raise ValueError("not a list of choices") + bad = [i for i in items if field.get("choices") and i not in field["choices"]] + if bad: + raise ValueError(f"{bad[0]} is not one of {', '.join(field['choices'])}") + return None, json.dumps(list(dict.fromkeys(items)), separators=(",", ":")) + if isinstance(value, (dict, list)): + raise ValueError("not text") + return None, str(value) + except DatabaseError: + raise + except (ValueError, TypeError, OverflowError) as exc: + raise DatabaseError(f"{label}: {value!r} is {exc}." if str(exc).startswith("not") else f"{label}: {value!r} is not a valid {ftype} value.", 422) + + +def present(ftype: str, num: float | None, txt: str | None): + if ftype in TEXT_TYPES: + if txt is None: + return None + if ftype == "multichoice": + try: + return json.loads(txt) + except ValueError: + return [txt] + return txt + if num is None: + return None + if ftype in ("integer", "image", "file"): + return int(num) + if ftype == "boolean": + return bool(num) + return num + + +def detect(samples: list[str]) -> str: + vals = [s.strip() for s in samples if isinstance(s, str) and s.strip()] + if not vals: + return "text" + if any("\n" in v for v in vals): + return "richtext" + + def all_of(test) -> bool: + for v in vals: + try: + if not test(v): + return False + except (ValueError, OverflowError): + return False + return True + + if all_of(lambda v: re.fullmatch(r"[+-]?\d+", v) is not None and abs(int(v)) < 2 ** 53): + return "integer" + if all_of(lambda v: re.fullmatch(r"[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?", v) is not None): + return "real" + if all_of(lambda v: v.lower() in _TRUE | _FALSE and not v.isdigit()): + return "boolean" + if all_of(lambda v: re.fullmatch(r"\d{4}-\d\d-\d\d([T ]\d\d:\d\d(:\d\d(\.\d+)?)?(Z|[+-]\d\d:?\d\d)?)?", v) is not None and _when(v) is not None): + return "datetime" + return "text" diff --git a/backend/app/services/database/forms.py b/backend/app/services/database/forms.py new file mode 100644 index 00000000..ea30119a --- /dev/null +++ b/backend/app/services/database/forms.py @@ -0,0 +1,201 @@ +import json +import sqlite3 + +from app.services.database import fields as fieldsmod +from app.services.database import store +from app.services.database.store import DatabaseError + +WIDTH = 600.0 +MARGIN = 20.0 +GAP = 8.0 +LABEL_W = 130.0 +ROW_H = 24.0 +STYLES = ("single", "double", "card", "custom") +KINDS = ("structure", "field", "label", "frame", "picture", "check", "button", "subform") +NAMES = {"single": "Single column", "double": "Two columns", "card": "Card"} +BUILTINS = (("number", "Number"), ("formula", "Formula"), ("mw", "Molecular weight")) +TALL = {"richtext": 72.0, "structure": 120.0, "reaction": 120.0, "image": 120.0, "multichoice": 48.0} + + +def _height(ftype: str) -> float: + return TALL.get(ftype, ROW_H) + + +def _item(kind: str, x: float, y: float, w: float, h: float, **extra) -> dict: + return {"kind": kind, **extra, "x": round(x, 1), "y": round(y, 1), "w": round(w, 1), "h": round(h, 1)} + + +def _entries(field_list: list[dict]) -> list[tuple[str, str, str]]: + out = [(name, label, "builtin") for name, label in BUILTINS] + for f in field_list: + if f["hidden"]: + continue + kind = "check" if f["type"] == "boolean" else "subform" if f["type"] == "link" else "field" + out.append((f["name"], f["label"], f["type"] if kind == "field" else kind)) + return out + + +def _column(entries: list[tuple[str, str, str]], x: float, y: float, w: float) -> tuple[list[dict], float]: + items = [] + for name, label, ftype in entries: + h = _height(ftype) + if ftype == "check": + items.append(_item("check", x + LABEL_W, y, w - LABEL_W, ROW_H, field=name, label=label)) + else: + kind = "subform" if ftype == "subform" else "field" + items.append(_item(kind, x + LABEL_W, y, w - LABEL_W, h, field=name, label=label)) + items.append(_item("label", x, y, LABEL_W - GAP, ROW_H, field=name, label=label)) + y += max(h, ROW_H) + GAP + return items, y + + +def layout(style: str, field_list: list[dict], title: str = "") -> list[dict]: + entries = _entries(field_list) + inner = WIDTH - 2 * MARGIN + items = [_item("label", MARGIN, MARGIN, inner, 28.0, label=title or "Record")] + top = MARGIN + 28.0 + GAP * 2 + if style == "card": + side = 220.0 + items.append(_item("structure", MARGIN, top, side, side)) + right_x = MARGIN + side + GAP * 2 + right_w = WIDTH - MARGIN - right_x + fit, y = [], top + rest = list(entries) + while rest and y + max(_height(rest[0][2]), ROW_H) <= top + side: + fit.append(rest.pop(0)) + y += max(_height(fit[-1][2]), ROW_H) + GAP + placed, _ = _column(fit, right_x, top, right_w) + items += placed + y = top + side + GAP * 2 + half = (inner - GAP * 2) / 2 + left, right = rest[0::2], rest[1::2] + a, _ = _column(left, MARGIN, y, half) + b, _ = _column(right, MARGIN + half + GAP * 2, y, half) + items += a + b + return items + items.append(_item("structure", MARGIN, top, inner if style == "single" else 300.0, 200.0)) + y = top + 200.0 + GAP * 2 + if style == "single": + placed, _ = _column(entries, MARGIN, y, inner) + return items + placed + half = (inner - GAP * 2) / 2 + split = (len(entries) + 1) // 2 + a, _ = _column(entries[:split], MARGIN, y, half) + b, _ = _column(entries[split:], MARGIN + half + GAP * 2, y, half) + return items + a + b + + +def overlaps(items: list[dict]) -> list[tuple[int, int]]: + out = [] + for i, p in enumerate(items): + for j in range(i + 1, len(items)): + q = items[j] + if p["x"] < q["x"] + q["w"] and q["x"] < p["x"] + p["w"] and p["y"] < q["y"] + q["h"] and q["y"] < p["y"] + p["h"]: + out.append((i, j)) + return out + + +def as_dict(row: sqlite3.Row) -> dict: + try: + items = json.loads(row["layout"]) + except ValueError: + items = [] + return {"id": row["id"], "name": row["name"], "style": row["style"], "is_default": bool(row["is_default"]), "items": items if isinstance(items, list) else []} + + +def all_forms(conn: sqlite3.Connection) -> list[dict]: + return [as_dict(r) for r in conn.execute("SELECT * FROM forms ORDER BY is_default DESC, id")] + + +def _insert(conn: sqlite3.Connection, style: str, name: str | None, title: str) -> dict: + items = layout(style, fieldsmod.all_fields(conn), title) + conn.execute("UPDATE forms SET is_default = 0") + cur = conn.execute("INSERT INTO forms (name, style, layout, is_default) VALUES (?, ?, ?, 1)", + ((name or "").strip() or NAMES[style], style, json.dumps(items, separators=(",", ":")))) + return as_dict(conn.execute("SELECT * FROM forms WHERE id = ?", (cur.lastrowid,)).fetchone()) + + +def listing(db: store.Database) -> list[dict]: + with store.reading(db): + found = all_forms(db.conn) + if found or db.readonly: + return found + with store.writing(db) as conn: + if not conn.execute("SELECT 1 FROM forms LIMIT 1").fetchone(): + _insert(conn, "single", None, db.meta("title") or "") + found = all_forms(conn) + return found + + +def generate(db: store.Database, style: str, name: str | None = None, actor: str = "person") -> dict: + if style not in NAMES: + raise DatabaseError("style must be single, double or card.", 422) + with store.writing(db) as conn: + made = _insert(conn, style, name, db.meta("title") or "") + store.audit(db, actor, "form-generate", None, {"form": made["id"], "style": style}) + store.notify(db, "forms") + return made + + +def _clean_items(raw: object) -> list[dict]: + if not isinstance(raw, list): + raise DatabaseError("items must be a list.", 422) + out = [] + for n, it in enumerate(raw): + if not isinstance(it, dict) or it.get("kind") not in KINDS: + raise DatabaseError(f"Item {n + 1} needs a kind: one of {', '.join(KINDS)}.", 422) + geo = {} + for k in ("x", "y", "w", "h"): + v = it.get(k) + if not isinstance(v, (int, float)) or isinstance(v, bool) or v != v or abs(v) > 1e6: + raise DatabaseError(f"Item {n + 1} needs a number for {k}.", 422) + geo[k] = float(v) + if geo["w"] < 0 or geo["h"] < 0: + raise DatabaseError(f"Item {n + 1} has a negative size.", 422) + item = {"kind": it["kind"], **{k: str(it[k]) for k in ("field", "label", "action") if isinstance(it.get(k), str)}, **geo} + if it["kind"] in ("field", "check", "subform") and not item.get("field"): + raise DatabaseError(f"Item {n + 1} ({it['kind']}) names its field.", 422) + out.append(item) + return out + + +def put(db: store.Database, form_id: int, form: dict, actor: str = "person") -> dict: + if not isinstance(form, dict): + raise DatabaseError("Send the form as an object.", 422) + style = form.get("style", "custom") + if style not in STYLES: + raise DatabaseError(f"style must be one of {', '.join(STYLES)}.", 422) + items = _clean_items(form.get("items", [])) + with store.writing(db) as conn: + row = conn.execute("SELECT * FROM forms WHERE id = ?", (form_id,)).fetchone() + if row is None: + raise DatabaseError(f"There is no form {form_id}.", 404) + name = form.get("name") if isinstance(form.get("name"), str) and form.get("name").strip() else row["name"] + if form.get("is_default") is True: + conn.execute("UPDATE forms SET is_default = 0") + default = 1 if form.get("is_default") is True else row["is_default"] + conn.execute("UPDATE forms SET name = ?, style = ?, layout = ?, is_default = ? WHERE id = ?", + (name.strip(), style, json.dumps(items, separators=(",", ":")), default, form_id)) + store.audit(db, actor, "form-save", None, {"form": form_id}) + made = as_dict(conn.execute("SELECT * FROM forms WHERE id = ?", (form_id,)).fetchone()) + store.notify(db, "forms") + return made + + +def refresh(conn: sqlite3.Connection, title: str) -> int: + field_list = fieldsmod.all_fields(conn) + found = conn.execute("SELECT id, style FROM forms WHERE style IN ('single', 'double', 'card')").fetchall() + for row in found: + conn.execute("UPDATE forms SET layout = ? WHERE id = ?", (json.dumps(layout(row["style"], field_list, title), separators=(",", ":")), row["id"])) + return len(found) + + +def drop_field(conn: sqlite3.Connection, name: str) -> None: + for row in conn.execute("SELECT id, layout FROM forms").fetchall(): + try: + items = json.loads(row["layout"]) + except ValueError: + continue + kept = [it for it in items if not (isinstance(it, dict) and it.get("field") == name)] + if len(kept) != len(items): + conn.execute("UPDATE forms SET layout = ? WHERE id = ?", (json.dumps(kept, separators=(",", ":")), row["id"])) diff --git a/backend/app/services/database/hitlists.py b/backend/app/services/database/hitlists.py new file mode 100644 index 00000000..ff7e67ab --- /dev/null +++ b/backend/app/services/database/hitlists.py @@ -0,0 +1,185 @@ +import json +import time +from contextlib import contextmanager + +from app.services.database import store +from app.services.database.store import Database, DatabaseError + +KEEP_UNSAVED = 20 +NAME_LIMIT = 200 +_SCRATCH = ( + "CREATE TEMP TABLE IF NOT EXISTS hitlists (id INTEGER PRIMARY KEY, name TEXT NOT NULL, query TEXT, created REAL NOT NULL, saved INTEGER NOT NULL DEFAULT 0)", + "CREATE TEMP TABLE IF NOT EXISTS hitlist_items (hitlist INTEGER NOT NULL, compound INTEGER NOT NULL, rank INTEGER NOT NULL, score REAL, PRIMARY KEY (hitlist, compound))", +) +_scratched: set[str] = set() + + +def _scratch(db: Database) -> None: + if not db.readonly or db.handle in _scratched: + return + with db.lock: + for statement in _SCRATCH: + db.conn.execute(statement) + db.conn.execute("INSERT OR IGNORE INTO temp.hitlists SELECT id, name, query, created, saved FROM main.hitlists") + db.conn.execute("INSERT OR IGNORE INTO temp.hitlist_items SELECT hitlist, compound, rank, score FROM main.hitlist_items") + _scratched.add(db.handle) + + +@contextmanager +def own_write(db: Database): + from app.services.database import search + with db.lock: + before = search.audit_head(db) + db.conn.execute("BEGIN IMMEDIATE") + try: + yield + db.conn.execute("COMMIT") + except BaseException: + db.conn.execute("ROLLBACK") + raise + search.advance(db, before, search.audit_head(db)) + + +def _row(db: Database, hid: int) -> dict | None: + r = db.conn.execute("SELECT h.id, h.name, h.query, h.created, h.saved, count(i.compound), count(i.score) FROM hitlists h " + "LEFT JOIN hitlist_items i ON i.hitlist = h.id WHERE h.id = ? GROUP BY h.id", (hid,)).fetchone() + return _shape(r) if r else None + + +def _shape(r) -> dict: + try: + q = json.loads(r[2]) if r[2] else None + except ValueError: + q = None + return {"id": r[0], "name": r[1], "count": r[5], "query": q, "created": r[3], "saved": bool(r[4]), "scored": r[6] > 0} + + +def get(db: Database, hid: int) -> dict: + _scratch(db) + with db.lock: + found = _row(db, int(hid)) + if found is None: + raise DatabaseError(f"There is no hit list {hid} in this database.", 404) + return found + + +def all_of(db: Database) -> list[dict]: + _scratch(db) + with db.lock: + rows = db.conn.execute("SELECT h.id, h.name, h.query, h.created, h.saved, count(i.compound), count(i.score) FROM hitlists h " + "LEFT JOIN hitlist_items i ON i.hitlist = h.id GROUP BY h.id ORDER BY h.created DESC, h.id DESC").fetchall() + return [_shape(r) for r in rows] + + +def _clean_name(name: str | None, fallback: str) -> str: + text = " ".join(str(name or "").split())[:NAME_LIMIT] + return text or fallback + + +def _prune(db: Database) -> list[int]: + gone = [r[0] for r in db.conn.execute("SELECT id FROM hitlists WHERE saved = 0 ORDER BY created DESC, id DESC LIMIT -1 OFFSET ?", (KEEP_UNSAVED,)).fetchall()] + if gone: + marks = ",".join("?" * len(gone)) + db.conn.execute(f"DELETE FROM hitlist_items WHERE hitlist IN ({marks})", gone) + db.conn.execute(f"DELETE FROM hitlists WHERE id IN ({marks})", gone) + return gone + + +def create(db: Database, name: str | None, ids: list[int], scores: dict[int, float] | None = None, query: dict | None = None, + actor: str = "person", saved: bool = False) -> dict: + _scratch(db) + label = _clean_name(name, "Hit list") + now = time.time() + seen: set[int] = set() + items = [] + for cid in ids: + if cid in seen: + continue + seen.add(cid) + items.append((cid, len(items) + 1, None if scores is None else scores.get(cid))) + with db.lock: + with own_write(db): + cur = db.conn.execute("INSERT INTO hitlists (name, query, created, saved) VALUES (?, ?, ?, ?)", + (label, json.dumps(query, separators=(",", ":")) if query is not None else None, now, 1 if saved else 0)) + hid = cur.lastrowid + db.conn.executemany("INSERT INTO hitlist_items (hitlist, compound, rank, score) VALUES (?, ?, ?, ?)", [(hid, c, r, s) for c, r, s in items]) + pruned = _prune(db) + store.audit(db, actor, "hitlist.create", None, {"id": hid, "name": label, "count": len(items), "pruned": pruned or None}) + out = _row(db, hid) + store.notify(db, "hitlists") + return out + + +COMBINE_OPS = ("union", "intersect", "difference") +_COMBINE_WORDS = {"union": "or", "intersect": "and", "difference": "minus"} + + +def update(db: Database, hid: int, name: str | None = None, saved: bool | None = None, actor: str = "person") -> dict: + db.writable() + current = get(db, hid) + label = _clean_name(name, current["name"]) if name is not None else current["name"] + keep = current["saved"] if saved is None else bool(saved) + with db.lock: + with own_write(db): + db.conn.execute("UPDATE hitlists SET name = ?, saved = ? WHERE id = ?", (label, 1 if keep else 0, current["id"])) + pruned = _prune(db) if not keep else [] + store.audit(db, actor, "hitlist.update", None, {"id": current["id"], "name": label, "saved": keep, "pruned": pruned or None}) + out = _row(db, current["id"]) + store.notify(db, "hitlists") + return out + + +def delete(db: Database, hid: int, actor: str = "person") -> dict: + db.writable() + current = get(db, hid) + with db.lock: + with own_write(db): + db.conn.execute("DELETE FROM hitlist_items WHERE hitlist = ?", (current["id"],)) + db.conn.execute("DELETE FROM hitlists WHERE id = ?", (current["id"],)) + store.audit(db, actor, "hitlist.delete", None, {"id": current["id"], "name": current["name"]}) + store.notify(db, "hitlists") + return {"deleted": current["id"]} + + +def _members(db: Database, hid: int) -> list[int]: + with db.lock: + return [r[0] for r in db.conn.execute("SELECT compound FROM hitlist_items WHERE hitlist = ? ORDER BY rank", (hid,)).fetchall()] + + +def combine(db: Database, a: int, b: int, op: str, name: str | None = None, actor: str = "person") -> dict: + if op not in COMBINE_OPS: + raise DatabaseError(f"op is one of {', '.join(COMBINE_OPS)}.", 422) + first, second = get(db, a), get(db, b) + left, right = _members(db, first["id"]), set(_members(db, second["id"])) + if op == "union": + seen = set(left) + ids = left + [c for c in _members(db, second["id"]) if c not in seen] + elif op == "intersect": + ids = [c for c in left if c in right] + else: + ids = [c for c in left if c not in right] + terms = [{"kind": "hitlist", "id": first["id"]}, {"kind": "hitlist", "id": second["id"]}] + if op == "union": + q = {"op": "or", "terms": terms} + elif op == "intersect": + q = {"op": "and", "terms": terms} + else: + q = {"op": "and", "terms": [terms[0], {"op": "not", "terms": [terms[1]]}]} + label = name or f"{first['name']} {_COMBINE_WORDS[op]} {second['name']}" + return create(db, label, ids, None, q, actor) + + +def from_selection(db: Database, uids: list[str], name: str | None = None, actor: str = "person") -> dict: + if not isinstance(uids, list) or not all(isinstance(u, str) for u in uids): + raise DatabaseError("uids is a list of record uids.", 422) + wanted = list(dict.fromkeys(uids)) + found: dict[str, int] = {} + with db.lock: + for start in range(0, len(wanted), 500): + part = wanted[start:start + 500] + marks = ",".join("?" * len(part)) + found.update({r[1]: r[0] for r in db.conn.execute(f"SELECT id, uid FROM compounds WHERE uid IN ({marks})", part).fetchall()}) + if wanted and not found: + raise DatabaseError("None of those records is in this database.", 404) + ids = [found[u] for u in wanted if u in found] + return create(db, name or f"Selection of {len(ids)} records", ids, None, None, actor) diff --git a/backend/app/services/database/imports.py b/backend/app/services/database/imports.py new file mode 100644 index 00000000..7ae19d92 --- /dev/null +++ b/backend/app/services/database/imports.py @@ -0,0 +1,500 @@ +import csv +import gzip +import io as stdio +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Iterator + +from rdkit import Chem +from rdkit.Chem import rdDepictor + +from app.services.chem import io as chemio +from app.services.chem import records as chemrecords +from app.services.chem import stream +from app.services.database import fields as fieldsmod +from app.services.database import info, jobs, records, schema, store +from app.services.database.store import DatabaseError + +FORMATS = ("sdf", "rdf", "smiles", "csv", "tsv", "fchem", "molfile", "inchi") +MODES = ("new", "append", "merge") +BATCH = 250 +SAMPLE = 200 +NAME_COLUMN = "name" +STRUCTURE_HEADERS = ("smiles", "canonical_smiles", "isomeric_smiles", "smiles_string", "structure", "inchi", "std_inchi", "standard_inchi") +SKIP_BUILTINS = {"formula", "mw", "exact_mass", "smiles", "inchikey", "inchi", "uid", "number", "batch", "created", "modified", "structure"} + + +@dataclass +class Item: + number: int + structure: dict | None + name: str = "" + data: dict = field(default_factory=dict) + error: str = "" + + +def format_of(path: Path, given: str | None = None) -> str: + if given: + g = given.lower().lstrip(".") + g = {"sd": "sdf", "smi": "smiles", "rd": "rdf", "mol": "molfile", "txt": "tsv"}.get(g, g) + if g not in FORMATS: + raise DatabaseError(f"FormChem imports {', '.join(FORMATS)} into a database, not {given}.", 422) + return g + suffixes = [s.lower() for s in path.suffixes] + if suffixes and suffixes[-1] == ".gz": + suffixes = suffixes[:-1] + ext = suffixes[-1] if suffixes else "" + if ext in (".csv",): + return "csv" + if ext in (".tsv", ".tab", ".txt"): + return "tsv" + found = chemrecords.EXTENSIONS.get(ext) + if found in FORMATS: + return found + raise DatabaseError(f"FormChem cannot tell the format of {path.name}; choose it in the import dialog.", 422) + + +def _path(path: str) -> Path: + if not isinstance(path, str) or not path.strip(): + raise DatabaseError("Give the path of the file to import.", 422) + p = Path(path.strip()).expanduser() + if not p.is_file(): + raise DatabaseError(f"No file at {p}.", 404) + return p + + +def _text_lines(path: Path) -> Iterator[str]: + opener = gzip.open(path, "rt", encoding="utf-8-sig", errors="replace", newline="") if path.suffix.lower() == ".gz" else \ + open(path, encoding="utf-8-sig", errors="replace", newline="") + with opener as fh: + yield from fh + + +def _molblock_of(mol: Chem.Mol) -> str: + drawn = Chem.Mol(mol) + if drawn.GetNumConformers() == 0: + rdDepictor.Compute2DCoords(drawn) + return Chem.MolToMolBlock(drawn) + + +PLAIN_REASONS = ( + ("Range Error", "a bond names an atom the connection table does not have"), + ("Atom line too short", "the connection table ends early or an atom line is cut short"), + ("Explicit valence", "an atom has more bonds than its valence allows"), +) + + +def plain(reason: str) -> str: + for start, text in PLAIN_REASONS: + if reason.startswith(start): + return f"{text} (RDKit: {reason})" + return reason + + +def _chem_items(path: Path, fmt: str) -> Iterator[Item]: + for rec in chemrecords.iter_records(path, fmt): + number = rec.index + 1 + block = getattr(rec, "block", "") or "" + data = {str(k): ("" if v is None else str(v)) for k, v in (rec.data or {}).items()} + name = (rec.name or "").strip() + if rec.mol is None: + yield Item(number, None, name, data, plain(rec.error or "could not be read")) + continue + if fmt in ("sdf", "rdf", "molfile") and "M END" in block: + structure = {"molfile": chemio.sd_fields(block)[0]} + else: + structure = {"molfile": _molblock_of(rec.mol)} + yield Item(number, structure, name, data) + + +def _delimiter(path: Path, fmt: str) -> str: + return "," if fmt == "csv" else "\t" + + +def _structure_column(header: list[str], rows: list[list[str]]) -> tuple[str | None, str]: + lowered = [h.strip().lower() for h in header] + for i, h in enumerate(lowered): + if h in STRUCTURE_HEADERS: + values = [r[i] for r in rows if i < len(r) and r[i].strip()] + return header[i], "inchi" if values and all(v.strip().startswith("InChI=") for v in values[:20]) or "inchi" in h else "smiles" + best, kind, score = None, "smiles", 0.0 + for i, h in enumerate(header): + values = [r[i].strip() for r in rows if i < len(r) and r[i].strip()][:50] + if not values: + continue + if sum(v.startswith("InChI=") for v in values) >= 0.8 * len(values): + return h, "inchi" + if all(v.replace(".", "").replace("-", "").isdigit() for v in values): + continue + ok = sum(1 for v in values if " " not in v and Chem.MolFromSmiles(v) is not None) + if ok / len(values) > max(score, 0.79): + best, score = h, ok / len(values) + return best, kind + + +def _table(path: Path, fmt: str) -> tuple[list[str], Iterator[list[str]]]: + lines = _text_lines(path) + reader = csv.reader(lines, delimiter=_delimiter(path, fmt)) + header = next(reader, None) + if not header: + raise DatabaseError(f"{path.name} is empty.", 422) + seen: dict[str, int] = {} + names = [] + for h in header: + h = h.strip() or "column" + seen[h] = seen.get(h, 0) + 1 + names.append(h if seen[h] == 1 else f"{h} {seen[h]}") + return names, reader + + +def _table_items(path: Path, fmt: str) -> Iterator[Item]: + header, reader = _table(path, fmt) + head_rows: list[list[str]] = [] + for row in reader: + head_rows.append(row) + if len(head_rows) >= SAMPLE: + break + column, kind = _structure_column(header, head_rows) + if column is None: + raise DatabaseError(f"No column of {path.name} holds SMILES or InChI; name one smiles or inchi.", 422) + at = header.index(column) + + def rows() -> Iterator[list[str]]: + yield from head_rows + yield from reader + + for n, row in enumerate(rows(), start=1): + if not any(c.strip() for c in row): + continue + data = {h: (row[i] if i < len(row) else "") for i, h in enumerate(header) if i != at} + text = row[at].strip() if at < len(row) else "" + if not text: + yield Item(n, None, "", data, f"no structure in the {column} column") + continue + if kind == "inchi": + mol = Chem.MolFromInchi(text) if text.startswith("InChI=") else None + if mol is None: + yield Item(n, None, "", data, "not a readable InChI") + continue + yield Item(n, {"molfile": _molblock_of(chemio.amide_form(mol))}, "", data) + elif Chem.MolFromSmiles(text) is None: + yield Item(n, None, "", data, stream.explain(lambda: Chem.MolFromSmiles(text)) or "not a valid SMILES") + else: + yield Item(n, {"smiles": text}, "", data) + + +def items(path: Path, fmt: str) -> Iterator[Item]: + if fmt in ("csv", "tsv"): + yield from _table_items(path, fmt) + else: + yield from _chem_items(path, fmt) + + +def _count(path: Path, fmt: str) -> int: + if fmt == "sdf": + n, last = 0, "" + for line in _text_lines(path): + if line.startswith("$$$$"): + n += 1 + last = "" + elif line.strip(): + last = line + return n + (1 if last else 0) + if fmt in ("smiles", "inchi"): + return sum(1 for line in _text_lines(path) if line.strip() and not line.lstrip().startswith("#")) + if fmt in ("csv", "tsv"): + _header, reader = _table(path, fmt) + return sum(1 for row in reader if any(c.strip() for c in row)) + return sum(1 for _ in items(path, fmt)) + + +def _columns(path: Path, fmt: str) -> tuple[list[dict], dict]: + samples: dict[str, list[str]] = {} + names_seen = False + extra: dict = {} + if fmt in ("csv", "tsv"): + header, reader = _table(path, fmt) + rows = [r for _, r in zip(range(SAMPLE), reader)] + column, kind = _structure_column(header, rows) + extra = {"structure_column": column, "structure_kind": kind} + for i, h in enumerate(header): + if h != column: + samples[h] = [r[i] for r in rows if i < len(r)] + else: + for _, it in zip(range(SAMPLE), items(path, fmt)): + if it.name: + names_seen = True + for k, v in it.data.items(): + samples.setdefault(k, []).append(v) + if names_seen and NAME_COLUMN not in samples: + samples = {NAME_COLUMN: [], **samples} + for _, it in zip(range(SAMPLE), items(path, fmt)): + samples[NAME_COLUMN].append(it.name) + cols = [{"name": k, "type": fieldsmod.detect(v), "sample": [s for s in v if s.strip()][:3]} for k, v in samples.items()] + return cols, extra + + +def default_mapping(conn, columns: list[dict]) -> dict[str, str]: + existing = fieldsmod.all_fields(conn) + by_name = {f["name"]: f for f in existing} + by_label = {f["label"].strip().lower(): f for f in existing} + out: dict[str, str] = {} + for col in columns: + name = col["name"] + found = by_name.get(name) or by_label.get(name.strip().lower()) + if found is not None and found["type"] != "computed": + out[name] = found["name"] + elif name.strip().lower() in SKIP_BUILTINS or found is not None: + out[name] = "" + else: + out[name] = "+" + ("Name" if name == NAME_COLUMN else name) + return out + + +def preview(db: store.Database, path: str, fmt: str | None = None) -> dict: + p = _path(path) + kind = format_of(p, fmt) + try: + cols, extra = _columns(p, kind) + total = _count(p, kind) + except (ValueError, OSError) as exc: + raise DatabaseError(f"{p.name} could not be read: {exc}", 422) + with store.reading(db): + mapping = default_mapping(db.conn, cols) + return {"format": kind, "count": total, "columns": cols, "mapping": mapping, "path": str(p), **extra} + + +def _check_mapping(conn, mapping: object, columns: list[dict]) -> dict[str, str]: + if mapping is None: + return default_mapping(conn, columns) + if not isinstance(mapping, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in mapping.items()): + raise DatabaseError("mapping must be an object of column to field name, \"\" to skip, or \"+label\" for a new field.", 422) + by_name = {f["name"]: f for f in fieldsmod.all_fields(conn)} + for col, target in mapping.items(): + if not target or target.startswith("+"): + if target.startswith("+") and not target[1:].strip(): + raise DatabaseError(f"The new field for {col} needs a label after the +.", 422) + continue + f = by_name.get(target) + if f is None: + raise DatabaseError(f"{col} is mapped to {target}, but this database has no such field.", 422) + if f["type"] == "computed": + raise DatabaseError(f"{col} is mapped to {f['label']}, which is computed from the structure.", 422) + return dict(mapping) + + +def _targets(conn, mapping: dict[str, str], types: dict[str, str], create: bool) -> tuple[dict[str, dict], list[str]]: + by_name = {f["name"]: f for f in fieldsmod.all_fields(conn)} + taken = set(by_name) + out: dict[str, dict] = {} + made: list[str] = [] + for col, target in mapping.items(): + if not target: + continue + if target.startswith("+"): + label = target[1:].strip() + ftype = types.get(col, "text") + if create: + f = fieldsmod.create(conn, {"label": label, "type": ftype}) + made.append(f["name"]) + else: + f = {"id": None, "name": fieldsmod.slug(label, taken), "label": label, "type": ftype, "choices": None} + taken.add(f["name"]) + by_name[f["name"]] = f + out[col] = f + else: + out[col] = by_name[target] + return out, made + + +def _dup_key(reg: dict, rules: dict) -> str: + key = reg["parent_key"] if rules.get("salts") == "strip" else reg["inchikey"] + return key.split("-")[0] if key and rules.get("stereo") == "ignore" else key + + +def _by_field(conn, f: dict, num, txt) -> int | None: + if f.get("id") is None: + return None + if txt is not None: + row = conn.execute("SELECT compound FROM field_values WHERE field = ? AND txt = ? LIMIT 1", (f["id"], txt)).fetchone() + else: + row = conn.execute("SELECT compound FROM field_values WHERE field = ? AND num = ? LIMIT 1", (f["id"], num)).fetchone() + return row[0] if row else None + + +@dataclass +class _Plan: + db: store.Database + mode: str + key: str | None + on_dup: str + rules: dict + seen: set = field(default_factory=set) + + +def _decide(conn, plan: _Plan, reg: dict, values: list) -> tuple[str, int | None]: + if plan.mode == "merge": + if plan.key == "structure": + ids = records.duplicate_ids(conn, reg, plan.rules) + mark = ("s", _dup_key(reg, plan.rules)) + return ("update", ids[0]) if ids else ("update", None) if mark in plan.seen else ("add", None) + keyed = next(((f, n, t) for f, n, t in values if f["name"] == plan.key), None) + if keyed is None: + return "add", None + found = _by_field(conn, *keyed) + mark = ("f", keyed[1], keyed[2]) + return ("update", found) if found else ("update", None) if mark in plan.seen else ("add", None) + if plan.on_dup in ("batch", "existing"): + ids = records.duplicate_ids(conn, reg, plan.rules) + if ids or ("s", _dup_key(reg, plan.rules)) in plan.seen: + return ("skip", None) if plan.on_dup == "existing" else ("batch", ids[0] if ids else None) + return "add", None + + +def _remember(plan: _Plan, reg: dict, values: list) -> None: + plan.seen.add(("s", _dup_key(reg, plan.rules))) + if plan.mode == "merge" and plan.key != "structure": + keyed = next(((f, n, t) for f, n, t in values if f["name"] == plan.key), None) + if keyed is not None: + plan.seen.add(("f", keyed[1], keyed[2])) + + +def _flush(job: jobs.Job, plan: _Plan, pending: list) -> None: + if not pending: + return + if job.dry_run: + with store.reading(plan.db): + for _number, reg, values in pending: + action, _ = _decide(plan.db.conn, plan, reg, values) + if action in ("add", "batch"): + job.added += 1 + elif action == "update": + job.updated += 1 + else: + job.skipped += 1 + _remember(plan, reg, values) + return + now = time.time() + with store.writing(plan.db) as conn: + for number, reg, values in pending: + conn.execute("SAVEPOINT record") + try: + action, target = _decide(conn, plan, reg, values) + if action == "update" and target is not None: + records.write_values(conn, target, values) + conn.execute("UPDATE compounds SET modified = ? WHERE id = ?", (now, target)) + job.updated += 1 + elif action == "skip": + job.skipped += 1 + else: + records.insert(plan.db, conn, reg, values, target if action == "batch" else None, now) + job.added += 1 + conn.execute("RELEASE record") + except Exception as exc: + conn.execute("ROLLBACK TO record") + conn.execute("RELEASE record") + job.fail(number, f"not stored: {exc}") + store.notify(plan.db, "records") + + +def _values_of(job: jobs.Job, it: Item, targets: dict[str, dict]) -> list: + out = [] + for col, f in targets.items(): + raw = it.data.get(col) if col in it.data else (it.name if col == NAME_COLUMN else None) + if raw is None or not str(raw).strip(): + continue + try: + num, txt = fieldsmod.coerce(f, raw, text=True) + except DatabaseError as exc: + job.note(it.number, f"stored without this value: {exc}") + continue + if num is not None or txt is not None: + out.append((f, num, txt)) + return out + + +def _work(job: jobs.Job, db: store.Database, p: Path, kind: str, mapping: dict, types: dict, plan: _Plan, actor: str) -> None: + who = "import" if actor == "person" else actor + if job.dry_run: + with store.reading(db): + targets, made = _targets(db.conn, mapping, types, create=False) + else: + with store.writing(db) as conn: + targets, made = _targets(conn, mapping, types, create=True) + if made: + fieldsmod.rebuild_view(conn) + from app.services.database import forms + forms.refresh(conn, db.meta("title") or "") + if made: + store.notify(db, "fields") + store.notify(db, "forms") + job.detail["created_fields"] = made + job.total = _count(p, kind) + pending: list = [] + for it in items(p, kind): + if job.cancelled: + break + job.read += 1 + if it.structure is None: + job.fail(it.number, it.error or "could not be read") + continue + try: + reg = records.register(it.structure) + except DatabaseError as exc: + job.fail(it.number, str(exc)) + continue + pending.append((it.number, reg, _values_of(job, it, targets))) + if len(pending) >= BATCH: + _flush(job, plan, pending) + pending = [] + if not job.cancelled: + _flush(job, plan, pending) + if not job.dry_run: + with store.writing(db): + store.audit(db, who, "import", None, {"file": str(p), "format": kind, "mode": plan.mode, "read": job.read, "added": job.added, + "updated": job.updated, "failed": job.failed, "cancelled": job.cancelled}) + store.notify(db, "info") + info.remember(db, opened=False) + + +def start(db: store.Database, path: str, fmt: str | None = None, mode: str = "new", key: str | None = None, mapping: dict | None = None, + dry_run: bool = False, actor: str = "person") -> dict: + if not dry_run: + db.writable() + if mode not in MODES: + raise DatabaseError(f"mode must be one of {', '.join(MODES)}.", 422) + p = _path(path) + kind = format_of(p, fmt) + try: + cols, _extra = _columns(p, kind) + except (ValueError, OSError) as exc: + raise DatabaseError(f"{p.name} could not be read: {exc}", 422) + with store.reading(db): + checked = _check_mapping(db.conn, mapping, cols) + names = {f["name"] for f in fieldsmod.all_fields(db.conn)} + if mode == "merge": + key = key or "structure" + new_names = {fieldsmod.slug(t[1:].strip(), names) for t in checked.values() if t.startswith("+")} + mapped = {t for t in checked.values() if t and not t.startswith("+")} | new_names + if key != "structure" and key not in mapped: + raise DatabaseError(f"Merge on {key} needs a column mapped to that field.", 422) + rules = db.rules() + on_dup = "new" if rules["on_duplicate"] == "ask" else rules["on_duplicate"] + plan = _Plan(db, mode, key if mode == "merge" else None, on_dup, rules) + types = {c["name"]: c["type"] for c in cols} + job = jobs.start("import", db.handle, lambda j: _work(j, db, p, kind, checked, types, plan, actor), dry_run, + {"format": kind, "mode": mode, "key": plan.key, "path": str(p)}) + return job.as_dict() + + +def job(job_id: str) -> dict: + return jobs.get(job_id).as_dict() + + +def cancel(job_id: str) -> dict: + return jobs.cancel(job_id).as_dict() + + +def wait(job_id: str, timeout: float | None = None) -> dict: + return jobs.wait(job_id, timeout).as_dict() diff --git a/backend/app/services/database/info.py b/backend/app/services/database/info.py new file mode 100644 index 00000000..d0ce952d --- /dev/null +++ b/backend/app/services/database/info.py @@ -0,0 +1,100 @@ +import json + +from app.services import library +from app.services.database import fields as fieldsmod +from app.services.database import forms, store +from app.services.database.store import DatabaseError + +RULE_VALUES = {"stereo": ("match", "ignore"), "salts": ("strip", "keep"), "on_duplicate": ("ask", "new", "batch", "existing")} + + +def count(db: store.Database) -> int: + with store.reading(db): + return db.conn.execute("SELECT count(*) FROM compounds").fetchone()[0] + + +def describe(db: store.Database) -> dict: + form_list = forms.listing(db) + with store.reading(db): + conn = db.conn + total = conn.execute("SELECT count(*) FROM compounds").fetchone()[0] + entries = conn.execute("SELECT count(*) FROM entries").fetchone()[0] + field_list = fieldsmod.all_fields(conn) + title = db.meta("title") or db.path.stem + description = db.meta("description") or "" + return {"db": db.handle, "path": str(db.path), "title": title, "description": description, "count": total, + "readonly": db.readonly, "readonly_reason": db.readonly_reason, "rules": db.rules(), "fields": field_list, + "forms": form_list, "entries": entries} + + +def remember(db: store.Database, opened: bool = True) -> None: + try: + library.remember_database(db.path, db.meta("title") or db.path.stem, count(db), opened) + except OSError: + pass + + +def _ready(db: store.Database) -> store.Database: + fieldsmod.ensure_view(db) + remember(db) + return db + + +def create_database(title: str, path: str | None = None) -> store.Database: + return _ready(store.create(title, path)) + + +def open_database(path: str) -> store.Database: + if not isinstance(path, str) or not path.strip(): + raise DatabaseError("Give the path of the database to open.", 422) + return _ready(store.open_path(path.strip())) + + +def close_database(handle: str) -> None: + db = store.get(handle) + remember(db, opened=False) + store.close(handle) + + +def known() -> list[dict]: + return library.databases() + + +def _rules(given: object, current: dict) -> dict: + if not isinstance(given, dict): + raise DatabaseError("rules must be an object.", 422) + out = dict(current) + for key, value in given.items(): + if key not in RULE_VALUES: + raise DatabaseError(f"{key} is not a duplicate rule; the rules are {', '.join(RULE_VALUES)}.", 422) + if value not in RULE_VALUES[key]: + raise DatabaseError(f"{key} must be one of {', '.join(RULE_VALUES[key])}.", 422) + out[key] = value + return out + + +def update(db: store.Database, body: dict, actor: str = "person") -> dict: + if not isinstance(body, dict): + raise DatabaseError("Send the changes as an object.", 422) + changed = {} + with store.writing(db): + if "title" in body: + if not isinstance(body["title"], str) or not body["title"].strip(): + raise DatabaseError("A database needs a title.", 422) + db.set_meta("title", body["title"].strip()) + changed["title"] = body["title"].strip() + if "description" in body: + if not isinstance(body["description"], str): + raise DatabaseError("description must be text.", 422) + db.set_meta("description", body["description"]) + changed["description"] = True + if "rules" in body: + rules = _rules(body["rules"], db.rules()) + db.set_meta("rules", json.dumps(rules, separators=(",", ":"))) + changed["rules"] = rules + if changed: + store.audit(db, actor, "database-update", None, changed) + if "title" in changed: + remember(db, opened=False) + store.notify(db, "info") + return describe(db) diff --git a/backend/app/services/database/jobs.py b/backend/app/services/database/jobs.py new file mode 100644 index 00000000..651b80c4 --- /dev/null +++ b/backend/app/services/database/jobs.py @@ -0,0 +1,104 @@ +import threading +import time +from dataclasses import dataclass, field +from typing import Callable + +from app.services.database import store +from app.services.database.store import DatabaseError + +KEEP = 50 +REPORT_CAP = 5000 +_LOCK = threading.RLock() +_JOBS: dict[str, "Job"] = {} + + +@dataclass +class Job: + id: str + kind: str + db: str + dry_run: bool = False + state: str = "running" + total: int | None = None + read: int = 0 + added: int = 0 + updated: int = 0 + failed: int = 0 + skipped: int = 0 + report: list[dict] = field(default_factory=list) + notes: list[dict] = field(default_factory=list) + error: str | None = None + detail: dict = field(default_factory=dict) + started: float = field(default_factory=time.time) + finished: float | None = None + cancel_requested: threading.Event = field(default_factory=threading.Event) + done: threading.Event = field(default_factory=threading.Event) + + def fail(self, record: int, reason: str) -> None: + self.failed += 1 + if len(self.report) < REPORT_CAP: + self.report.append({"record": record, "reason": reason}) + + def note(self, record: int, reason: str) -> None: + if len(self.notes) < REPORT_CAP: + self.notes.append({"record": record, "reason": reason}) + + @property + def cancelled(self) -> bool: + return self.cancel_requested.is_set() + + def as_dict(self) -> dict: + end = self.finished or time.time() + return {"job": self.id, "kind": self.kind, "db": self.db, "state": self.state, "total": self.total, "read": self.read, + "added": self.added, "updated": self.updated, "failed": self.failed, "skipped": self.skipped, + "report": list(self.report), "report_truncated": self.failed > len(self.report), "notes": list(self.notes), + "dry_run": self.dry_run, "error": self.error, "seconds": round(end - self.started, 3), **self.detail} + + +def _prune() -> None: + finished = sorted((j for j in _JOBS.values() if j.state != "running"), key=lambda j: j.finished or 0) + for old in finished[:max(0, len(finished) - KEEP)]: + _JOBS.pop(old.id, None) + + +def start(kind: str, db: str, work: Callable[[Job], None], dry_run: bool = False, detail: dict | None = None) -> Job: + job = Job(store.new_id("j", 10), kind, db, dry_run, detail=dict(detail or {})) + + def run() -> None: + try: + work(job) + job.state = "cancelled" if job.cancelled else "done" + except DatabaseError as exc: + job.state, job.error = "failed", str(exc) + except Exception as exc: + job.state, job.error = "failed", f"{type(exc).__name__}: {exc}" + finally: + job.finished = time.time() + job.done.set() + + with _LOCK: + _prune() + _JOBS[job.id] = job + threading.Thread(target=run, name=f"formchem-{kind}-{job.id}", daemon=True).start() + return job + + +def get(job_id: str) -> Job: + with _LOCK: + job = _JOBS.get(job_id) + if job is None: + raise DatabaseError(f"There is no job {job_id}.", 404) + return job + + +def cancel(job_id: str) -> Job: + job = get(job_id) + if job.state == "running": + job.cancel_requested.set() + return job + + +def wait(job_id: str, timeout: float | None = None) -> Job: + job = get(job_id) + job.done.wait(timeout) + return job diff --git a/backend/app/services/database/plot.py b/backend/app/services/database/plot.py new file mode 100644 index 00000000..86baaab2 --- /dev/null +++ b/backend/app/services/database/plot.py @@ -0,0 +1,86 @@ +import rdkit + +from app.services.database.store import Database, DatabaseError + +ENGINE = f"RDKit {rdkit.__version__}" +BUILTINS = { + "number": ("Number", None, None), + "batch": ("Batch", None, None), + "mw": ("Molecular weight", "g/mol", f"average mass from IUPAC atomic weights ({ENGINE} periodic table)"), + "exact_mass": ("Exact mass", "Da", f"monoisotopic mass from the most common isotopes ({ENGINE} periodic table)"), + "heavy_atoms": ("Heavy atoms", None, f"heavy atom count ({ENGINE})"), + "created": ("Created", None, None), + "modified": ("Modified", None, None), +} +NUMERIC_TYPES = frozenset({"integer", "real", "datetime", "boolean", "computed"}) +TEXT_BUILTINS = frozenset({"uid", "smiles", "formula", "inchikey", "structure"}) + + +def _axis(db: Database, name: str) -> dict: + if not isinstance(name, str) or not name.strip(): + raise DatabaseError("Give x, a numeric field or one of number, batch, mw, exact_mass, heavy_atoms, created, modified.", 422) + name = name.strip() + if name in BUILTINS: + label, unit, method = BUILTINS[name] + return {"name": name, "builtin": True, "label": label, "unit": unit, "method": method, "type": "datetime" if name in ("created", "modified") else "real"} + if name in TEXT_BUILTINS: + raise DatabaseError(f"{name} is text, which has no numbers to plot.", 422) + with db.lock: + r = db.conn.execute("SELECT id, name, label, type, unit, computed FROM fields WHERE name = ?", (name,)).fetchone() + if r is None: + raise DatabaseError(f"There is no field {name!r} to plot.", 404) + if r[3] not in NUMERIC_TYPES: + raise DatabaseError(f"Field {name!r} holds {r[3]}, which has no numbers to plot.", 422) + method = f"computed descriptor {r[5]} (the analysis property service, {ENGINE})" if r[3] == "computed" and r[5] else None + return {"name": name, "builtin": False, "id": r[0], "label": r[2] or name, "unit": r[4], "method": method, "type": r[3]} + + +def _values(db: Database, axis: dict) -> dict[int, float]: + with db.lock: + if axis["builtin"]: + rows = db.conn.execute(f"SELECT id, {axis['name']} FROM compounds WHERE {axis['name']} IS NOT NULL").fetchall() + else: + rows = db.conn.execute("SELECT compound, num FROM field_values WHERE field = ? AND num IS NOT NULL", (axis["id"],)).fetchall() + return {r[0]: float(r[1]) for r in rows if isinstance(r[1], (int, float))} + + +def _base(db: Database, hitlist: int | None) -> list[tuple[int, str]]: + with db.lock: + if hitlist is None: + return db.conn.execute("SELECT id, uid FROM compounds ORDER BY number, batch").fetchall() + if db.conn.execute("SELECT 1 FROM hitlists WHERE id = ?", (hitlist,)).fetchone() is None: + raise DatabaseError(f"There is no hit list {hitlist} in this database.", 404) + return db.conn.execute("SELECT c.id, c.uid FROM hitlist_items i JOIN compounds c ON c.id = i.compound WHERE i.hitlist = ? ORDER BY i.rank", + (hitlist,)).fetchall() + + +def _label(axis: dict) -> str: + return f"{axis['label']} ({axis['unit']})" if axis.get("unit") else axis["label"] + + +def points(db: Database, x: str, y: str | None = None, hitlist: int | None = None) -> dict: + from app.services.database import hitlists + hitlists._scratch(db) + ax = _axis(db, x) + ay = _axis(db, y) if y else None + base = _base(db, int(hitlist) if hitlist is not None else None) + xs = _values(db, ax) + ys = _values(db, ay) if ay else None + out = [] + missing = 0 + for cid, uid in base: + vx = xs.get(cid) + if ys is None: + if vx is None: + missing += 1 + continue + out.append([uid, vx]) + continue + vy = ys.get(cid) + if vx is None or vy is None: + missing += 1 + continue + out.append([uid, vx, vy]) + return {"points": out, "x_label": _label(ax), "y_label": _label(ay) if ay else None, "missing": missing, + "x_type": ax["type"], "y_type": ay["type"] if ay else None, + "methods": {k: v for k, v in (("x", ax["method"]), ("y", ay["method"] if ay else None)) if v}} diff --git a/backend/app/services/database/query.py b/backend/app/services/database/query.py new file mode 100644 index 00000000..3f0bfca7 --- /dev/null +++ b/backend/app/services/database/query.py @@ -0,0 +1,334 @@ +import math +import re +from datetime import datetime, timezone + +from app.services.database.store import DatabaseError + +GROUP_OPS = ("and", "or", "not") +KINDS = ("exact", "substructure", "similarity", "formula", "mass", "text", "number", "date", "choice", "empty", "hitlist") +STRUCTURE_KINDS = frozenset({"exact", "substructure", "similarity"}) +TEXT_MATCHES = ("contains", "starts", "word", "equals", "regex") +COMPARISONS = ("<", "<=", "=", ">=", ">", "between") +MASS_FIELDS = ("mw", "exact_mass") +TEXT_BUILTINS = frozenset({"smiles", "uid", "formula", "inchikey"}) +NUMBER_BUILTINS = frozenset({"number", "batch", "mw", "exact_mass", "heavy_atoms"}) +DATE_BUILTINS = frozenset({"created", "modified"}) +EMPTY_BUILTINS = frozenset({"smiles", "formula", "inchikey", "mw", "exact_mass"}) +TEXT_TYPES = frozenset({"text", "richtext", "choice", "multichoice", "link", "structure", "reaction", "computed"}) +NUMBER_TYPES = frozenset({"integer", "real", "datetime", "boolean", "computed"}) +DATE_TYPES = frozenset({"datetime"}) +CHOICE_TYPES = frozenset({"choice", "multichoice"}) +MAX_DEPTH = 16 +MAX_TERMS = 200 +MAX_TEXT = 2000 +MAX_STRUCTURE = 2_000_000 +DEFAULT_THRESHOLD = 0.7 + + +class QueryError(DatabaseError): + def __init__(self, message: str): + super().__init__(message, 422) + + +def _num(v, what: str, required: bool = True) -> float | None: + if v is None or v == "": + if required: + raise QueryError(f"{what} needs a number.") + return None + if isinstance(v, bool) or not isinstance(v, (int, float, str)): + raise QueryError(f"{what} must be a number.") + try: + out = float(v) + except ValueError: + raise QueryError(f"{what} must be a number, not {str(v)[:40]!r}.") + if not math.isfinite(out): + raise QueryError(f"{what} must be a finite number.") + return out + + +def _time(v, what: str) -> float | None: + if v is None or v == "": + return None + if isinstance(v, str) and not re.fullmatch(r"\s*-?\d+(\.\d+)?\s*", v): + try: + when = datetime.fromisoformat(v.strip().replace("Z", "+00:00")) + except ValueError: + raise QueryError(f"{what} must be seconds since 1970 or a date like 2026-01-31.") + if when.tzinfo is None: + when = when.replace(tzinfo=timezone.utc) + return when.timestamp() + return _num(v, what) + + +def _field(term: dict, fields: dict[str, str], builtins: frozenset, types: frozenset, kind: str) -> str: + name = term.get("field") + if not isinstance(name, str) or not name.strip(): + raise QueryError(f"A {kind} term needs field.") + name = name.strip() + if name in builtins: + return name + if name not in fields: + lowered = {k.lower(): k for k in fields} + name = lowered.get(name.lower(), name) + ftype = fields.get(name) + if ftype is None: + known = sorted(builtins) + sorted(k for k, t in fields.items() if t in types) + raise QueryError(f"There is no field {name!r} for a {kind} term. Fields that fit: {', '.join(known) or 'none'}.") + if ftype not in types: + raise QueryError(f"Field {name!r} holds {ftype}, which a {kind} term cannot search.") + return name + + +def _structure(term: dict, kind: str) -> dict: + s = term.get("structure") + if isinstance(s, str): + s = {"molfile": s} if "\n" in s else {"smiles": s} + if not isinstance(s, dict): + raise QueryError(f"A {kind} term needs structure: {{smiles}}, {{molfile}} or, for substructure, {{smarts}}.") + for key in ("smarts", "molfile", "smiles"): + v = s.get(key) + if isinstance(v, str) and v.strip(): + if key == "smarts" and kind != "substructure": + raise QueryError(f"SMARTS works only in a substructure term, not {kind}.") + if len(v) > MAX_STRUCTURE: + raise QueryError("The query structure is too large.") + return {key: v if key == "molfile" else v.strip()} + raise QueryError(f"A {kind} term needs structure: {{smiles}}, {{molfile}} or, for substructure, {{smarts}}.") + + +def _choice(v, allowed: tuple, what: str, default): + if v is None: + return default + if v not in allowed: + raise QueryError(f"{what} is one of {', '.join(map(str, allowed))}.") + return v + + +def _term(term: dict, fields: dict[str, str]) -> dict: + kind = term.get("kind") + if kind not in KINDS: + raise QueryError(f"Unknown term kind {str(kind)[:40]!r}. Kinds: {', '.join(KINDS)}.") + if kind == "exact": + return {"kind": kind, "structure": _structure(term, kind), + "stereo": _choice(term.get("stereo"), ("match", "ignore"), "stereo", None), + "salts": _choice(term.get("salts"), ("strip", "keep"), "salts", None), + "charges": _choice(term.get("charges"), ("match", "ignore"), "charges", "match"), + "tautomers": _choice(term.get("tautomers"), ("match", "ignore"), "tautomers", "ignore")} + if kind == "substructure": + return {"kind": kind, "structure": _structure(term, kind), "chirality": term.get("chirality") is True} + if kind == "similarity": + t = _num(term.get("threshold"), "threshold", required=False) + t = DEFAULT_THRESHOLD if t is None else t + if t > 1 and t <= 100: + t = t / 100.0 + if not 0 <= t <= 1: + raise QueryError("threshold is between 0 and 1.") + return {"kind": kind, "structure": _structure(term, kind), "threshold": round(t, 4)} + if kind == "formula": + text = term.get("formula") + if not isinstance(text, str) or not text.strip(): + raise QueryError("A formula term needs formula, for example C6-8H*N1O0-2.") + parse_formula(text) + return {"kind": kind, "formula": "".join(text.split()), "mode": _choice(term.get("mode"), ("contains", "exact"), "mode", "contains")} + if kind == "mass": + lo, hi = _num(term.get("min"), "min", False), _num(term.get("max"), "max", False) + if lo is None and hi is None: + raise QueryError("A mass term needs min, max or both.") + if lo is not None and hi is not None and lo > hi: + lo, hi = hi, lo + return {"kind": kind, "field": _choice(term.get("field"), MASS_FIELDS, "field", "mw"), "min": lo, "max": hi} + if kind == "text": + value = term.get("value") + if not isinstance(value, str) or value == "": + raise QueryError("A text term needs value.") + if len(value) > MAX_TEXT: + raise QueryError(f"value is longer than {MAX_TEXT} characters.") + match = _choice(term.get("match"), TEXT_MATCHES, "match", "contains") + if match == "regex": + try: + re.compile(value) + except re.error as exc: + raise QueryError(f"The regular expression does not read: {exc}.") + return {"kind": kind, "field": _field(term, fields, TEXT_BUILTINS, TEXT_TYPES, kind), "match": match, "value": value, "case": term.get("case") is True} + if kind == "number": + cmp = _choice(term.get("cmp"), COMPARISONS, "cmp", "=") + value = _num(term.get("value"), "value") + value2 = _num(term.get("value2"), "value2", required=cmp == "between") + if cmp == "between" and value > value2: + value, value2 = value2, value + return {"kind": kind, "field": _field(term, fields, NUMBER_BUILTINS, NUMBER_TYPES, kind), "cmp": cmp, "value": value, "value2": value2 if cmp == "between" else None} + if kind == "date": + lo, hi = _time(term.get("from"), "from"), _time(term.get("to"), "to") + if lo is None and hi is None: + raise QueryError("A date term needs from, to or both.") + if lo is not None and hi is not None and lo > hi: + lo, hi = hi, lo + return {"kind": kind, "field": _field(term, fields, DATE_BUILTINS, DATE_TYPES, kind), "from": lo, "to": hi} + if kind == "choice": + wanted = term.get("any") + if isinstance(wanted, str): + wanted = [wanted] + if not isinstance(wanted, list) or not wanted or not all(isinstance(w, str) for w in wanted): + raise QueryError("A choice term needs any, a list of choices.") + return {"kind": kind, "field": _field(term, fields, frozenset(), CHOICE_TYPES, kind), "any": list(dict.fromkeys(wanted))} + if kind == "empty": + return {"kind": kind, "field": _field(term, fields, EMPTY_BUILTINS, frozenset(fields.values()), kind), "empty": term.get("empty") is not False} + hid = term.get("id") + if isinstance(hid, bool) or not isinstance(hid, (int, float, str)) or not str(hid).strip().isdigit(): + raise QueryError("A hitlist term needs id, a hit list id.") + return {"kind": kind, "id": int(hid)} + + +_FORMULA_PART = re.compile(r"([A-Z][a-z]?)(\*|\d+-\d*|\d+)?") + + +def _elements() -> frozenset: + global _ELEMENTS + if _ELEMENTS is None: + from rdkit import Chem + table = Chem.GetPeriodicTable() + _ELEMENTS = frozenset(table.GetElementSymbol(z) for z in range(1, 119)) + return _ELEMENTS + + +_ELEMENTS: frozenset | None = None + + +def parse_formula(text: str) -> list[tuple[str, int, int | None]]: + elements = _elements() + flat = "".join(str(text).split()) + if not flat: + raise QueryError("The formula is empty.") + out: list[tuple[str, int, int | None]] = [] + seen: set[str] = set() + pos = 0 + while pos < len(flat): + m = _FORMULA_PART.match(flat, pos) + if not m: + raise QueryError(f"The formula does not read at character {pos + 1} ({flat[pos:pos + 8]!r}). Write element symbols each with a count or range, like C6-8H*N1O0-2.") + sym, count = m.group(1), m.group(2) + if sym not in elements: + raise QueryError(f"{sym} at character {pos + 1} is not an element symbol.") + if sym in seen: + raise QueryError(f"{sym} appears twice in the formula.") + seen.add(sym) + if count is None: + lo, hi = 1, 1 + elif count == "*": + lo, hi = 0, None + elif "-" in count: + a, b = count.split("-", 1) + lo, hi = int(a), (int(b) if b else None) + if hi is not None and hi < lo: + raise QueryError(f"The range {count} for {sym} runs backwards.") + else: + lo = hi = int(count) + out.append((sym, lo, hi)) + pos = m.end() + return out + + +def normalise(node, fields: dict[str, str] | None = None) -> dict: + count = [0] + + def walk(n, depth: int) -> dict: + if not isinstance(n, dict): + raise QueryError("A query is a JSON object: a group {op, terms} or a term {kind, ...}.") + count[0] += 1 + if count[0] > MAX_TERMS: + raise QueryError(f"A query has at most {MAX_TERMS} terms and groups.") + if depth > MAX_DEPTH: + raise QueryError(f"Groups nest at most {MAX_DEPTH} deep.") + if "op" in n: + op = n.get("op") + if op not in GROUP_OPS: + raise QueryError("op is and, or or not.") + terms = n.get("terms") + if not isinstance(terms, list) or not terms: + raise QueryError(f"An {op} group needs terms, a non-empty list.") + if op == "not" and len(terms) != 1: + raise QueryError("A not group takes exactly one term.") + inner = [walk(t, depth + 1) for t in terms] + if op != "not" and len(inner) == 1: + return inner[0] + return {"op": op, "terms": inner} + return _term(n, fields or {}) + + return walk(node, 0) + + +NAME_LIMIT = 80 +_CMP_WORDS = {"<": "<", "<=": "<=", "=": "=", ">=": ">=", ">": ">"} + + +def _short(text: str, n: int) -> str: + text = " ".join(str(text).split()) + return text if len(text) <= n else text[: n - 3] + "..." + + +def structure_text(structure: dict) -> str: + if structure.get("smarts"): + return structure["smarts"] + if structure.get("smiles"): + return structure["smiles"] + try: + from rdkit import Chem + from app.services.database import chem + return Chem.MolToSmiles(Chem.RemoveHs(chem.mol_from(structure))) + except Exception: + return "drawn structure" + + +def _figure(v: float | None) -> str: + if v is None: + return "" + return str(int(v)) if float(v).is_integer() else f"{v:g}" + + +def _day(v: float | None) -> str: + return datetime.fromtimestamp(v, tz=timezone.utc).strftime("%Y-%m-%d") if v is not None else "" + + +def _term_name(t: dict) -> str: + kind = t["kind"] + if kind == "exact": + return f"Exact {_short(structure_text(t['structure']), 48)}" + if kind == "substructure": + return f"Substructure {_short(structure_text(t['structure']), 48)}" + if kind == "similarity": + return f"Similarity {t['threshold']:.2f} to {_short(structure_text(t['structure']), 40)}" + if kind == "formula": + return f"Formula {t['formula']}" + (" exactly" if t["mode"] == "exact" else "") + if kind == "mass": + lo, hi = _figure(t["min"]), _figure(t["max"]) + if lo and hi: + return f"{t['field']} {lo} to {hi}" + return f"{t['field']} >= {lo}" if lo else f"{t['field']} <= {hi}" + if kind == "text": + word = {"contains": "contains", "starts": "starts with", "word": "has the word", "equals": "is", "regex": "matches"}[t["match"]] + return f"{t['field']} {word} {_short(t['value'], 32)}" + if kind == "number": + if t["cmp"] == "between": + return f"{t['field']} {_figure(t['value'])} to {_figure(t['value2'])}" + return f"{t['field']} {_CMP_WORDS[t['cmp']]} {_figure(t['value'])}" + if kind == "date": + if t["from"] is not None and t["to"] is not None: + return f"{t['field']} {_day(t['from'])} to {_day(t['to'])}" + return f"{t['field']} from {_day(t['from'])}" if t["from"] is not None else f"{t['field']} until {_day(t['to'])}" + if kind == "choice": + return f"{t['field']} any of {_short(', '.join(t['any']), 40)}" + if kind == "empty": + return f"{t['field']} empty" if t["empty"] else f"{t['field']} not empty" + return f"Hit list {t['id']}" + + +def name_of(node: dict) -> str: + def walk(n: dict, top: bool) -> str: + if "op" not in n: + return _term_name(n) + if n["op"] == "not": + return f"not ({walk(n['terms'][0], False)})" + inner = f" {n['op']} ".join(walk(t, False) for t in n["terms"]) + return inner if top else f"({inner})" + + return _short(walk(node, True), NAME_LIMIT) diff --git a/backend/app/services/database/records.py b/backend/app/services/database/records.py new file mode 100644 index 00000000..8cbb787d --- /dev/null +++ b/backend/app/services/database/records.py @@ -0,0 +1,293 @@ +import sqlite3 +import time + +from app.services.database import attachments, computed, fields as fieldsmod, store +from app.services.database.chem import StructureError, register_values +from app.services.database.store import DatabaseError + +MAX_LIMIT = 500 +CHUNK = 500 +ROW_COLUMNS = "c.id, c.uid, c.number, c.batch, c.parent, c.smiles, c.formula, c.mw, c.exact_mass, c.inchikey, c.created, c.modified" +SORTS = { + "number": "c.number{d}, c.batch{d}", "batch": "c.batch{d}, c.number", "uid": "c.uid{d}", "structure": "c.smiles{d}", + "smiles": "c.smiles{d}", "formula": "c.formula{d}", "mw": "c.mw IS NULL, c.mw{d}", "exact_mass": "c.exact_mass IS NULL, c.exact_mass{d}", + "inchikey": "c.inchikey{d}", "created": "c.created{d}", "modified": "c.modified{d}", "heavy_atoms": "c.heavy_atoms{d}", +} +ON_DUPLICATE = ("ask", "new", "batch", "existing") +REG_COLUMNS = ("molfile", "smiles", "inchi", "inchikey", "skeleton", "parent_key", "formula", "mw", "exact_mass", "heavy_atoms", "fp", "sfp", "counts") + + +class DuplicateError(DatabaseError): + def __init__(self, duplicates: list[dict]): + super().__init__("This structure is already registered.", 409) + self.duplicates = duplicates + + +def _field_map(conn: sqlite3.Connection) -> dict[int, dict]: + return {f["id"]: f for f in fieldsmod.all_fields(conn)} + + +def _values(conn: sqlite3.Connection, ids: list[int], fmap: dict[int, dict]) -> dict[int, dict]: + out: dict[int, dict] = {i: {} for i in ids} + for k in range(0, len(ids), CHUNK): + part = ids[k:k + CHUNK] + marks = ",".join("?" * len(part)) + for r in conn.execute(f"SELECT compound, field, num, txt FROM field_values WHERE compound IN ({marks})", part): + f = fmap.get(r["field"]) + if f is not None: + out[r["compound"]][f["name"]] = fieldsmod.present(f["type"], r["num"], r["txt"]) + return out + + +def _row(r: sqlite3.Row, values: dict, score: float | None = None, scored: bool = False) -> dict: + out = {"uid": r["uid"], "number": r["number"], "batch": r["batch"], "smiles": r["smiles"] or "", "formula": r["formula"] or "", + "mw": r["mw"], "exact_mass": r["exact_mass"], "inchikey": r["inchikey"] or "", "created": r["created"], "modified": r["modified"], + "values": values} + if scored: + out["score"] = score + return out + + +def rows_in(conn: sqlite3.Connection, ids: list[int], scores: dict[int, float] | None = None) -> list[dict]: + if not ids: + return [] + fmap = _field_map(conn) + found: dict[int, sqlite3.Row] = {} + for k in range(0, len(ids), CHUNK): + part = ids[k:k + CHUNK] + marks = ",".join("?" * len(part)) + for r in conn.execute(f"SELECT {ROW_COLUMNS} FROM compounds c WHERE c.id IN ({marks})", part): + found[r["id"]] = r + present = [i for i in ids if i in found] + vals = _values(conn, present, fmap) + return [_row(found[i], vals[i], (scores or {}).get(i), scores is not None) for i in present] + + +def rows(db: store.Database, ids: list[int], scores: dict[int, float] | None = None) -> list[dict]: + with store.reading(db): + return rows_in(db.conn, list(ids), scores) + + +def ids_for(db: store.Database, uids: list[str]) -> list[int]: + out: list[int] = [] + with store.reading(db): + for k in range(0, len(uids), CHUNK): + part = [u for u in uids[k:k + CHUNK] if isinstance(u, str)] + if not part: + continue + marks = ",".join("?" * len(part)) + found = {r["uid"]: r["id"] for r in db.conn.execute(f"SELECT id, uid FROM compounds WHERE uid IN ({marks})", part)} + out.extend(found[u] for u in part if u in found) + return out + + +def _id_of(conn: sqlite3.Connection, uid: str) -> sqlite3.Row: + row = conn.execute("SELECT * FROM compounds WHERE uid = ?", (uid,)).fetchone() + if row is None: + raise DatabaseError(f"There is no record {uid}.", 404) + return row + + +def record_in(conn: sqlite3.Connection, uid: str) -> dict: + row = _id_of(conn, uid) + out = rows_in(conn, [row["id"]])[0] + out.update(molfile=row["molfile"], parent=row["parent"], attachments=attachments.listing(conn, compound=row["id"])) + return out + + +def get(db: store.Database, uid: str) -> dict: + with store.reading(db): + return record_in(db.conn, uid) + + +def _order(conn: sqlite3.Connection, sort: str | None, desc: bool, ranked: bool) -> tuple[str, str, list]: + d = " DESC" if desc else "" + if not sort: + return ("", "h.rank" + d + ", c.number, c.batch", []) if ranked else ("", f"c.number{d}, c.batch{d}", []) + if sort == "score" and ranked: + return "", f"h.score IS NULL, h.score{d}, h.rank", [] + if sort == "rank" and ranked: + return "", "h.rank" + d, [] + if sort in SORTS: + return "", SORTS[sort].format(d=d) + ", c.number, c.batch", [] + f = conn.execute("SELECT id, type FROM fields WHERE name = ?", (sort,)).fetchone() + if f is None: + raise DatabaseError(f"Cannot sort by {sort}: there is no such column.", 422) + col = "txt" if fieldsmod.stores_text(f["type"]) else "num" + join = "LEFT JOIN field_values s ON s.compound = c.id AND s.field = ?" + return join, f"s.{col} IS NULL, s.{col}{' COLLATE NOCASE' if col == 'txt' else ''}{d}, c.number, c.batch", [f["id"]] + + +def page(db: store.Database, hitlist: int | None = None, offset: int = 0, limit: int = 100, sort: str | None = None, desc: bool = False) -> dict: + offset = max(0, int(offset or 0)) + limit = max(1, min(MAX_LIMIT, int(limit or 100))) + with store.reading(db): + conn = db.conn + ranked = hitlist is not None + join, order, params = _order(conn, sort, desc, ranked) + if ranked: + if conn.execute("SELECT 1 FROM hitlists WHERE id = ?", (hitlist,)).fetchone() is None: + raise DatabaseError(f"There is no hit list {hitlist}.", 404) + total = conn.execute("SELECT count(*) FROM hitlist_items WHERE hitlist = ?", (hitlist,)).fetchone()[0] + scored = conn.execute("SELECT 1 FROM hitlist_items WHERE hitlist = ? AND score IS NOT NULL LIMIT 1", (hitlist,)).fetchone() is not None + found = conn.execute(f"SELECT c.id, h.score FROM hitlist_items h JOIN compounds c ON c.id = h.compound {join} WHERE h.hitlist = ? " + f"ORDER BY {order} LIMIT ? OFFSET ?", (*params, hitlist, limit, offset)).fetchall() + ids = [r["id"] for r in found] + out = rows_in(conn, ids, {r["id"]: r["score"] for r in found} if scored else None) + else: + total = conn.execute("SELECT count(*) FROM compounds").fetchone()[0] + ids = [r[0] for r in conn.execute(f"SELECT c.id FROM compounds c {join} ORDER BY {order} LIMIT ? OFFSET ?", (*params, limit, offset))] + out = rows_in(conn, ids) + return {"total": total, "offset": offset, "rows": out} + + +def _structure(structure: object) -> dict: + if isinstance(structure, str) and structure.strip(): + return {"molfile": structure} if "\n" in structure else {"smiles": structure.strip()} + if isinstance(structure, dict) and (isinstance(structure.get("molfile"), str) or isinstance(structure.get("smiles"), str)): + return structure + raise DatabaseError("Give the structure as {smiles} or {molfile}.", 422) + + +def register(structure: object) -> dict: + try: + return register_values(_structure(structure)) + except StructureError as exc: + raise DatabaseError(str(exc), 422) + except DatabaseError: + raise + except Exception as exc: + raise DatabaseError(f"RDKit could not register this structure: {exc}", 422) + + +def duplicate_ids(conn: sqlite3.Connection, reg: dict, rules: dict, exclude: int | None = None) -> list[int]: + strip = rules.get("salts") == "strip" + key = reg["parent_key"] if strip else reg["inchikey"] + if not key: + return [] + if rules.get("stereo") == "ignore": + block = key.split("-")[0] + if strip: + sql, params = "parent_key >= ? AND parent_key < ?", [block + "-", block + "."] + else: + sql, params = "skeleton = ?", [block] + else: + sql, params = ("parent_key = ?" if strip else "inchikey = ?"), [key] + if exclude is not None: + sql += " AND id != ?" + params.append(exclude) + return [r[0] for r in conn.execute(f"SELECT id FROM compounds WHERE {sql} ORDER BY number, batch", params)] + + +def prepare_values(conn: sqlite3.Connection, values: object, allow_computed: bool = False) -> list[tuple[dict, float | None, str | None]]: + if values is None: + return [] + if not isinstance(values, dict): + raise DatabaseError("values must be an object of field name to value.", 422) + by_name = {f["name"]: f for f in fieldsmod.all_fields(conn)} + out = [] + for name, value in values.items(): + f = by_name.get(name) + if f is None: + raise DatabaseError(f"This database has no field named {name}.", 404) + if f["type"] == "computed" and not allow_computed: + raise DatabaseError(f"{f['label']} is computed from the structure, so it cannot be written.", 422) + num, txt = fieldsmod.coerce(f, value) + if f["type"] == "link" and txt and conn.execute("SELECT 1 FROM compounds WHERE uid = ?", (txt,)).fetchone() is None: + raise DatabaseError(f"{f['label']}: there is no record {txt} to link to.", 422) + if f["type"] in ("image", "file") and num is not None and conn.execute("SELECT 1 FROM attachments WHERE id = ?", (int(num),)).fetchone() is None: + raise DatabaseError(f"{f['label']}: there is no attachment {int(num)}.", 422) + out.append((f, num, txt)) + return out + + +def write_values(conn: sqlite3.Connection, cid: int, prepared: list[tuple[dict, float | None, str | None]]) -> None: + for f, num, txt in prepared: + if num is None and txt is None: + conn.execute("DELETE FROM field_values WHERE compound = ? AND field = ?", (cid, f["id"])) + else: + conn.execute("INSERT OR REPLACE INTO field_values (compound, field, num, txt) VALUES (?, ?, ?, ?)", (cid, f["id"], num, txt)) + + +def insert(db: store.Database, conn: sqlite3.Connection, reg: dict, prepared: list, batch_of: int | None = None, now: float | None = None) -> tuple[int, str]: + now = now or time.time() + if batch_of is not None: + base = conn.execute("SELECT uid, number, parent FROM compounds WHERE id = ?", (batch_of,)).fetchone() + number = base["number"] + batch = conn.execute("SELECT max(batch) FROM compounds WHERE number = ?", (number,)).fetchone()[0] + 1 + parent = base["parent"] or base["uid"] + else: + number, batch, parent = store.next_number(db), 1, None + uid = store.new_id("c") + while conn.execute("SELECT 1 FROM compounds WHERE uid = ?", (uid,)).fetchone(): + uid = store.new_id("c") + cur = conn.execute( + f"INSERT INTO compounds (uid, number, batch, parent, {', '.join(REG_COLUMNS)}, created, modified) " + f"VALUES (?, ?, ?, ?, {', '.join('?' * len(REG_COLUMNS))}, ?, ?)", + (uid, number, batch, parent, *[reg[k] for k in REG_COLUMNS], now, now)) + cid = cur.lastrowid + write_values(conn, cid, prepared) + computed.write(conn, cid, reg["molfile"], computed.computed_fields(conn)) + return cid, uid + + +def add(db: store.Database, structure: object, values: dict | None = None, on_duplicate: str | None = None, actor: str = "person") -> dict: + db.writable() + if on_duplicate is not None and on_duplicate not in ON_DUPLICATE: + raise DatabaseError(f"on_duplicate must be one of {', '.join(ON_DUPLICATE)}.", 422) + reg = register(structure) + rules = db.rules() + choice = on_duplicate or rules["on_duplicate"] + with store.writing(db) as conn: + prepared = prepare_values(conn, values) + dups = duplicate_ids(conn, reg, rules) + if dups and choice == "ask": + raise DuplicateError(rows_in(conn, dups)) + if dups and choice == "existing": + found = record_in(conn, conn.execute("SELECT uid FROM compounds WHERE id = ?", (dups[0],)).fetchone()[0]) + return {**found, "existing": True} + cid, uid = insert(db, conn, reg, prepared, dups[0] if dups and choice == "batch" else None) + store.audit(db, actor, "record-add", uid, {"smiles": reg["smiles"], "duplicate": choice if dups else None}) + made = record_in(conn, uid) + store.notify(db, "records", [uid]) + return made + + +def update(db: store.Database, uid: str, structure: object = None, values: dict | None = None, actor: str = "person") -> dict: + db.writable() + reg = register(structure) if structure is not None else None + with store.writing(db) as conn: + row = _id_of(conn, uid) + prepared = prepare_values(conn, values) + now = time.time() + if reg is not None: + conn.execute(f"UPDATE compounds SET {', '.join(f'{k} = ?' for k in REG_COLUMNS)}, modified = ? WHERE id = ?", + (*[reg[k] for k in REG_COLUMNS], now, row["id"])) + conn.execute("DELETE FROM thumbs WHERE compound = ?", (row["id"],)) + computed.write(conn, row["id"], reg["molfile"], computed.computed_fields(conn)) + if prepared: + write_values(conn, row["id"], prepared) + conn.execute("UPDATE compounds SET modified = ? WHERE id = ?", (now, row["id"])) + detail = {"structure": reg["smiles"] if reg else None, "fields": [f["name"] for f, _, _ in prepared]} + store.audit(db, actor, "record-update", uid, detail) + made = record_in(conn, uid) + store.notify(db, "records", [uid]) + return made + + +def delete(db: store.Database, uids: list[str], actor: str = "person") -> int: + if not isinstance(uids, list) or not all(isinstance(u, str) for u in uids): + raise DatabaseError("uids must be a list of record ids.", 422) + gone: list[str] = [] + with store.writing(db) as conn: + for k in range(0, len(uids), CHUNK): + part = uids[k:k + CHUNK] + marks = ",".join("?" * len(part)) + found = [r[0] for r in conn.execute(f"SELECT uid FROM compounds WHERE uid IN ({marks})", part)] + conn.execute(f"DELETE FROM compounds WHERE uid IN ({marks})", part) + gone.extend(found) + if gone: + store.audit(db, actor, "record-delete", gone[0] if len(gone) == 1 else None, {"count": len(gone), "uids": gone[:100]}) + if gone: + store.notify(db, "records", gone) + return len(gone) diff --git a/backend/app/services/database/saved.py b/backend/app/services/database/saved.py new file mode 100644 index 00000000..e6a5660e --- /dev/null +++ b/backend/app/services/database/saved.py @@ -0,0 +1,126 @@ +import json +import time + +from app.services.database import query, store +from app.services.database.store import Database, DatabaseError + +NAME_LIMIT = 200 +FOLDER_LIMIT = 400 + + +def _shape(r) -> dict: + try: + q = json.loads(r[3]) + except (TypeError, ValueError): + q = None + return {"id": r[0], "name": r[1], "folder": r[2], "query": q, "created": r[4], "last_run": r[5], "last_count": r[6]} + + +_COLUMNS = "id, name, folder, query, created, last_run, last_count" + + +def all_of(db: Database) -> list[dict]: + with db.lock: + rows = db.conn.execute(f"SELECT {_COLUMNS} FROM queries ORDER BY folder, name COLLATE NOCASE, id").fetchall() + return [_shape(r) for r in rows] + + +def get(db: Database, qid: int) -> dict: + with db.lock: + r = db.conn.execute(f"SELECT {_COLUMNS} FROM queries WHERE id = ?", (int(qid),)).fetchone() + if r is None: + raise DatabaseError(f"There is no saved query {qid} in this database.", 404) + return _shape(r) + + +def _name(name) -> str: + text = " ".join(str(name or "").split())[:NAME_LIMIT] + if not text: + raise DatabaseError("A saved query needs a name.", 422) + return text + + +def _folder(folder) -> str: + if folder is None: + return "" + if not isinstance(folder, str): + raise DatabaseError("folder is a path of names separated by /.", 422) + parts = [" ".join(p.split()) for p in folder.split("/")] + text = "/".join(p for p in parts if p) + if len(text) > FOLDER_LIMIT: + raise DatabaseError(f"folder is longer than {FOLDER_LIMIT} characters.", 422) + return text + + +def _checked(db: Database, q) -> dict: + from app.services.database import search + fields = search.fields_of(db) + return query.normalise(q, {k: v[1] for k, v in fields.items()}) + + +def create(db: Database, name, folder, q, actor: str = "person") -> dict: + db.writable() + label, path, node = _name(name), _folder(folder), _checked(db, q) + with db.lock: + db.conn.execute("BEGIN IMMEDIATE") + try: + cur = db.conn.execute("INSERT INTO queries (name, folder, query, created) VALUES (?, ?, ?, ?)", + (label, path, json.dumps(node, separators=(",", ":")), time.time())) + qid = cur.lastrowid + store.audit(db, actor, "query.create", None, {"id": qid, "name": label, "folder": path}) + db.conn.execute("COMMIT") + except Exception: + db.conn.execute("ROLLBACK") + raise + store.notify(db, "queries") + return get(db, qid) + + +def update(db: Database, qid: int, name=None, folder=None, q=None, actor: str = "person") -> dict: + db.writable() + current = get(db, qid) + label = _name(name) if name is not None else current["name"] + path = _folder(folder) if folder is not None else current["folder"] + node = _checked(db, q) if q is not None else current["query"] + with db.lock: + db.conn.execute("BEGIN IMMEDIATE") + try: + db.conn.execute("UPDATE queries SET name = ?, folder = ?, query = ? WHERE id = ?", + (label, path, json.dumps(node, separators=(",", ":")), current["id"])) + store.audit(db, actor, "query.update", None, {"id": current["id"], "name": label, "folder": path, "query_changed": q is not None}) + db.conn.execute("COMMIT") + except Exception: + db.conn.execute("ROLLBACK") + raise + store.notify(db, "queries") + return get(db, current["id"]) + + +def delete(db: Database, qid: int, actor: str = "person") -> dict: + db.writable() + current = get(db, qid) + with db.lock: + db.conn.execute("BEGIN IMMEDIATE") + try: + db.conn.execute("DELETE FROM queries WHERE id = ?", (current["id"],)) + store.audit(db, actor, "query.delete", None, {"id": current["id"], "name": current["name"]}) + db.conn.execute("COMMIT") + except Exception: + db.conn.execute("ROLLBACK") + raise + store.notify(db, "queries") + return {"deleted": current["id"]} + + +def run(db: Database, qid: int, within: int | None = None, actor: str = "person") -> dict: + from app.services.database import hitlists, search + current = get(db, qid) + if current["query"] is None: + raise DatabaseError(f"Saved query {qid} holds no readable query.", 422) + result = search.run(db, current["query"], within=within, name=current["name"], actor=actor) + if not db.readonly: + with db.lock: + with hitlists.own_write(db): + db.conn.execute("UPDATE queries SET last_run = ?, last_count = ? WHERE id = ?", (time.time(), result["count"], current["id"])) + store.notify(db, "queries") + return {**result, "saved_query": get(db, current["id"])} diff --git a/backend/app/services/database/schema.py b/backend/app/services/database/schema.py new file mode 100644 index 00000000..9faa7a01 --- /dev/null +++ b/backend/app/services/database/schema.py @@ -0,0 +1,202 @@ +import sqlite3 +import time +from pathlib import Path + +FORMAT = "formchem-database" +FORMAT_VERSION = 1 +APPLICATION_ID = 0x46434442 +EXTENSION = ".fcdb" + +RESERVED = frozenset({"number", "uid", "structure", "formula", "mw", "exact_mass", "smiles", "inchikey", "created", "modified", "batch"}) +FIELD_TYPES = ("integer", "real", "text", "richtext", "datetime", "boolean", "choice", "multichoice", "structure", "reaction", "image", "file", "link", "computed") +NUMERIC_TYPES = frozenset({"integer", "real", "datetime", "boolean", "image", "file", "computed"}) +DEFAULT_RULES = {"stereo": "match", "salts": "strip", "on_duplicate": "ask"} +ENTRY_STATUSES = ("open", "signed", "modified") +ENTRY_ROLES = ("reactant", "reagent", "product") + +TABLES = ( + """CREATE TABLE IF NOT EXISTS meta ( + key TEXT PRIMARY KEY, + value TEXT)""", + """CREATE TABLE IF NOT EXISTS compounds ( + id INTEGER PRIMARY KEY, + uid TEXT NOT NULL UNIQUE, + number INTEGER NOT NULL, + batch INTEGER NOT NULL DEFAULT 1, + parent TEXT, + molfile TEXT NOT NULL, + smiles TEXT, + inchi TEXT, + inchikey TEXT, + skeleton TEXT, + parent_key TEXT, + formula TEXT, + mw REAL, + exact_mass REAL, + heavy_atoms INTEGER, + fp BLOB, + sfp BLOB, + counts TEXT, + created REAL NOT NULL, + modified REAL NOT NULL, + UNIQUE (number, batch))""", + "CREATE INDEX IF NOT EXISTS compounds_inchikey ON compounds (inchikey)", + "CREATE INDEX IF NOT EXISTS compounds_skeleton ON compounds (skeleton)", + "CREATE INDEX IF NOT EXISTS compounds_parent_key ON compounds (parent_key)", + "CREATE INDEX IF NOT EXISTS compounds_formula ON compounds (formula)", + "CREATE INDEX IF NOT EXISTS compounds_mw ON compounds (mw)", + """CREATE TABLE IF NOT EXISTS fields ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + label TEXT NOT NULL, + type TEXT NOT NULL, + unit TEXT, + digits INTEGER, + choices TEXT, + computed TEXT, + position INTEGER NOT NULL DEFAULT 0, + width REAL, + hidden INTEGER NOT NULL DEFAULT 0)""", + """CREATE TABLE IF NOT EXISTS field_values ( + compound INTEGER NOT NULL REFERENCES compounds (id) ON DELETE CASCADE, + field INTEGER NOT NULL REFERENCES fields (id) ON DELETE CASCADE, + num REAL, + txt TEXT, + PRIMARY KEY (compound, field))""", + "CREATE INDEX IF NOT EXISTS field_values_field ON field_values (field, num)", + """CREATE TABLE IF NOT EXISTS entries ( + id INTEGER PRIMARY KEY, + uid TEXT NOT NULL UNIQUE, + number INTEGER NOT NULL UNIQUE, + title TEXT NOT NULL, + author TEXT, + date REAL, + template TEXT, + scheme TEXT, + procedure TEXT, + observations TEXT, + products TEXT, + tags TEXT, + status TEXT NOT NULL DEFAULT 'open', + signed_at REAL, + signed_by TEXT, + signed_hash TEXT, + created REAL NOT NULL, + modified REAL NOT NULL)""", + """CREATE TABLE IF NOT EXISTS entry_versions ( + id INTEGER PRIMARY KEY, + entry INTEGER NOT NULL REFERENCES entries (id) ON DELETE CASCADE, + at REAL NOT NULL, + reason TEXT NOT NULL, + content TEXT NOT NULL, + hash TEXT NOT NULL)""", + """CREATE TABLE IF NOT EXISTS entry_compounds ( + entry INTEGER NOT NULL REFERENCES entries (id) ON DELETE CASCADE, + compound INTEGER NOT NULL REFERENCES compounds (id) ON DELETE CASCADE, + role TEXT NOT NULL, + sample TEXT, + PRIMARY KEY (entry, compound, role))""", + """CREATE TABLE IF NOT EXISTS attachments ( + id INTEGER PRIMARY KEY, + compound INTEGER REFERENCES compounds (id) ON DELETE CASCADE, + entry INTEGER REFERENCES entries (id) ON DELETE CASCADE, + name TEXT NOT NULL, + mime TEXT, + size INTEGER, + sha256 TEXT, + data BLOB, + path TEXT, + created REAL NOT NULL)""", + """CREATE TABLE IF NOT EXISTS hitlists ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + query TEXT, + created REAL NOT NULL, + saved INTEGER NOT NULL DEFAULT 0)""", + """CREATE TABLE IF NOT EXISTS hitlist_items ( + hitlist INTEGER NOT NULL REFERENCES hitlists (id) ON DELETE CASCADE, + compound INTEGER NOT NULL REFERENCES compounds (id) ON DELETE CASCADE, + rank INTEGER NOT NULL, + score REAL, + PRIMARY KEY (hitlist, compound))""", + """CREATE TABLE IF NOT EXISTS queries ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + folder TEXT NOT NULL DEFAULT '', + query TEXT NOT NULL, + created REAL NOT NULL, + last_run REAL, + last_count INTEGER)""", + """CREATE TABLE IF NOT EXISTS forms ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + style TEXT NOT NULL, + layout TEXT NOT NULL, + is_default INTEGER NOT NULL DEFAULT 0)""", + """CREATE TABLE IF NOT EXISTS audit ( + id INTEGER PRIMARY KEY, + at REAL NOT NULL, + actor TEXT NOT NULL, + action TEXT NOT NULL, + target TEXT, + detail TEXT)""", + """CREATE TABLE IF NOT EXISTS thumbs ( + compound INTEGER NOT NULL REFERENCES compounds (id) ON DELETE CASCADE, + size INTEGER NOT NULL, + svg TEXT NOT NULL, + PRIMARY KEY (compound, size))""", +) + + +class SchemaError(Exception): + pass + + +def connect(path: Path, readonly: bool = False) -> sqlite3.Connection: + uri = f"{Path(path).resolve().as_uri()}?mode={'ro' if readonly else 'rwc'}" + conn = sqlite3.connect(uri, uri=True, check_same_thread=False, isolation_level=None) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + if not readonly: + conn.execute("PRAGMA journal_mode = DELETE") + return conn + + +def version_of(conn: sqlite3.Connection) -> tuple[int, int]: + app = conn.execute("PRAGMA application_id").fetchone()[0] + ver = conn.execute("PRAGMA user_version").fetchone()[0] + return app, ver + + +def create(conn: sqlite3.Connection, title: str, app_version: str) -> None: + now = time.time() + conn.execute("BEGIN IMMEDIATE") + try: + for statement in TABLES: + conn.execute(statement) + conn.execute(f"PRAGMA application_id = {APPLICATION_ID}") + conn.execute(f"PRAGMA user_version = {FORMAT_VERSION}") + rows = {"format": FORMAT, "format_version": str(FORMAT_VERSION), "title": title, "description": "", "created": repr(now), "app_version": app_version} + conn.executemany("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", rows.items()) + conn.execute("COMMIT") + except Exception: + conn.execute("ROLLBACK") + raise + + +def check(conn: sqlite3.Connection) -> bool: + app, ver = version_of(conn) + if app != APPLICATION_ID: + raise SchemaError("This file is not a FormChem database.") + if ver > FORMAT_VERSION: + return False + return True + + +def migrate(conn: sqlite3.Connection) -> None: + _, ver = version_of(conn) + if ver == FORMAT_VERSION: + for statement in TABLES: + conn.execute(statement) + return + raise SchemaError(f"No migration from database format {ver} to {FORMAT_VERSION}.") diff --git a/backend/app/services/database/search.py b/backend/app/services/database/search.py new file mode 100644 index 00000000..a2f331ac --- /dev/null +++ b/backend/app/services/database/search.py @@ -0,0 +1,579 @@ +import json +import os +import re +import threading +import time +from dataclasses import dataclass, field + +import numpy as np +import rdkit +from rdkit import Chem +from rdkit.Chem import rdSubstructLibrary + +from app.services.database import chem, query +from app.services.database.query import QueryError +from app.services.database.store import Database + +ENGINE = f"RDKit {rdkit.__version__}" +FP_WORDS = chem.FP_BITS // 64 +BACKFILL_BATCH = 400 +BINARY_FROM = 5000 +LOAD_PAGE = 5000 + +_CACHES: dict[str, "Screen"] = {} +_CACHES_LOCK = threading.Lock() + + +@dataclass +class Screen: + stamp: tuple + ids: np.ndarray + numbers: np.ndarray + batches: np.ndarray + sfp: np.ndarray + fp: np.ndarray + fp_bits: np.ndarray + smiles: list[str] + counts_raw: list[str] + order: np.ndarray + counts: list[dict] | None = None + library: object | None = None + gate: tuple | None = None + binary: bool = False + elements: dict = field(default_factory=dict) + lock: threading.Lock = field(default_factory=threading.Lock) + + def __len__(self) -> int: + return int(self.ids.shape[0]) + + def mask_of(self, ids) -> np.ndarray: + mask = np.zeros(len(self), dtype=bool) + if ids is None: + return mask + wanted = np.fromiter(ids, dtype=np.int64) + if wanted.size == 0 or len(self) == 0: + return mask + pos = np.searchsorted(self.ids, wanted) + inside = pos < len(self) + pos, wanted = pos[inside], wanted[inside] + mask[pos[self.ids[pos] == wanted]] = True + return mask + + def substructure_library(self): + if self.library is None: + holder = rdSubstructLibrary.CachedTrustedSmilesMolHolder() + for s in self.smiles: + holder.AddSmiles(s or "") + self.library = rdSubstructLibrary.SubstructLibrary(holder) + if len(self.smiles) >= BINARY_FROM: + threading.Thread(target=self._binary_library, name="formchem-db-mols", daemon=True).start() + return self.library + + def _binary_library(self) -> None: + holder = rdSubstructLibrary.CachedMolHolder() + for s in self.smiles: + m = Chem.MolFromSmiles(s or "", sanitize=False) + if m is None: + m = Chem.Mol() + else: + m.UpdatePropertyCache(strict=False) + Chem.FastFindRings(m) + holder.AddBinary(m.ToBinary()) + built = rdSubstructLibrary.SubstructLibrary(holder) + with self.lock: + self.library = built + self.binary = True + + +def _popcount(words: np.ndarray) -> np.ndarray: + return np.bitwise_count(words).sum(axis=-1, dtype=np.int64) + + +def _words(raw: bytes | None) -> np.ndarray | None: + if not isinstance(raw, (bytes, bytearray, memoryview)) or len(raw) != chem.FP_BITS // 8: + return None + return np.frombuffer(bytes(raw), dtype=" tuple: + row = db.conn.execute("SELECT count(*), max(id), max(modified) FROM compounds").fetchone() + return tuple(row) + + +def _gate(db: Database) -> tuple: + row = db.conn.execute("SELECT count(*), max(id) FROM compounds").fetchone() + return (row[0], row[1], audit_head(db)) + + +def audit_head(db: Database) -> int | None: + return db.conn.execute("SELECT max(id) FROM audit").fetchone()[0] + + +def advance(db: Database, before: int | None, after: int | None) -> None: + with _CACHES_LOCK: + found = _CACHES.get(db.handle) + if found is not None and found.gate is not None and found.gate[2] == before: + found.gate = (found.gate[0], found.gate[1], after) + + +def _backfill(db: Database, missing: list[tuple[int, str, str]]) -> dict[int, tuple[bytes, bytes]]: + out: dict[int, tuple[bytes, bytes]] = {} + for cid, smiles, molfile in missing: + try: + mol = chem.mol_from({"smiles": smiles} if smiles else {"molfile": molfile}) + except chem.StructureError: + continue + plain = Chem.RemoveHs(mol) + out[cid] = (chem.to_bytes(chem.similarity_fp(plain)), chem.to_bytes(chem.screen_fp(plain))) + if db.readonly or not out: + return out + items = list(out.items()) + for start in range(0, len(items), BACKFILL_BATCH): + with db.lock: + db.conn.execute("BEGIN IMMEDIATE") + try: + db.conn.executemany("UPDATE compounds SET fp = ?, sfp = ? WHERE id = ?", [(fp, sfp, cid) for cid, (fp, sfp) in items[start:start + BACKFILL_BATCH]]) + db.conn.execute("COMMIT") + except Exception: + db.conn.execute("ROLLBACK") + raise + return out + + +def _load(db: Database, stamp: tuple) -> Screen: + rows: list = [] + after = -1 + while True: + with db.lock: + part = db.conn.execute("SELECT id, number, batch, smiles, counts, fp, sfp FROM compounds WHERE id > ? ORDER BY id LIMIT ?", (after, LOAD_PAGE)).fetchall() + rows.extend(part) + if len(part) < LOAD_PAGE: + break + after = part[-1][0] + n = len(rows) + ids = np.empty(n, dtype=np.int64) + numbers = np.empty(n, dtype=np.int64) + batches = np.empty(n, dtype=np.int64) + fp = np.zeros((n, FP_WORDS), dtype=np.uint64) + sfp = np.zeros((n, FP_WORDS), dtype=np.uint64) + smiles: list[str] = [""] * n + counts_raw: list[str] = [""] * n + missing: list[tuple[int, int]] = [] + for i, r in enumerate(rows): + ids[i], numbers[i], batches[i] = r[0], r[1], r[2] or 1 + smiles[i] = r[3] or "" + counts_raw[i] = r[4] or "" + a, b = _words(r[5]), _words(r[6]) + if a is None or b is None: + missing.append((i, r[0])) + continue + fp[i] = a + sfp[i] = b + if missing: + with db.lock: + extra = {cid: db.conn.execute("SELECT molfile FROM compounds WHERE id = ?", (cid,)).fetchone()[0] for _, cid in missing} + filled = _backfill(db, [(cid, smiles[i], extra.get(cid) or "") for i, cid in missing]) + for i, cid in missing: + if cid in filled: + fp[i] = _words(filled[cid][0]) + sfp[i] = _words(filled[cid][1]) + else: + sfp[i] = np.uint64(0xFFFFFFFFFFFFFFFF) + order = np.empty(n, dtype=np.int64) + order[np.lexsort((batches, numbers))] = np.arange(n) + return Screen(stamp, ids, numbers, batches, sfp, fp, _popcount(fp), smiles, counts_raw, order) + + +def screen(db: Database) -> Screen: + with db.lock: + gate = _gate(db) + with _CACHES_LOCK: + found = _CACHES.get(db.handle) + if found is not None and found.gate == gate: + return found + with db.lock: + stamp = _stamp(db) + if found is not None and found.stamp == stamp: + found.gate = gate + return found + fresh = _load(db, stamp) + fresh.gate = gate + from app.services.database import store + live = {d.handle for d in store.all_open()} + with _CACHES_LOCK: + for handle in [h for h in _CACHES if h not in live]: + del _CACHES[handle] + _CACHES[db.handle] = fresh + return fresh + + +def forget(handle: str) -> None: + with _CACHES_LOCK: + _CACHES.pop(handle, None) + + +THREADS = max(1, min(2, os.cpu_count() or 1)) + + +def query_mol(structure: dict) -> Chem.Mol: + try: + q = chem.query_from(structure) + except chem.StructureError as exc: + raise QueryError(str(exc)) + if "smarts" in structure: + q.UpdatePropertyCache(strict=False) + Chem.FastFindRings(q) + return q + return Chem.RemoveHs(q) + + +def _substructure(s: Screen, t: dict, universe: np.ndarray, stats: dict) -> np.ndarray: + q = query_mol(t["structure"]) + qwords = _words(chem.to_bytes(chem.screen_fp(q))) + passed = universe & np.all((s.sfp & qwords) == qwords, axis=1) + stats["screened"] = stats.get("screened", 0) + int(universe.sum()) + idx = np.flatnonzero(passed) + stats["candidates"] = stats.get("candidates", 0) + int(idx.size) + found = np.zeros(len(s), dtype=bool) + if idx.size == 0: + return found + with s.lock: + lib = s.substructure_library() + lib.SetSearchOrder([int(i) for i in idx]) + hits = lib.GetMatches(q, recursionPossible=True, useChirality=bool(t.get("chirality")), useQueryQueryMatches=False, + numThreads=THREADS, maxResults=int(idx.size)) + if len(hits): + found[np.fromiter(hits, dtype=np.int64)] = True + return found + + +SIMILARITY_METHOD = f"Tanimoto on {chem.FP_METHOD}, {ENGINE}" + + +def _similarity(s: Screen, t: dict, universe: np.ndarray, stats: dict) -> tuple[np.ndarray, np.ndarray]: + q = query_mol(t["structure"]) + qwords = _words(chem.to_bytes(chem.similarity_fp(q))) + qbits = int(np.bitwise_count(qwords).sum()) + stats["screened"] = stats.get("screened", 0) + int(universe.sum()) + scores = np.zeros(len(s), dtype=np.float64) + if len(s) == 0: + return universe.copy(), scores + both = _popcount(s.fp & qwords) + either = s.fp_bits + qbits - both + np.divide(both, either, out=scores, where=either > 0) + scores = np.round(scores, 6) + return universe & (scores >= t["threshold"] - 1e-9), scores + + +def _neutral(mol: Chem.Mol, strip: bool) -> Chem.Mol: + from rdkit.Chem.MolStandardize import rdMolStandardize + out = chem.parent(mol) if strip else Chem.Mol(mol) + try: + return rdMolStandardize.Uncharger().uncharge(out) + except Exception: + return out + + +def _canonical(mol: Chem.Mol, stereo: bool) -> str: + return Chem.MolToSmiles(Chem.RemoveHs(mol), isomericSmiles=stereo) + + +def _exact(db: Database, s: Screen, t: dict, universe: np.ndarray) -> np.ndarray: + rules = db.rules() + stereo = (t.get("stereo") or rules["stereo"]) == "match" + strip = (t.get("salts") or rules["salts"]) == "strip" + loose_charge = t.get("charges") == "ignore" and not strip + try: + qv = chem.register_values(t["structure"]) + qmol = chem.mol_from(t["structure"]) + except chem.StructureError as exc: + raise QueryError(str(exc)) + if loose_charge or not stereo: + key = (qv["parent_key"] if strip else qv["skeleton"]).split("-")[0] + sql = "SELECT id, smiles FROM compounds WHERE substr(parent_key, 1, 14) = ?" if strip else "SELECT id, smiles FROM compounds WHERE skeleton = ?" + else: + key = qv["parent_key"] if strip else qv["inchikey"] + sql = f"SELECT id, smiles FROM compounds WHERE {'parent_key' if strip else 'inchikey'} = ?" + if not key: + raise QueryError("No InChIKey could be made for this structure, so exact search cannot compare it.") + with db.lock: + rows = db.conn.execute(sql, (key,)).fetchall() + confirm = loose_charge or t.get("tautomers") == "match" + if confirm and rows: + if loose_charge: + want = _canonical(_neutral(qmol, False), stereo) + else: + want = _canonical(chem.parent(qmol) if strip else qmol, stereo) + kept = [] + for cid, smiles in rows: + m = Chem.MolFromSmiles(smiles or "") + if m is None: + continue + got = _canonical(_neutral(m, False), stereo) if loose_charge else _canonical(chem.parent(m) if strip else m, stereo) + if got == want: + kept.append((cid, smiles)) + rows = kept + return universe & s.mask_of(r[0] for r in rows) + + +def _counts(s: Screen) -> list[dict]: + with s.lock: + if s.counts is None: + parsed = [] + for raw in s.counts_raw: + try: + found = json.loads(raw) if raw else {} + except ValueError: + found = {} + parsed.append(found if isinstance(found, dict) else {}) + s.counts = parsed + return s.counts + + +def _formula(s: Screen, t: dict, universe: np.ndarray) -> np.ndarray: + spec = query.parse_formula(t["formula"]) + out = universe.copy() + named = np.zeros(len(s), dtype=np.int64) + for sym, lo, hi in spec: + n = _element(s, sym) + named += n + out &= n >= lo + if hi is not None: + out &= n <= hi + if t.get("mode") == "exact": + out &= named == _element(s, "*") + return out + + +def _element(s: Screen, sym: str) -> np.ndarray: + counts = _counts(s) + with s.lock: + found = s.elements.get(sym) + if found is None: + if sym == "*": + found = np.fromiter((sum(c.values()) for c in counts), dtype=np.int64, count=len(counts)) + else: + found = np.fromiter((c.get(sym, 0) for c in counts), dtype=np.int64, count=len(counts)) + s.elements[sym] = found + return found + + +def _mass(db: Database, s: Screen, t: dict, universe: np.ndarray) -> np.ndarray: + col = "exact_mass" if t["field"] == "exact_mass" else "mw" + where, args = [], [] + if t.get("min") is not None: + where.append(f"{col} >= ?") + args.append(t["min"]) + if t.get("max") is not None: + where.append(f"{col} <= ?") + args.append(t["max"]) + with db.lock: + rows = db.conn.execute(f"SELECT id FROM compounds WHERE {' AND '.join(where)}", args).fetchall() + return universe & s.mask_of(r[0] for r in rows) + + +BUILTIN_COLUMNS = {"smiles": "smiles", "uid": "uid", "formula": "formula", "inchikey": "inchikey", "number": "number", "batch": "batch", + "mw": "mw", "exact_mass": "exact_mass", "heavy_atoms": "heavy_atoms", "created": "created", "modified": "modified"} +EQUAL_TOLERANCE = 1e-9 + + +def fields_of(db: Database) -> dict[str, tuple[int, str]]: + with db.lock: + rows = db.conn.execute("SELECT id, name, type FROM fields").fetchall() + return {r[1]: (r[0], r[2]) for r in rows} + + +def _values(db: Database, name: str, fields: dict, want: str) -> list[tuple[int, object]]: + with db.lock: + if name in BUILTIN_COLUMNS: + col = BUILTIN_COLUMNS[name] + return db.conn.execute(f"SELECT id, {col} FROM compounds WHERE {col} IS NOT NULL").fetchall() + fid = fields[name][0] + if want == "txt": + return db.conn.execute("SELECT compound, coalesce(txt, CAST(num AS TEXT)) FROM field_values WHERE field = ? AND (txt IS NOT NULL OR num IS NOT NULL)", (fid,)).fetchall() + return db.conn.execute("SELECT compound, num FROM field_values WHERE field = ? AND num IS NOT NULL", (fid,)).fetchall() + + +def _text(db: Database, s: Screen, t: dict, universe: np.ndarray, fields: dict) -> np.ndarray: + value, match, case = t["value"], t["match"], t.get("case") is True + if match in ("word", "regex"): + pattern = re.compile(rf"(? np.ndarray: + cmp, a, b = t["cmp"], float(t["value"]), t.get("value2") + tol = EQUAL_TOLERANCE * max(1.0, abs(a)) + tests = {"<": lambda x: x < a, "<=": lambda x: x <= a + tol, "=": lambda x: abs(x - a) <= tol, ">=": lambda x: x >= a - tol, ">": lambda x: x > a, + "between": lambda x: a - tol <= x <= float(b) + tol} + test = tests[cmp] + return universe & s.mask_of(cid for cid, x in _values(db, t["field"], fields, "num") if isinstance(x, (int, float)) and test(float(x))) + + +def _date(db: Database, s: Screen, t: dict, universe: np.ndarray, fields: dict) -> np.ndarray: + lo, hi = t.get("from"), t.get("to") + ok = lambda x: (lo is None or x >= lo) and (hi is None or x <= hi) + return universe & s.mask_of(cid for cid, x in _values(db, t["field"], fields, "num") if isinstance(x, (int, float)) and ok(float(x))) + + +def _choice(db: Database, s: Screen, t: dict, universe: np.ndarray, fields: dict) -> np.ndarray: + wanted = set(t["any"]) + multi = fields[t["field"]][1] == "multichoice" + hits = [] + for cid, txt in _values(db, t["field"], fields, "txt"): + if multi: + try: + held = json.loads(txt) + except (TypeError, ValueError): + held = [txt] + held = held if isinstance(held, list) else [held] + if wanted.intersection(str(h) for h in held): + hits.append(cid) + elif str(txt) in wanted: + hits.append(cid) + return universe & s.mask_of(hits) + + +def _empty(db: Database, s: Screen, t: dict, universe: np.ndarray, fields: dict) -> np.ndarray: + name = t["field"] + with db.lock: + if name in BUILTIN_COLUMNS: + col = BUILTIN_COLUMNS[name] + rows = db.conn.execute(f"SELECT id FROM compounds WHERE {col} IS NOT NULL AND CAST({col} AS TEXT) != ''").fetchall() + else: + rows = db.conn.execute("SELECT compound FROM field_values WHERE field = ? AND (num IS NOT NULL OR (txt IS NOT NULL AND txt != '' AND txt != '[]'))", + (fields[name][0],)).fetchall() + filled = s.mask_of(r[0] for r in rows) + return universe & (~filled if t["empty"] else filled) + + +def hitlist_ids(db: Database, hid: int) -> list[int]: + from app.services.database import hitlists + from app.services.database.store import DatabaseError + hitlists._scratch(db) + with db.lock: + if db.conn.execute("SELECT 1 FROM hitlists WHERE id = ?", (hid,)).fetchone() is None: + raise DatabaseError(f"There is no hit list {hid} in this database.", 404) + return [r[0] for r in db.conn.execute("SELECT compound FROM hitlist_items WHERE hitlist = ? ORDER BY rank", (hid,)).fetchall()] + + +STRUCTURE_FIRST_LAST = {"exact": 1, "similarity": 2, "substructure": 3} +FIELD_TERMS = {"text": _text, "number": _number, "date": _date, "choice": _choice, "empty": _empty} + + +def _cost(node: dict) -> int: + if "op" in node: + return max(_cost(t) for t in node["terms"]) + return STRUCTURE_FIRST_LAST.get(node["kind"], 0) + + +def _merge(a: np.ndarray | None, b: np.ndarray | None) -> np.ndarray | None: + if a is None: + return b + if b is None: + return a + return np.maximum(a, b) + + +def _evaluate(db: Database, s: Screen, node: dict, universe: np.ndarray, fields: dict, stats: dict) -> tuple[np.ndarray, np.ndarray | None]: + if "op" in node: + op = node["op"] + if op == "not": + inner, _ = _evaluate(db, s, node["terms"][0], universe, fields, stats) + return universe & ~inner, None + terms = sorted(node["terms"], key=_cost) + scores = None + if op == "and": + mask = universe + for t in terms: + if not mask.any(): + break + mask, sc = _evaluate(db, s, t, mask, fields, stats) + scores = _merge(scores, sc) + return mask, scores + mask = np.zeros(len(s), dtype=bool) + for t in terms: + rest = universe & ~mask + if not rest.any(): + break + got, sc = _evaluate(db, s, t, rest, fields, stats) + mask |= got + scores = _merge(scores, sc) + return mask, scores + kind = node["kind"] + stats.setdefault("kinds", set()).add(kind) + if kind == "substructure": + return _substructure(s, node, universe, stats), None + if kind == "similarity": + return _similarity(s, node, universe, stats) + if kind == "exact": + return _exact(db, s, node, universe), None + if kind == "formula": + return _formula(s, node, universe), None + if kind == "mass": + return _mass(db, s, node, universe), None + if kind == "hitlist": + return universe & s.mask_of(hitlist_ids(db, node["id"])), None + return FIELD_TERMS[kind](db, s, node, universe, fields), None + + +def _match(db: Database, node: dict, within_ids: list[int] | None, fields: dict) -> tuple[list[int], dict[int, float] | None, dict]: + s = screen(db) + universe = np.ones(len(s), dtype=bool) if within_ids is None else s.mask_of(within_ids) + stats: dict = {} + mask, scores = _evaluate(db, s, node, universe, fields, stats) + idx = np.flatnonzero(mask) + if scores is not None: + idx = idx[np.lexsort((s.order[idx], -scores[idx]))] + else: + idx = idx[np.argsort(s.order[idx], kind="stable")] + ids = [int(i) for i in s.ids[idx]] + by_id = {int(s.ids[i]): float(scores[i]) for i in idx} if scores is not None else None + return ids, by_id, stats + + +def matching_ids(db: Database, q: dict, within_ids: list[int] | None = None) -> tuple[list[int], dict[int, float] | None]: + fields = fields_of(db) + node = query.normalise(q, {k: v[1] for k, v in fields.items()}) + ids, scores, _ = _match(db, node, within_ids, fields) + return ids, scores + + +def methods_for(kinds: set) -> dict: + out = {} + if kinds & {"substructure"}: + out["screen"] = f"{chem.SCREEN_METHOD}, {ENGINE}" + out["substructure"] = f"RDKit SubstructLibrary match, {ENGINE}" + if "similarity" in kinds: + out["similarity"] = SIMILARITY_METHOD + if "exact" in kinds: + out["exact"] = f"Standard InChIKey, {ENGINE}" + return out + + +def run(db: Database, q: dict, within: int | None = None, name: str | None = None, actor: str = "person") -> dict: + from app.services.database import hitlists + started = time.perf_counter() + fields = fields_of(db) + node = query.normalise(q, {k: v[1] for k, v in fields.items()}) + within_ids = hitlist_ids(db, int(within)) if within is not None else None + ids, scores, stats = _match(db, node, within_ids, fields) + took = (time.perf_counter() - started) * 1000.0 + label = name or query.name_of(node) + if within is not None and not name: + label = f"{label} within hit list {int(within)}" + stored = node if within is None else {"op": "and", "terms": [{"kind": "hitlist", "id": int(within)}, node]} + made = hitlists.create(db, label, ids, scores, stored, actor) + return {**made, "took_ms": round(took, 1), "screened": stats.get("screened"), "candidates": stats.get("candidates"), + "methods": methods_for(stats.get("kinds") or set())} diff --git a/backend/app/services/database/store.py b/backend/app/services/database/store.py new file mode 100644 index 00000000..87ef1a66 --- /dev/null +++ b/backend/app/services/database/store.py @@ -0,0 +1,266 @@ +import asyncio +import json +import os +import secrets +import socket +import sqlite3 +import string +import threading +import time +from contextlib import contextmanager +from dataclasses import dataclass, field +from pathlib import Path +from typing import Iterator + +from app import __version__ +from app.core import config +from app.services.database import schema + +_ALPHABET = string.ascii_lowercase + string.digits +_LOCK = threading.RLock() +_OPEN: dict[str, "Database"] = {} +_loop: asyncio.AbstractEventLoop | None = None + + +class DatabaseError(Exception): + def __init__(self, message: str, status: int = 400): + super().__init__(message) + self.status = status + + +@dataclass +class Database: + handle: str + path: Path + conn: sqlite3.Connection + readonly: bool + readonly_reason: str | None + lock: threading.RLock = field(default_factory=threading.RLock) + owns_lockfile: bool = False + + def meta(self, key: str, default: str | None = None) -> str | None: + row = self.conn.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone() + return row[0] if row else default + + def set_meta(self, key: str, value: str) -> None: + self.writable() + self.conn.execute("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", (key, value)) + + def rules(self) -> dict: + try: + found = json.loads(self.meta("rules") or "{}") + except ValueError: + found = {} + return {**schema.DEFAULT_RULES, **{k: v for k, v in found.items() if k in schema.DEFAULT_RULES}} + + def writable(self) -> None: + if self.readonly: + raise DatabaseError(self.readonly_reason or "This database is open read-only.", 423) + + +def new_id(prefix: str, n: int = 10) -> str: + return prefix + "".join(secrets.choice(_ALPHABET) for _ in range(n)) + + +def databases_dir() -> Path: + target = config.data_dir() / "Databases" + target.mkdir(parents=True, exist_ok=True) + return target + + +def bind(loop: asyncio.AbstractEventLoop) -> None: + global _loop + _loop = loop + + +def notify(db: "Database | str", change: str, uids: list[str] | None = None) -> None: + from app.services.hub import HUB + handle = db.handle if isinstance(db, Database) else db + message = {"t": "database", "db": handle, "change": change} + if uids is not None: + message["uids"] = uids + loop = _loop + if loop is None or loop.is_closed(): + return + try: + running = asyncio.get_running_loop() + except RuntimeError: + running = None + if running is loop: + loop.create_task(HUB.broadcast_all(message)) + else: + asyncio.run_coroutine_threadsafe(HUB.broadcast_all(message), loop) + + +def _lockfile(path: Path) -> Path: + return path.with_name(path.name + ".lock") + + +def _alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + except OSError: + return False + return True + + +def _take_lock(path: Path) -> str | None: + lf = _lockfile(path) + mine = {"pid": os.getpid(), "host": socket.gethostname(), "app": "formchem", "opened": time.time()} + for _ in range(2): + try: + fd = os.open(lf, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) + except FileExistsError: + try: + held = json.loads(lf.read_text(encoding="utf-8")) + except (OSError, ValueError): + held = {} + pid, host = held.get("pid"), held.get("host") + if host == mine["host"] and isinstance(pid, int) and pid != mine["pid"] and not _alive(pid): + lf.unlink(missing_ok=True) + continue + if host == mine["host"] and pid == mine["pid"]: + return "This database is already open in this FormChem." + who = held.get("host") or "another computer" + return f"This database is open in another FormChem ({who}), so it opened read-only." + except OSError as exc: + return f"No lock could be made beside the database ({exc.strerror}), so it opened read-only." + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump(mine, fh) + return None + return "The database's lock could not be taken, so it opened read-only." + + +def _by_path(path: Path) -> "Database | None": + for d in _OPEN.values(): + if d.path == path: + return d + return None + + +def _open_file(path: Path, create_title: str | None = None) -> Database: + path = path.expanduser().resolve() + with _LOCK: + found = _by_path(path) + if found: + return found + if create_title is None and not path.is_file(): + raise DatabaseError(f"No database at {path}.", 404) + if create_title is not None and path.exists(): + raise DatabaseError(f"{path.name} already exists.", 409) + path.parent.mkdir(parents=True, exist_ok=True) + reason = _take_lock(path) + readonly = reason is not None + owned = not readonly + if create_title is not None and readonly: + raise DatabaseError(reason or "The database could not be created.", 423) + try: + conn = schema.connect(path, readonly=readonly) + conn.execute("PRAGMA busy_timeout = 5000") + if create_title is not None: + schema.create(conn, create_title, __version__) + elif not schema.check(conn): + readonly, reason = True, "This database was made by a newer FormChem, so it opened read-only." + conn.close() + conn = schema.connect(path, readonly=True) + elif not readonly: + schema.migrate(conn) + except (sqlite3.DatabaseError, schema.SchemaError) as exc: + if owned: + _lockfile(path).unlink(missing_ok=True) + raise DatabaseError(str(exc) if isinstance(exc, schema.SchemaError) else f"{path.name} is not a readable database: {exc}", 422) + db = Database(new_id("g", 8), path, conn, readonly, reason, owns_lockfile=owned) + _OPEN[db.handle] = db + return db + + +def create(title: str, path: str | None = None) -> Database: + title = (title or "").strip() or "Untitled database" + if path: + target = Path(path).expanduser() + if target.suffix.lower() != schema.EXTENSION: + target = target.with_name(target.name + schema.EXTENSION) + else: + safe = "".join(c if c.isalnum() or c in " -_" else "_" for c in title).strip() or "Database" + target = databases_dir() / f"{safe}{schema.EXTENSION}" + n = 2 + while target.exists(): + target = databases_dir() / f"{safe} {n}{schema.EXTENSION}" + n += 1 + return _open_file(target, create_title=title) + + +def open_path(path: str) -> Database: + return _open_file(Path(path)) + + +def get(handle: str) -> Database: + with _LOCK: + db = _OPEN.get(handle) + if db is None: + raise DatabaseError("That database is not open.", 404) + return db + + +def all_open() -> list[Database]: + with _LOCK: + return list(_OPEN.values()) + + +def close(handle: str) -> None: + with _LOCK: + db = _OPEN.pop(handle, None) + if db is None: + return + with db.lock: + try: + db.conn.close() + finally: + if db.owns_lockfile: + _lockfile(db.path).unlink(missing_ok=True) + + +def close_all() -> None: + for db in all_open(): + close(db.handle) + + +@contextmanager +def writing(db: Database) -> Iterator[sqlite3.Connection]: + db.writable() + with db.lock: + db.conn.execute("BEGIN IMMEDIATE") + try: + yield db.conn + except BaseException: + db.conn.execute("ROLLBACK") + raise + db.conn.execute("COMMIT") + + +@contextmanager +def reading(db: Database) -> Iterator[sqlite3.Connection]: + with db.lock: + yield db.conn + + +def next_number(db: Database) -> int: + row = db.conn.execute("SELECT max(number) FROM compounds").fetchone() + try: + last = int(db.meta("last_number") or 0) + except ValueError: + last = 0 + n = max(last, row[0] or 0) + 1 + db.set_meta("last_number", str(n)) + return n + + +def audit(db: Database, actor: str, action: str, target: str | None = None, detail: dict | None = None) -> None: + if db.readonly: + return + db.conn.execute("INSERT INTO audit (at, actor, action, target, detail) VALUES (?, ?, ?, ?, ?)", + (time.time(), actor, action, target, json.dumps(detail, separators=(",", ":")) if detail else None)) diff --git a/backend/app/services/database/thumbs.py b/backend/app/services/database/thumbs.py new file mode 100644 index 00000000..63350e50 --- /dev/null +++ b/backend/app/services/database/thumbs.py @@ -0,0 +1,85 @@ +from rdkit import Chem +from rdkit.Chem import rdDepictor +from rdkit.Chem.Draw import rdMolDraw2D + +from app.services.database import store +from app.services.database.store import DatabaseError + +MIN_SIZE, MAX_SIZE = 64, 512 +THEMES = ("dark", "light") +METHOD = "RDKit MolDraw2DSVG" +_GROUPS = {6: 1, 1: 1, 7: 2, 8: 3, 16: 4, 15: 5, 9: 6, 17: 7, 35: 8, 53: 9} +_PALETTES = { + "light": ("#1d1f24", "#2f4fd0", "#d0312d", "#a37d00", "#c06a00", "#23893a", "#23893a", "#8a3b1d", "#6a2ca0"), + "dark": ("#e8e9ec", "#7d9bff", "#ff6b66", "#f0c94a", "#ffa04d", "#74d98a", "#5fcf7a", "#e0866a", "#c58cf2"), +} + + +def _sentinel(k: int) -> tuple[float, float, float]: + v = (k + 0.5) / 255.0 + return (v, v, v) + + +def _sentinel_hex(k: int) -> str: + return f"#{k:02X}{k:02X}{k:02X}" + + +def _mol(molfile: str) -> Chem.Mol: + mol = Chem.MolFromMolBlock(molfile, sanitize=True, removeHs=False, strictParsing=False) + if mol is None: + mol = Chem.MolFromMolBlock(molfile, sanitize=False, removeHs=False, strictParsing=False) + if mol is None: + raise DatabaseError("The stored structure could not be drawn.", 422) + try: + mol = Chem.RemoveHs(mol, sanitize=False) + except Exception: + pass + if mol.GetNumConformers() == 0 or (mol.GetNumAtoms() > 1 and not any(abs(x) + abs(y) > 1e-6 for x, y, _ in mol.GetConformer().GetPositions())): + rdDepictor.Compute2DCoords(mol) + return mol + + +def render(molfile: str, size: int) -> str: + mol = _mol(molfile) + drawer = rdMolDraw2D.MolDraw2DSVG(size, size) + opts = drawer.drawOptions() + opts.clearBackground = False + opts.padding = 0.08 + opts.bondLineWidth = 1.5 if size <= 160 else 2.0 + opts.fixedBondLength = max(14.0, size / 5.0) + palette = {-1: _sentinel(1)} + palette.update({z: _sentinel(k) for z, k in _GROUPS.items()}) + opts.setAtomPalette(palette) + try: + prepared = rdMolDraw2D.PrepareMolForDrawing(mol) + except Exception: + prepared = mol + drawer.DrawMolecule(prepared) + drawer.FinishDrawing() + text = drawer.GetDrawingText() + start = text.find("= 0 else text + + +def themed(svg: str, theme: str) -> str: + colours = _PALETTES["light" if theme == "light" else "dark"] + for k, colour in enumerate(colours, start=1): + svg = svg.replace(_sentinel_hex(k), colour) + return svg + + +def svg(db: store.Database, uid: str, size: int = 128, theme: str = "dark") -> str: + size = max(MIN_SIZE, min(MAX_SIZE, int(size))) + with store.reading(db): + row = db.conn.execute("SELECT c.id, c.molfile, t.svg FROM compounds c LEFT JOIN thumbs t ON t.compound = c.id AND t.size = ? WHERE c.uid = ?", + (size, uid)).fetchone() + if row is None: + raise DatabaseError(f"There is no record {uid}.", 404) + cached = row["svg"] + if cached is None: + cached = render(row["molfile"], size) + if not db.readonly: + with store.writing(db) as conn: + if conn.execute("SELECT 1 FROM compounds WHERE id = ?", (row["id"],)).fetchone(): + conn.execute("INSERT OR REPLACE INTO thumbs (compound, size, svg) VALUES (?, ?, ?)", (row["id"], size, cached)) + return themed(cached, theme) diff --git a/backend/app/services/database/uploads.py b/backend/app/services/database/uploads.py new file mode 100644 index 00000000..0e8f7c73 --- /dev/null +++ b/backend/app/services/database/uploads.py @@ -0,0 +1,63 @@ +import os +import time +from pathlib import Path +from typing import BinaryIO + +from app.core import files +from app.services.database import schema, store +from app.services.database.store import DatabaseError + +FOLDER = ".uploads" +LIMIT = 1024 * 1024 * 1024 +KEEP_SECONDS = 24 * 3600 +CHUNK = 1024 * 1024 + + +def uploads_dir() -> Path: + target = store.databases_dir() / FOLDER + target.mkdir(parents=True, exist_ok=True) + return target + + +def sweep() -> int: + now, gone = time.time(), 0 + for p in uploads_dir().iterdir(): + try: + if p.is_file() and now - p.stat().st_mtime > KEEP_SECONDS: + p.unlink() + gone += 1 + except OSError: + pass + return gone + + +def adopt(path: str) -> Path: + if not isinstance(path, str) or not path.strip(): + raise DatabaseError("Give the path of the uploaded database.", 422) + source = Path(path.strip()).resolve() + if source.parent != uploads_dir().resolve() or not source.is_file(): + raise DatabaseError("Only a database uploaded by this window can be kept.", 422) + if source.suffix.lower() != schema.EXTENSION: + raise DatabaseError(f"{source.name} is not a FormChem database ({schema.EXTENSION}).", 422) + target = files.free_name(store.databases_dir(), source.name) + os.replace(source, target) + return target + + +def save(name: str, source: BinaryIO) -> Path: + sweep() + safe = files.safe_name(Path(name or "").name, "upload") + target = files.free_name(uploads_dir(), safe) + tmp = target.with_name(f".{target.name}.{os.getpid()}.part") + size = 0 + try: + with open(tmp, "wb") as out: + while chunk := source.read(CHUNK): + size += len(chunk) + if size > LIMIT: + raise DatabaseError(f"{safe} is larger than {LIMIT // (1024 * 1024)} MB.", 413) + out.write(chunk) + os.replace(tmp, target) + finally: + tmp.unlink(missing_ok=True) + return target diff --git a/backend/app/services/describe.py b/backend/app/services/describe.py new file mode 100644 index 00000000..d4fb57a6 --- /dev/null +++ b/backend/app/services/describe.py @@ -0,0 +1,319 @@ +from dataclasses import dataclass, field + +from rdkit import Chem +from rdkit.Chem import rdCIPLabeler + +from app.services.chem import ENGINE, ids, perceive + +VERSION = "1" +GROUPS_METHOD = f"FormChem functional group table {VERSION} (SMARTS matched with RDKit, each atom counted once)" +RINGS_METHOD = "RDKit smallest set of smallest rings, joined into ring systems where rings share atoms" +FORMULA_METHOD = "Hill formula from the RDKit molecule (FormChem ids.formula)" +STEREO_METHOD = "RDKit CIP labeller (rdCIPLabeler) on the drawn stereo" +CIP_MAX_ITERATIONS = perceive.CIP_MAX_ITERATIONS + +GROUPS: list[tuple[str, str, str]] = [ + ("carboxylate", "carboxylate", "[CX3:1](=[OX1:2])[OX1-:3]"), + ("carboxylic_acid", "carboxylic acid", "[CX3:1](=[OX1:2])[OX2H1:3]"), + ("anhydride", "acid anhydride", "[CX3:1](=[OX1:2])[OX2:3][CX3:4]=[OX1:5]"), + ("acyl_halide", "acyl halide", "[CX3:1](=[OX1:2])[F,Cl,Br,I:3]"), + ("carbonate", "carbonate ester", "[#8X2:1][#6X3:2](=[OX1:3])[#8X2:4]"), + ("carbamate", "carbamate", "[#7X3:1][#6X3:2](=[OX1:3])[#8X2:4]"), + ("urea", "urea", "[#7X3:1][#6X3:2](=[OX1:3])[#7X3:4]"), + ("imide", "imide", "[#6X3:1](=[OX1:2])[#7X3:3][#6X3:4]=[OX1:5]"), + ("ester", "ester", "[#6][#6X3:1](=[OX1:2])[#8X2H0:3][#6]"), + ("amide", "amide", "[#7X3:1][#6X3:2]=[OX1:3]"), + ("sulfonamide", "sulfonamide", "[SX4:1](=[OX1:2])(=[OX1:3])[NX3:4]"), + ("sulfonic_acid", "sulfonic acid", "[SX4:1](=[OX1:2])(=[OX1:3])[OX2H1:4]"), + ("sulfone", "sulfone", "[#6][SX4:1](=[OX1:2])(=[OX1:3])[#6]"), + ("sulfoxide", "sulfoxide", "[#6][SX3:1](=[OX1:2])[#6]"), + ("phosphate", "phosphate", "[PX4:1](=[OX1:2])([OX2:3])([OX2:4])[OX2:5]"), + ("aldehyde", "aldehyde", "[$([CX3H1][#6]),$([CX3H2]):1]=[OX1:2]"), + ("ketone", "ketone", "[#6][#6X3:1](=[OX1:2])[#6]"), + ("nitro", "nitro group", "[$([NX3](=O)=O),$([NX3+](=O)[O-]):1](~[OX1:2])~[OX1:3]"), + ("nitrile", "nitrile", "[CX2:1]#[NX1:2]"), + ("isocyanate", "isocyanate", "[NX2:1]=[CX2:2]=[OX1:3]"), + ("oxime", "oxime", "[CX3:1]=[NX2:2][OX2H1:3]"), + ("azo", "azo group", "[#6][NX2:1]=[NX2:2][#6]"), + ("imine", "imine", "[CX3:1]=[NX2:2]"), + ("hydrazine", "hydrazine", "[NX3:1][NX3:2]"), + ("epoxide", "epoxide", "[OX2r3:1]1[#6r3:2][#6r3:3]1"), + ("phenol", "phenol", "[OX2H1:1][c]"), + ("alcohol", "alcohol", "[OX2H1:1][CX4]"), + ("ether", "ether", "[OX2H0:1]([#6])[#6]"), + ("quaternary_ammonium", "quaternary ammonium", "[NX4+:1]([#6])([#6])([#6])[#6]"), + ("ammonium", "protonated amine (ammonium)", "[NX4+;H1,H2,H3:1][#6]"), + ("aryl_amine", "aromatic amine", "[NX3;H2,H1;!$(N[#6]=[O,S,N]):1][c]"), + ("primary_amine", "primary amine", "[NX3;H2:1][CX4]"), + ("secondary_amine", "secondary amine", "[NX3;H1:1]([CX4])[CX4]"), + ("tertiary_amine", "tertiary amine", "[NX3;H0:1]([CX4])([CX4])[CX4]"), + ("thiol", "thiol", "[SX2H1:1][#6]"), + ("disulfide", "disulfide", "[SX2:1][SX2:2]"), + ("sulfide", "sulfide (thioether)", "[SX2H0:1]([#6])[#6]"), + ("boronic_acid", "boronic acid", "[BX3:1]([OX2H1:2])[OX2H1:3]"), + ("alkyne", "alkyne", "[CX2:1]#[CX2:2]"), + ("alkene", "alkene", "[CX3:1]=[CX3:2]"), + ("aryl_halide", "aryl halide", "[c][F,Cl,Br,I:1]"), + ("alkyl_halide", "alkyl halide", "[CX4][F,Cl,Br,I:1]"), +] + + +@dataclass +class _Pattern: + id: str + name: str + query: Chem.Mol + core: list[int] = field(default_factory=list) + + +def _compile() -> list[_Pattern]: + out: list[_Pattern] = [] + for gid, name, smarts in GROUPS: + q = Chem.MolFromSmarts(smarts) + if q is None: + raise ValueError(f"functional group {gid} has an invalid SMARTS") + core = [a.GetIdx() for a in q.GetAtoms() if a.GetAtomMapNum()] + out.append(_Pattern(gid, name, q, core or [a.GetIdx() for a in q.GetAtoms()])) + return out + + +_PATTERNS: list[_Pattern] | None = None + + +def patterns() -> list[_Pattern]: + global _PATTERNS + if _PATTERNS is None: + _PATTERNS = _compile() + return _PATTERNS + + +class DescribeError(ValueError): + pass + + +@dataclass +class Source: + mol: Chem.Mol + owners: list[tuple[str, str] | None] + warnings: list[dict] = field(default_factory=list) + + +def from_fragments(frags: list[dict], expansions: dict | None = None) -> Source: + combined: Chem.Mol | None = None + owners: list[tuple[str, str] | None] = [] + warnings: list[dict] = [] + for frag in frags: + if not frag.get("atoms"): + continue + conv = perceive.prepare(frag, expansions) + warnings.extend(w for w in conv.warnings if isinstance(w, dict)) + fid = str(frag.get("id") or "") + for i in range(conv.mol.GetNumAtoms()): + owners.append((fid, conv.owner[i]) if conv.drawn[i] else None) + mol = conv.mol.GetMol() + combined = mol if combined is None else Chem.CombineMols(combined, mol) + if combined is None: + raise DescribeError("There is no structure to describe.") + return Source(combined, owners, warnings) + + +def from_smiles(smiles: str) -> Source: + mol = Chem.MolFromSmiles(smiles) + if mol is None: + raise DescribeError("smiles is not a valid SMILES") + Chem.AssignStereochemistry(mol, cleanIt=True, force=True) + return Source(mol, [None] * mol.GetNumAtoms()) + + +def functional_groups(mol: Chem.Mol) -> list[dict]: + claimed: set[int] = set() + out: list[dict] = [] + for p in patterns(): + hits: list[list[int]] = [] + for match in mol.GetSubstructMatches(p.query, uniquify=True, maxMatches=1000): + core = [match[i] for i in p.core] + if any(a in claimed for a in core): + continue + claimed.update(core) + hits.append(sorted(core)) + if hits: + out.append({"id": p.id, "name": p.name, "count": len(hits), "atoms": hits}) + return out + + +def _ring_systems(mol: Chem.Mol) -> list[list[int]]: + rings = [set(r) for r in mol.GetRingInfo().AtomRings()] + systems: list[dict] = [] + for i, r in enumerate(rings): + joined = [s for s in systems if s["atoms"] & r] + merged = {"atoms": set(r), "rings": [i]} + for s in joined: + merged["atoms"] |= s["atoms"] + merged["rings"] += s["rings"] + systems.remove(s) + systems.append(merged) + return [sorted(s["rings"]) for s in sorted(systems, key=lambda s: min(s["atoms"]))] + + +def _join_kind(rings: list[set[int]]) -> str: + if len(rings) < 2: + return "single" + shared = [len(a & b) for i, a in enumerate(rings) for b in rings[i + 1:] if a & b] + if any(n > 2 for n in shared): + return "bridged" + if all(n == 1 for n in shared): + return "spiro" + return "fused" + + +RING_NAMES: list[tuple[str, str]] = [ + ("benzene", "c1ccccc1"), ("naphthalene", "c1ccc2ccccc2c1"), ("anthracene", "c1ccc2cc3ccccc3cc2c1"), + ("phenanthrene", "c1ccc2c(c1)ccc1ccccc12"), ("pyridine", "c1ccncc1"), ("pyrimidine", "c1cncnc1"), + ("pyrazine", "c1cnccn1"), ("pyridazine", "c1ccnnc1"), ("pyrrole", "c1cc[nH]c1"), ("furan", "c1ccoc1"), + ("thiophene", "c1ccsc1"), ("imidazole", "c1c[nH]cn1"), ("pyrazole", "c1cn[nH]c1"), ("oxazole", "c1cocn1"), + ("thiazole", "c1cscn1"), ("isoxazole", "c1cnoc1"), ("triazole", "c1nc[nH]n1"), ("tetrazole", "c1nnn[nH]1"), + ("indole", "c1ccc2[nH]ccc2c1"), ("benzofuran", "c1ccc2occc2c1"), ("benzothiophene", "c1ccc2sccc2c1"), + ("benzimidazole", "c1ccc2[nH]cnc2c1"), ("quinoline", "c1ccc2ncccc2c1"), ("isoquinoline", "c1ccc2cnccc2c1"), + ("purine", "c1ncc2[nH]cnc2n1"), ("cyclopropane", "C1CC1"), ("cyclobutane", "C1CCC1"), ("cyclopentane", "C1CCCC1"), + ("cyclohexane", "C1CCCCC1"), ("cycloheptane", "C1CCCCCC1"), ("cyclohexene", "C1=CCCCC1"), ("cyclopentene", "C1=CCCC1"), + ("aziridine", "C1CN1"), ("oxirane", "C1CO1"), ("azetidine", "C1CNC1"), ("oxetane", "C1COC1"), + ("pyrrolidine", "C1CCNC1"), ("tetrahydrofuran", "C1CCOC1"), ("tetrahydrothiophene", "C1CCSC1"), + ("piperidine", "C1CCNCC1"), ("piperazine", "C1CNCCN1"), ("morpholine", "C1COCCN1"), ("tetrahydropyran", "C1CCOCC1"), + ("1,4-dioxane", "C1COCCO1"), ("1,3-dioxolane", "C1OCCO1"), ("decalin", "C1CCC2CCCCC2C1"), + ("norbornane", "C1CC2CCC1C2"), ("adamantane", "C1C2CC3CC1CC(C2)C3"), ("tetralin", "c1ccc2c(c1)CCCC2"), + ("indane", "c1ccc2c(c1)CCC2"), ("steroid nucleus (gonane)", "C1CCC2C(C1)CCC1C2CCC2CCCC21"), +] + + +def _skeleton_key(mol: Chem.Mol, atoms: list[int]) -> str | None: + keep = set(atoms) + bonds = [b.GetIdx() for b in mol.GetBonds() if b.GetBeginAtomIdx() in keep and b.GetEndAtomIdx() in keep] + try: + text = Chem.MolFragmentToSmiles(mol, atomsToUse=atoms, bondsToUse=bonds or None, isomericSmiles=False, canonical=True) + part = Chem.MolFromSmiles(text, sanitize=False) + if part is None: + return None + for a in part.GetAtoms(): + a.SetNoImplicit(True) + a.SetNumExplicitHs(0) + a.SetFormalCharge(0) + part.UpdatePropertyCache(strict=False) + return Chem.MolToSmiles(part, isomericSmiles=False, canonical=True) + except Exception: + return None + + +_RING_KEYS: dict[str, str] | None = None + + +def ring_name(mol: Chem.Mol, atoms: list[int]) -> str | None: + global _RING_KEYS + if _RING_KEYS is None: + keys: dict[str, str] = {} + for name, smiles in RING_NAMES: + m = Chem.MolFromSmiles(smiles) + key = _skeleton_key(m, list(range(m.GetNumAtoms()))) if m is not None else None + if key and key not in keys: + keys[key] = name + _RING_KEYS = keys + key = _skeleton_key(mol, atoms) + return _RING_KEYS.get(key) if key else None + + +def ring_systems(mol: Chem.Mol) -> list[dict]: + ri = mol.GetRingInfo() + all_rings = ri.AtomRings() + pt = Chem.GetPeriodicTable() + out: list[dict] = [] + for members in _ring_systems(mol): + rings = [set(all_rings[i]) for i in members] + atoms = sorted(set().union(*rings)) + aromatic = [all(mol.GetAtomWithIdx(a).GetIsAromatic() for a in r) for r in rings] + hetero = sorted({pt.GetElementSymbol(mol.GetAtomWithIdx(a).GetAtomicNum()) for a in atoms if mol.GetAtomWithIdx(a).GetAtomicNum() not in (1, 6)}) + out.append({ + "rings": len(rings), + "sizes": sorted(len(r) for r in rings), + "atoms": len(atoms), + "aromatic": all(aromatic), + "aromatic_rings": sum(aromatic), + "kind": _join_kind(rings), + "hetero": hetero, + "name": ring_name(mol, atoms), + "atom_indices": atoms, + }) + return out + + +def stereo(src: Source) -> dict: + probe = Chem.Mol(src.mol) + note = None + try: + rdCIPLabeler.AssignCIPLabels(probe, maxRecursiveIterations=CIP_MAX_ITERATIONS) + except Exception as exc: + note = f"CIP labels were not assigned: {exc}" + try: + found = list(Chem.FindPotentialStereo(probe)) + except Exception: + found = [] + pt = Chem.GetPeriodicTable() + centres: list[dict] = [] + bonds: list[dict] = [] + for si in found: + if si.type == Chem.StereoType.Atom_Tetrahedral: + a = probe.GetAtomWithIdx(si.centeredOn) + label = a.GetProp("_CIPCode") if a.HasProp("_CIPCode") else None + owner = src.owners[si.centeredOn] if si.centeredOn < len(src.owners) else None + centres.append({"index": si.centeredOn, "element": pt.GetElementSymbol(a.GetAtomicNum()), "label": label, + "specified": si.specified == Chem.StereoSpecified.Specified, + "fragment": owner[0] if owner else None, "atom": owner[1] if owner else None}) + elif si.type == Chem.StereoType.Bond_Double: + b = probe.GetBondWithIdx(si.centeredOn) + label = b.GetProp("_CIPCode") if b.HasProp("_CIPCode") else None + bonds.append({"index": si.centeredOn, "label": label, "specified": si.specified == Chem.StereoSpecified.Specified, + "atoms": [b.GetBeginAtomIdx(), b.GetEndAtomIdx()]}) + out = {"centres": centres, "double_bonds": bonds, "method": STEREO_METHOD, "version": ENGINE} + if note: + out["note"] = note + return out + + +def _name(mol: Chem.Mol) -> dict | None: + from app.services import names + if any(a.GetAtomicNum() == 0 for a in mol.GetAtoms()): + return None + if len(Chem.GetMolFrags(mol)) != 1: + return None + try: + text = ids.smiles(ids.identifier_mol(mol)) + clean = Chem.MolFromSmiles(text) if text else None + if clean is None: + return None + engine = names.engine() + result = engine.to_name(clean) + except Exception: + return None + if not result.names: + return None + first = result.names[0] + return {"text": first.text, "kind": first.kind, "confidence": first.confidence, "method": first.method, + "engine": result.engine, "version": result.version} + + +def describe(src: Source, want_name: bool = True) -> dict: + mol = src.mol + heavy = sum(1 for a in mol.GetAtoms() if a.GetAtomicNum() > 1) + charge = sum(a.GetFormalCharge() for a in mol.GetAtoms()) + components = len(Chem.GetMolFrags(mol)) if mol.GetNumAtoms() else 0 + out = { + "formula": {"text": ids.formula(mol), "method": FORMULA_METHOD, "version": ENGINE}, + "charge": charge, + "atoms": mol.GetNumAtoms(), + "heavy_atoms": heavy, + "components": components, + "name": _name(mol) if want_name else None, + "rings": {"systems": ring_systems(mol), "method": RINGS_METHOD, "version": ENGINE}, + "groups": {"items": functional_groups(mol), "method": GROUPS_METHOD, "version": ENGINE}, + "stereo": stereo(src), + "warnings": src.warnings, + } + return out diff --git a/backend/app/services/file_watch.py b/backend/app/services/file_watch.py new file mode 100644 index 00000000..7ab49eae --- /dev/null +++ b/backend/app/services/file_watch.py @@ -0,0 +1,155 @@ +import asyncio +import json +import logging +import os +import zipfile +from pathlib import Path + +POLL_SECONDS = 1.0 +log = logging.getLogger("formchem.file_watch") +_STATE: dict[str, dict] = {} +_TASK: dict = {"task": None} + + +class WatchError(ValueError): + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + + +def stamp(path: Path) -> tuple[int, int] | None: + try: + st = os.stat(path) + except OSError: + return None + return st.st_mtime_ns, st.st_size + + +def disk_modified(path: Path) -> str | None: + try: + with zipfile.ZipFile(path) as z: + doc = json.loads(z.read("document.json")) + except (OSError, KeyError, ValueError, zipfile.BadZipFile): + return None + found = doc.get("modified") if isinstance(doc, dict) else None + return found if isinstance(found, str) else None + + +def ensure_started() -> None: + task = _TASK["task"] + if task is not None and not task.done(): + return + _TASK["task"] = asyncio.get_running_loop().create_task(_loop()) + + +def stop() -> None: + task = _TASK["task"] + if task is not None: + task.cancel() + _TASK["task"] = None + + +async def _loop() -> None: + while True: + try: + await check() + except asyncio.CancelledError: + raise + except Exception: + log.exception("the file watch failed a round") + await asyncio.sleep(POLL_SECONDS) + + +async def check() -> list[str]: + from app.services.hub import HUB + from app.services.store import STORE + changed: list[str] = [] + seen: set[str] = set() + for s in list(STORE.sessions.values()): + if s.path is None: + continue + seen.add(s.id) + path = str(s.path) + now = stamp(s.path) + state = _STATE.get(s.id) + if state is None or state["path"] != path: + _STATE[s.id] = {"path": path, "stamp": now, "pending": False} + continue + if now == state["stamp"]: + continue + state["stamp"] = now + if now is not None: + on_disk = await asyncio.to_thread(disk_modified, s.path) + with s.lock: + mine = s.doc.get("modified") + if on_disk is not None and on_disk == mine: + continue + state["pending"] = True + changed.append(s.id) + await HUB.broadcast_all({"t": "file-changed", "doc": s.id, "path": path, "missing": now is None}) + for gone in set(_STATE) - seen: + _STATE.pop(gone, None) + return changed + + +def _session(doc_id: str): + from app.services.store import STORE + try: + s = STORE.get(doc_id) + except KeyError: + raise WatchError(f"The drawing {doc_id} is not open.", 404) from None + if s.path is None: + raise WatchError("This drawing has no file on disk.", 409) + return s + + +async def reload(doc_id: str) -> dict: + from app.services import package + from app.services import ops as opsmod + from app.services.hub import HUB + from app.services.store import STORE + s = _session(doc_id) + path = s.path + try: + doc, media = await asyncio.to_thread(package.read, path) + except package.PackageError as exc: + raise WatchError(str(exc), 422) from None + with s.lock: + ops: list[dict] = [] + for key in sorted((set(s.doc) | set(doc)) - set(opsmod.PROTECTED_ROOTS)): + if key not in doc: + ops.append({"op": "set", "path": [key]}) + elif key not in s.doc or not opsmod.same_value(s.doc[key], doc[key]): + ops.append({"op": "set", "path": [key], "value": doc[key]}) + for mid, raw in media.items(): + s.media.setdefault(mid, raw) + if ops: + await STORE.apply(doc_id, {"label": "Reload from Disk", "ops": ops}, "user") + with s.lock: + if isinstance(doc.get("modified"), str): + s.doc["modified"] = doc["modified"] + s.saved_rev = s.rev + s.dirty = False + rev = s.rev + _STATE[doc_id] = {"path": str(path), "stamp": stamp(path), "pending": False} + await HUB.broadcast_all({"t": "saved", "doc": doc_id, "rev": rev, "path": str(path), "modified": s.doc.get("modified"), "dirty": False}) + await HUB.broadcast_all({"t": "file-resolved", "doc": doc_id, "choice": "reload"}) + return {"doc": doc_id, "choice": "reload", "rev": rev, "changed": len(ops)} + + +async def keep(doc_id: str) -> dict: + from app.services.hub import HUB + s = _session(doc_id) + with s.lock: + s.dirty = True + rev = s.rev + state = _STATE.get(doc_id) + if state is not None: + state["pending"] = False + await HUB.broadcast_all({"t": "saved", "doc": doc_id, "rev": rev, "path": str(s.path), "modified": s.doc.get("modified"), "dirty": True}) + await HUB.broadcast_all({"t": "file-resolved", "doc": doc_id, "choice": "keep"}) + return {"doc": doc_id, "choice": "keep", "rev": rev} + + +def pending() -> list[dict]: + return [{"doc": d, "path": st["path"], "missing": st["stamp"] is None} for d, st in _STATE.items() if st.get("pending")] diff --git a/backend/app/services/helm/__init__.py b/backend/app/services/helm/__init__.py new file mode 100644 index 00000000..b18f516b --- /dev/null +++ b/backend/app/services/helm/__init__.py @@ -0,0 +1,90 @@ +import time + +from rdkit import Chem + +from app.services.chem import DEFAULT_BOND_LENGTH, ENGINE, convert, ids, layout, mass +from app.services.helm import monomers +from app.services.helm.assemble import assemble as build_molecule +from app.services.helm.parser import HelmError, parse +from app.services.helm.writer import WriteError, write + +VERSION = "1.0" +READER = f"FormChem HELM {VERSION}" +V3000_FROM = 999 + + +def method() -> dict: + lib = monomers.library() + return {"reader": READER, "monomers": f"FormChem monomer data {lib.version} ({lib.count()} monomers)", "chemistry": ENGINE, + "mass": f"average and monoisotopic masses from the {ENGINE} periodic table", "layout": f"FormChem scored 2D layout on {ENGINE}"} + + +def _summary(asm) -> list[dict]: + out: dict[str, dict] = {} + for p in asm.placed: + row = out.setdefault(p.polymer, {"id": p.polymer, "type": p.polymer.rstrip("0123456789"), "monomers": 0}) + row["monomers"] += 1 + return list(out.values()) + + +def _numbers(mol: Chem.Mol) -> dict: + _text, key, _notes = ids.inchi(mol) + return {"smiles": ids.smiles(mol), "inchikey": key or None, "formula": ids.formula(mol), + "average_mass": round(mass.average_mass(mol), 4), "exact_mass": round(mass.exact_mass(mol), 6)} + + +def molfile(mol: Chem.Mol) -> str: + return Chem.MolToMolBlock(mol, forceV3000=mol.GetNumAtoms() > V3000_FROM) + + +def read(text: str, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (0.0, 0.0), draw: bool = True) -> dict: + started = time.perf_counter() + out: dict = {"ok": False, "helm": text, "method": method(), "warnings": [], "error": None} + try: + helm = parse(text) + asm = build_molecule(helm) + except HelmError as exc: + out["error"] = exc.as_dict() + return out + mol = asm.mol + out.update(_numbers(mol)) + out.update({"ok": True, "polymers": _summary(asm), "residues": asm.residues(), "connections": len(helm.connections), + "heavy_atoms": mol.GetNumAtoms(), "warnings": list(asm.notes)}) + if draw: + score = layout.depict(mol) + out["layout"] = f"scored, best candidate {score.parts.get('method')}" if score is not None else f"coordgen, unscored over {layout.CANDIDATE_LIMIT} atoms" + out["molfile"] = molfile(mol) + out["fragment"] = convert.from_mol(mol, bond_length, origin) + out["seconds"] = round(time.perf_counter() - started, 3) + return out + + +def _same(a: Chem.Mol, b: Chem.Mol, stereo: bool) -> bool: + if stereo: + ka, kb = ids.inchi(a)[1], ids.inchi(b)[1] + if ka and kb: + return ka == kb + return Chem.MolToSmiles(a, isomericSmiles=stereo) == Chem.MolToSmiles(b, isomericSmiles=stereo) + + +def from_mol(mol: Chem.Mol) -> dict: + out: dict = {"ok": False, "helm": None, "method": method(), "warnings": [], "reason": None} + try: + text, notes, residues = write(mol) + except WriteError as exc: + out["reason"] = str(exc) + return out + try: + back = build_molecule(parse(text)).mol + except HelmError as exc: + out["reason"] = f"The HELM written could not be read back ({exc.text}), so it is not offered." + return out + guessed = any(n.get("code") == "stereo_assumed" for n in notes) + if not _same(Chem.RemoveHs(mol), back, not guessed): + out["reason"] = "The HELM written does not read back to the same structure, so it is not offered." + return out + out.update({"ok": True, "helm": text, "residues": residues, "warnings": notes, **_numbers(back)}) + return out + + +__all__ = ["HelmError", "WriteError", "VERSION", "READER", "method", "read", "from_mol", "molfile", "parse", "build_molecule", "write"] diff --git a/backend/app/services/helm/assemble.py b/backend/app/services/helm/assemble.py new file mode 100644 index 00000000..2e70d569 --- /dev/null +++ b/backend/app/services/helm/assemble.py @@ -0,0 +1,147 @@ +from dataclasses import dataclass, field + +from rdkit import Chem + +from app.services.helm import monomers as mono +from app.services.helm.parser import Helm, HelmError + +MAX_ATOMS = 20_000 + + +@dataclass +class Placed: + polymer: str + number: int + monomer: mono.Monomer + offset: int + points: dict[str, int] + position: int + + +@dataclass +class Link: + a: int + ra: str + b: int + rb: str + position: int + kind: str + + +@dataclass +class Assembly: + mol: Chem.Mol + placed: list[Placed] + links: list[Link] + notes: list[dict] = field(default_factory=list) + + def residues(self) -> list[dict]: + return [{"polymer": p.polymer, "number": p.number, "symbol": p.monomer.symbol, "name": p.monomer.name} for p in self.placed] + + +def _resolve(lib: mono.Library, kind: str, unit, pid: str) -> mono.Monomer: + if unit.inline: + try: + return mono.inline(kind, unit.symbol) + except mono.MonomerDataError as exc: + raise HelmError(f"The inline monomer in {pid} cannot be used: {exc}.", unit.position) from None + found = lib.get(kind, unit.symbol) + if found is not None: + return found + if kind == "CHEM": + raise HelmError(f"FormChem has no CHEM monomer named {unit.symbol}; write the linker as inline SMILES with [*:1] and [*:2] points.", unit.position) + elsewhere = [k for k in lib.by_polymer if k != kind and unit.symbol in lib.by_polymer[k]] + hint = f" ({unit.symbol} is a {elsewhere[0]} monomer)" if elsewhere else "" + raise HelmError(f"{unit.symbol} is not a {kind} monomer FormChem knows{hint}.", unit.position) + + +def _combine(mols: list[Chem.Mol]) -> Chem.Mol: + if not mols: + return Chem.Mol() + while len(mols) > 1: + nxt = [Chem.CombineMols(mols[i], mols[i + 1]) for i in range(0, len(mols) - 1, 2)] + if len(mols) % 2: + nxt.append(mols[-1]) + mols = nxt + return mols[0] + + +def _links(helm: Helm, index: dict[tuple[str, int], int], placed: list[Placed]) -> list[Link]: + out: list[Link] = [] + for p in helm.polymers: + prev = None + for n, u in enumerate(p.units): + k = index[(p.id, n + 1)] + if u.branch_of is not None: + out.append(Link(index[(p.id, u.branch_of + 1)], "R3", k, "R1", u.position, "branch")) + continue + if prev is not None: + out.append(Link(prev, "R2", k, "R1", u.position, "backbone")) + prev = k + for c in helm.connections: + a, b = index[(c.source, c.source_unit)], index[(c.target, c.target_unit)] + if a == b: + raise HelmError("A connection joins a monomer to itself.", c.position) + out.append(Link(a, c.source_r, b, c.target_r, c.position, "connection")) + return out + + +def _check(links: list[Link], placed: list[Placed]) -> None: + used: dict[tuple[int, str], Link] = {} + for link in links: + for k, r in ((link.a, link.ra), (link.b, link.rb)): + p = placed[k] + if r not in p.points: + have = ", ".join(sorted(p.points)) or "none" + raise HelmError(f"{p.polymer} monomer {p.number} ({p.monomer.symbol}) has no attachment point {r}; it has {have}.", link.position) + if (k, r) in used: + raise HelmError(f"{r} of {p.polymer} monomer {p.number} ({p.monomer.symbol}) is used twice.", link.position) + used[(k, r)] = link + + +def assemble(helm: Helm, lib: mono.Library | None = None) -> Assembly: + lib = lib or mono.library() + placed: list[Placed] = [] + index: dict[tuple[str, int], int] = {} + mols: list[Chem.Mol] = [] + offset = 0 + for p in helm.polymers: + for n, u in enumerate(p.units): + m = _resolve(lib, p.type, u, p.id) + mol = m.mol() + points = {r: offset + i for r, i in mono.attachment_labels(mol).items()} + index[(p.id, n + 1)] = len(placed) + placed.append(Placed(p.id, n + 1, m, offset, points, u.position)) + mols.append(mol) + offset += mol.GetNumAtoms() + if offset > MAX_ATOMS: + raise HelmError(f"The structure would pass {MAX_ATOMS:,} atoms, which FormChem does not draw.", u.position) + links = _links(helm, index, placed) + _check(links, placed) + rw = Chem.RWMol(_combine(mols)) + paired: dict[int, int] = {} + for j, link in enumerate(links): + paired[placed[link.a].points[link.ra]] = j + 1 + paired[placed[link.b].points[link.rb]] = j + 1 + for p in placed: + for r, idx in p.points.items(): + atom = rw.GetAtomWithIdx(idx) + if idx in paired: + atom.SetAtomMapNum(paired[idx]) + else: + atom.SetAtomMapNum(0) + atom.SetAtomicNum(mono.LEAVING[p.monomer.attachments.get(r, "H")]) + atom.SetNoImplicit(False) + try: + zipped = Chem.molzip(rw.GetMol()) if links else rw.GetMol() + Chem.SanitizeMol(zipped) + mol = Chem.RemoveHs(zipped) + except Exception as exc: + raise HelmError(f"The monomers could not be joined into one valid structure: {exc}", 0) from None + for a in mol.GetAtoms(): + a.SetAtomMapNum(0) + Chem.AssignStereochemistry(mol, cleanIt=True, force=True) + out = Assembly(mol, placed, links, list(helm.notes)) + if len(Chem.GetMolFrags(mol)) > 1: + out.notes.append({"code": "disconnected", "text": "The polymers are not connected to each other, so they are drawn as separate structures."}) + return out diff --git a/backend/app/services/helm/monomers.py b/backend/app/services/helm/monomers.py new file mode 100644 index 00000000..20a044f9 --- /dev/null +++ b/backend/app/services/helm/monomers.py @@ -0,0 +1,162 @@ +import json +from dataclasses import dataclass, field +from functools import lru_cache +from pathlib import Path + +from rdkit import Chem + +DATA = Path(__file__).resolve().parents[2] / "data" / "helm_monomers.json" +POLYMERS = ("PEPTIDE", "RNA", "CHEM") +LEAVING = {"H": 1, "OH": 8} + + +class MonomerDataError(ValueError): + pass + + +@dataclass(frozen=True) +class Monomer: + symbol: str + polymer: str + role: str + name: str + smiles: str + capped: str + attachments: dict[str, str] + natural: str | None = None + source: str = "" + inline: bool = False + key: str = field(default="", compare=False) + flat: str = field(default="", compare=False) + + def mol(self) -> Chem.Mol: + return Chem.Mol(_parsed(self.smiles)) + + @property + def helm(self) -> str: + return self.symbol if len(self.symbol) == 1 else f"[{self.symbol}]" + + def as_dict(self) -> dict: + return {"symbol": self.symbol, "polymer": self.polymer, "role": self.role, "name": self.name, "smiles": self.smiles, + "capped": self.capped, "attachments": dict(self.attachments), "natural": self.natural, "source": self.source} + + +@dataclass +class Library: + version: str + source: str + by_polymer: dict[str, dict[str, Monomer]] + by_capped: dict[str, dict[str, Monomer]] + by_flat: dict[str, dict[str, list[Monomer]]] + + def get(self, polymer: str, symbol: str) -> Monomer | None: + return self.by_polymer.get(polymer, {}).get(symbol) + + def count(self) -> int: + return sum(len(v) for v in self.by_polymer.values()) + + +@lru_cache(maxsize=512) +def _parsed(smiles: str) -> Chem.Mol: + mol = Chem.MolFromSmiles(smiles) + if mol is None: + raise MonomerDataError(f"{smiles} is not a valid SMILES") + return mol + + +def attachment_labels(mol: Chem.Mol) -> dict[str, int]: + out: dict[str, int] = {} + for a in mol.GetAtoms(): + if a.GetAtomicNum() == 0: + n = a.GetAtomMapNum() + if n < 1 or a.GetDegree() != 1: + raise MonomerDataError("every attachment point is a [*:n] with one neighbour") + label = f"R{n}" + if label in out: + raise MonomerDataError(f"{label} appears twice") + out[label] = a.GetIdx() + return out + + +def cap(mol: Chem.Mol, leaving: dict[str, str], keep: set[str] = frozenset()) -> Chem.Mol: + rw = Chem.RWMol(mol) + for a in rw.GetAtoms(): + if a.GetAtomicNum() != 0: + continue + label = f"R{a.GetAtomMapNum()}" + if label in keep: + continue + a.SetAtomicNum(LEAVING[leaving.get(label, "H")]) + a.SetAtomMapNum(0) + a.SetIsotope(0) + a.SetNoImplicit(False) + out = rw.GetMol() + Chem.SanitizeMol(out) + return Chem.RemoveHs(out) + + +def canonical(mol: Chem.Mol, isomeric: bool = True) -> str: + return Chem.MolToSmiles(mol, isomericSmiles=isomeric) + + +def _monomer(row: dict, where: str) -> Monomer: + for k in ("symbol", "polymer", "role", "name", "smiles", "capped", "attachments", "source"): + if not row.get(k): + raise MonomerDataError(f"{where} has no {k}") + if row["polymer"] not in POLYMERS: + raise MonomerDataError(f"{where}: polymer is one of {', '.join(POLYMERS)}") + att = row["attachments"] + if not isinstance(att, dict) or any(v not in LEAVING for v in att.values()): + raise MonomerDataError(f"{where}: each leaving group is one of {', '.join(LEAVING)}") + mol = _parsed(row["smiles"]) + try: + labels = attachment_labels(mol) + except MonomerDataError as exc: + raise MonomerDataError(f"{where}: {exc}") from None + if set(labels) != set(att): + raise MonomerDataError(f"{where}: the SMILES has {sorted(labels)} but attachments name {sorted(att)}") + capped = canonical(cap(mol, att)) + written = canonical(_parsed(row["capped"])) + if capped != written: + raise MonomerDataError(f"{where}: capping the SMILES gives {capped}, not the capped form {written}") + return Monomer(symbol=row["symbol"], polymer=row["polymer"], role=row["role"], name=row["name"], smiles=row["smiles"], + capped=row["capped"], attachments=dict(att), natural=row.get("natural"), source=row["source"], + key=capped, flat=canonical(_parsed(row["capped"]), isomeric=False)) + + +def build(data: dict) -> Library: + by_polymer: dict[str, dict[str, Monomer]] = {p: {} for p in POLYMERS} + by_capped: dict[str, dict[str, Monomer]] = {p: {} for p in POLYMERS} + by_flat: dict[str, dict[str, list[Monomer]]] = {p: {} for p in POLYMERS} + for n, row in enumerate(data.get("monomers") or []): + m = _monomer(row, f"monomer {n + 1} ({row.get('symbol', '?')})") + if m.symbol in by_polymer[m.polymer]: + raise MonomerDataError(f"{m.polymer} {m.symbol} is defined twice") + by_polymer[m.polymer][m.symbol] = m + by_capped[m.polymer].setdefault(m.key, m) + by_flat[m.polymer].setdefault(m.flat, []).append(m) + return Library(version=str(data.get("version") or "0"), source=str(data.get("source") or ""), by_polymer=by_polymer, + by_capped=by_capped, by_flat=by_flat) + + +@lru_cache(maxsize=1) +def library() -> Library: + try: + data = json.loads(DATA.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise MonomerDataError(f"{DATA.name} could not be read: {exc}") from None + return build(data) + + +def inline(polymer: str, smiles: str) -> Monomer: + mol = Chem.MolFromSmiles(smiles) + if mol is None: + raise MonomerDataError("the inline SMILES does not parse") + labels = attachment_labels(mol) + if not labels: + raise MonomerDataError("an inline SMILES monomer needs attachment points written as [*:1], [*:2] and so on") + att = {k: "H" for k in sorted(labels)} + capped = canonical(cap(mol, att)) + return Monomer(symbol=smiles, polymer=polymer, role="inline", name="inline SMILES monomer", smiles=smiles, capped=capped, + attachments=att, source="Written in the HELM text.", inline=True, key=capped, + flat=canonical(Chem.MolFromSmiles(capped), isomeric=False)) diff --git a/backend/app/services/helm/parser.py b/backend/app/services/helm/parser.py new file mode 100644 index 00000000..da003d8b --- /dev/null +++ b/backend/app/services/helm/parser.py @@ -0,0 +1,355 @@ +import re +from dataclasses import dataclass, field + +MAX_TEXT = 100_000 +MAX_MONOMERS = 2000 +MAX_REPEAT = 500 +TYPES = ("PEPTIDE", "RNA", "CHEM", "BLOB") +POLYMER_ID = re.compile(r"(PEPTIDE|RNA|CHEM|BLOB)([1-9][0-9]*)") +ATTACH = re.compile(r"R([1-9][0-9]?)") +VERSION = re.compile(r"V\d+(\.\d+)?", re.IGNORECASE) + + +class HelmError(ValueError): + def __init__(self, text: str, position: int): + super().__init__(text) + self.text = text + self.position = position + + def as_dict(self) -> dict: + return {"code": "helm_syntax", "text": self.text, "position": self.position} + + +@dataclass +class Unit: + symbol: str + position: int + inline: bool = False + branch_of: int | None = None + annotation: str | None = None + + +@dataclass +class Polymer: + id: str + type: str + position: int + units: list[Unit] = field(default_factory=list) + annotation: str | None = None + + +@dataclass +class Connection: + source: str + target: str + source_unit: int + source_r: str + target_unit: int + target_r: str + position: int + + +@dataclass +class Helm: + polymers: list[Polymer] + connections: list[Connection] + annotation: str + version: str + notes: list[dict] = field(default_factory=list) + + def polymer(self, pid: str) -> Polymer | None: + return next((p for p in self.polymers if p.id == pid), None) + + +def _sections(text: str) -> list[tuple[str, int]]: + out, start, depth, quoted = [], 0, 0, False + for i, ch in enumerate(text): + if quoted: + quoted = ch != '"' + continue + if ch == '"': + quoted = True + elif ch in "[{(": + depth += 1 + elif ch in "]})": + depth -= 1 + if depth < 0: + raise HelmError(f"'{ch}' closes nothing.", i) + elif ch == "$" and depth == 0: + out.append((text[start:i], start)) + start = i + 1 + if quoted: + raise HelmError("A quoted annotation is not closed.", len(text)) + if depth: + raise HelmError("A bracket or brace is not closed.", len(text)) + out.append((text[start:], start)) + return out + + +def _split(body: str, base: int, sep: str) -> list[tuple[str, int]]: + out, start, depth, quoted = [], 0, 0, False + for i, ch in enumerate(body): + if quoted: + quoted = ch != '"' + continue + if ch == '"': + quoted = True + elif ch in "[{(": + depth += 1 + elif ch in "]})": + depth -= 1 + elif ch == sep and depth == 0: + out.append((body[start:i], base + start)) + start = i + 1 + out.append((body[start:], base + start)) + return out + + +def _closer(s: str) -> int: + depth, quoted = 0, False + for i, ch in enumerate(s): + if quoted: + quoted = ch != '"' + elif ch == '"': + quoted = True + elif ch in "[{(": + depth += 1 + elif ch in "]})": + depth -= 1 + if depth == 0: + return i if ch == "}" else -1 + return -1 + + +class _Reader: + def __init__(self, text: str, base: int): + self.s = text + self.i = 0 + self.base = base + + def at(self) -> int: + return self.base + self.i + + def peek(self) -> str: + return self.s[self.i] if self.i < len(self.s) else "" + + def done(self) -> bool: + return self.i >= len(self.s) + + def fail(self, text: str, offset: int = 0): + raise HelmError(text, self.at() + offset) + + def symbol(self) -> tuple[str, bool, int]: + pos = self.at() + ch = self.peek() + if ch == "[": + depth, j = 0, self.i + while j < len(self.s): + if self.s[j] == "[": + depth += 1 + elif self.s[j] == "]": + depth -= 1 + if depth == 0: + break + j += 1 + if j >= len(self.s): + self.fail("A [ monomer name is not closed.") + inner = self.s[self.i + 1: j] + if not inner: + self.fail("Empty brackets [] name no monomer.") + self.i = j + 1 + return inner, "*" in inner, pos + if ch.isalpha(): + self.i += 1 + return ch, False, pos + if not ch: + self.fail("A monomer is missing here.") + self.fail(f"'{ch}' cannot start a monomer; write a one-letter code or a [name].") + + def annotation(self) -> str | None: + if self.peek() != '"': + return None + end = self.s.find('"', self.i + 1) + if end < 0: + self.fail("A quoted annotation is not closed.") + text = self.s[self.i + 1: end] + self.i = end + 1 + return text + + def repeat(self) -> int: + if self.peek() != "'": + return 1 + end = self.s.find("'", self.i + 1) + if end < 0: + self.fail("A repeat count 'n' is not closed.") + raw = self.s[self.i + 1: end] + if not raw.isdigit(): + self.fail("Only a whole repeat count such as '3' is read; ranges such as '2-5' describe a mixture, not one molecule.", 1) + n = int(raw) + if not 1 <= n <= MAX_REPEAT: + self.fail(f"A repeat count is from 1 to {MAX_REPEAT}.", 1) + self.i = end + 1 + return n + + +def _units(kind: str, body: str, base: int) -> list[Unit]: + if not body.strip(): + raise HelmError("The polymer has no monomers between its braces.", base) + out: list[Unit] = [] + for part, at in _split(body, base, "."): + if not part: + raise HelmError("Two dots, or a dot at an end, leave a monomer out.", at) + r = _Reader(part, at) + group: list[Unit] = [] + while not r.done(): + if r.peek() == "(": + if kind != "RNA": + r.fail("Parentheses in a PEPTIDE or CHEM list describe a mixture of monomers, which FormChem does not read.") + if not group or group[-1].branch_of is not None: + r.fail("A branch in parentheses must follow a backbone monomer.") + r.i += 1 + sym, inline, pos = r.symbol() + if r.peek() in (",", "+"): + r.fail("A list of alternative monomers describes a mixture, which FormChem does not read.") + if r.peek() != ")": + r.fail("A branch takes one monomer and closes with ).") + r.i += 1 + parent = next(k for k in range(len(group) - 1, -1, -1) if group[k].branch_of is None) + group.append(Unit(sym, pos, inline, branch_of=parent)) + continue + sym, inline, pos = r.symbol() + group.append(Unit(sym, pos, inline)) + note = r.annotation() + if note is not None: + group[-1].annotation = note + if r.peek() == "'": + n = r.repeat() + size = len(group) + group = [Unit(u.symbol, u.position, u.inline, None if u.branch_of is None else u.branch_of + k * size, u.annotation) + for k in range(n) for u in group] + if not r.done(): + r.fail("A repeat count ends its unit; put a dot after it.") + elif kind != "RNA" and not r.done(): + r.fail("Separate monomers with dots.") + offset = len(out) + for u in group: + if u.branch_of is not None: + u.branch_of += offset + out.extend(group) + if len(out) > MAX_MONOMERS: + raise HelmError(f"FormChem reads up to {MAX_MONOMERS} monomers.", at) + return out + + +def _polymers(section: str, base: int) -> list[Polymer]: + if not section.strip(): + raise HelmError("There is no polymer: write one such as PEPTIDE1{A.G.C}.", base) + out: list[Polymer] = [] + seen: set[str] = set() + for part, at in _split(section, base, "|"): + m = POLYMER_ID.match(part) + if not m: + raise HelmError("A polymer starts with PEPTIDE, RNA, CHEM or BLOB and a number, such as PEPTIDE1.", at) + pid, kind = m.group(0), m.group(1) + if kind == "BLOB": + raise HelmError("BLOB polymers have no defined structure, so FormChem cannot draw them.", at) + if pid in seen: + raise HelmError(f"{pid} is defined twice.", at) + seen.add(pid) + rest = part[m.end():] + if not rest.startswith("{"): + raise HelmError(f"{pid} needs its monomers in braces, such as {pid}{{A.G}}.", at + m.end()) + close = _closer(rest) + if close < 0: + raise HelmError(f"The braces of {pid} are not closed.", at + len(part)) + body = rest[1:close] + tail = rest[close + 1:] + poly = Polymer(pid, kind, at, _units(kind, body, at + m.end() + 1)) + if tail: + r = _Reader(tail, at + m.end() + close + 1) + poly.annotation = r.annotation() + if not r.done(): + r.fail("Separate polymers with |.") + if kind == "CHEM" and len(poly.units) != 1: + raise HelmError(f"{pid} is a CHEM polymer and holds exactly one monomer.", at) + out.append(poly) + return out + + +def _end(raw: str, at: int) -> tuple[int, str]: + m = re.fullmatch(r"([1-9][0-9]*):(R[1-9][0-9]?|pair|\?)", raw) + if not m: + raise HelmError("A connection end is a monomer number and an attachment point, such as 3:R3.", at) + if m.group(2) == "pair": + raise HelmError("Hydrogen-bond pairs are not covalent bonds and are not drawn.", at) + if m.group(2) == "?": + raise HelmError("An unknown attachment point (?) cannot be drawn; name it, such as R3.", at) + return int(m.group(1)), m.group(2) + + +def _connections(section: str, base: int) -> list[Connection]: + if not section.strip(): + return [] + out: list[Connection] = [] + for part, at in _split(section, base, "|"): + body = part + q = part.find('"') + if q >= 0: + body = part[:q] + fields = body.split(",") + if len(fields) != 3: + raise HelmError("A connection reads source,target,n:Rx-m:Ry, such as PEPTIDE1,PEPTIDE1,1:R3-6:R3.", at) + src, dst, link = fields + for name, off in ((src, 0), (dst, len(src) + 1)): + if not POLYMER_ID.fullmatch(name): + raise HelmError(f"'{name}' is not a polymer id such as PEPTIDE1.", at + off) + ends = link.split("-") + start = at + len(src) + len(dst) + 2 + if len(ends) != 2: + raise HelmError("A connection joins two ends with one dash, such as 1:R3-6:R3.", start) + u1, r1 = _end(ends[0], start) + u2, r2 = _end(ends[1], start + len(ends[0]) + 1) + out.append(Connection(src, dst, u1, r1, u2, r2, at)) + return out + + +def parse(text: str) -> Helm: + if not isinstance(text, str) or not text.strip(): + raise HelmError("Type HELM text, such as PEPTIDE1{A.G.C}$$$$V2.0.", 0) + if len(text) > MAX_TEXT: + raise HelmError(f"HELM text is limited to {MAX_TEXT:,} characters.", MAX_TEXT) + lead = len(text) - len(text.lstrip()) + raw = text.strip() + parts = _sections(raw) + if len(parts) == 1: + parts += [("", len(raw))] * 3 + if len(parts) < 4: + raise HelmError("HELM has four sections separated by $: polymers, connections, groups and annotations (then an optional version).", lead + len(raw)) + if len(parts) > 5: + raise HelmError("There are more than five $-separated sections.", lead + parts[5][1] - 1) + shifted = [(s, p + lead) for s, p in parts] + polymers = _polymers(*shifted[0]) + connections = _connections(*shifted[1]) + groups, gat = shifted[2] + if groups.strip(): + raise HelmError("Polymer groups describe mixtures or ambiguous structures; FormChem reads only an empty group section.", gat) + annotation = shifted[3][0] + version = "" + if len(shifted) == 5: + version, vat = shifted[4] + if version and not VERSION.fullmatch(version.strip()): + raise HelmError("The last section is a version such as V2.0.", vat) + if version and not version.strip().upper().startswith("V2"): + raise HelmError("Only HELM version 2 (V2.0) is read.", vat) + helm = Helm(polymers, connections, annotation, version.strip()) + ids = {p.id: p for p in polymers} + for c in connections: + for pid, n in ((c.source, c.source_unit), (c.target, c.target_unit)): + p = ids.get(pid) + if p is None: + raise HelmError(f"The connection names {pid}, which is not a polymer above.", c.position) + if n > len(p.units): + raise HelmError(f"{pid} has {len(p.units)} monomers, so it has no monomer {n}.", c.position) + if any(u.annotation for p in polymers for u in p.units) or any(p.annotation for p in polymers) or annotation.strip(): + helm.notes.append({"code": "annotations", "text": "Annotations were read and kept as text; they do not change the structure."}) + return helm diff --git a/backend/app/services/helm/writer.py b/backend/app/services/helm/writer.py new file mode 100644 index 00000000..f9e6720b --- /dev/null +++ b/backend/app/services/helm/writer.py @@ -0,0 +1,308 @@ +from dataclasses import dataclass, field +from functools import lru_cache + +from rdkit import Chem +from rdkit.Chem.rdMolDescriptors import CalcMolFormula + +from app.services.helm import monomers as mono + +ORIG = "helm_orig" +LABELS = "helm_r" +MAX_ATOMS = 5000 +MAX_MATCHES = 2000 +CUTS = ( + ("peptide", "[NX3][CX4][CX3](=[OX1])-[NX3]", 2, 4, "OH", "H"), + ("acetyl", "[CH3][CX3](=[OX1])-[NX3]", 1, 3, "OH", "H"), + ("disulfide", "[CX4][SX2]-[SX2][CX4]", 1, 2, "H", "H"), + ("isopeptide", "[CH2][CX3](=[OX1])-[NX3H1][CH2][CH2]", 1, 3, "OH", "H"), + ("phosphate", "[CX4][OX2]-[PX4](=[OX1])", 1, 2, "H", "OH"), + ("glycosidic", "[OX2;r5][CX4;r5]-[#7;a]", 1, 2, "OH", "H"), +) +PATTERNS = {name: Chem.MolFromSmarts(s) for name, s, *_ in CUTS} +PARTNER = {"R2": "R1", "R1": "R2", "R3": "R1"} + + +class WriteError(ValueError): + pass + + +@dataclass +class Piece: + mol: Chem.Mol + atoms: list[int] + monomer: mono.Monomer | None = None + guessed: bool = False + labels: dict[int, set[str]] = field(default_factory=dict) + + +@dataclass +class Cut: + a: int + b: int + kind: str + piece_a: int = -1 + piece_b: int = -1 + label_a: str | None = None + label_b: str | None = None + + +@lru_cache(maxsize=256) +def _anchored(smiles: str, leaving: tuple[tuple[str, str], ...]) -> Chem.Mol: + rw = Chem.RWMol(Chem.MolFromSmiles(smiles)) + groups = dict(leaving) + for a in rw.GetAtoms(): + if a.GetAtomicNum() != 0: + continue + label = f"R{a.GetAtomMapNum()}" + n = a.GetNeighbors()[0] + have = n.GetProp(LABELS).split(",") if n.HasProp(LABELS) else [] + n.SetProp(LABELS, ",".join(have + [label])) + a.SetAtomicNum(mono.LEAVING[groups.get(label, "H")]) + a.SetAtomMapNum(0) + a.SetNoImplicit(False) + out = rw.GetMol() + Chem.SanitizeMol(out) + return Chem.RemoveHs(out) + + +def _anchors(m: mono.Monomer) -> Chem.Mol: + return _anchored(m.smiles, tuple(sorted(m.attachments.items()))) + + +def _cuts(mol: Chem.Mol) -> list[Cut]: + out: list[Cut] = [] + seen: set[int] = set() + for name, _s, i, j, _la, _lb in CUTS: + for match in mol.GetSubstructMatches(PATTERNS[name], uniquify=False, maxMatches=100_000): + a, b = match[i], match[j] + bond = mol.GetBondBetweenAtoms(a, b) + if bond is None or bond.GetIdx() in seen: + continue + seen.add(bond.GetIdx()) + out.append(Cut(a, b, name)) + return out + + +def _pieces(mol: Chem.Mol, cuts: list[Cut]) -> list[Piece]: + work = Chem.Mol(mol) + for a in work.GetAtoms(): + a.SetIntProp(ORIG, a.GetIdx()) + if cuts: + bonds = [work.GetBondBetweenAtoms(c.a, c.b).GetIdx() for c in cuts] + work = Chem.FragmentOnBonds(work, bonds, addDummies=True) + rw = Chem.RWMol(work) + leave = {name: (la, lb) for name, _s, _i, _j, la, lb in CUTS} + group_of: dict[int, str] = {} + for c in cuts: + group_of[c.a] = leave[c.kind][0] + group_of[c.b] = leave[c.kind][1] + for d in rw.GetAtoms(): + if d.GetAtomicNum() != 0 or d.HasProp(ORIG): + continue + anchor = d.GetNeighbors()[0] + d.SetAtomicNum(mono.LEAVING[group_of.get(anchor.GetIntProp(ORIG), "H")]) + d.SetIsotope(0) + d.SetNoImplicit(False) + frag = rw.GetMol() + Chem.SanitizeMol(frag) + out: list[Piece] = [] + for part in Chem.GetMolFrags(frag, asMols=True, sanitizeFrags=True): + part = Chem.RemoveHs(part) + Chem.AssignStereochemistry(part, cleanIt=True, force=True) + atoms = [a.GetIntProp(ORIG) for a in part.GetAtoms() if a.HasProp(ORIG)] + out.append(Piece(part, atoms)) + return out + + +def _match(piece: Piece, lib: mono.Library) -> None: + key = mono.canonical(piece.mol) + for kind in ("PEPTIDE", "RNA"): + m = lib.by_capped[kind].get(key) + if m is not None: + piece.monomer = m + return + chiral = Chem.FindMolChiralCenters(piece.mol, includeUnassigned=True, useLegacyImplementation=False) + if any(label != "?" for _i, label in chiral): + return + flat = mono.canonical(piece.mol, isomeric=False) + for kind in ("PEPTIDE", "RNA"): + found = lib.by_flat[kind].get(flat) + if found: + piece.monomer = found[0] + piece.guessed = len(chiral) > 0 + return + + +def _labels(piece: Piece) -> dict[int, set[str]]: + ref = _anchors(piece.monomer) + want = {a.GetIntProp(ORIG) for a in piece.mol.GetAtoms() if a.HasProp(ORIG)} + best: dict[int, set[str]] = {} + for match in piece.mol.GetSubstructMatches(ref, useChirality=not piece.guessed, uniquify=False, maxMatches=MAX_MATCHES): + found: dict[int, set[str]] = {} + for ref_idx, idx in enumerate(match): + atom = ref.GetAtomWithIdx(ref_idx) + if atom.HasProp(LABELS): + orig = piece.mol.GetAtomWithIdx(idx).GetIntProp(ORIG) + if orig in want: + found.setdefault(orig, set()).update(atom.GetProp(LABELS).split(",")) + if not best or len(found) > len(best): + best = found + return best + + +def pieces_of(mol: Chem.Mol, lib: mono.Library | None = None) -> tuple[list[Piece], list[Cut], list[dict]]: + lib = lib or mono.library() + notes: list[dict] = [] + cuts = _cuts(mol) + pieces = _pieces(mol, cuts) + owner = {a: k for k, p in enumerate(pieces) for a in p.atoms} + for c in cuts: + c.piece_a, c.piece_b = owner.get(c.a, -1), owner.get(c.b, -1) + for p in pieces: + _match(p, lib) + if p.monomer is not None: + p.labels = _labels(p) + return pieces, cuts, notes + + +def describe(piece: Piece) -> str: + return f"{CalcMolFormula(piece.mol)} ({piece.mol.GetNumAtoms()} heavy atoms)" + + +def _assign(pieces: list[Piece], cuts: list[Cut]) -> None: + used: dict[int, set[str]] = {k: set() for k in range(len(pieces))} + + def options(k: int, atom: int) -> list[str]: + return sorted(pieces[k].labels.get(atom, set()) - used[k]) + + pending = list(cuts) + while pending: + progress = False + for c in list(pending): + oa, ob = options(c.piece_a, c.a), options(c.piece_b, c.b) + if not oa or not ob: + raise WriteError(f"The {c.kind} bond between atoms {c.a + 1} and {c.b + 1} does not sit on an attachment point of " + f"{pieces[c.piece_a].monomer.symbol} and {pieces[c.piece_b].monomer.symbol}.") + if len(oa) == 1 and len(ob) > 1 and PARTNER.get(oa[0]) in ob: + ob = [PARTNER[oa[0]]] + elif len(ob) == 1 and len(oa) > 1 and PARTNER.get(ob[0]) in oa: + oa = [PARTNER[ob[0]]] + if len(oa) == 1 and len(ob) == 1: + c.label_a, c.label_b = oa[0], ob[0] + used[c.piece_a].add(oa[0]) + used[c.piece_b].add(ob[0]) + pending.remove(c) + progress = True + if not progress: + c = pending.pop(0) + oa, ob = options(c.piece_a, c.a), options(c.piece_b, c.b) + c.label_a, c.label_b = oa[0], ob[0] + used[c.piece_a].add(oa[0]) + used[c.piece_b].add(ob[0]) + + +def _branch(p: Piece) -> bool: + return p.monomer.role == "base" + + +def _topology(pieces: list[Piece], cuts: list[Cut]) -> tuple[list[tuple[str, list[int]]], dict[int, int], list[Cut]]: + nxt: dict[int, tuple[int, Cut]] = {} + prv: dict[int, tuple[int, Cut]] = {} + branch_of: dict[int, int] = {} + rest: list[Cut] = [] + for c in cuts: + ends = [(c.piece_a, c.label_a), (c.piece_b, c.label_b)] + ends.sort(key=lambda e: e[1] != "R2" and e[1] != "R3") + (x, rx), (y, ry) = ends + px, py = pieces[x], pieces[y] + same = px.monomer.polymer == py.monomer.polymer + if same and rx == "R2" and ry == "R1" and not _branch(px) and not _branch(py) and x not in nxt and y not in prv: + nxt[x], prv[y] = (y, c), (x, c) + elif same and rx == "R3" and ry == "R1" and _branch(py) and not _branch(px) and y not in branch_of: + branch_of[y] = x + else: + rest.append(c) + backbone = [k for k, p in enumerate(pieces) if not _branch(p)] + lone = [k for k, p in enumerate(pieces) if _branch(p) and k not in branch_of] + if lone: + raise WriteError(f"The base {pieces[lone[0]].monomer.name} is not attached to a sugar, so it is not part of a nucleic acid chain.") + first = {k: min(pieces[k].atoms) if pieces[k].atoms else 0 for k in range(len(pieces))} + chains: list[tuple[str, list[int]]] = [] + seen: set[int] = set() + starts = sorted((k for k in backbone if k not in prv), key=first.get) + loops = sorted((k for k in backbone if k in prv), key=first.get) + for k in starts + loops: + if k in seen: + continue + chain = [k] + seen.add(k) + while chain[-1] in nxt: + y, c = nxt[chain[-1]] + if y in seen: + rest.append(c) + break + chain.append(y) + seen.add(y) + chains.append((pieces[k].monomer.polymer, chain)) + return chains, branch_of, rest + + +def write(mol: Chem.Mol, lib: mono.Library | None = None) -> tuple[str, list[dict], list[dict]]: + if mol.GetNumAtoms() == 0: + raise WriteError("There is no structure to write.") + if mol.GetNumAtoms() > MAX_ATOMS: + raise WriteError(f"Structures over {MAX_ATOMS:,} heavy atoms are not written as HELM.") + if any(a.GetAtomicNum() == 0 for a in mol.GetAtoms()): + raise WriteError("The structure holds labels, R-groups or any-atoms, which have no HELM monomer.") + pieces, cuts, notes = pieces_of(mol, lib) + unknown = [p for p in pieces if p.monomer is None] + if unknown: + size = len(unknown) + what = "; ".join(describe(p) for p in unknown[:3]) + lead = "is" if size == 1 else "are" + raise WriteError(f"{size} part{'' if size == 1 else 's'} of the structure {lead} not a peptide residue, cap, sugar, phosphate or base in FormChem's monomer data: {what}.") + _assign(pieces, cuts) + chains, branch_of, rest = _topology(pieces, cuts) + counters: dict[str, int] = {} + where: dict[int, tuple[str, int]] = {} + texts: list[str] = [] + branches: dict[int, int] = {x: y for y, x in branch_of.items()} + for kind, chain in chains: + counters[kind] = counters.get(kind, 0) + 1 + pid = f"{kind}{counters[kind]}" + n = 0 + parts: list[str] = [] + for k in chain: + n += 1 + where[k] = (pid, n) + item = pieces[k].monomer.helm + if k in branches: + n += 1 + where[branches[k]] = (pid, n) + item += f"({pieces[branches[k]].monomer.helm})" + parts.append(item) + if kind == "RNA": + units, cur = [], "" + for k, item in zip(chain, parts): + cur += item + if pieces[k].monomer.role == "phosphate": + units.append(cur) + cur = "" + if cur: + units.append(cur) + parts = units + texts.append(f"{pid}{{{'.'.join(parts)}}}") + links = [] + for c in rest: + (pa, na), (pb, nb) = where[c.piece_a], where[c.piece_b] + ends = sorted([(pa, na, c.label_a), (pb, nb, c.label_b)], key=lambda e: (e[0], e[1])) + links.append(ends) + links.sort() + conn = "|".join(f"{a[0]},{b[0]},{a[1]}:{a[2]}-{b[1]}:{b[2]}" for a, b in links) + guessed = [where[k] for k, p in enumerate(pieces) if p.guessed] + if guessed: + shown = ", ".join(f"{pid} {n}" for pid, n in guessed[:6]) + notes.append({"code": "stereo_assumed", "text": f"The drawing shows no stereochemistry at {len(guessed)} residue{'' if len(guessed) == 1 else 's'} ({shown}); they were written as the natural L-amino acids or D-sugars."}) + residues = [{"polymer": where[k][0], "number": where[k][1], "symbol": p.monomer.symbol, "name": p.monomer.name, "atoms": len(p.atoms)} + for k, p in sorted(enumerate(pieces), key=lambda kp: where[kp[0]])] + return f"{'|'.join(texts)}${conn}$$$V2.0", notes, residues diff --git a/backend/app/services/library.py b/backend/app/services/library.py index cb22552f..1937cadd 100644 --- a/backend/app/services/library.py +++ b/backend/app/services/library.py @@ -125,6 +125,37 @@ def remember(path: str | Path, name: str | None = None) -> dict: return _recent_item(entry) or entry +def databases() -> list[dict]: + with _LOCK: + stored = _read().get("databases") + out = [] + for raw in stored if isinstance(stored, list) else []: + if not isinstance(raw, dict) or not isinstance(raw.get("path"), str) or not raw["path"]: + continue + p = Path(raw["path"]).expanduser() + out.append({"path": str(p), "name": str(raw.get("name") or p.stem), "opened": _number(raw.get("opened")), + "count": int(raw["count"]) if isinstance(raw.get("count"), int) else None, "exists": p.is_file()}) + return out + + +def remember_database(path: str | Path, name: str, count: int | None = None, opened: bool = True) -> None: + p = str(Path(path).expanduser().resolve()) + with _LOCK: + data = _read() + stored = data.get("databases") if isinstance(data.get("databases"), list) else [] + old = next((raw for raw in stored if isinstance(raw, dict) and raw.get("path") == p), {}) + entry = {"id": item_id(f"databases:{p}"), "path": p, "name": name or Path(p).stem, + "opened": time.time() if opened or not isinstance(old.get("opened"), (int, float)) else old["opened"], + "count": count if count is not None else old.get("count")} + if old and not opened: + data["databases"] = [entry if raw is old else raw for raw in stored] + else: + rest = [raw for raw in stored if not (isinstance(raw, dict) and raw.get("path") == p)] + data["databases"] = [entry, *rest][:RECENT_CAP] + data["updated"] = time.time() + _write(data) + + def forget(ids: list[str] | None = None, paths: list[str] | None = None, everything: bool = False) -> dict: drop_ids = {str(x) for x in ids or []} drop_ids |= {item_id(str(Path(p).expanduser())) for p in paths or [] if isinstance(p, str) and p} diff --git a/backend/app/services/live_structures.py b/backend/app/services/live_structures.py new file mode 100644 index 00000000..643690be --- /dev/null +++ b/backend/app/services/live_structures.py @@ -0,0 +1,600 @@ +import base64 +import copy +import json +import re +import secrets +import string +import struct +import threading +import zlib +from pathlib import Path + +from app.core import config, files +from app.services import embedded_source, model + +LIBRARY = "Library" +ITEMS = "items" +INDEX = "library.json" +FORMAT = "formai-structure-library" +OBJECT_FORMAT = "formai-structure" +FORMAT_VERSION = 1 +KINDS = ("favourite", "recent", "template", "live") +RECENT_CAP = 50 +PNG_WIDTH = 512 +ID_PATTERN = re.compile(r"s[a-z0-9]{10}") +_ALPHABET = string.ascii_lowercase + string.digits +_LOCK = threading.RLock() + + +class LibraryError(ValueError): + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + + +def folder() -> Path: + return config.data_dir() / LIBRARY + + +def index_path() -> Path: + return folder() / INDEX + + +def item_path(rel: str) -> Path: + return folder() / rel + + +def _empty() -> dict: + return {"format": FORMAT, "format_version": FORMAT_VERSION, "updated": model.now_iso(), "items": []} + + +def _valid_item(raw: object) -> bool: + return isinstance(raw, dict) and isinstance(raw.get("id"), str) and bool(ID_PATTERN.fullmatch(raw["id"])) + + +def read_index() -> dict: + try: + found = json.loads(index_path().read_text(encoding="utf-8")) + except (OSError, ValueError): + return _empty() + if not isinstance(found, dict) or found.get("format") != FORMAT: + return _empty() + found["items"] = [it for it in found.get("items") or [] if _valid_item(it)] if isinstance(found.get("items"), list) else [] + return found + + +def write_file(rel: str, data: bytes) -> None: + files.write_atomic(item_path(rel), data) + + +def write_index(index: dict) -> None: + index["format"] = FORMAT + index.setdefault("format_version", FORMAT_VERSION) + index["updated"] = model.now_iso() + write_file(INDEX, (json.dumps(index, indent=2, ensure_ascii=False) + "\n").encode("utf-8")) + + +def kinds_of(item: dict) -> list[str]: + raw = item.get("kinds") + return [k for k in raw if k in KINDS] if isinstance(raw, list) else [] + + +def clean_kinds(raw: object) -> list[str]: + if not isinstance(raw, list) or not all(isinstance(k, str) for k in raw): + raise LibraryError(f"kinds must be a list of {', '.join(KINDS)}.", 422) + unknown = [k for k in raw if k not in KINDS] + if unknown: + raise LibraryError(f"{unknown[0]} is not a library kind; use {', '.join(KINDS)}.", 422) + return [k for k in KINDS if k in raw] + + +def present(item: dict) -> bool: + rel = item.get("svg") + return isinstance(rel, str) and item_path(rel).is_file() + + +def listing(kind: str | None = None) -> dict: + if kind is not None and kind not in KINDS: + raise LibraryError(f"{kind} is not a library kind; use {', '.join(KINDS)}.", 422) + with _LOCK: + index = read_index() + out = copy.deepcopy(index) + out["items"] = [it for it in index["items"] if present(it) and (kind is None or kind in kinds_of(it))] + return out + + +def find(index: dict, item_id: str) -> dict | None: + return next((it for it in index["items"] if it.get("id") == item_id), None) + + +def get_item(item_id: str) -> dict: + with _LOCK: + found = find(read_index(), item_id) + if found is None or not present(found): + raise LibraryError(f"The structure library has no item {item_id}.", 404) + return found + + +def new_id(index: dict) -> str: + taken = {it["id"] for it in index["items"]} + while True: + candidate = "s" + "".join(secrets.choice(_ALPHABET) for _ in range(10)) + if candidate not in taken and not any((folder() / ITEMS).glob(f"{candidate}.*")): + return candidate + + +def drop_files(item: dict) -> None: + for key in ("svg", "png", "mol"): + rel = item.get(key) + if isinstance(rel, str) and rel.startswith(f"{ITEMS}/"): + files.remove_quietly(item_path(rel)) + + +def _used(item: dict) -> str: + stamp = item.get("used") or item.get("modified") or item.get("created") + return stamp if isinstance(stamp, str) else "" + + +def source_document(raw: object) -> dict: + if isinstance(raw, str): + raw = embedded_source.read_text(raw.encode("utf-8")) + if not isinstance(raw, dict) or raw.get("format") != "formchem": + raise LibraryError("source must be a FormChem document (document.json).", 422) + doc = copy.deepcopy(raw) + doc.pop("derived", None) + doc.pop("media", None) + doc["objects"] = {k: o for k, o in (doc.get("objects") or {}).items() if not (isinstance(o, dict) and o.get("kind") == "image")} + for page in doc.get("pages") or []: + if isinstance(page, dict) and isinstance(page.get("order"), list): + page["order"] = [i for i in page["order"] if i in doc["objects"]] + errors = model.validate(doc) + if errors: + raise LibraryError(f"The drawing is not valid: {errors[0]}", 422) + return doc + + +def _steps(doc: dict) -> list[dict]: + page = (doc.get("pages") or [{}])[0] + return [s for r in page.get("reactions") or [] if isinstance(r, dict) for s in r.get("steps") or [] if isinstance(s, dict)] + + +def _text_of(doc: dict, fmt: str) -> str: + from app.services.chem import writers + try: + return writers.export_document(doc, fmt).text or "" + except writers.ExportError: + return "" + + +def describe(doc: dict) -> dict: + from rdkit import Chem, rdBase + from app.services.chem import ids, mass, perceive + method = f"FormChem perceive and mass.average_mass with RDKit {rdBase.rdkitVersion}" + if _steps(doc): + rxn = _text_of(doc, "rxn") + if rxn: + return {"kind": "reaction", "smiles": _text_of(doc, "rsmiles").strip(), "inchikey": "", "formula": "", "mw": None, "molfile": rxn, "method": method} + page = (doc.get("pages") or [{}])[0] + objects = doc.get("objects") or {} + expansions = doc.get("expansions") or {} + mol = None + stack = list(page.get("order") or []) + while stack: + obj = objects.get(stack.pop(0)) or {} + if obj.get("kind") == "group": + stack.extend(obj.get("children") or []) + elif obj.get("kind") == "fragment" and obj.get("atoms"): + try: + part = perceive.prepare(obj, expansions).mol + except Exception: + continue + mol = Chem.Mol(part) if mol is None else Chem.CombineMols(mol, part) + if mol is None: + raise LibraryError("There is no structure to keep in the library: draw or select a structure first.", 422) + clean = ids.identifier_mol(mol) + _, key, _ = ids.inchi(clean) + weight = mass.average_mass(clean) + return {"kind": "structure", "smiles": ids.smiles(clean), "inchikey": key, "formula": ids.formula(clean), + "mw": round(weight, 3) if weight else None, "molfile": _text_of(doc, "molfile"), "method": method} + + +def source_svg(svg: str, doc: dict) -> str: + if embedded_source.from_svg(svg.encode("utf-8")) is not None: + return svg + payload = base64.b64encode(json.dumps(doc, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).decode("ascii") + block = (f'{payload}') + head = re.search(r"]*>", svg) + if head is None: + raise LibraryError("The picture is not an SVG.", 422) + return svg[:head.end()] + block + svg[head.end():] + + +def source_png(png: bytes, doc: dict) -> bytes: + if not png.startswith(embedded_source.PNG_SIGNATURE) or embedded_source.from_png(png) is not None: + return png + text = json.dumps(doc, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + body = b"iTXt" + embedded_source.PNG_KEYWORD + b"\0\0\0\0\0" + text + chunk = struct.pack(">I", len(body) - 4) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF) + end = png.rfind(b"IEND") - 4 + return png[:end] + chunk + png[end:] + + +def svg_size(svg: str) -> tuple[float, float]: + head = re.search(r"]*>", svg) + found = {} + for key in ("width", "height"): + m = re.search(rf'\b{key}=["\']([\d.]+)(pt|px)?["\']', head.group(0)) if head else None + if m: + found[key] = float(m.group(1)) * (0.75 if m.group(2) != "pt" else 1.0) + return round(found.get("width", 0.0), 1), round(found.get("height", 0.0), 1) + + +def engine_pictures(doc: dict, chem: dict) -> tuple[str, bytes | None]: + from rdkit import Chem + from rdkit.Chem import rdChemReactions + from app.services.chem import depict + if chem["kind"] == "reaction": + item = rdChemReactions.ReactionFromRxnBlock(chem["molfile"]) + else: + item = Chem.MolFromMolBlock(chem["molfile"], sanitize=False) if chem["molfile"] else Chem.MolFromSmiles(chem["smiles"]) + if item is not None: + item.UpdatePropertyCache(strict=False) + if item is None: + raise LibraryError("The engine could not draw this structure; save it from the FormChem window instead.", 422) + svg = source_svg(depict.svg(item, transparent=True), doc) + w, h = svg_size(svg) + png = None + try: + png = source_png(depict.png(item, (PNG_WIDTH, max(16, round(PNG_WIDTH * h / w))) if w and h else (-1, -1), transparent=True), doc) + except Exception: + png = None + return svg, png + + +def png_bytes(raw: object) -> bytes | None: + if raw is None or raw == "": + return None + try: + data = base64.b64decode(str(raw), validate=True) + except (ValueError, TypeError): + raise LibraryError("png must be base64 PNG bytes.", 422) from None + if not data.startswith(embedded_source.PNG_SIGNATURE): + raise LibraryError("png must be base64 PNG bytes.", 422) + return data + + +def _number(value: object) -> float | None: + return round(float(value), 1) if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0 else None + + +def store_files(item_id: str, doc: dict, chem: dict, svg: str | None, png: bytes | None, width: object = None, height: object = None) -> dict: + if isinstance(svg, str) and svg.strip(): + svg = source_svg(svg, doc) + png = source_png(png, doc) if png else None + else: + svg, png = engine_pictures(doc, chem) + width = height = None + w, h = svg_size(svg) + out = {"svg": f"{ITEMS}/{item_id}.svg", "width": _number(width) or w, "height": _number(height) or h} + if chem.get("molfile"): + out["mol"] = f"{ITEMS}/{item_id}.{'rxn' if chem['kind'] == 'reaction' else 'mol'}" + write_file(out["mol"], chem["molfile"].encode("utf-8")) + if png: + out["png"] = f"{ITEMS}/{item_id}.png" + write_file(out["png"], png) + write_file(out["svg"], svg.encode("utf-8")) + return out + + +def _title(doc: dict, chem: dict) -> str: + objects = doc.get("objects") or {} + for oid in ((doc.get("pages") or [{}])[0].get("order") or []): + name = (objects.get(oid) or {}).get("name") + if isinstance(name, str) and name.strip(): + return name.strip() + embedded = (doc.get("meta") or {}).get("embedded") if isinstance(doc.get("meta"), dict) else None + title = "" if isinstance(embedded, dict) and embedded.get("scope") == "selection" else str(doc.get("title") or "").strip() + return title if title and title != "Untitled" else chem.get("formula") or chem.get("smiles") or "Structure" + + +def chem_fields(chem: dict) -> dict: + return {k: chem[k] for k in ("kind", "smiles", "inchikey", "formula", "mw", "method")} + + +def add(source: object, name: str | None = None, kinds: object = ("favourite",), svg: str | None = None, png: object = None, + width: object = None, height: object = None, tags: object = None) -> dict: + doc = source_document(source) + wanted = clean_kinds(list(kinds) if isinstance(kinds, (list, tuple)) else kinds) + if not wanted: + raise LibraryError("Give at least one kind for the item.", 422) + picture = png_bytes(png) + chem = describe(doc) + now = model.now_iso() + with _LOCK: + index = read_index() + same = None + if "live" not in wanted and chem["smiles"]: + same = next((it for it in index["items"] if present(it) and "live" not in kinds_of(it) and it.get("kind") == chem["kind"] + and it.get("smiles") == chem["smiles"]), None) + if same is not None: + same["kinds"] = [k for k in KINDS if k in kinds_of(same) or k in wanted] + same["used"] = now + if isinstance(name, str) and name.strip(): + same["name"] = name.strip() + item = same + else: + item_id = new_id(index) + item = {"id": item_id, "name": name.strip() if isinstance(name, str) and name.strip() else _title(doc, chem), "kinds": wanted, + **chem_fields(chem), "rev": 1, **store_files(item_id, doc, chem, svg, picture, width, height), + "created": now, "modified": now, "used": now, + "tags": [str(t) for t in tags if isinstance(t, str)] if isinstance(tags, list) else []} + index["items"].insert(0, item) + gone = prune(index) + write_index(index) + for old in gone: + drop_files(old) + return copy.deepcopy(item) + + +def update(item_id: str, name: object = None, kinds: object = None, tags: object = None, used: bool = False) -> dict: + with _LOCK: + index = read_index() + item = find(index, item_id) + if item is None: + raise LibraryError(f"The structure library has no item {item_id}.", 404) + if name is not None: + if not isinstance(name, str) or not name.strip(): + raise LibraryError("name must be some text.", 422) + item["name"] = name.strip()[:200] + if kinds is not None: + item["kinds"] = clean_kinds(kinds) + if tags is not None: + if not isinstance(tags, list): + raise LibraryError("tags must be a list of text.", 422) + item["tags"] = [str(t).strip() for t in tags if isinstance(t, str) and t.strip()] + if used: + item["kinds"] = [k for k in KINDS if k in kinds_of(item) or k == "recent"] + item["used"] = model.now_iso() + gone = prune(index) + write_index(index) + for old in gone: + drop_files(old) + if any(old.get("id") == item_id for old in gone): + return {"deleted": item_id, "id": item_id, "kinds": []} + return copy.deepcopy(item) + + +def delete(item_id: str) -> dict: + with _LOCK: + index = read_index() + item = find(index, item_id) + if item is None: + raise LibraryError(f"The structure library has no item {item_id}.", 404) + index["items"] = [it for it in index["items"] if it is not item] + write_index(index) + drop_files(item) + return {"deleted": item_id} + + +def live_object(item_id: str) -> dict: + item = get_item(item_id) + mol = item.get("mol") + try: + molfile = item_path(mol).read_text(encoding="utf-8") if isinstance(mol, str) else "" + except OSError: + molfile = "" + return {"format": OBJECT_FORMAT, "format_version": FORMAT_VERSION, "id": item["id"], "rev": item.get("rev", 1), "app": "formchem", + "name": item.get("name", ""), "kind": item.get("kind", "structure"), "smiles": item.get("smiles", ""), "inchikey": item.get("inchikey", ""), + "svg": item_path(item["svg"]).read_text(encoding="utf-8"), "molfile": molfile, "width": item.get("width"), "height": item.get("height")} + + +def _rev(value: object) -> int: + return value if isinstance(value, int) and not isinstance(value, bool) and value >= 1 else 1 + + +def object_source(obj: object) -> tuple[dict, dict]: + if not isinstance(obj, dict) or obj.get("format") != OBJECT_FORMAT: + raise LibraryError(f"object must be a live structure object (format {OBJECT_FORMAT}).", 422) + if not isinstance(obj.get("id"), str) or not ID_PATTERN.fullmatch(obj["id"]): + raise LibraryError("The object's id is not a library id (s and 10 letters or digits).", 422) + svg = obj.get("svg") + found = embedded_source.from_svg(svg.encode("utf-8")) if isinstance(svg, str) else None + if found is None: + raise LibraryError("The object's picture has no FormChem drawing inside.", 422) + return obj, source_document(found) + + +def adopt(obj: object) -> dict: + obj, doc = object_source(obj) + rev = _rev(obj.get("rev")) + with _LOCK: + index = read_index() + have = find(index, obj["id"]) + if have is not None and present(have) and _rev(have.get("rev")) >= rev: + return copy.deepcopy(have) + chem = describe(doc) + try: + _, png = engine_pictures(doc, chem) + except LibraryError: + png = None + now = model.now_iso() + with _LOCK: + index = read_index() + have = find(index, obj["id"]) + paths = store_files(obj["id"], doc, chem, obj["svg"], png, obj.get("width"), obj.get("height")) + if have is None: + have = {"id": obj["id"], "created": now, "tags": []} + index["items"].insert(0, have) + have.update(name=str(obj.get("name") or have.get("name") or _title(doc, chem)), **chem_fields(chem), **paths, rev=rev, modified=now, used=now) + have["kinds"] = [k for k in KINDS if k in kinds_of(have) or k == "live"] + gone = prune(index) + write_index(index) + for old in gone: + drop_files(old) + return copy.deepcopy(have) + + +def rewrite(item_id: str, doc: dict, svg: str | None, png: bytes | None, width: object, height: object) -> dict: + chem = describe(doc) + now = model.now_iso() + with _LOCK: + index = read_index() + item = find(index, item_id) + if item is None: + item = {"id": item_id, "name": _title(doc, chem), "kinds": ["live"], "rev": 0, "created": now, "tags": []} + index["items"].insert(0, item) + before = {k: item.get(k) for k in ("svg", "png", "mol")} + paths = store_files(item_id, doc, chem, svg, png, width, height) + if "png" not in paths: + item.pop("png", None) + item.update(**chem_fields(chem), **paths, rev=_rev(item.get("rev")) + 1 if item.get("rev") else 1, modified=now) + item["kinds"] = [k for k in KINDS if k in kinds_of(item) or k == "live"] + write_index(index) + for key, rel in before.items(): + if isinstance(rel, str) and rel != item.get(key) and rel.startswith(f"{ITEMS}/"): + files.remove_quietly(item_path(rel)) + return copy.deepcopy(item) + + +LINKS: dict[str, dict] = {} +_SIBLING = re.compile(r"[^\w .-]+") + + +def sibling_name(raw: object) -> str: + return _SIBLING.sub("", raw).strip()[:40] if isinstance(raw, str) else "" + + +def links() -> list[dict]: + from app.services.store import STORE + for doc_id in [d for d in LINKS if d not in STORE.sessions]: + LINKS.pop(doc_id, None) + return [{"doc": d, **link} for d, link in LINKS.items()] + + +def _drawing(src: dict, title: str) -> dict: + from app import __version__ + doc = copy.deepcopy(src) + doc["id"] = model.new_id("d") + doc["title"] = title or "Live structure" + now = model.now_iso() + doc["created"] = now + doc["modified"] = now + doc["meta"] = {**(doc.get("meta") if isinstance(doc.get("meta"), dict) else {}), "app": f"formchem {__version__}"} + doc["meta"].pop("embedded", None) + errors = model.validate(doc) + if errors: + raise LibraryError(f"The drawing inside the live structure is not valid: {errors[0]}", 422) + return doc + + +async def open_live(item_id: str | None = None, obj: object = None, sibling: object = None) -> dict: + import asyncio + from app.services.hub import HUB + from app.services.store import STORE + if obj is not None: + item = await asyncio.to_thread(adopt, obj) + sibling = sibling or (obj.get("from") if isinstance(obj, dict) else None) + elif isinstance(item_id, str) and item_id: + item = get_item(item_id) + else: + raise LibraryError("Send the id of a library item or a live structure object.", 422) + for link in links(): + if link["id"] == item["id"]: + await HUB.broadcast_all({"t": "live-open", **link}) + return link + src = embedded_source.from_svg(await asyncio.to_thread(item_path(item["svg"]).read_bytes)) + if src is None: + raise LibraryError(f"The picture of {item.get('name') or item['id']} has no FormChem drawing inside.", 422) + s = STORE.add(_drawing(src, str(item.get("name") or "")), dirty=False) + LINKS[s.id] = {"id": item["id"], "rev": _rev(item.get("rev")), "from": sibling_name(sibling), "name": str(item.get("name") or "")} + await HUB.broadcast_all({"t": "opened", "doc": s.id, "info": STORE.info(s)}) + STORE.schedule_derive(s) + await HUB.broadcast_all({"t": "live-open", "doc": s.id, **LINKS[s.id]}) + return {"doc": s.id, **LINKS[s.id]} + + +async def save_live(doc_id: str, svg: object = None, png: object = None, width: object = None, height: object = None) -> dict: + import asyncio + from app.services.hub import HUB + from app.services.store import STORE + link = LINKS.get(doc_id) + if link is None: + raise LibraryError("This drawing is not a live structure; save it as a file instead.", 409) + try: + s = STORE.get(doc_id) + except KeyError: + LINKS.pop(doc_id, None) + raise LibraryError(f"The drawing {doc_id} is not open.", 404) from None + with s.lock: + rev = s.rev + snap = copy.deepcopy(s.doc) + doc = source_document(snap) + item = await asyncio.to_thread(rewrite, link["id"], doc, svg if isinstance(svg, str) else None, png_bytes(png), width, height) + link["rev"] = item["rev"] + with s.lock: + s.saved_rev = rev + s.dirty = s.rev != rev + dirty = s.dirty + await HUB.broadcast_all({"t": "saved", "doc": doc_id, "rev": rev, "path": None, "modified": item["modified"], "dirty": dirty}) + await HUB.broadcast_all({"t": "live-structure", "id": item["id"], "rev": item["rev"]}) + return item + + +def open_request(id_or_file: str, sibling: str | None = None) -> dict: + arg = str(id_or_file or "").strip() + body: dict = {"from": sibling} if sibling else {} + if ID_PATTERN.fullmatch(arg): + return {**body, "id": arg} + p = Path(arg).expanduser() + if p.suffix.lower() == ".svg" and p.stem and ID_PATTERN.fullmatch(p.stem) and p.parent.name == ITEMS: + return {**body, "id": p.stem} + try: + obj = json.loads(p.read_text(encoding="utf-8")) + except OSError as exc: + raise LibraryError(f"Could not read {p}: {exc.strerror or exc}.") from None + except ValueError: + raise LibraryError(f"{p.name} is not a live structure object (JSON).") from None + return {**body, "object": obj} + + +def edit_live(id_or_file: str, sibling: str | None = None) -> int: + import urllib.error + import urllib.request + from app.core import agent_token + try: + body = open_request(id_or_file, sibling) + except LibraryError as exc: + print(str(exc)) + return 2 + try: + port = int(json.loads(config.discovery_path().read_text(encoding="utf-8"))["port"]) + except (OSError, ValueError, KeyError, TypeError): + print("FormChem is not running. Start it with ./formchem, then run edit-live again.") + return 1 + req = urllib.request.Request(f"http://127.0.0.1:{port}/api/structures/open", data=json.dumps(body).encode("utf-8"), method="POST", + headers={"content-type": "application/json", "authorization": f"Bearer {agent_token.value()}"}) + try: + with urllib.request.urlopen(req, timeout=30) as res: + found = json.loads(res.read().decode("utf-8")) + except urllib.error.HTTPError as exc: + try: + detail = json.loads(exc.read().decode("utf-8")).get("detail") + except (ValueError, AttributeError): + detail = None + print(f"FormChem refused: {detail or exc.reason}") + return 1 + except (urllib.error.URLError, OSError) as exc: + print(f"Could not reach FormChem on port {port}: {exc}") + return 1 + print(f"Opened {found.get('name') or found.get('id')} for editing in FormChem (live structure {found.get('id')}, rev {found.get('rev')}).") + return 0 + + +def prune(index: dict) -> list[dict]: + recent = sorted((it for it in index["items"] if "recent" in kinds_of(it)), key=_used, reverse=True) + for old in recent[RECENT_CAP:]: + old["kinds"] = [k for k in kinds_of(old) if k != "recent"] + gone = [it for it in index["items"] if not kinds_of(it)] + index["items"] = [it for it in index["items"] if kinds_of(it)] + return gone diff --git a/backend/app/services/model.py b/backend/app/services/model.py index 9e6d8819..fa834738 100644 --- a/backend/app/services/model.py +++ b/backend/app/services/model.py @@ -113,6 +113,17 @@ class ScanPoint(TypedDict): angle: float +class ConformerProgram(TypedDict): + name: Literal["xtb", "CREST"] + version: str + method: Literal["GFN2-xTB", "GFN-FF"] + solvent: str + charge: int + uhf: int + energy_eh: float | None + gap_ev: NotRequired[float] + + class Conformer(TypedDict): id: str coords: dict[str, list[float]] @@ -122,6 +133,7 @@ class Conformer(TypedDict): method: NotRequired[str] converged: NotRequired[bool] scan: NotRequired[ScanPoint] + program: NotRequired[ConformerProgram] class Fragment(TypedDict): diff --git a/backend/app/services/notebook/__init__.py b/backend/app/services/notebook/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/backend/app/services/notebook/attachments.py b/backend/app/services/notebook/attachments.py new file mode 100644 index 00000000..3ea56b7c --- /dev/null +++ b/backend/app/services/notebook/attachments.py @@ -0,0 +1,81 @@ +import hashlib +import mimetypes +import sqlite3 +import time +from pathlib import Path + +from app.core import files +from app.services.database import store +from app.services.database.store import Database, DatabaseError +from app.services.notebook import content, entries + +STORED_LIMIT = 50 * 1024 * 1024 +CHUNK = 1024 * 1024 + + +def _mime(name: str, given: str | None) -> str: + if given and given != "application/octet-stream": + return given + return mimetypes.guess_type(name)[0] or "application/octet-stream" + + +def _file_hash(path: Path) -> tuple[str, int]: + h = hashlib.sha256() + size = 0 + with path.open("rb") as fh: + while chunk := fh.read(CHUNK): + h.update(chunk) + size += len(chunk) + return h.hexdigest(), size + + +def _insert(db: Database, uid: str, name: str, mime: str, size: int, sha: str, data: bytes | None, path: str | None, actor: str) -> dict: + def run(conn: sqlite3.Connection) -> int: + r = entries._row(conn, uid) + before = content.of_row(conn, r) + now = time.time() + cur = conn.execute("INSERT INTO attachments (compound, entry, name, mime, size, sha256, data, path, created) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)", + (r["id"], name, mime, size, sha, data, path, now)) + entries.after_change(conn, r, before, now) + store.audit(db, actor, "entry.attach", uid, {"name": name, "size": size, "sha256": sha, "linked": path is not None}) + return cur.lastrowid + + new_id = entries._write(db, run) + store.notify(db, "entries", [uid]) + with db.lock: + return next(a for a in entries.attachments_of(db.conn, entries._row(db.conn, uid)["id"]) if a["id"] == new_id) + + +def add_bytes(db: Database, uid: str, name: str, data: bytes, mime: str | None = None, actor: str = "person") -> dict: + if len(data) > STORED_LIMIT: + raise DatabaseError(f"{name} is larger than {STORED_LIMIT // (1024 * 1024)} MB; link it by its path instead.", 413) + clean = files.safe_name(Path(name or "").name, "Attachment") + return _insert(db, uid, clean, _mime(clean, mime), len(data), hashlib.sha256(data).hexdigest(), data, None, actor) + + +def add_link(db: Database, uid: str, path: str, actor: str = "person") -> dict: + if not isinstance(path, str) or not path.strip(): + raise DatabaseError("Give the absolute path of the file to link.", 400) + p = Path(path.strip()).expanduser() + if not p.is_absolute(): + raise DatabaseError("Give the absolute path of the file to link.", 400) + if not p.is_file(): + raise DatabaseError(f"{p} does not exist.", 404) + try: + sha, size = _file_hash(p) + except OSError as exc: + raise DatabaseError(f"Could not read {p.name}: {exc.strerror or exc}.", 400) + return _insert(db, uid, p.name, _mime(p.name, None), size, sha, None, str(p.resolve()), actor) + + +def read(db: Database, attachment_id: int) -> tuple[str, str, bytes]: + with db.lock: + row = db.conn.execute("SELECT name, mime, data, path FROM attachments WHERE id = ?", (attachment_id,)).fetchone() + if row is None: + raise DatabaseError(f"There is no attachment {attachment_id}.", 404) + if row["data"] is not None: + return row["name"], row["mime"] or "application/octet-stream", bytes(row["data"]) + try: + return row["name"], row["mime"] or "application/octet-stream", Path(row["path"]).read_bytes() + except OSError as exc: + raise DatabaseError(f"The linked file {row['path']} could not be read: {exc.strerror or exc}.", 404) diff --git a/backend/app/services/notebook/content.py b/backend/app/services/notebook/content.py new file mode 100644 index 00000000..9e7a414b --- /dev/null +++ b/backend/app/services/notebook/content.py @@ -0,0 +1,48 @@ +import hashlib +import json +import sqlite3 + +KEYS = ("uid", "number", "title", "author", "date", "scheme", "procedure", "observations", "products", "tags", "attachments") +HASH_METHOD = "SHA-256 (hex) of the canonical JSON (sorted keys, no spaces, UTF-8) of uid, number, title, author, date, scheme, procedure, observations, products, tags and the sorted attachment SHA-256 values" + + +def loads(text: str | None, fallback): + if text is None or text == "": + return fallback + try: + return json.loads(text) + except ValueError: + return fallback + + +def dumps(value) -> str: + return json.dumps(value, ensure_ascii=False, separators=(",", ":")) + + +def canonical(value) -> bytes: + return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8") + + +def digest(content: dict) -> str: + return hashlib.sha256(canonical({k: content.get(k) for k in KEYS})).hexdigest() + + +def attachment_hashes(conn: sqlite3.Connection, entry_id: int) -> list[str]: + rows = conn.execute("SELECT sha256 FROM attachments WHERE entry = ?", (entry_id,)).fetchall() + return sorted(r[0] or "" for r in rows) + + +def of_row(conn: sqlite3.Connection, row: sqlite3.Row) -> dict: + return { + "uid": row["uid"], + "number": row["number"], + "title": row["title"], + "author": row["author"], + "date": row["date"], + "scheme": loads(row["scheme"], None), + "procedure": row["procedure"] or "", + "observations": row["observations"] or "", + "products": loads(row["products"], []), + "tags": loads(row["tags"], []), + "attachments": attachment_hashes(conn, row["id"]), + } diff --git a/backend/app/services/notebook/entries.py b/backend/app/services/notebook/entries.py new file mode 100644 index 00000000..36f05f81 --- /dev/null +++ b/backend/app/services/notebook/entries.py @@ -0,0 +1,300 @@ +import json +import math +import sqlite3 +import time + +from app.services.database import store +from app.services.database.store import Database, DatabaseError +from app.services.notebook import content, products, scheme, templates + +TITLE_LIMIT = 500 +TAG_LIMIT = 100 +TEXT_LIMIT = 5 * 1024 * 1024 +PAGE_LIMIT = 500 +CONTENT_FIELDS = ("title", "author", "date", "scheme", "procedure", "observations", "products", "tags") +EDITABLE = CONTENT_FIELDS + ("template",) +ROW_COLUMNS = "id, uid, number, title, author, date, status, tags, modified" + + +def _write(db: Database, fn): + with db.lock: + db.writable() + conn = db.conn + conn.execute("BEGIN IMMEDIATE") + try: + out = fn(conn) + conn.execute("COMMIT") + except BaseException: + conn.execute("ROLLBACK") + raise + return out + + +def _bad(exc: Exception) -> DatabaseError: + return DatabaseError(str(exc), 400) + + +def _row(conn: sqlite3.Connection, uid: str) -> sqlite3.Row: + row = conn.execute("SELECT * FROM entries WHERE uid = ?", (uid,)).fetchone() + if row is None: + raise DatabaseError(f"No notebook entry has the uid {uid}.", 404) + return row + + +def _title(value: object) -> str: + if not isinstance(value, str) or not value.strip(): + raise DatabaseError("An entry needs a title.", 400) + text = " ".join(value.split()) + if len(text) > TITLE_LIMIT: + raise DatabaseError(f"A title is at most {TITLE_LIMIT} characters.", 400) + return text + + +def _text(value: object, name: str) -> str: + if value is None: + return "" + if not isinstance(value, str): + raise DatabaseError(f"{name} is text.", 400) + if len(value) > TEXT_LIMIT: + raise DatabaseError(f"{name} is longer than FormChem keeps in one entry.", 400) + return value.replace("\r\n", "\n") + + +def _author(value: object) -> str | None: + if value is None: + return None + if not isinstance(value, str): + raise DatabaseError("The author is a name.", 400) + return " ".join(value.split()) or None + + +def _date(value: object) -> float | None: + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise DatabaseError("The date is seconds since the Unix epoch.", 400) + return float(value) + + +def _tags(value: object) -> list[str]: + if value is None: + return [] + if not isinstance(value, list) or not all(isinstance(t, str) for t in value): + raise DatabaseError("Tags are a list of words.", 400) + out: list[str] = [] + for t in value: + t = " ".join(t.split()) + if t and t not in out: + out.append(t) + if len(out) > TAG_LIMIT: + raise DatabaseError(f"An entry has at most {TAG_LIMIT} tags.", 400) + return out + + +def row_of(r: sqlite3.Row) -> dict: + return {"uid": r["uid"], "number": r["number"], "title": r["title"], "author": r["author"], "date": r["date"], + "status": r["status"], "tags": content.loads(r["tags"], []), "modified": r["modified"]} + + +def attachments_of(conn: sqlite3.Connection, entry_id: int) -> list[dict]: + rows = conn.execute("SELECT id, name, mime, size, sha256, path, created FROM attachments WHERE entry = ? ORDER BY id", (entry_id,)).fetchall() + return [{"id": r["id"], "name": r["name"], "mime": r["mime"], "size": r["size"], "sha256": r["sha256"], "linked": r["path"] is not None, + "created": r["created"]} for r in rows] + + +def versions_of(conn: sqlite3.Connection, entry_id: int) -> list[dict]: + rows = conn.execute("SELECT id, at, reason FROM entry_versions WHERE entry = ? ORDER BY id", (entry_id,)).fetchall() + return [{"id": r["id"], "at": r["at"], "reason": r["reason"]} for r in rows] + + +def _snapshot(db: Database, uid: str) -> tuple[dict, dict | None]: + with db.lock: + r = _row(db.conn, uid) + now = content.of_row(db.conn, r) + out = {**row_of(r), "template": r["template"], "scheme": now["scheme"], "procedure": now["procedure"], + "observations": now["observations"], "products": now["products"], "signed_at": r["signed_at"], + "signed_by": r["signed_by"], "signed_hash": r["signed_hash"], "hash": content.digest(now), "created": r["created"], + "attachments": attachments_of(db.conn, r["id"]), "versions": versions_of(db.conn, r["id"])} + return out, now["scheme"] + + +def get(db: Database, uid: str, stoichiometry: bool = True) -> dict: + out, doc = _snapshot(db, uid) + out["hash_method"] = content.HASH_METHOD + out["stoichiometry"] = scheme.stoichiometry(doc) if stoichiometry else None + return out + + +def create(db: Database, title: str, template: object = None, author: object = None, date: object = None, actor: str = "person") -> dict: + name = _title(title) + try: + tmpl = templates.pick(template) + except templates.TemplateError as exc: + raise _bad(exc) + start = templates.starting(tmpl) + who, when = _author(author), _date(date) + uid = store.new_id("n") + + def run(conn: sqlite3.Connection) -> None: + now = time.time() + number = (conn.execute("SELECT COALESCE(MAX(number), 0) FROM entries").fetchone()[0] or 0) + 1 + conn.execute("INSERT INTO entries (uid, number, title, author, date, template, scheme, procedure, observations, products, tags, status, created, modified) " + "VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, '[]', '[]', 'open', ?, ?)", + (uid, number, name, who, when if when is not None else now, tmpl, start["procedure"], start["observations"], now, now)) + store.audit(db, actor, "entry.create", uid, {"number": number, "title": name, "template": tmpl}) + + _write(db, run) + store.notify(db, "entries", [uid]) + store.notify(db, "info") + return get(db, uid) + + +def _value(field: str, raw: object): + try: + if field == "title": + return _title(raw) + if field == "author": + return _author(raw) + if field == "date": + return _date(raw) + if field in ("procedure", "observations"): + return _text(raw, field.capitalize()) + if field == "tags": + return json.dumps(_tags(raw), ensure_ascii=False, separators=(",", ":")) + if field == "scheme": + doc = scheme.checked(raw) + return None if doc is None else content.dumps(doc) + if field == "template": + return templates.pick(raw) + except (scheme.SchemeError, templates.TemplateError) as exc: + raise _bad(exc) + raise DatabaseError(f"{field} cannot be changed.", 400) + + +def after_change(conn: sqlite3.Connection, r: sqlite3.Row, before: dict, now: float) -> bool: + fresh = _row(conn, r["uid"]) + after = content.of_row(conn, fresh) + if content.digest(after) == content.digest(before): + return False + conn.execute("UPDATE entries SET modified = ? WHERE id = ?", (now, r["id"])) + if r["status"] == "signed": + signed = conn.execute("SELECT content, hash FROM entry_versions WHERE entry = ? AND reason = 'signed' ORDER BY id DESC LIMIT 1", (r["id"],)).fetchone() + kept, kept_hash = (signed["content"], signed["hash"]) if signed else (content.dumps(before), content.digest(before)) + conn.execute("INSERT INTO entry_versions (entry, at, reason, content, hash) VALUES (?, ?, 'edited-after-signing', ?, ?)", (r["id"], now, kept, kept_hash)) + conn.execute("UPDATE entries SET status = 'modified' WHERE id = ?", (r["id"],)) + return True + + +def update(db: Database, uid: str, body: dict, actor: str = "person") -> dict: + if not isinstance(body, dict): + raise DatabaseError("Send the changed fields as an object.", 400) + unknown = sorted(k for k in body if k not in EDITABLE) + if unknown: + raise DatabaseError(f"These fields cannot be changed: {', '.join(unknown)}.", 400) + values = {k: _value(k, v) for k, v in body.items() if k != "products"} + try: + prods = products.normalise(body["products"]) if "products" in body else None + except products.ProductError as exc: + raise _bad(exc) + + def run(conn: sqlite3.Connection) -> bool: + r = _row(conn, uid) + before = content.of_row(conn, r) + cols = dict(values) + if prods is not None: + try: + ids = products.resolve(conn, prods) + except products.ProductError as exc: + raise DatabaseError(str(exc), 404) + cols["products"] = content.dumps(prods) + products.link(conn, r["id"], prods, ids) + if cols: + conn.execute(f"UPDATE entries SET {', '.join(f'{k} = ?' for k in cols)} WHERE id = ?", (*cols.values(), r["id"])) + changed = after_change(conn, r, before, time.time()) + if changed: + store.audit(db, actor, "entry.update", uid, {"fields": sorted(body)}) + return changed + + if _write(db, run): + store.notify(db, "entries", [uid]) + return get(db, uid) + + +def sign(db: Database, uid: str, by: object, actor: str = "person") -> dict: + name = _author(by) + if not name: + raise DatabaseError("Give the name of the person signing.", 400) + + def run(conn: sqlite3.Connection) -> str: + r = _row(conn, uid) + now = time.time() + snap = content.of_row(conn, r) + digest = content.digest(snap) + conn.execute("UPDATE entries SET status = 'signed', signed_at = ?, signed_by = ?, signed_hash = ?, modified = ? WHERE id = ?", + (now, name, digest, now, r["id"])) + conn.execute("INSERT INTO entry_versions (entry, at, reason, content, hash) VALUES (?, ?, 'signed', ?, ?)", (r["id"], now, content.dumps(snap), digest)) + store.audit(db, actor, "entry.sign", uid, {"by": name, "hash": digest}) + return digest + + _write(db, run) + store.notify(db, "entries", [uid]) + return get(db, uid) + + +def version(db: Database, uid: str, version_id: int) -> dict: + with db.lock: + r = _row(db.conn, uid) + v = db.conn.execute("SELECT at, reason, content, hash FROM entry_versions WHERE id = ? AND entry = ?", (version_id, r["id"])).fetchone() + if v is None: + raise DatabaseError(f"Entry {r['number']} has no version {version_id}.", 404) + return {"content": content.loads(v["content"], {}), "hash": v["hash"], "at": v["at"], "reason": v["reason"]} + + +def _words(q: str) -> list[str]: + return [w.casefold() for w in q.split() if w] + + +def _haystack(r: sqlite3.Row) -> str: + samples = [str(p.get("sample") or "") for p in content.loads(r["products"], []) if isinstance(p, dict)] + parts = [r["title"] or "", r["procedure"] or "", r["observations"] or "", " ".join(content.loads(r["tags"], [])), " ".join(samples)] + return "\n".join(parts).casefold() + + +def listing(db: Database, q: str | None = None, substructure: str | None = None, offset: int = 0, limit: int = 100) -> dict: + offset = max(0, int(offset or 0)) + limit = max(1, min(int(limit or 100), PAGE_LIMIT)) + words = _words(q or "") + try: + query = scheme.query(substructure) if substructure and substructure.strip() else None + except scheme.SchemeError as exc: + raise _bad(exc) + with db.lock: + rows = db.conn.execute(f"SELECT {ROW_COLUMNS}, procedure, observations, products, scheme IS NOT NULL AS has_scheme FROM entries ORDER BY number DESC").fetchall() + hits = [] + for r in rows: + if words: + text = _haystack(r) + if not all(w in text for w in words): + continue + if query is not None: + if not r["has_scheme"]: + continue + mols = scheme.cached_molecules((str(db.path), r["id"], r["modified"]), lambda rid=r["id"]: _scheme_text(db, rid)) + if not scheme.contains(mols, query): + continue + hits.append(r) + out = {"total": len(hits), "rows": [row_of(r) for r in hits[offset:offset + limit]]} + if query is not None: + out["method"] = scheme.MATCH_METHOD + return out + + +def _scheme_text(db: Database, entry_id: int) -> str | None: + with db.lock: + row = db.conn.execute("SELECT scheme FROM entries WHERE id = ?", (entry_id,)).fetchone() + return row[0] if row else None + + +def count(db: Database) -> int: + with db.lock: + return db.conn.execute("SELECT count(*) FROM entries").fetchone()[0] diff --git a/backend/app/services/notebook/export.py b/backend/app/services/notebook/export.py new file mode 100644 index 00000000..8159d65e --- /dev/null +++ b/backend/app/services/notebook/export.py @@ -0,0 +1,234 @@ +import base64 +import html +import re +import time +from datetime import datetime, timezone +from pathlib import Path + +from app import __version__ +from app.core import files +from app.services.database import store +from app.services.database.store import Database, DatabaseError +from app.services.notebook import attachments, content, entries, markup, scheme + +FORMATS = {"html": (".html", "text/html"), "json": (".json", "application/json")} +FORMAT_NAME = "formchem-entry" +FORMAT_VERSION = 1 +INLINE_IMAGES = {"image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml"} +INLINE_LIMIT = 4 * 1024 * 1024 +PICTURE_LIMIT = 8 * 1024 * 1024 +STATUS_TEXT = {"open": "Open", "signed": "Signed", "modified": "Modified after signing"} + +STYLE = """ +:root{color-scheme:light} +body{margin:0;background:#fff;color:#1b1b1f;font:14px/1.5 -apple-system,"Segoe UI",Arimo,Arial,sans-serif} +main{max-width:860px;margin:0 auto;padding:32px 28px 48px} +h1{margin:0 0 4px;font-size:24px;line-height:1.25} +h2{margin:28px 0 8px;padding-bottom:4px;border-bottom:1px solid #d6d6dc;font-size:15px;letter-spacing:.3px;text-transform:uppercase;color:#45454d} +.kicker{margin:0;color:#6b6b74;font-size:12px;letter-spacing:.4px;text-transform:uppercase} +.meta{display:grid;grid-template-columns:max-content 1fr;gap:2px 16px;margin:16px 0 0;font-size:13px} +.meta dt{color:#6b6b74} +.meta dd{margin:0} +.badge{display:inline-block;padding:1px 8px;border:1px solid currentColor;border-radius:10px;font-size:12px;font-weight:600} +.badge.signed{color:#1d7a3e}.badge.modified{color:#a4500b}.badge.open{color:#45454d} +.banner{margin:16px 0 0;padding:8px 12px;border-left:3px solid #a4500b;background:#fdf3ea;color:#6a3205} +.sig{margin:16px 0 0;padding:8px 12px;border:1px solid #d6d6dc;border-radius:6px;font-size:13px} +.hash{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;word-break:break-all} +.scheme{display:flex;flex-wrap:wrap;gap:16px;align-items:center;margin:8px 0} +.scheme svg{max-width:100%;height:auto} +table{width:100%;border-collapse:collapse;font-size:13px;font-variant-numeric:tabular-nums} +th,td{padding:4px 8px;border-bottom:1px solid #e4e4e8;text-align:left;vertical-align:top} +th{color:#45454d;font-weight:600;border-bottom-color:#c9c9cf} +td.num,th.num{text-align:right} +.method{margin:6px 0 0;color:#6b6b74;font-size:12px} +.att img{display:block;max-width:100%;max-height:420px;margin:6px 0 12px} +.empty{color:#6b6b74;font-style:italic} +footer{margin-top:36px;padding-top:8px;border-top:1px solid #d6d6dc;color:#6b6b74;font-size:12px} +@media print{main{max-width:none;padding:0}h2{break-after:avoid}table,tr,.scheme,.sig,.att img{break-inside:avoid}a{color:inherit}} +""" + + +def _when(t: float | None, with_time: bool = True) -> str: + if t is None: + return "" + d = datetime.fromtimestamp(t, timezone.utc) + return d.strftime("%Y-%m-%d %H:%M UTC") if with_time else d.strftime("%Y-%m-%d") + + +def _num(v: float | None, places: int = 3) -> str: + if v is None: + return "" + return f"{v:.{places}g}" if abs(v) < 1e5 else f"{v:,.0f}" + + +def _size(n: int | None) -> str: + if n is None: + return "" + for unit, k in (("MB", 1024 * 1024), ("KB", 1024)): + if n >= k: + return f"{n / k:.1f} {unit}" + return f"{n} bytes" + + +def _clean_svg(svg: str) -> str: + svg = re.sub(r"<\?xml[^>]*\?>", "", svg) + svg = re.sub(r"]*>", "", svg, flags=re.I) + svg = re.sub(r"", "", svg, flags=re.I | re.S) + svg = re.sub(r"", "", svg, flags=re.I | re.S) + svg = re.sub(r"\son[a-z]+\s*=\s*(\"[^\"]*\"|'[^']*')", "", svg, flags=re.I) + return re.sub(r"(href\s*=\s*[\"'])\s*javascript:[^\"']*", r"\1#", svg, flags=re.I).strip() + + +def _scheme_html(doc: dict | None, picture: str | None) -> str: + if picture: + return f'
{_clean_svg(picture)}
' + pics = scheme.pictures(doc) + if not pics: + return '

No scheme.

' + return '
' + "".join(_clean_svg(p) for p in pics) + "
" + + +def _stoich_html(st: dict | None) -> str: + if not st or not st.get("steps"): + return "" + e = html.escape + parts = ["

Stoichiometry

"] + head = "
" + for n, step in enumerate(st["steps"], 1): + if len(st["steps"]) > 1: + parts.append(f"

Step {n}

") + rows = [] + for r in step.get("rows") or []: + role = {"agent": "reagent"}.get(r.get("role"), r.get("role") or "") + if r.get("limiting"): + role += " (limiting)" + rows.append(f"" + f"" + f"") + parts.append(f"

Clipboard

Copy puts the drawing, SMILES and a picture on the clipboard at once; Copy As picks SMILES, CXSMILES, Molfile, InChI, InChIKey, SMARTS, SVG, PNG or CDXML; Paste reads all of them back, and Paste Special lets you choose.

Command line

./formchem convert, batch, descriptors and render work on whole files and folders (10,000 SD records to SMILES in about a second and a half), with optional standardising and a report of every record that failed.

Command line

./formchem convert, batch, descriptors and render work on whole files and folders (10,000 SD records to SMILES in about a second and a half), with optional standardising and a report of every record that failed; ./formchem db creates, fills, searches and exports databases.

Dark page and grids

A dark drawing page, on by default, that keeps element colours readable and never reaches exports. Line, dot, cross, isometric and hexagonal grids with their own spacing, kept per drawing, and Snap to Grid.

Size on the sheet

Drag a corner handle, or use Arrange > Scale, Scale Up and Scale Down, to make structures larger or smaller on the page by percent or bond length, with their labels and line widths or without.

Proteins and ligands

PDB and mmCIF files open as cartoon with the ligand in focus and waters hidden, the file kept byte for byte in the drawing. Extract Ligand turns a ligand into an editable structure with its coordinates; 3D SD files keep theirs. Export as MOL, SD, PDB or XYZ with every hydrogen.

MCP server

60 tools over HTTP (with an agent token) and stdio: agents open and save drawings, draw from SMILES, reaction SMILES, molfiles or names, build and edit atom by atom by id, read structures back as SMILES, InChIKey, molfiles and names, render what you see, validate, predict NMR, open spectra and pick their peaks, build 3D conformers, scan and measure them, open PDB files and extract ligands, convert files as the command line does, and run every menu command. Agent Activity lists each call with undo and Stop.

Databases

Structure databases in one SQLite file (.fcdb) that any SQLite browser opens: your own fields (numbers with units, dates, choices, files, links and computed descriptors), Add to Database with duplicate rules for stereo and salts, and table, gallery, form and plot views that scroll 10,000 records without a stall. Import SD, RD, SMILES, CSV and TSV with a preview and a report of every bad record; export to SD, SMILES or CSV.

Search and hit lists

Exact (stereo, salts, charges and tautomers matched or ignored), substructure, Tanimoto similarity with scores, formula ranges such as C6-8N1, and every field, combined in All of, Any of and None of groups. Each search is a hit list to keep, export or combine; saved queries live in folders. Benzene among 9,997 records in 145 ms.

Lab notebook

Experiment entries in the same database: a reaction scheme with its stoichiometry computed, procedure and observations, products linked to their records, files and tags, searchable by words and by substructure. Sign an entry with a SHA-256 hash of its content; a later change shows "Modified after signing" and keeps the signed version. Export as self-contained HTML or JSON.

Live structures

Copy as Live Structure puts a structure into FormDeck, FormTxt or form.md as a picture with the FormChem drawing inside. The sibling app opens it in FormChem again with a formai://formchem/edit link or ./formchem edit-live; Save writes the new picture back with a higher revision, no path asked.

Structure library

Favourites, Recent, Templates and Live structures in a plain folder of SVG, PNG and molfiles that every Form app reads without FormChem running. Star a structure, save a template, insert or open from Window > Structure Library. A bar offers Reload or Keep Mine when a drawing's file changes on disk.

Biopolymers

Insert > Biopolymer from HELM reads peptides and nucleic acids as you type, disulfides and rings included, and Copy as HELM writes them back only when the HELM reads back to the same structure. 55 monomers written for FormChem from textbook structures.

Keyboard and screen readers

Focus Structure puts the focus on the drawing: Tab walks atoms, arrows follow bonds, Enter and an arrow draw a new bond. Every move is spoken ("Oxygen. 1 hydrogen. Single bond to Carbon."), and Describe Structure reads the formula, name, rings, functional groups and stereocentres.

Element colours

Standard, High contrast (every element at 7:1 or more on white) and Colour-blind safe (Okabe-Ito blue, vermillion, bluish green and reddish purple), applied to the canvas, pictures and the clipboard, switched without a flash.

xtb and CREST

GFN2-xTB or GFN-FF optimisations and single points with ALPB solvents, and CREST conformer searches, when you have installed the programs: energies in hartree and kcal/mol with the gap and the program's version. FormChem never ships or downloads them.

MCP server

77 tools over HTTP (with an agent token) and stdio: agents open and save drawings, draw from SMILES, reaction SMILES, molfiles or names, build and edit atom by atom by id, read structures back as SMILES, InChIKey, molfiles and names, render what you see, validate, predict NMR, open spectra and pick their peaks, build 3D conformers, scan and measure them, open PDB files and extract ligands, create, import into, search and export databases, add and find notebook entries, keep the structure library, draw from HELM, run xtb and CREST, convert files as the command line does, and run every menu command. Agent Activity lists each call with undo and Stop.

The family shell

Home, Preferences, twelve menus with full keyboard use (those that do not fit fold into More menus), Find a Command, the terminal and agent dock, Help and updates, in 26 interface languages.

Form extensions

Extensions installed by FormPortal run in a sandboxed frame from the Extensions menu and panel, and ask before they read or change a drawing.
CompoundFormulaRoleMW (g/mol)EquivAmount (mmol)Mass (mg)Volume (mL)Yield (%)
{e(str(r.get('label') or ''))}{e(str(r.get('formula') or ''))}{e(role)}{_num(r.get('mw'), 6)}{_num(r.get('equiv'))}{_num(r.get('mmol'))}{_num(r.get('mass_mg'))}{_num(r.get('volume_ml'))}{_num(r.get('yield_pct'))}
{head}{''.join(rows)}
") + for w in step.get("warnings") or []: + parts.append(f'

{e(str(w.get("text") or ""))}

') + parts.append(f'

Computed by {e(st.get("method") or "")}.

') + return "".join(parts) + + +def _products_html(items: list[dict]) -> str: + e = html.escape + if not items: + return '

No products recorded.

' + rows = "".join( + f"{e(p.get('name') or '')}{e(p.get('compound') or '')}{e(p.get('sample') or '')}" + f"{_num(p.get('mass_g'), 4)}{_num(p.get('yield_pct'))}{_num(p.get('purity_pct'))}{e(p.get('notes') or '')}" + for p in items) + return f"{rows}
ProductRecordSampleMass (g)Yield (%)Purity (%)Notes
" + + +def _attachments_html(db: Database, items: list[dict]) -> str: + e = html.escape + if not items: + return '

No attachments.

' + rows, shown = [], [] + for a in items: + where = "linked" if a["linked"] else "stored" + rows.append(f"{e(a['name'])}{e(a.get('mime') or '')}{_size(a.get('size'))}{where}{e(a.get('sha256') or '')}") + if a.get("mime") in INLINE_IMAGES and (a.get("size") or 0) <= INLINE_LIMIT: + try: + _, mime, data = attachments.read(db, a["id"]) + except DatabaseError: + continue + shown.append(f'
{e(a[
{e(a["name"])}
') + table = f"{''.join(rows)}
FileTypeSizeKeptSHA-256
" + return table + "".join(shown) + + +def _versions_html(items: list[dict]) -> str: + if not items: + return "" + reasons = {"signed": "Signed", "edited-after-signing": "Signed content kept when the entry was changed"} + rows = "".join(f"{v['id']}{_when(v['at'])}{html.escape(reasons.get(v['reason'], v['reason']))}{html.escape(v.get('hash') or '')}" for v in items) + return f"

Versions

{rows}
VersionAtReasonHash
" + + +def _versions_full(db: Database, entry: dict) -> list[dict]: + out = [] + for v in entry["versions"]: + found = entries.version(db, entry["uid"], v["id"]) + out.append({"id": v["id"], "at": v["at"], "reason": v["reason"], "hash": found["hash"], "content": found["content"]}) + return out + + +def to_html(db: Database, entry: dict, picture: str | None = None) -> str: + e = html.escape + status = entry["status"] + meta = [("Entry", str(entry["number"])), ("Date", _when(entry["date"], False)), ("Author", entry.get("author") or ""), + ("Template", entry.get("template") or ""), ("Tags", ", ".join(entry["tags"])), ("Created", _when(entry["created"])), + ("Modified", _when(entry["modified"])), ("Identifier", entry["uid"])] + meta_html = "".join(f"
{e(k)}
{e(v)}
" for k, v in meta if v) + banner = "" + if status == "modified": + banner = '' + sig = "" + if entry.get("signed_hash"): + sig = (f'
Signed by {e(entry.get("signed_by") or "")} on {_when(entry.get("signed_at"))}
' + f'Signed hash {e(entry["signed_hash"])}
') + versions = _versions_full(db, entry) + body = ( + f'

FormChem notebook entry {entry["number"]} {e(STATUS_TEXT.get(status, status))}

' + f"

{e(entry['title'])}

{meta_html}
{banner}{sig}" + f"

Scheme

{_scheme_html(entry.get('scheme'), picture)}" + f"{_stoich_html(entry.get('stoichiometry'))}" + f"

Procedure

{markup.to_html(entry['procedure']) or '

No procedure.

'}" + f"

Observations

{markup.to_html(entry['observations']) or '

No observations.

'}" + f"

Products

{_products_html(entry['products'])}" + f"

Attachments

{_attachments_html(db, entry['attachments'])}" + f"{_versions_html(versions)}" + f'" + ) + title = f"Entry {entry['number']}: {entry['title']}" + return f'\n{e(title)}
{body}
\n' + + +def to_json(db: Database, entry: dict) -> str: + with db.lock: + r = entries._row(db.conn, entry["uid"]) + now = content.of_row(db.conn, r) + out = {"format": FORMAT_NAME, "format_version": FORMAT_VERSION, **now, "hash": content.digest(now), "hash_method": content.HASH_METHOD, + "status": entry["status"], "template": entry.get("template"), "created": entry["created"], "modified": entry["modified"], + "signed_at": entry.get("signed_at"), "signed_by": entry.get("signed_by"), "signed_hash": entry.get("signed_hash"), + "attachment_files": [{k: a[k] for k in ("name", "mime", "size", "sha256", "linked", "created")} for a in entry["attachments"]], + "stoichiometry": entry.get("stoichiometry"), "versions": _versions_full(db, entry), + "exported": time.time(), "app": f"formchem {__version__}"} + return content.dumps(out) + "\n" + + +def render(db: Database, uid: str, fmt: str, picture: str | None = None) -> tuple[str, str, bytes]: + if fmt not in FORMATS: + raise DatabaseError("Export an entry as html or json.", 400) + if picture is not None and (not isinstance(picture, str) or len(picture) > PICTURE_LIMIT or " dict: + name, _, data = render(db, uid, fmt, picture) + if path: + target = files.with_suffix(Path(path), FORMATS[fmt][0]) + if not target.is_absolute(): + raise DatabaseError("Give the absolute path to write the entry to.", 400) + else: + folder = store.databases_dir() / ".exports" + folder.mkdir(parents=True, exist_ok=True) + target = files.free_name(folder, name) + try: + files.write_atomic(target, data) + except OSError as exc: + raise DatabaseError(f"Could not write {target.name}: {exc.strerror or exc}.", 400) + if not db.readonly: + with db.lock: + store.audit(db, actor, "entry.export", uid, {"format": fmt, "path": str(target)}) + return {"path": str(target)} diff --git a/backend/app/services/notebook/markup.py b/backend/app/services/notebook/markup.py new file mode 100644 index 00000000..08dc1ed4 --- /dev/null +++ b/backend/app/services/notebook/markup.py @@ -0,0 +1,41 @@ +import html +import re + +_BOLD = re.compile(r"\*\*(?=\S)(.+?)(?<=\S)\*\*") +_ITALIC = re.compile(r"(? str: + out = html.escape(text, quote=False) + out = _BOLD.sub(r"\1", out) + return _ITALIC.sub(r"\1", out) + + +def blocks(text: str) -> list[tuple[str, list[str]]]: + out: list[tuple[str, list[str]]] = [] + for para in re.split(r"\n\s*\n", (text or "").replace("\r\n", "\n").strip()): + lines = [ln.rstrip() for ln in para.split("\n") if ln.strip()] + if not lines: + continue + run: list[str] = [] + kind = None + for ln in lines: + this = "list" if ln.lstrip().startswith("- ") else "p" + if kind is not None and this != kind: + out.append((kind, run)) + run = [] + kind = this + run.append(ln.lstrip()[2:] if this == "list" else ln.strip()) + if run: + out.append((kind or "p", run)) + return out + + +def to_html(text: str) -> str: + parts = [] + for kind, lines in blocks(text): + if kind == "list": + parts.append("") + else: + parts.append("

" + "
".join(inline(ln) for ln in lines) + "

") + return "\n".join(parts) diff --git a/backend/app/services/notebook/products.py b/backend/app/services/notebook/products.py new file mode 100644 index 00000000..02333059 --- /dev/null +++ b/backend/app/services/notebook/products.py @@ -0,0 +1,76 @@ +import math +import sqlite3 + +TEXT_KEYS = ("name", "sample", "notes") +NUMBER_KEYS = ("mass_g", "yield_pct", "purity_pct") +LIMIT = 500 + + +class ProductError(ValueError): + pass + + +def _number(value: object, key: str, n: int) -> float | None: + if value is None or value == "": + return None + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0: + raise ProductError(f"Product {n}: {key} must be a number of zero or more, or empty.") + return float(value) + + +def normalise(value: object) -> list[dict]: + if value is None: + return [] + if not isinstance(value, list): + raise ProductError("Products are a list.") + if len(value) > LIMIT: + raise ProductError(f"An entry holds at most {LIMIT} products.") + out = [] + for n, item in enumerate(value, 1): + if not isinstance(item, dict): + raise ProductError(f"Product {n} is not an object.") + compound = item.get("compound") + if compound in ("", None): + compound = None + elif not isinstance(compound, str): + raise ProductError(f"Product {n}: compound is a record uid or null.") + row = {"compound": compound} + for key in TEXT_KEYS: + v = item.get(key) + row[key] = "" if v is None else str(v) + for key in NUMBER_KEYS: + row[key] = _number(item.get(key), key, n) + out.append(row) + return out + + +def resolve(conn: sqlite3.Connection, products: list[dict]) -> dict[str, int]: + uids = sorted({p["compound"] for p in products if p["compound"]}) + found: dict[str, int] = {} + for uid in uids: + row = conn.execute("SELECT id FROM compounds WHERE uid = ?", (uid,)).fetchone() + if row is None: + raise ProductError(f"No record in this database has the uid {uid}.") + found[uid] = row[0] + return found + + +def link(conn: sqlite3.Connection, entry_id: int, products: list[dict], ids: dict[str, int]) -> None: + conn.execute("DELETE FROM entry_compounds WHERE entry = ? AND role = 'product'", (entry_id,)) + samples: dict[int, list[str]] = {} + for p in products: + cid = ids.get(p["compound"] or "") + if cid is None: + continue + samples.setdefault(cid, []) + if p["sample"] and p["sample"] not in samples[cid]: + samples[cid].append(p["sample"]) + conn.executemany("INSERT INTO entry_compounds (entry, compound, role, sample) VALUES (?, ?, 'product', ?)", + [(entry_id, cid, ", ".join(s) or None) for cid, s in samples.items()]) + + +def entries_for(conn: sqlite3.Connection, compound_uid: str) -> list[dict]: + rows = conn.execute( + "SELECT e.uid, e.number, e.title, ec.role, ec.sample FROM entry_compounds ec JOIN entries e ON e.id = ec.entry " + "JOIN compounds c ON c.id = ec.compound WHERE c.uid = ? ORDER BY e.number", (compound_uid,)).fetchall() + return [{"uid": r[0], "number": r[1], "title": r[2], "role": r[3], "sample": r[4]} for r in rows] diff --git a/backend/app/services/notebook/scheme.py b/backend/app/services/notebook/scheme.py new file mode 100644 index 00000000..bca8af43 --- /dev/null +++ b/backend/app/services/notebook/scheme.py @@ -0,0 +1,185 @@ +import copy +import threading +from collections import OrderedDict +from collections.abc import Callable + +from rdkit import Chem + +from app import __version__ +from app.services import model, package +from app.services import ops as opsmod +from app.services.chem import ENGINE, depict, derive, reactions, rxnio, stoich +from app.services.chem import scheme as chem_scheme + +STOICH_METHOD = f"FormChem reaction perception and stoichiometry {__version__} (services/chem/reactions.py, stoich.py), masses from {ENGINE}" +MATCH_METHOD = f"RDKit substructure match ({ENGINE}) over each fragment of the scheme" +CACHE_SIZE = 4096 + +_cache: "OrderedDict[tuple, list[Chem.Mol]]" = OrderedDict() +_lock = threading.Lock() + + +class SchemeError(ValueError): + pass + + +def checked(value: object) -> dict | None: + if value is None: + return None + if not isinstance(value, dict): + raise SchemeError("A scheme is a FormChem document (document.json) or null.") + doc = copy.deepcopy(value) + try: + package.check(doc, "The scheme") + except package.PackageError as exc: + raise SchemeError(str(exc)) from None + pages = doc.get("pages") or [] + if len(pages) != 1: + raise SchemeError(f"A scheme holds one page; this document has {len(pages)}.") + doc.pop("derived", None) + return doc + + +def fragments(doc: dict | None) -> list[dict]: + if not isinstance(doc, dict): + return [] + return [f for f in derive.fragments_of(doc).values() if f.get("atoms")] + + +def molecules(doc: dict | None) -> list[Chem.Mol]: + if not isinstance(doc, dict): + return [] + expansions = doc.get("expansions") or {} + out: list[Chem.Mol] = [] + for frag in fragments(doc): + smiles = derive.derive_fragment(frag, expansions).get("smiles") or "" + mol = Chem.MolFromSmiles(smiles) if smiles else None + if mol is not None and mol.GetNumAtoms(): + out.append(mol) + return out + + +def cached_molecules(key: tuple, load: Callable[[], str | None]) -> list[Chem.Mol]: + with _lock: + hit = _cache.get(key) + if hit is not None: + _cache.move_to_end(key) + return hit + from app.services.notebook.content import loads + found = molecules(loads(load(), None)) + with _lock: + _cache[key] = found + while len(_cache) > CACHE_SIZE: + _cache.popitem(last=False) + return found + + +def query(text: str) -> Chem.Mol: + text = (text or "").strip() + if not text: + raise SchemeError("Give the substructure as SMILES or SMARTS.") + mol = Chem.MolFromSmiles(text) + if mol is None or not mol.GetNumAtoms(): + mol = Chem.MolFromSmarts(text) + if mol is None or not mol.GetNumAtoms(): + raise SchemeError(f"RDKit could not read {text!r} as SMILES or SMARTS.") + return mol + + +def contains(mols: list[Chem.Mol], q: Chem.Mol) -> bool: + return any(m.HasSubstructMatch(q) for m in mols) + + +def _steps(doc: dict) -> list[tuple[dict, dict]]: + used = reactions.used_ids(doc) + out: list[tuple[dict, dict]] = [] + for page in doc.get("pages") or []: + if not isinstance(page, dict): + continue + found, _ = reactions.perceive_page(doc, page, used) + for reaction in found: + for step in reaction.get("steps") or []: + out.append((reaction, step)) + return out + + +def stoichiometry(doc: dict | None) -> dict | None: + if not isinstance(doc, dict) or not fragments(doc): + return None + derived = derive.derive_document(doc) + steps = [] + for reaction, step in _steps(doc): + try: + steps.append(stoich.compute(doc, reaction, step, derived)) + except Exception as exc: + steps.append({"reaction": reaction.get("id"), "step": step.get("id"), "rows": [], "warnings": [{"code": "engine_error", "text": f"The stoichiometry of this step could not be computed: {exc}"}]}) + return {"method": STOICH_METHOD, "steps": steps} + + +def from_reaction(text: str, title: str, fmt: str | None = None) -> dict: + doc = model.empty_document(title) + page = doc["pages"][0] + try: + ops, _ = chem_scheme.insert_ops(doc, page, text, fmt) + for op in ops: + opsmod.apply(doc, op) + found, _ = reactions.perceive_ops(doc) + for op in found: + opsmod.apply(doc, op) + except Exception as exc: + raise SchemeError(f"The reaction could not be read: {exc}") from None + if not fragments(doc): + raise SchemeError("The reaction has no structures.") + return doc + + +def _reachable(doc: dict, ids: list, out: set[str]) -> None: + for oid in ids: + if not isinstance(oid, str) or oid in out: + continue + out.add(oid) + obj = (doc.get("objects") or {}).get(oid) + if isinstance(obj, dict) and obj.get("kind") == "group": + _reachable(doc, obj.get("children") or [], out) + + +def one_page(doc: dict, page_id: str | None = None) -> dict: + pages = [p for p in doc.get("pages") or [] if isinstance(p, dict)] + page = next((p for p in pages if p.get("id") == page_id), pages[0] if pages else None) + if page is None: + raise SchemeError("The drawing has no page.") + keep: set[str] = set() + _reachable(doc, page.get("order") or [], keep) + out = {k: copy.deepcopy(v) for k, v in doc.items() if k not in ("pages", "objects", "derived")} + out["pages"] = [copy.deepcopy(page)] + out["objects"] = {k: copy.deepcopy(v) for k, v in (doc.get("objects") or {}).items() if k in keep} + return out + + +def fchem(doc: dict, title: str) -> bytes: + out = copy.deepcopy(doc) + out["title"] = title + return package.pack(out) + + +def pictures(doc: dict | None) -> list[str]: + if not isinstance(doc, dict): + return [] + out: list[str] = [] + covered: set[str] = set() + for _, step in _steps(doc): + try: + rxn, _ = rxnio.build(doc, step) + out.append(depict.svg(rxn, transparent=True)) + covered |= {f["id"] for oid in reactions.role_ids(step) for f in rxnio.fragments_in(doc, oid)} + except Exception: + continue + for frag in fragments(doc): + if frag.get("id") in covered: + continue + try: + mol, _ = rxnio.molecule(doc, frag) + out.append(depict.svg(mol, transparent=True)) + except Exception: + continue + return out diff --git a/backend/app/services/notebook/templates.py b/backend/app/services/notebook/templates.py new file mode 100644 index 00000000..0364bd17 --- /dev/null +++ b/backend/app/services/notebook/templates.py @@ -0,0 +1,42 @@ +NAMES = ("blank", "reaction", "analysis", "purification") +DEFAULT = "blank" + +_HEADINGS = { + "blank": (), + "reaction": ("Aim", "Setup", "Reaction", "Monitoring", "Work-up"), + "analysis": ("Sample", "Method", "Instrument and conditions", "Results"), + "purification": ("Crude material", "Method", "Fractions", "Recovery"), +} + +_OBSERVATIONS = { + "blank": (), + "reaction": ("Appearance", "TLC"), + "analysis": ("Spectra and traces",), + "purification": ("Purity checks",), +} + +LABELS = {"blank": "Blank", "reaction": "Reaction", "analysis": "Analysis", "purification": "Purification"} + + +class TemplateError(ValueError): + pass + + +def _sections(headings: tuple[str, ...]) -> str: + return "\n\n".join(f"**{h}**" for h in headings) + + +def pick(name: object) -> str: + if name in (None, ""): + return DEFAULT + if name not in NAMES: + raise TemplateError(f"There is no notebook template named {name!r}; use one of {', '.join(NAMES)}.") + return str(name) + + +def starting(name: str) -> dict: + return {"procedure": _sections(_HEADINGS[name]), "observations": _sections(_OBSERVATIONS[name])} + + +def listing() -> list[dict]: + return [{"name": n, "label": LABELS[n], "headings": list(_HEADINGS[n])} for n in NAMES] diff --git a/backend/app/services/xtb/__init__.py b/backend/app/services/xtb/__init__.py new file mode 100644 index 00000000..bbf38a24 --- /dev/null +++ b/backend/app/services/xtb/__init__.py @@ -0,0 +1,37 @@ +HARTREE_KCAL = 627.509474 +EV_DIGITS = 4 +EH_DIGITS = 8 +XTB_HOME = "https://github.com/grimme-lab/xtb" +CREST_HOME = "https://github.com/crest-lab/crest" +LICENCE = "LGPL-3.0" +SETTING_XTB = "xtbPath" +SETTING_CREST = "crestPath" +SETTING_THREADS = "xtbThreads" +MAX_THREADS = 256 +METHODS = {"gfn2": "GFN2-xTB", "gfnff": "GFN-FF"} +OPT_LEVELS = ("crude", "sloppy", "loose", "lax", "normal", "tight", "vtight", "extreme") +XTB_LIMIT = 600 +CREST_LIMIT = 3600 +MAX_LIMIT = 7 * 24 * 3600 +TAIL_LINES = 20 + + +class XtbError(ValueError): + def __init__(self, message: str, status: int = 422): + super().__init__(message) + self.status = status + + +def method_of(value: object, default: str = "gfn2") -> str: + if value is None or value == "": + return default + if isinstance(value, str): + key = value.strip().lower().replace("-", "").replace("_", "").replace(" ", "") + for name, label in METHODS.items(): + if key in (name, label.lower().replace("-", "")): + return name + raise XtbError("method must be gfn2 (GFN2-xTB) or gfnff (GFN-FF)") + + +def kcal(hartree: float) -> float: + return hartree * HARTREE_KCAL diff --git a/backend/app/services/xtb/discovery.py b/backend/app/services/xtb/discovery.py new file mode 100644 index 00000000..920fdf28 --- /dev/null +++ b/backend/app/services/xtb/discovery.py @@ -0,0 +1,236 @@ +import os +import re +import shutil +import subprocess +import sys +import threading +import time +from dataclasses import asdict, dataclass, field +from pathlib import Path + +from app.core import config +from app.services.xtb import CREST_HOME, LICENCE, MAX_THREADS, SETTING_CREST, SETTING_THREADS, SETTING_XTB, XTB_HOME, XtbError + +PROGRAMS = { + "xtb": {"title": "xtb", "names": ("xtb",), "setting": SETTING_XTB, "home": XTB_HOME, + "version": re.compile(r"xtb\s+version\s+(\d+(?:\.\d+)+)", re.I)}, + "crest": {"title": "CREST", "names": ("crest",), "setting": SETTING_CREST, "home": CREST_HOME, + "version": re.compile(r"\bversion\s+(\d+(?:\.\d+)+)", re.I)}, +} +ANY_VERSION = re.compile(r"\b(\d+\.\d+(?:\.\d+)*)\b") +VERSION_WAIT = 15.0 +LIFE = 30.0 +_lock = threading.Lock() +_cache: dict[str, tuple[float, "Found"]] = {} + + +@dataclass +class Found: + program: str + title: str + path: str | None = None + how: str = "" + state: str = "missing" + version: str | None = None + banner: str = "" + message: str = "" + home: str = "" + licence: str = LICENCE + looked: list[str] = field(default_factory=list) + + def answer(self) -> dict: + return asdict(self) + + +def _windows() -> bool: + return sys.platform.startswith("win") + + +def _setting(key: str) -> str: + value = config.read_settings().get(key) + return value.strip() if isinstance(value, str) else "" + + +def threads() -> int: + value = config.read_settings().get(SETTING_THREADS) + if isinstance(value, int) and not isinstance(value, bool) and 1 <= value <= MAX_THREADS: + return value + return max(1, min(4, os.cpu_count() or 1)) + + +def settings() -> dict: + s = config.read_settings() + return {"xtb": _setting(SETTING_XTB), "crest": _setting(SETTING_CREST), + "threads": s.get(SETTING_THREADS) if isinstance(s.get(SETTING_THREADS), int) else None, "threadsUsed": threads()} + + +def save(patch: dict) -> dict: + out: dict = {} + for key, name in (("xtb", SETTING_XTB), ("crest", SETTING_CREST)): + if key in patch: + value = patch[key] + if value is not None and not isinstance(value, str): + raise ValueError(f"{key} must be a path or empty") + out[name] = (value or "").strip()[:4000] + if "threads" in patch: + value = patch["threads"] + if value is None or value == "": + out[SETTING_THREADS] = None + elif isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= MAX_THREADS: + raise ValueError(f"threads must be a whole number from 1 to {MAX_THREADS}, or empty for automatic") + else: + out[SETTING_THREADS] = value + if out: + config.write_settings(out) + forget() + return settings() + + +def forget() -> None: + with _lock: + _cache.clear() + + +def folders() -> list[Path]: + home = Path.home() + out: list[Path] = [] + for var in ("CONDA_PREFIX", "MAMBA_ROOT_PREFIX"): + if os.environ.get(var): + base = Path(os.environ[var]) + out += [base / "Library" / "bin", base / "Scripts"] if _windows() else [base / "bin"] + for name in ("miniforge3", "mambaforge", "miniconda3", "anaconda3", "micromamba"): + out.append(home / name / ("Library/bin" if _windows() else "bin")) + if _windows(): + local = Path(os.environ.get("LOCALAPPDATA") or home / "AppData" / "Local") + out += [local / "Programs" / "xtb" / "bin", local / "Programs" / "crest", home / "xtb" / "bin"] + return list(dict.fromkeys(out)) + out += [home / ".local" / "bin", home / "bin", home / "xtb" / "bin", home / ".local" / "xtb" / "bin", Path("/opt/conda/bin"), + Path("/opt/homebrew/bin"), Path("/usr/local/bin"), Path("/opt/local/bin"), Path("/usr/bin")] + return list(dict.fromkeys(out)) + + +def _runnable(path: Path) -> bool: + return path.is_file() and (_windows() or os.access(path, os.X_OK)) + + +def _candidates(program: str) -> list[tuple[str, Path]]: + spec = PROGRAMS[program] + endings = (".exe", ".bat", ".cmd", "") if _windows() else ("",) + out: list[tuple[str, Path]] = [] + for name in spec["names"]: + hit = shutil.which(name) + if hit: + out.append(("path", Path(hit))) + out += [("folder", folder / (name + ending)) for folder in folders() for name in spec["names"] for ending in endings] + return out + + +def version_of(path: str, program: str) -> tuple[str | None, str, str]: + try: + done = subprocess.run([path, "--version"], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + timeout=VERSION_WAIT, env=child_env(1), **hidden()) + except subprocess.TimeoutExpired: + return None, "", f"did not answer --version within {VERSION_WAIT:.0f} s" + except OSError as exc: + return None, "", f"could not start: {exc.strerror or exc}" + text = done.stdout.decode("utf-8", "replace") + found = PROGRAMS[program]["version"].search(text) + if found: + return found.group(1), _line_of(text, found.start()), "" + loose = ANY_VERSION.search(text) + if loose and program.lower() in text.lower(): + return loose.group(1), _line_of(text, loose.start()), "" + return None, text.strip().splitlines()[-1][:200] if text.strip() else "", f"--version gave no {PROGRAMS[program]['title']} version line (exit code {done.returncode})" + + +def _line_of(text: str, at: int) -> str: + start = text.rfind("\n", 0, at) + 1 + end = text.find("\n", at) + return text[start:end if end >= 0 else len(text)].strip()[:200] + + +def hidden() -> dict: + return {"creationflags": getattr(subprocess, "CREATE_NO_WINDOW", 0)} if _windows() else {} + + +def child_env(n: int) -> dict: + env = dict(os.environ) + env.update({"OMP_NUM_THREADS": f"{n},1", "MKL_NUM_THREADS": str(n), "OPENBLAS_NUM_THREADS": str(n), "OMP_MAX_ACTIVE_LEVELS": "1"}) + env.setdefault("OMP_STACKSIZE", "1G") + return env + + +def _missing(found: Found) -> str: + spec = PROGRAMS[found.program] + return (f"{spec['title']} was not found. FormChem does not include or download it ({LICENCE}): install it from {spec['home']}, " + f"then put it on PATH or set its path in Preferences > 3D.") + + +def find(program: str, fresh: bool = False) -> Found: + if program not in PROGRAMS: + raise KeyError(program) + with _lock: + hit = _cache.get(program) + if hit and not fresh and hit[1].state == "runs" and time.monotonic() - hit[0] < LIFE: + return hit[1] + found = _locate(program) + with _lock: + _cache[program] = (time.monotonic(), found) + return found + + +def _locate(program: str) -> Found: + spec = PROGRAMS[program] + found = Found(program, spec["title"], home=spec["home"]) + chosen = _setting(spec["setting"]) + if chosen: + p = Path(chosen).expanduser() + found.looked.append(str(p)) + if p.is_dir(): + inside = [p / (name + e) for name in spec["names"] for e in ((".exe", "") if _windows() else ("",))] + p = next((c for c in inside if _runnable(c)), p) + if not _runnable(p): + found.state = "bad_setting" + found.path = str(p) + found.how = "setting" + found.message = (f"The {spec['title']} path in Preferences > 3D ({p}) is not a program that can run: correct it, or clear it to search PATH. " + f"FormChem does not include or download {spec['title']} ({LICENCE}); it is available from {spec['home']}.") + return found + return _checked(found, str(p), "setting") + seen: set[str] = set() + for how, p in _candidates(program): + key = os.path.normcase(str(p)) + if key in seen: + continue + seen.add(key) + found.looked.append(str(p)) + if _runnable(p): + return _checked(found, str(p), how) + found.message = _missing(found) + return found + + +def _checked(found: Found, path: str, how: str) -> Found: + found.path, found.how = path, how + version, banner, error = version_of(path, found.program) + found.version, found.banner = version, banner + if version: + found.state = "runs" + found.message = f"{found.title} {version} at {path}" + else: + found.state = "broken" + found.message = f"{found.title} at {path} {error}." + return found + + +def usable(program: str) -> Found: + found = find(program) + if found.state != "runs": + found = find(program, fresh=True) + if found.state != "runs": + raise XtbError(found.message, 424) + return found + + +def status(fresh: bool = False) -> dict: + return {key: find(key, fresh).answer() for key in PROGRAMS} diff --git a/backend/app/services/xtb/inputs.py b/backend/app/services/xtb/inputs.py new file mode 100644 index 00000000..f8c3079a --- /dev/null +++ b/backend/app/services/xtb/inputs.py @@ -0,0 +1,87 @@ +from dataclasses import dataclass, field + +from rdkit import Chem + +from app.services.three_d import ThreeDError, build, molecule +from app.services.xtb import XtbError + +MAX_CHARGE = 20 +MAX_UHF = 30 + + +@dataclass +class Start: + model: molecule.Model + symbols: list[str] + geometries: list[list[tuple[float, float, float]]] + ids: list[str | None] + built: bool + charge: int + uhf: int + electrons: int + warnings: list[dict] = field(default_factory=list) + + +def _points(model: molecule.Model, conf_id: int) -> list[tuple[float, float, float]]: + return [tuple(float(v) for v in p) for p in model.mol.GetConformer(conf_id).GetPositions()] + + +def start(frag: dict, expansions: dict | None, scope: str = "shown", cid: str | None = None) -> Start: + try: + stored = [c for c in frag.get("conformers") or [] if isinstance(c, dict)] + if stored: + model = molecule.prepare(frag, expansions) + chosen = stored if scope == "all" else [molecule.find_conformer(frag, cid)] + geometries = [molecule.positions(model, c) for c in chosen] + ids: list[str | None] = [c.get("id") for c in chosen] + built, notes = False, [] + else: + made = build.build(frag, expansions, True, "MMFF94") + model = made["model"] + geometries, ids, built = [_points(model, made["conf_id"])], [None], True + notes = list(made["report"]["warnings"]) + except ThreeDError as exc: + raise XtbError(str(exc), exc.status) from exc + mol = model.mol + symbols = [a.GetSymbol() for a in mol.GetAtoms()] + electrons = sum(a.GetAtomicNum() for a in mol.GetAtoms()) + charge = Chem.GetFormalCharge(mol) + uhf = sum(a.GetNumRadicalElectrons() for a in mol.GetAtoms()) + return Start(model, symbols, geometries, ids, built, charge, uhf, electrons, notes) + + +def electrons_check(start: Start, charge: int, uhf: int) -> None: + if not -MAX_CHARGE <= charge <= MAX_CHARGE: + raise XtbError(f"charge must be a whole number from {-MAX_CHARGE} to {MAX_CHARGE}") + if not 0 <= uhf <= MAX_UHF: + raise XtbError(f"unpaired electrons must be a whole number from 0 to {MAX_UHF}") + n = start.electrons - charge + if n < uhf: + raise XtbError(f"With charge {charge} the structure has {n} electrons, fewer than {uhf} unpaired.") + if (n - uhf) % 2: + want = "an odd" if n % 2 else "an even" + raise XtbError(f"With charge {charge} the structure has {n} electrons, so the number of unpaired electrons must be {want} number.") + + +def xyz(symbols: list[str], points: list[tuple[float, float, float]], comment: str = "") -> str: + rows = [f"{len(symbols)}", comment.replace("\n", " ")[:200]] + rows += [f"{s:<2} {x:16.10f} {y:16.10f} {z:16.10f}" for s, (x, y, z) in zip(symbols, points)] + return "\n".join(rows) + "\n" + + +def xtb_argv(path: str, name: str, task: str, method: str, charge: int, uhf: int, solvent: str | None, threads: int, level: str) -> list[str]: + argv = [path, name] + argv += ["--gfnff"] if method == "gfnff" else ["--gfn", "2"] + if task == "opt": + argv += ["--opt", level] + argv += ["--chrg", str(charge), "--uhf", str(uhf)] + if solvent: + argv += ["--alpb", solvent] + return argv + ["-P", str(threads)] + + +def crest_argv(path: str, name: str, method: str, charge: int, uhf: int, solvent: str | None, ewin: float, threads: int) -> list[str]: + argv = [path, name, "--gfnff" if method == "gfnff" else "--gfn2", "--chrg", str(charge), "--uhf", str(uhf), "--ewin", f"{ewin:g}"] + if solvent: + argv += ["--alpb", solvent] + return argv + ["-T", str(threads)] diff --git a/backend/app/services/xtb/jobs.py b/backend/app/services/xtb/jobs.py new file mode 100644 index 00000000..e0270167 --- /dev/null +++ b/backend/app/services/xtb/jobs.py @@ -0,0 +1,308 @@ +import asyncio +import os +import shutil +import tempfile +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Awaitable, Callable + +from app.services.three_d import warning +from app.services.xtb import CREST_LIMIT, MAX_LIMIT, METHODS, OPT_LEVELS, XTB_LIMIT, XtbError, discovery, inputs, method_of, parse, runner, solvents, writeback +from app.services.xtb.inputs import Start + +KINDS = {"optimise": "xtb", "single": "xtb", "crest": "crest"} +TITLES = {"optimise": "xtb optimisation", "single": "xtb single point", "crest": "CREST conformer search"} +MAX_RUNNING = 1 +KEEP_JOBS = 50 +FORGET_AFTER = 3600.0 +MAX_KEEP = 200 +INPUT = "input.xyz" + +Apply = Callable[[list[dict], str | None], Awaitable[dict]] +_jobs: dict[str, "Job"] = {} +_gate: dict[int, asyncio.Semaphore] = {} +_count = [0] + + +@dataclass +class Options: + kind: str + method: str = "gfn2" + charge: int = 0 + uhf: int = 0 + solvent: str | None = None + level: str = "normal" + ewin: float = 6.0 + keep: int = 20 + threads: int = 1 + limit: float = XTB_LIMIT + + +@dataclass +class Job: + id: str + kind: str + doc: str + object: str + options: Options + start: Start + found: discovery.Found + apply: Apply + agent: str | None = None + state: str = "queued" + stage: str = "" + cycle: int | None = None + step: int = 0 + steps: int = 1 + total: int = 0 + created: float = field(default_factory=time.time) + began: float | None = None + ended: float | None = None + tail: list[str] = field(default_factory=list) + error: str = "" + folder: str | None = None + command: str = "" + table: list[dict] = field(default_factory=list) + report: dict = field(default_factory=dict) + changed: dict = field(default_factory=dict) + cancel: threading.Event = field(default_factory=threading.Event) + finished: asyncio.Event = field(default_factory=asyncio.Event) + + @property + def program(self) -> dict: + o = self.options + return writeback.program(self.found.title, self.found.version, o.method, o.solvent, o.charge, o.uhf) + + def public(self) -> dict: + now = self.ended or time.time() + prog = self.program + return { + "id": self.id, "kind": self.kind, "title": TITLES[self.kind], "state": self.state, "doc": self.doc, "object": self.object, + "program": prog, "label": writeback.label(prog), "path": self.found.path, + "options": {"method": self.options.method, "charge": self.options.charge, "uhf": self.options.uhf, "solvent": self.options.solvent, + "level": self.options.level if self.kind == "optimise" else None, "ewin": self.options.ewin if self.kind == "crest" else None, + "threads": self.options.threads, "limit": self.options.limit}, + "elapsed": round(now - (self.began or now), 1), "limit": self.options.limit, "stage": self.stage, "cycle": self.cycle, + "step": self.step, "steps": self.steps, "tail": self.tail, "error": self.error, "folder": self.folder, "command": self.command, + "conformers": self.table, "report": self.report, **self.changed, + } + + +def options(kind: str, body: dict, start: Start) -> Options: + def whole(key: str, default: int, low: int, high: int) -> int: + value = body.get(key, default) + if value is None: + value = default + if isinstance(value, str): + try: + value = float(value) + except ValueError: + raise XtbError(f"{key} must be a whole number") + if isinstance(value, bool) or not isinstance(value, (int, float)) or int(value) != value or not low <= value <= high: + raise XtbError(f"{key} must be a whole number from {low} to {high}") + return int(value) + + def number(key: str, default: float, low: float, high: float) -> float: + value = body.get(key, default) + if value is None: + value = default + try: + value = float(value) + except (TypeError, ValueError): + raise XtbError(f"{key} must be a number from {low} to {high}") + if isinstance(body.get(key), bool) or not low <= value <= high: + raise XtbError(f"{key} must be a number from {low} to {high}") + return value + + method = method_of(body.get("method")) + level = body.get("level") or "normal" + if level not in OPT_LEVELS: + raise XtbError(f"level must be one of {', '.join(OPT_LEVELS)}") + o = Options(kind, method, whole("charge", start.charge, -inputs.MAX_CHARGE, inputs.MAX_CHARGE), whole("uhf", start.uhf, 0, inputs.MAX_UHF), + solvents.solvent_of(body.get("solvent")), level, number("ewin", 6.0, 0.1, 100.0), whole("keep", 20, 1, MAX_KEEP), + whole("threads", discovery.threads(), 1, 256), number("limit", CREST_LIMIT if kind == "crest" else XTB_LIMIT, 1, MAX_LIMIT)) + inputs.electrons_check(start, o.charge, o.uhf) + return o + + +def _gate_for_loop() -> asyncio.Semaphore: + loop = asyncio.get_running_loop() + gate = _gate.get(id(loop)) + if gate is None: + gate = _gate[id(loop)] = asyncio.Semaphore(MAX_RUNNING) + return gate + + +def _prune() -> None: + now = time.time() + done = [j for j in _jobs.values() if j.state not in ("queued", "running")] + for j in done: + if now - (j.ended or now) > FORGET_AFTER or len(_jobs) > KEEP_JOBS: + _jobs.pop(j.id, None) + if j.folder: + shutil.rmtree(j.folder, ignore_errors=True) + + +def submit(kind: str, doc: str, fid: str, start: Start, opts: Options, found: discovery.Found, apply: Apply, agent: str | None = None) -> Job: + _prune() + _count[0] += 1 + job = Job(f"x{int(time.time() * 1000):x}{_count[0]:03d}", kind, doc, fid, opts, start, found, apply, agent) + job.steps = len(start.geometries) if kind != "crest" else 1 + _jobs[job.id] = job + asyncio.get_running_loop().create_task(_drive(job)) + return job + + +def get(job_id: str) -> Job: + job = _jobs.get(job_id) + if job is None: + raise XtbError(f"No xtb or CREST job has the id {job_id}.", 404) + return job + + +def listing() -> list[dict]: + return [j.public() for j in sorted(_jobs.values(), key=lambda j: j.created, reverse=True)] + + +def cancel(job_id: str) -> Job: + job = get(job_id) + job.cancel.set() + if job.state == "queued": + _end(job, "cancelled", "Cancelled before it started.") + return job + + +def _end(job: Job, state: str, error: str = "") -> None: + if job.state in ("done", "failed", "cancelled", "timeout"): + return + job.state, job.error, job.ended = state, error, time.time() + if job.folder and state != "failed": + shutil.rmtree(job.folder, ignore_errors=True) + job.folder = None + job.finished.set() + + +def _env(job: Job) -> dict: + env = discovery.child_env(job.options.threads) + if job.kind == "crest": + xtb = discovery.find("xtb") + if xtb.state == "runs" and xtb.path: + env["PATH"] = os.pathsep.join([str(Path(xtb.path).parent), env.get("PATH", "")]) + return env + + +def _argv(job: Job, path: str) -> list[str]: + o = job.options + if job.kind == "crest": + return inputs.crest_argv(path, INPUT, o.method, o.charge, o.uhf, o.solvent, o.ewin, o.threads) + return inputs.xtb_argv(path, INPUT, "opt" if job.kind == "optimise" else "sp", o.method, o.charge, o.uhf, o.solvent, o.threads, o.level) + + +def _on_line(job: Job) -> Callable[[str], None]: + def seen(line: str) -> None: + text = line.strip() + if not text or set(text) <= set(".-=|* "): + return + n = parse.xtb_progress(text) + if n is not None: + job.cycle = n + job.stage = text.strip(".-=|*: ")[:160] + return seen + + +async def _drive(job: Job) -> None: + async with _gate_for_loop(): + if job.cancel.is_set(): + _end(job, "cancelled", "Cancelled before it started.") + return + job.state, job.began = "running", time.time() + try: + job.folder = tempfile.mkdtemp(prefix="formchem-xtb-") + results = await _run_all(job) + if results is None: + return + await _finish(job, results) + except XtbError as exc: + _end(job, "failed", str(exc)) + except Exception as exc: + _end(job, "failed", f"The job stopped: {exc}") + + +async def _run_all(job: Job) -> list[writeback.Result] | None: + deadline = time.monotonic() + job.options.limit + out: list[writeback.Result] = [] + geometries = job.start.geometries if job.kind != "crest" else job.start.geometries[:1] + for k, points in enumerate(geometries): + job.step, job.cycle = k + 1, None + folder = Path(job.folder) / f"{k + 1:03d}" + folder.mkdir() + (folder / INPUT).write_text(inputs.xyz(job.start.symbols, points, f"FormChem {job.object}"), encoding="utf-8") + argv = _argv(job, job.found.path or job.found.title) + job.command = " ".join([Path(argv[0]).name, *argv[1:]]) + proc = runner.Process(argv, folder, _env(job), max(0.5, deadline - time.monotonic()), _on_line(job)) + outcome = await asyncio.to_thread(proc.run, job.cancel) + job.tail = proc.tail() + if outcome.state == "cancelled": + _end(job, "cancelled", "Cancelled; the drawing was not changed.") + return None + if outcome.state == "timeout": + _end(job, "timeout", f"Stopped at the time limit of {job.options.limit:g} s; the drawing was not changed.") + return None + if outcome.state != "done": + code = f"exit code {outcome.code}" if outcome.code is not None else "it did not start" + _end(job, "failed", f"{job.found.title} stopped with {code}; its last lines are below.") + return None + out += await asyncio.to_thread(_collect, job, folder, points, proc.output(), job.start.ids[k] if k < len(job.start.ids) else None) + return out + + +def _collect(job: Job, folder: Path, points: list, log: str, source: str | None) -> list[writeback.Result]: + if job.kind == "crest": + frames = parse.read_xyz(parse.read_text(folder / "crest_conformers.xyz"), "crest_conformers.xyz") + if any(f.energy is None for f in frames) and (folder / "crest.energies").is_file(): + rows = parse.crest_energies(parse.read_text(folder / "crest.energies")) + for f, row in zip(frames, rows): + if f.energy is None and row[1] is not None: + f.energy = row[1] + job.total = len(frames) + return [writeback.Result(f.symbols, f.points, f.energy, None) for f in frames[:job.options.keep]] + summary = parse.xtb_output(log) + if job.kind == "single": + if summary.energy is None: + raise XtbError("xtb finished without a TOTAL ENERGY line.", 502) + return [writeback.Result(job.start.symbols, points, summary.energy, None, summary.gap, source)] + frame = parse.read_xyz(parse.read_text(folder / "xtbopt.xyz"), "xtbopt.xyz")[-1] + converged = summary.converged + if converged is None: + converged = True if (folder / ".xtboptok").exists() else False if (folder / "NOT_CONVERGED").exists() else None + energy = summary.energy if summary.energy is not None else frame.energy + if energy is None: + raise XtbError("xtb finished without a total energy.", 502) + return [writeback.Result(frame.symbols, frame.points, energy, converged, summary.gap, source)] + + +async def _finish(job: Job, results: list[writeback.Result]) -> None: + prog = job.program + records, table, notes = await asyncio.to_thread(writeback.records, job.start, results, prog, job.kind == "crest") + warnings = list(job.start.warnings) + notes + if job.start.built: + warnings.append(warning("built_first", "The structure had no 3D coordinates, so ETKDGv3+MMFF94 built a start geometry first.")) + if any(r.converged is False for r in results): + warnings.append(warning("not_converged", "The geometry optimisation did not converge within xtb's cycle limit; try a looser level or a better start.")) + if job.kind == "crest" and job.total > len(results): + warnings.append(warning("ensemble_cut", f"CREST found {job.total} conformers; the lowest {len(results)} were kept (keep).")) + job.report = {"program": prog, "label": writeback.label(prog), "engine": f"{prog['name']} {prog['version']}", "method": METHODS[job.options.method], + "solvent": prog["solvent"], "warnings": warnings, "built": job.start.built, "kept": len(records), "found": job.total or len(results), + "command": job.command, + "populations": writeback.population_note(), "seconds": round(time.time() - (job.began or time.time()), 1)} + job.table = table + job.stage = "Writing the conformers into the drawing" + job.changed = await job.apply(records, records[0]["id"] if records else None) + _end(job, "done") + + +async def wait(job: Job) -> Job: + await job.finished.wait() + return job diff --git a/backend/app/services/xtb/parse.py b/backend/app/services/xtb/parse.py new file mode 100644 index 00000000..256a514c --- /dev/null +++ b/backend/app/services/xtb/parse.py @@ -0,0 +1,156 @@ +import math +import re +from dataclasses import dataclass, field +from pathlib import Path + +from app.services.xtb import XtbError + +NUMBER = r"([-+]?\d+\.\d+(?:[eEdD][-+]?\d+)?)" +TOTAL = re.compile(r"\|\s*TOTAL ENERGY\s+" + NUMBER + r"\s+Eh") +GAP = re.compile(r"\|\s*HOMO-LUMO GAP\s+" + NUMBER + r"\s+eV") +GNORM = re.compile(r"\|\s*GRADIENT NORM\s+" + NUMBER) +CONVERGED = re.compile(r"GEOMETRY OPTIMIZATION CONVERGED AFTER\s+(\d+)\s+ITERATIONS") +FAILED = re.compile(r"FAILED TO CONVERGE GEOMETRY OPTIMIZATION(?:\s+IN\s+(\d+)\s+ITERATIONS)?") +CYCLE = re.compile(r"\.{3,}\s*CYCLE\s+(\d+)\s*\.{3,}") +VERSION = re.compile(r"xtb\s+version\s+(\d+(?:\.\d+)+)", re.I) +COMMENT_ENERGY = re.compile(r"energy:\s*" + NUMBER, re.I) +FIRST_NUMBER = re.compile(NUMBER) +ABNORMAL = ("abnormal termination", "[ERROR]", "#ERROR") + + +@dataclass +class Frame: + symbols: list[str] + points: list[tuple[float, float, float]] + comment: str = "" + energy: float | None = None + + +@dataclass +class XtbSummary: + energy: float | None = None + gap: float | None = None + gradient_norm: float | None = None + converged: bool | None = None + iterations: int | None = None + cycles: int = 0 + normal: bool = False + errors: list[str] = field(default_factory=list) + + +def _float(text: str) -> float: + value = float(text.replace("D", "E").replace("d", "e")) + if not math.isfinite(value): + raise ValueError(text) + return value + + +def symbol(raw: str) -> str: + text = raw.strip() + if text.isdigit(): + from rdkit import Chem + return Chem.GetPeriodicTable().GetElementSymbol(int(text)) + letters = re.match(r"[A-Za-z]+", text) + if not letters: + raise ValueError(raw) + word = letters.group(0) + return word[0].upper() + word[1:2].lower() + + +def read_xyz(text: str, name: str = "xyz file") -> list[Frame]: + lines = text.splitlines() + frames: list[Frame] = [] + i = 0 + while i < len(lines): + head = lines[i].strip() + if not head: + i += 1 + continue + try: + n = int(head.split()[0]) + except ValueError: + raise XtbError(f"{name} line {i + 1}: expected an atom count, found {head[:40]!r}") + if n <= 0 or i + 2 + n > len(lines): + raise XtbError(f"{name} line {i + 1}: the file ends before {n} atoms") + comment = lines[i + 1] + symbols, points = [], [] + for k in range(n): + row = lines[i + 2 + k].split() + try: + symbols.append(symbol(row[0])) + points.append((_float(row[1]), _float(row[2]), _float(row[3]))) + except (IndexError, ValueError): + raise XtbError(f"{name} line {i + 3 + k}: expected an element and three coordinates") + frames.append(Frame(symbols, points, comment.strip(), comment_energy(comment))) + i += 2 + n + if not frames: + raise XtbError(f"{name} holds no structure") + return frames + + +def comment_energy(comment: str) -> float | None: + found = COMMENT_ENERGY.search(comment) or FIRST_NUMBER.match(comment.strip()) + if not found: + return None + try: + return _float(found.group(1)) + except ValueError: + return None + + +def xtb_output(text: str) -> XtbSummary: + out = XtbSummary() + totals = TOTAL.findall(text) + if totals: + out.energy = _float(totals[-1]) + gaps = GAP.findall(text) + if gaps: + out.gap = _float(gaps[-1]) + norms = GNORM.findall(text) + if norms: + out.gradient_norm = _float(norms[-1]) + done = CONVERGED.search(text) + failed = FAILED.search(text) + if done: + out.converged, out.iterations = True, int(done.group(1)) + elif failed: + out.converged = False + out.iterations = int(failed.group(1)) if failed.group(1) else None + out.cycles = len(CYCLE.findall(text)) + out.normal = "normal termination of xtb" in text + out.errors = [line.strip() for line in text.splitlines() if any(mark in line for mark in ABNORMAL)][:10] + return out + + +def xtb_progress(line: str) -> int | None: + found = CYCLE.search(line) + return int(found.group(1)) if found else None + + +def crest_energies(text: str) -> list[tuple[int, float | None, float]]: + rows: list[tuple[int, float | None, float]] = [] + for n, line in enumerate(text.splitlines(), 1): + parts = line.split() + if not parts: + continue + try: + index = int(parts[0]) + values = [_float(p) for p in parts[1:]] + except ValueError: + raise XtbError(f"crest.energies line {n}: expected a conformer number and its energies") + if not values: + raise XtbError(f"crest.energies line {n}: no energy") + absolute = values[0] if len(values) >= 2 else None + rows.append((index, absolute, values[-1])) + return rows + + +def read_text(path: Path, limit: int = 256 * 1024 * 1024) -> str: + try: + if path.stat().st_size > limit: + raise XtbError(f"{path.name} is larger than {limit // (1024 * 1024)} MB") + return path.read_text(encoding="utf-8", errors="replace") + except FileNotFoundError: + raise XtbError(f"The program wrote no {path.name}.", 502) + except OSError as exc: + raise XtbError(f"{path.name} could not be read: {exc.strerror or exc}", 502) diff --git a/backend/app/services/xtb/runner.py b/backend/app/services/xtb/runner.py new file mode 100644 index 00000000..5e50bbb1 --- /dev/null +++ b/backend/app/services/xtb/runner.py @@ -0,0 +1,146 @@ +import atexit +import os +import signal +import subprocess +import sys +import threading +import time +from collections import deque +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +from app.services.xtb import TAIL_LINES + +POLL = 0.2 +GRACE = 3.0 +LOG = "output.log" +_live: set["Process"] = set() +_live_lock = threading.Lock() + + +@dataclass +class Outcome: + state: str + code: int | None + seconds: float + + +def _windows() -> bool: + return sys.platform.startswith("win") + + +class Process: + def __init__(self, argv: list[str], cwd: Path, env: dict, limit: float, on_line: Callable[[str], None] | None = None, log: str = LOG): + self.argv, self.cwd, self.env, self.limit = argv, cwd, env, limit + self.on_line = on_line + self.log = cwd / log + self.lines: deque[str] = deque(maxlen=TAIL_LINES) + self.proc: subprocess.Popen | None = None + self._offset = 0 + self._partial = "" + + def run(self, cancel: threading.Event) -> Outcome: + start = time.monotonic() + with open(self.log, "wb") as out: + try: + self.proc = subprocess.Popen(self.argv, cwd=self.cwd, env=self.env, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT, + **self._group()) + except OSError as exc: + self.lines.append(f"could not start {self.argv[0]}: {exc.strerror or exc}") + return Outcome("failed", None, 0.0) + with _live_lock: + _live.add(self) + try: + while True: + code = self.proc.poll() + self._read() + if code is not None: + return Outcome("done" if code == 0 else "failed", code, time.monotonic() - start) + if cancel.is_set(): + self.stop() + return Outcome("cancelled", self.proc.returncode, time.monotonic() - start) + if time.monotonic() - start > self.limit: + self.stop() + return Outcome("timeout", self.proc.returncode, time.monotonic() - start) + cancel.wait(POLL) + finally: + self._read(final=True) + with _live_lock: + _live.discard(self) + + def _group(self) -> dict: + if _windows(): + return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP | getattr(subprocess, "CREATE_NO_WINDOW", 0)} + return {"start_new_session": True} + + def stop(self) -> None: + proc = self.proc + if proc is None or proc.poll() is not None: + return + if _windows(): + subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + else: + self._signal(proc, signal.SIGTERM) + try: + proc.wait(GRACE) + return + except subprocess.TimeoutExpired: + self._signal(proc, signal.SIGKILL) + try: + proc.wait(GRACE) + except subprocess.TimeoutExpired: + proc.kill() + + @staticmethod + def _signal(proc: subprocess.Popen, sig: int) -> None: + try: + os.killpg(proc.pid, sig) + except (ProcessLookupError, PermissionError): + try: + proc.send_signal(sig) + except ProcessLookupError: + pass + + def _read(self, final: bool = False) -> None: + try: + with open(self.log, "rb") as f: + f.seek(self._offset) + chunk = f.read() + self._offset += len(chunk) + except OSError: + return + if not chunk and not (final and self._partial): + return + text = self._partial + chunk.decode("utf-8", "replace").replace("\r\n", "\n").replace("\r", "\n") + parts = text.split("\n") + self._partial = "" if final else parts.pop() + for line in parts: + if not line.strip(): + continue + self.lines.append(line.rstrip()[:400]) + if self.on_line: + try: + self.on_line(line) + except Exception: + pass + + def tail(self) -> list[str]: + return list(self.lines) + + def output(self) -> str: + try: + return self.log.read_text(encoding="utf-8", errors="replace") + except OSError: + return "" + + +def stop_all() -> None: + with _live_lock: + running = list(_live) + for p in running: + p.stop() + + +atexit.register(stop_all) diff --git a/backend/app/services/xtb/solvents.py b/backend/app/services/xtb/solvents.py new file mode 100644 index 00000000..3e9485ed --- /dev/null +++ b/backend/app/services/xtb/solvents.py @@ -0,0 +1,51 @@ +from app.services.xtb import XtbError + +ALPB: tuple[tuple[str, str], ...] = ( + ("acetone", "Acetone"), + ("acetonitrile", "Acetonitrile"), + ("aniline", "Aniline"), + ("benzaldehyde", "Benzaldehyde"), + ("benzene", "Benzene"), + ("ch2cl2", "Dichloromethane"), + ("chcl3", "Chloroform"), + ("cs2", "Carbon disulfide"), + ("dioxane", "1,4-Dioxane"), + ("dmf", "N,N-Dimethylformamide"), + ("dmso", "Dimethyl sulfoxide"), + ("ether", "Diethyl ether"), + ("ethylacetate", "Ethyl acetate"), + ("furane", "Furan"), + ("hexandecane", "Hexadecane"), + ("hexane", "n-Hexane"), + ("methanol", "Methanol"), + ("nitromethane", "Nitromethane"), + ("octanol", "1-Octanol"), + ("woctanol", "1-Octanol (wet)"), + ("phenol", "Phenol"), + ("toluene", "Toluene"), + ("thf", "Tetrahydrofuran"), + ("water", "Water"), +) +NAMES = {key: label for key, label in ALPB} +ALIASES = {"dcm": "ch2cl2", "dichloromethane": "ch2cl2", "chloroform": "chcl3", "dimethylsulfoxide": "dmso", "diethylether": "ether", + "furan": "furane", "hexadecane": "hexandecane", "tetrahydrofuran": "thf", "h2o": "water", "meoh": "methanol", "etoac": "ethylacetate", + "mecn": "acetonitrile", "acn": "acetonitrile"} + + +def solvent_of(value: object) -> str | None: + if value is None or value == "" or value == "none" or value is False: + return None + if isinstance(value, str): + key = value.strip().lower().replace(" ", "").replace("-", "").replace(",", "") + key = ALIASES.get(key, key) + if key in NAMES: + return key + raise XtbError(f"solvent must be one of {', '.join(NAMES)} (ALPB), or none for the gas phase") + + +def label(key: str | None) -> str: + return f"ALPB ({NAMES[key]})" if key else "gas phase" + + +def listing() -> list[dict]: + return [{"id": key, "label": name} for key, name in ALPB] diff --git a/backend/app/services/xtb/writeback.py b/backend/app/services/xtb/writeback.py new file mode 100644 index 00000000..12960853 --- /dev/null +++ b/backend/app/services/xtb/writeback.py @@ -0,0 +1,68 @@ +from dataclasses import dataclass + +from app.services.three_d import TEMPERATURE, molecule, rounded, verify, warning +from app.services.three_d.conformers import populations +from app.services.xtb import EH_DIGITS, EV_DIGITS, METHODS, XtbError, kcal, solvents +from app.services.xtb.inputs import Start + +CONFORMER_METHOD = "xtb" + + +@dataclass +class Result: + symbols: list[str] + points: list[tuple[float, float, float]] + energy: float | None + converged: bool | None = None + gap: float | None = None + source: str | None = None + + +def program(name: str, version: str | None, method: str, solvent: str | None, charge: int, uhf: int) -> dict: + return {"name": name, "version": version or "unknown", "method": METHODS[method], "solvent": solvents.label(solvent), + "charge": charge, "uhf": uhf} + + +def label(prog: dict) -> str: + return f"{prog['name']} {prog['version']}, {prog['method']}, {prog['solvent']}" + + +def records(start: Start, results: list[Result], prog: dict, drop_lost: bool = False) -> tuple[list[dict], list[dict], list[dict]]: + model = start.model + want = verify.expected(model) + rows: list[tuple[float, dict, Result]] = [] + lost, notes = 0, [] + for k, res in enumerate(results): + if res.symbols != start.symbols: + how = "in another order" if len(res.symbols) == len(start.symbols) else f"{len(res.symbols)} atoms for {len(start.symbols)}" + raise XtbError(f"{prog['name']} returned the atoms {how}, so the result cannot be mapped back onto the structure.", 502) + cid = molecule.add_conformer(model, res.points) + if not verify.stereo(model, cid, want)["kept"]: + lost += 1 + if drop_lost: + continue + energy = kcal(res.energy) if res.energy is not None else None + rec = molecule.record(model, cid, CONFORMER_METHOD, energy, res.converged, cid=res.source) + rec["program"] = {**prog, "energy_eh": round(res.energy, EH_DIGITS) if res.energy is not None else None, + **({"gap_ev": round(res.gap, EV_DIGITS)} if res.gap is not None else {})} + rows.append((energy if energy is not None else float("inf"), rec, res)) + if lost: + text = (f"{lost} conformer(s) from {prog['name']} changed the drawn stereo and were left out." if drop_lost + else f"{lost} result(s) from {prog['name']} no longer match the drawn stereo; check the structure.") + notes.append(warning("stereo_dropped" if drop_lost else "stereo_changed", text)) + if not rows: + raise XtbError(f"Every conformer from {prog['name']} changed the drawn stereo; nothing was kept.", 409) + rows.sort(key=lambda r: r[0]) + finite = [r[0] for r in rows if r[0] != float("inf")] + low = min(finite) if finite else None + pops = populations(finite) if len(finite) == len(rows) else [None] * len(rows) + table = [] + for (energy, rec, res), pop in zip(rows, pops): + table.append({"id": rec["id"], "energy": rec.get("energy"), "relative": rounded(energy - low) if low is not None and energy != float("inf") else None, + "energy_eh": rec["program"]["energy_eh"], "gap_ev": rec["program"].get("gap_ev"), "converged": res.converged, + "population": round(pop, 4) if pop is not None else None, "method": CONFORMER_METHOD, "label": label(prog)}) + return [r[1] for r in rows], table, notes + + +def population_note() -> str: + return f"Boltzmann populations at {TEMPERATURE} K over the kept conformers" diff --git a/docs/3D.md b/docs/3D.md index de2fae2d..666b2fb6 100644 --- a/docs/3D.md +++ b/docs/3D.md @@ -1,6 +1,6 @@ # FormChem in 3D -How FormChem builds 3D structures from drawings, searches conformers, minimises, scans dihedrals, measures, draws surfaces, reads PDB, mmCIF and 3D SD files, extracts ligands and exports 3D files, built from 0.10.0. What a drawing stores (a fragment's `conformers` and `conformer`, and the `model3d` object) is defined in [FORMAT.md](FORMAT.md), which wins over this page; this page describes the services behind the 3D menu, the 3D View panel and the agent tools, and their HTTP routes. +How FormChem builds 3D structures from drawings, searches conformers, minimises, scans dihedrals, measures, draws surfaces, reads PDB, mmCIF and 3D SD files, extracts ligands and exports 3D files, built from 0.10.0, and how it runs xtb and CREST when you have installed them, from 0.12.0. What a drawing stores (a fragment's `conformers` and `conformer`, and the `model3d` object) is defined in [FORMAT.md](FORMAT.md), which wins over this page; this page describes the services behind the 3D menu, the 3D View panel and the agent tools, and their HTTP routes. ## Contents @@ -18,6 +18,7 @@ How FormChem builds 3D structures from drawings, searches conformers, minimises, - 3D objects on the page - Exports - Methods, versions and accuracy +- xtb and CREST (0.12.0) - HTTP API - Agent tools - Known limits @@ -34,8 +35,10 @@ How FormChem builds 3D structures from drawings, searches conformers, minimises, | `frontend/src/canvas/render/model3d.ts` | the 3D object on the page | | `frontend/src/io/glb.ts`, `chem/elements3d.ts`, `chem/geom3d.ts`, `chem/conformer-mol.ts` | the glTF writer, the 3D palette and radii, measurement maths, a local molfile of a stored conformer | | `frontend/src/app/view3d-commands.ts` | the 3D commands | +| `backend/app/services/xtb/`, `backend/app/routers/xtb.py` | xtb and CREST (0.12.0): `discovery.py` (finding the programs), `inputs.py`, `runner.py` (the separate process), `jobs.py`, `parse.py` (their output files), `writeback.py`, `solvents.py` | +| `frontend/src/app/xtb-commands.ts`, `ui/xtb-dialog.ts`, `ui/prefs/xtb.ts` | the xtb and CREST commands, dialogs and Preferences section (0.12.0) | -The reasons behind each choice are in `backend/HASHOUT_LOG.md` entries 199 to 222 and `frontend/HASHOUT_LOG.md` entries 222 to 244. +The reasons behind each choice are in `backend/HASHOUT_LOG.md` entries 199 to 222 and 270 to 275 and `frontend/HASHOUT_LOG.md` entries 222 to 244, 298 and 299. ## The 3D View @@ -137,9 +140,36 @@ The molfile is V2000 unless the structure has more than 999 atoms. The glTF file ## Methods, versions and accuracy -Every computed number names its method and engine version: the panel's status line ("Built: ETKDGv3+MMFF94, rdkit 2025.09.3 · -1.34 kcal/mol"), the conformer list, the scan dialog ("barrier 5.10 kcal/mol · MMFF94, rdkit 2025.09.3"), the ESP legend, and every route and agent answer (`engine` and `method`). Conformers store `method` (`ETKDG` for an embedding without minimisation, `MMFF94`, `MMFF94s`, `UFF`, or `file` for coordinates read from a file) and `energy` in kcal/mol for that method. +Every computed number names its method and engine version: the panel's status line ("Built: ETKDGv3+MMFF94, rdkit 2025.09.3 · -1.34 kcal/mol"), the conformer list, the scan dialog ("barrier 5.10 kcal/mol · MMFF94, rdkit 2025.09.3"), the ESP legend, and every route and agent answer (`engine` and `method`). Conformers store `method` (`ETKDG` for an embedding without minimisation, `MMFF94`, `MMFF94s`, `UFF`, `xtb` for an xtb or CREST result, or `file` for coordinates read from a file) and `energy` in kcal/mol for that method; an xtb or CREST conformer also stores a `program` record (FORMAT.md). -These are force-field results. MMFF94 energies compare conformers of one structure; they are not heats of formation and are not comparable between structures of different composition or between force fields. Populations are Boltzmann weights over the kept conformers only. ESP colours are a picture of empirical charges, not a computed potential. The exit check for geometry was ethanol's C-O bond: 1.420 Å after MMFF94, inside the expected 1.41 to 1.44 Å; no wider benchmark against experimental structures was run. Tight-binding methods (xtb, CREST) are not offered: plan question Q9 is unanswered, so the default applies (a program the person installs and points to), and that is not built yet. +Force-field results: MMFF94 energies compare conformers of one structure; they are not heats of formation and are not comparable between structures of different composition or between force fields. Populations are Boltzmann weights over the kept conformers only. ESP colours are a picture of empirical charges, not a computed potential. The exit check for geometry was ethanol's C-O bond: 1.420 Å after MMFF94, inside the expected 1.41 to 1.44 Å; no wider benchmark against experimental structures was run. GFN2-xTB and GFN-FF energies come from the xtb program you installed (below), are total energies in hartree shown also in kcal/mol, and are never mixed with force-field energies in one conformer list. + +## xtb and CREST (0.12.0) + +xtb (semiempirical tight binding, GFN2-xTB, and the GFN-FF force field) and CREST (conformer search by metadynamics on top of xtb) are programs of the Grimme group under the LGPL-3.0. FormChem never includes or downloads them: it runs them as separate programs when you have installed them, and tells you where to get them when it cannot find them (https://github.com/grimme-lab/xtb and https://github.com/crest-lab/crest). + +Finding the programs. Preferences > 3D > Tight-Binding Programs holds a path for xtb and one for CREST (a program file, or the folder holding it) and the number of threads (automatic is the smaller of 4 and the number of processors). FormChem looks at the path you set, then your PATH, then conda and mamba environments and the usual program folders, and runs `--version`. Each row shows what it found: the version and path, a path that does not run, or where to get the program. A program you install while FormChem is open is found the next time the dialog or Preferences opens. + +3D > Optimise with xtb... works on the selected structure's shown conformer (a structure without one is built first, ETKDGv3 and MMFF94): + +- Method: GFN2-xTB (the default) or GFN-FF. +- Charge (default: the sum of the drawn formal charges) and unpaired electrons (default: the drawn radicals). A combination that cannot match the number of electrons is refused before anything runs, with the reason. +- Solvent: gas phase, or one of xtb's 24 ALPB implicit solvents (water, methanol, acetonitrile, DMSO, dichloromethane, chloroform, toluene, THF and the others xtb lists). +- Calculation: Optimise the geometry, with Convergence from crude to extreme (default normal), or Single point energy, which moves no atom; Conformers: the shown conformer, or every stored conformer (the default for a single point). +- Threads and a time limit (default 10 minutes for xtb, 1 hour for CREST, at most a week). + +3D > Conformer Search with CREST... takes the same method, charge, unpaired electrons, solvent, threads and limit, plus the energy window (default 6 kcal/mol) and the most conformers to keep (default 20, at most 200). + +While a job runs the dialog shows the program and version, the stage, the optimisation cycle, a progress bar and the program's last lines; Cancel Job stops it. Closing the dialog does not stop the job; a toast reports the end. One job runs at a time. A job that fails keeps its working folder so you can read the program's own files (the path is shown); a successful, cancelled or timed-out job leaves nothing behind. + +Results go back as one undo step: + +- An optimisation replaces the structure's conformers with the optimised one, so the 3D View never lists MMFF94 and xtb energies side by side. The dialog reads, for example, "Done in 2 s: -11.39210563 Eh (-7148.65 kcal/mol), HOMO-LUMO gap 12.846 eV · xtb 6.7.1, GFN2-xTB, ALPB (Water)" (a stand-in run of water), and says whether the optimisation converged. +- A CREST search replaces the conformers with the ensemble, lowest first and shown, with relative energies and Boltzmann populations at 298.15 K. Conformers whose stereo no longer matches the drawing are dropped and counted. +- Each conformer stores method `xtb`, the energy in kcal/mol and a `program` record (program, version, method, solvent, charge, unpaired electrons, energy in hartree, gap). +- An edit to the structure while a job runs makes the job end with the usual 3D message, and the drawing is left as it was. + +What has not been checked: no real xtb or CREST run on this project's machines. Discovery, the runs, cancel, the time limit, the output readers, the dialogs and the agent tools were checked with stand-in programs that write xtb's and CREST's documented output files. Real output layouts, real timings and CREST's atom order on a real run are therefore unseen, and so are the Windows process stop and the Windows install folders. ## HTTP API @@ -162,13 +192,23 @@ Every changing route needs the window key header (`x-formchem-window-key`); the `POST /api/documents/{id}/media` also takes PDB, mmCIF, SDF and MOL bytes (FORMAT.md). +The xtb and CREST routes (0.12.0) all need the window key. A missing program answers 424 with the project's address, bad input 422 (with the electron parity reason), an unknown drawing or object 404. + +| Route | Body or query | Answer | +| --- | --- | --- | +| `GET /api/xtb/status` | `fresh?` | `xtb` and `crest` (each `program`, `title`, `path`, `how`, `state` (`runs`, `broken`, `missing`, `bad_setting`), `version`, `message`, `home`, `licence`, `looked`), `settings`, `solvents`, `methods`, `levels`, `limits` | +| `POST /api/xtb/settings` | `xtb?`, `crest?`, `threads?` | the status, looked up again | +| `POST /api/documents/{id}/xtb/optimise`, `.../xtb/single`, `.../xtb/crest` | `object`, `conformer?`, `scope?` (`shown` or `all`), `method?` (`gfn2` or `gfnff`), `charge?`, `uhf?`, `solvent?`, `level?`, `ewin?`, `keep?`, `threads?`, `limit?`, `wait?` | the job | +| `GET /api/xtb/jobs`, `GET /api/xtb/jobs/{job}` | | the jobs, or one job: `id`, `kind`, `state` (`queued`, `running`, `done`, `failed`, `cancelled`, `timeout`), `program`, `label`, `elapsed`, `limit`, `stage`, `cycle`, `step`, `steps`, `tail`, `error`, `folder`, `conformers`, `report`, `changed`, `rev` | +| `POST /api/xtb/jobs/{job}/cancel` | | the job | + ## Agent tools -`build_3d`, `conformers_3d`, `minimise_3d`, `scan_dihedral`, `measure_3d`, `open_3d_structure`, `extract_ligand` and `export_3d`, with every argument and result, are in [AGENTS.md](AGENTS.md). They call the same route functions in process and commit under the agent's name. +`build_3d`, `conformers_3d`, `minimise_3d`, `scan_dihedral`, `measure_3d`, `open_3d_structure`, `extract_ligand` and `export_3d`, and from 0.12.0 `xtb_optimise` and `crest_conformers`, with every argument and result, are in [AGENTS.md](AGENTS.md). They call the same route functions in process and commit under the agent's name; the two xtb tools wait for the job to finish. ## Known limits -- No tight-binding or quantum method; every energy is a force-field energy (see Methods, versions and accuracy). +- Quantum and tight-binding energies only through xtb and CREST you install yourself, which were checked here with stand-in programs only (see xtb and CREST); no other quantum method. - Atropisomers and allene axial chirality are not perceived, so they are neither kept nor checked. - Surfaces are computed on the main thread: a surface on a large protein holds the window for a while. glTF holds atoms and bonds only. - ESP is off for PDB and mmCIF models. diff --git a/docs/ACCESSIBILITY.md b/docs/ACCESSIBILITY.md new file mode 100644 index 00000000..443e4c06 --- /dev/null +++ b/docs/ACCESSIBILITY.md @@ -0,0 +1,100 @@ +# Accessibility + +How to draw and read structures in FormChem from the keyboard and with a screen reader, and how to choose element colours that stay apart, from 0.12.0: the keys, what FormChem says, the Structure Summary, the palettes, focus and hit targets, and what has not been checked with a real screen reader. + +## Contents + +- Keyboard focus on the drawing +- Building a structure with the keyboard +- What FormChem says +- The Structure Summary +- Element colours +- Focus outlines and hit targets +- Not verified +- Where the code lives + +## Keyboard focus on the drawing + +View > Focus Structure (`Alt+Mod+A`; `Mod` is Cmd on macOS and Ctrl elsewhere) puts the keyboard focus on the first atom of the drawing and draws a ring around it: a white halo under an accent stroke, readable at any zoom, shaped as a capsule around a bond. On an empty drawing it says how to start. + +| Key | What it does | +| --- | --- | +| Tab, Shift+Tab | the next or previous atom, fragment by fragment in reading order; Tab past the last atom leaves the drawing | +| an arrow key | the bonded neighbour nearest that direction (within 90 degrees) | +| Ctrl, Cmd or Alt with an arrow | the bond nearest that direction; the next step continues from the bond's far end | +| Space | adds the focused atom or bond to the selection, or takes it out | +| Enter | on an empty drawing, adds a carbon; on an atom, arms a new bond: the next arrow draws it in that direction | +| an element key (O, N, Cl...) and the other hover keys | act on the focused atom, as they do on the atom under the pointer | +| Escape | clears the focus | +| `Alt+Mod+]`, `Alt+Mod+[` | View > Next Atom and Previous Atom, the same as Tab and Shift+Tab from the menu | +| `Alt+Mod+S` | View > Describe Structure (below) | + +The keys work while a drawing is shown. While Home or the database workspace covers the drawing, they do nothing. + +## Building a structure with the keyboard + +Ethanol, with no mouse: + +1. `Alt+Mod+A`. FormChem says "The drawing is empty. Press Enter to add a carbon atom, then Enter and an arrow key to add bonds." +2. Enter adds a carbon: "Carbon. 4 hydrogens. No bonds. Not in a ring. Atom 1 of 1." +3. Enter, then Right: a second carbon to the right, focused. +4. Enter, then Up: a third atom above it. +5. O: the focused atom becomes oxygen: "Oxygen. 1 hydrogen. Single bond to Carbon. Not in a ring. Atom 3 of 3." +6. `Alt+Mod+S`: "Formula C2H6O. Name: ethanol. Neutral overall. No rings. Functional groups: alcohol. No stereocentres." + +## What FormChem says + +Every move is spoken through one polite live region that the whole window shares (urgent messages use a second, assertive one). For an atom, in this order: the element by name ("Carbon", not "C"; an R-group or label by its label), its charge ("Negative charge.", "Positive charge of 2."), its hydrogens, its isotope ("Isotope of mass 13."), its bonds by order and neighbour ("2 single bonds to Carbon. Double bond to Oxygen."), its ring ("Not in a ring.", "In an aromatic 6-membered ring.", "In 2 rings, of sizes 5, 6."), its R or S label ("Stereo label S.") and its place ("Atom 2 of 6."). For a bond: its order and ends ("Single bond between Carbon and Oxygen."), its ring and how a wedge is drawn ("Drawn as a hashed wedge, away from the viewer."). When a key has nothing to move to, it says so ("No bond in that direction. Press Enter, then an arrow key, to add one."). Space says "Selected." or "Not selected.". + +Hydrogen counts, rings and R or S labels come from the engine's latest perception only when it matches what is drawn; while the engine is still working, FormChem counts hydrogens itself, so a label typed a moment ago is never spoken from old data. Every sentence goes through the translation table and is spoken in the window's language. + +## The Structure Summary + +View > Describe Structure (`Alt+Mod+S`) speaks a summary of the drawing (or the selection) and shows it in a dialog with the text focused, so a screen reader reads it. It holds, each with the method and version that produced it: + +- the formula, and the name when FormChem's name engine has one (dictionary or systematic, with its confidence); +- the overall charge and the number of separate molecules or ions; +- the ring systems: named when the ring atoms alone match one of FormChem's 51 ring skeletons (benzene, pyridine, indole, piperidine, purine, adamantane and others), otherwise described by kind and sizes ("A fused system of 3 rings, sizes 6, 6, 6."), with the heteroatoms in them; +- the functional groups from FormChem's own table of 42, each atom counted once (an ester's oxygen is not also an ether); +- the stereocentres and stereo double bonds with their CIP labels. + +Copy copies the text; Escape returns focus to the drawing. A screen reader may read the summary twice: once from the live region and once from the focused text. + +## Element colours + +Preferences > Interface > Element colours, or View > Element Colours, chooses one of three palettes. They apply when Colour atoms by element is on (Preferences > Drawing), to the canvas, pictures, exports and the clipboard. The choice is kept on this computer and applied before the first drawing appears; switching changes only the atom colours, nothing moves. + +| Element | Standard | High contrast | Colour-blind safe | +| --- | --- | --- | --- | +| N | #2f4fd8 | #0026b3 | #0072b2 (Okabe-Ito blue) | +| O | #d01c1c | #b00000 | #d55e00 (vermillion) | +| S | #a88400 | #5c4700 | ink | +| P | #d06a00 | #8a3300 | #cc79a7 (reddish purple) | +| F, Cl | #3a9a2a, #1f9a1f | #005c13 | #009e73 (bluish green) | +| Br, I | #8a2a1a, #6a1f8a | #6e1400, #4f0f80 | #009e73 | +| B, Si, Se | #c06a5a, #8a7a5a, #a06a00 | #7a2e1f, #4a4030, #5c3a00 | ink | + +High contrast keeps every element colour at 7.38:1 or more against the white page. The colour-blind palette uses the four Okabe-Ito colours that stay at 3:1 or more on white; the paler Okabe-Ito hues (orange, yellow, sky blue) are under 2.4:1, so those elements keep the ink colour and are told apart by their labels. Carbon and hydrogen are always ink. + +## Focus outlines and hit targets + +Every dialog control shows a 2 pixel outline when it has keyboard focus. Dialog colour swatches and the custom accent button are 24 by 24 pixels; tool rail buttons are 32 pixels (28 in the compact density) and never under 24. The command palette (`Shift+Mod+P`) reaches every command by name, including the ones above. + +## Not verified + +- No real screen reader (VoiceOver, NVDA, Orca) has been run: what is described above was read back from the live region in Chromium. +- The desktop app's webview and the macOS key glyphs for `Alt+Cmd+[` and `]` were not seen. +- On many European Windows keyboards Ctrl+Alt is AltGr, so `Ctrl+Alt+[` and `]` may not be typeable; use View > Next Atom and Previous Atom or the command palette. +- Moving and rotating in the 3D View from the keyboard is not built. +- Hit targets in Preferences were measured at the standard density only. + +## Where the code lives + +| Path | What | +| --- | --- | +| `frontend/src/canvas/a11y/` | the key route, navigation, spoken atoms and bonds, the focus ring, palettes and the commands | +| `frontend/src/ui/a11y-announcer.ts` | the shared live regions | +| `frontend/src/ui/structure-summary.ts` | the Structure Summary dialog | +| `frontend/src/canvas/render/atom.ts` | the three palettes | +| `frontend/src/styles/a11y.css` | focus ring, outlines, hit targets, screen-reader-only text | +| `backend/app/services/describe.py`, `routers/describe.py` | `POST /api/describe`: formula, name, rings, groups and stereo with their methods | diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 3315e5b0..089268f9 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -1,6 +1,6 @@ # FormChem for agents -From 0.8.0 an agent draws in FormChem directly. The engine's MCP server has 60 tools: it opens and makes drawings, draws structures and reaction schemes from SMILES, molfiles or (from 0.9.0) chemical names, builds and edits them atom by atom by id, reads every structure back in machine form and names it, checks its own work with a picture drawn by the window's own renderer, predicts 1H and 13C NMR spectra, opens JCAMP-DX spectra and picks their peaks and integrals, (from 0.10.0) builds 3D conformers, minimises, scans and measures them, opens PDB, mmCIF and 3D SD files, extracts ligands and exports 3D files, and converts files with the same code as the command line. The person watches every change land in the FormChem window, can undo any agent call in one step, and can stop an agent at any time. +From 0.8.0 an agent draws in FormChem directly. The engine's MCP server has 77 tools: it opens and makes drawings, draws structures and reaction schemes from SMILES, molfiles or (from 0.9.0) chemical names, builds and edits them atom by atom by id, reads every structure back in machine form and names it, checks its own work with a picture drawn by the window's own renderer, predicts 1H and 13C NMR spectra, opens JCAMP-DX spectra and picks their peaks and integrals, (from 0.10.0) builds 3D conformers, minimises, scans and measures them, opens PDB, mmCIF and 3D SD files, extracts ligands and exports 3D files, (from 0.11.0) creates, imports into, searches and exports structure databases and keeps lab notebook entries in them, (from 0.12.0) keeps structures in the shared structure library every Form app reads, hands out live structure objects, draws peptides and nucleic acids from HELM and runs xtb and CREST when the person has installed them, and converts files with the same code as the command line. The person watches every change land in the FormChem window, can undo any agent call in one step, and can stop an agent at any time. This page is the reference for agent authors and for anyone wiring a client. The generated list of every argument is `.claude/skills/formchem-harness/references/tools.md` (`./formchem agents sync` writes it from the server); how to set a client up step by step is in the wiki's Agents page. @@ -19,6 +19,8 @@ This page is the reference for agent authors and for anyone wiring a client. The - Example: build acetic acid atom by atom - Example: a name, its names and its NMR (0.9.0) - Example: ethanol in 3D, and a ligand from a PDB file (0.10.0) +- Example: a database search and a notebook entry (0.11.0) +- Example: the library, HELM and xtb (0.12.0) - Where the code lives - Known limits @@ -67,6 +69,12 @@ Reading never asks. The first change an outside agent makes asks the person in t | `convert` | only with `output` outside the system's temporary folder | | `batch_convert` | unless its output folder is inside the temporary folder | | `handoff` | only with a `state` | +| `db_list`, `db_search`, `db_get_record`, `nb_search` | never | +| `db_create`, `db_open`, `db_add_record`, `db_update_record`, `nb_add_entry` | the first time | +| `db_import` | unless `dry_run` is true | +| `db_export` | only with a `path` outside the system's temporary folder | +| `library_list`, `live_structure_object` | never | +| `library_add`, `draw_from_helm`, `xtb_optimise`, `crest_conformers` | the first time | While an agent changes the drawing the person is looking at, the title bar shows "[agent] is editing" with a Stop button. Stop refuses every further call of that agent name, reads included, with a sentence that tells the agent to ask the person to allow it again; it also withdraws Always allow, so every outside agent is asked again on its next change. A call already running when Stop is pressed finishes. The person lets the agent in again from Agent activity (Allow again); its next change asks first. Stops last until the engine restarts. Agents are known by the MCP `clientInfo` name (or the in-app tab's name), so two sessions with one name stop together. @@ -97,7 +105,7 @@ The values come from the engine's derived cache after the transaction, never ech ## Which drawing a tool uses -`doc` when given; else the only open drawing; else the drawing the FormChem window shows; else the tool asks for `doc` (an id from `list_open_documents`). `draw_from_smiles`, `draw_from_molfile`, `draw_from_name`, `add_atom` and `add_reaction` make a new drawing when none is open, show it in the window, and close it again when their input cannot be read (`draw_from_name` refuses an unread name before any drawing is made). `open_spectrum` always opens a new drawing. `open_3d_structure` opens into the drawing chosen by the rule above, makes one when none is open, and closes that new drawing again when the file cannot be read. The 0.9.0 NMR and spectrum tools and the 0.10.0 3D tools follow the same rule as the 0.8.0 tools. The 0.5.0 and 0.6.0 tools (the reaction and analysis tools) still need `doc` when several drawings are open. +`doc` when given; else the only open drawing; else the drawing the FormChem window shows; else the tool asks for `doc` (an id from `list_open_documents`). `draw_from_smiles`, `draw_from_molfile`, `draw_from_name`, `add_atom` and `add_reaction` make a new drawing when none is open, show it in the window, and close it again when their input cannot be read (`draw_from_name` refuses an unread name before any drawing is made). `open_spectrum` always opens a new drawing. `open_3d_structure` opens into the drawing chosen by the rule above, makes one when none is open, and closes that new drawing again when the file cannot be read. The 0.9.0 NMR and spectrum tools and the 0.10.0 3D tools follow the same rule as the 0.8.0 tools. The 0.5.0 and 0.6.0 tools (the reaction and analysis tools) still need `doc` when several drawings are open. The database tools of 0.11.0 work on a database, not a drawing: `db` is a handle from `db_list`, `db_create` or `db_open` and may be left out when exactly one database is open; `nb_add_entry` and `nb_search` always need it. Of the 0.12.0 tools, `draw_from_helm`, `xtb_optimise` and `crest_conformers` follow the drawing rule above, and `draw_from_helm` makes a drawing when none is open. `library_add` takes `smiles`, or `doc`, which may be left out only when exactly one drawing is open. `library_list` and `live_structure_object` need no drawing. Coordinates are points, x to the right and y down, on the page; the default bond length is 14.4 points. Ids are the ones the tools return (`fragment`, `atom`, `bond`, `arrow` and so on); they never change while the object exists. @@ -215,6 +223,41 @@ The method is FormChem increments 0.9.0, FormChem's own additive rules with no s The 3D tools answer with the method and the engine version (`rdkit 2025.09.3`) next to every energy and measurement. `build_3d` compares the CIP labels read back from the 3D coordinates with the drawing's and says which were kept; check that line before using the geometry. A later edit to a structure's atoms or bonds removes its conformers in the same undo step (moves do not), so build again after editing. `extract_ligand` takes bond orders from a table of 30 common ligands and otherwise infers them from the geometry, and the answer says "inferred from the geometry"; check such a ligand's SMILES. `build_3d`, `conformers_3d`, `minimise_3d`, `open_3d_structure` and `extract_ligand` ask the person the first time; `scan_dihedral` only with `store: true`, `export_3d` only with an `output` outside the temporary folder. Methods, limits and the routes behind the tools: [3D.md](3D.md). +### Databases and the notebook (0.11.0) + +A database is one `.fcdb` file (see [DATABASES.md](DATABASES.md) and the contract [DATABASE.md](DATABASE.md)). Records are known by `uid` (`c` plus 10 characters), entries by `uid` (`n` plus 10 characters). A structure is `smiles` or `molfile`. Rows carry `uid`, `number`, `batch`, `smiles`, `formula`, `mw`, field `values` and, after a similarity search, `score`. + +| Tool | Arguments | Result | +| --- | --- | --- | +| `db_list` | none | `open` (handle, title, path, count, read-only and why, fields) and `known` (path, name, count, whether the file exists) | +| `db_create` | `title`, `path?` (absolute; default the Databases folder) | the new, open database's Info (`db`, `path`, `title`, `count`, `readonly`, `rules`, `fields`, `forms`, `entries`) | +| `db_open` | `path` (absolute `.fcdb`) | Info; opened read-only, with the reason, when another FormChem holds the file | +| `db_import` | `path` (absolute), `db?`, `format?` (`sdf`, `rdf`, `smiles`, `csv`, `tsv`, `fchem`), `mode?` (`new`, `append`, `merge`), `key?` (`structure` or a field name, for merge), `mapping?` (left out: the detected mapping), `dry_run?`, `wait?` (seconds, 0 to 600, default 60) | the Job: `state`, `read`, `added`, `updated`, `failed`, `report` (each `record` and `reason`; the text shows the first 10), `seconds`; a job still running is reported with its id | +| `db_search` | `db?`, `smiles?` with `mode?` (`substructure` default, `similarity` with `threshold?` 0 to 1, default 0.7, or `exact`) and `smarts?`, or `query?` (a query node of DATABASE.md); `within?` (hit list id), `name?`, `limit?` (default 20, at most 100) | the hit list (`id`, `name`, `count`, `took_ms`, `screened`, `methods`) and its first `rows`; the person sees it in the window's hit lists | +| `db_get_record` | `uid`, `db?` | the record: number, batch, SMILES, InChIKey, formula, masses, `molfile`, field values, attachments | +| `db_add_record` | `smiles` or `molfile`, `db?`, `values?` (by field name), `on_duplicate?` (`ask`, `existing`, `batch`, `new`) | the record; with a duplicate and no `on_duplicate`, an error listing the duplicates (`structuredContent` `{detail, duplicates}`) and the three choices, and nothing added | +| `db_update_record` | `uid`, `db?`, `smiles?` or `molfile?`, `values?` | the record; computed fields follow the new structure | +| `db_export` | `format` (`sdf`, `smiles`, `csv`), `db?`, `path?` (absolute; default FormChem's export folder), `hitlist?`, `uids?`, `fields?`, `v3000?`, `structure_as?` (`smiles` or `inchi`, for CSV) | `path`, `written`, `skipped` | +| `nb_add_entry` | `db`, `title`, `template?` (`blank`, `reaction`, `analysis`, `purification`), `date?` (YYYY-MM-DD), `author?`, `procedure?`, `observations?` (the notebook's markup), `tags?`, `products?` (each `compound` uid, `name`, `sample`, `mass_g`, `yield_pct`, `purity_pct`, `notes`), `reaction?` (reaction SMILES or RXN) or `doc?` (an open drawing whose first page becomes the scheme) | `uid`, `number`, `title`, `date`, `status` (`open`), `hash`, `products` and the `stoichiometry` computed from the scheme with its method | +| `nb_search` | `db`, `query?` (every word must appear in the title, procedure, observations, tags or sample ids), `substructure?` (SMILES or SMARTS against every structure of each entry's scheme), `limit?` (default 20, at most 200) | `total` and rows (`number`, `uid`, `title`, `date`, `status`, `tags`), newest first; `method` with a substructure | + +Every write is recorded in the database's `audit` table as `agent:[client name]` and in Agent activity. Every search, also an agent's, becomes a hit list the person sees (the newest 20 unkept are kept), which is why `db_search` reads but leaves a trace. Agents never sign entries: an agent's entry stays open for a person to read and sign. `nb_add_entry` checks the products and their record uids before it writes, so a refused call adds nothing. A read-only database refuses every write with the reason. Bad records never stop `db_import`; read the report and fix or skip those records. Before relying on a similarity hit, read its `score`; before relying on an exact search, know the database's rules (stereo and salts) from `db_open` or `db_list`. + +### The structure library, HELM and xtb (0.12.0) + +The shared structure library is the folder every Form app reads ([LIVE_STRUCTURES.md](LIVE_STRUCTURES.md) is its contract, [LIVE-STRUCTURES.md](LIVE-STRUCTURES.md) the person's page). Items are known by `id` (`s` plus 10 lower-case letters or digits). HELM is described in [HELM.md](HELM.md), xtb and CREST in [3D.md](3D.md). + +| Tool | Arguments | Result | +| --- | --- | --- | +| `library_list` | `kind?` (`favourite`, `recent`, `template`, `live`) | `folder` and `items` (each `id`, `name`, `kinds`, `kind`, `smiles`, `inchikey`, `formula`, `mw`, `rev`, `svg`, `mol`, `png`, `modified`), `method`; the text lists the first 40. Reads only | +| `library_add` | `smiles`, or `doc?` with `ids?` (objects of the drawing's page; default the whole first page), `name?`, `kinds?` (default `["favourite"]`) | `item`; the engine draws the pictures with the FormChem drawing inside. A structure already in the library gains the new kind instead of a copy; a `live` add is always a new item | +| `live_structure_object` | `id` | the object a sibling app stores: `format` (`formai-structure`), `format_version`, `id`, `rev`, `app`, `name`, `kind`, `smiles`, `inchikey`, `svg` (with the drawing inside), `molfile`, `width`, `height`. Reads only | +| `draw_from_helm` | `helm`, `doc?`, `x?`, `y?` (default free space), `name?` (default the HELM, shortened) | the new structure as one undo step ("Draw from HELM"), with its ids, SMILES, InChIKey, formula, average and monoisotopic mass with their method and version, and a picture. Bad HELM is refused with the character where reading stopped | +| `xtb_optimise` | `doc?`, `object?`, `method?` (`gfn2` default or `gfnff`), `charge?`, `uhf?`, `solvent?` (`none` or one of the 24 ALPB keys such as `water`, `dmso`, `ch2cl2`), `single_point?`, `scope?` (`shown` or `all`), `level?` (`crude` to `extreme`, default `normal`), `conformer?`, `threads?`, `limit?` (seconds, default 600) | waits for xtb, then stores the result as the structure's conformers as one undo step ("xtb optimisation" or "xtb single point"): total energy in hartree and kcal/mol, HOMO-LUMO gap, whether it converged, and the program, version, method and solvent | +| `crest_conformers` | `doc?`, `object?`, `method?`, `charge?`, `uhf?`, `solvent?`, `ewin?` (kcal/mol, default 6), `keep?` (1 to 200, default 20), `threads?`, `limit?` (seconds, default 3600) | waits for CREST, then replaces the conformers with the ensemble, the lowest shown, as one undo step ("CREST conformers"): relative energies, Boltzmann populations at 298.15 K, and the program, version, method and solvent | + +`library_add`, `draw_from_helm`, `xtb_optimise` and `crest_conformers` ask the person the first time; `library_list` and `live_structure_object` never ask. xtb and CREST are LGPL programs FormChem does not include or download: when the person has not installed them, the two tools say where to get them and change nothing. A charge and unpaired-electron count that cannot match the electrons is refused before anything runs. CREST can run for minutes to hours; set `limit` to what you can wait for. An edit to the structure while a job runs ends the job and leaves the drawing as it was. No MCP tool opens a live structure for editing; `run_command` with `open-live-structure` and `{id, from}` does it in the window, as the deep link and `./formchem edit-live` do. + ### Window commands, extensions and handoffs | Tool | Arguments | Result | @@ -347,6 +390,53 @@ From the integration run, in process as an in-app agent. The values are as recor The C-C bond measured 1.515 Å. `minimise_3d`, `conformers_3d` (one conformer kept: ethanol's rotamers differ only in hydrogens) and `export_3d` as XYZ text and as an SD file ran in the same session, and Agent activity listed every call with the agent's name, each changing call one undo step. +## Example: a database search and a notebook entry (0.11.0) + +From the integration run over HTTP with the agent token, on a database of 9,997 records imported from an SD file, with one notebook entry made in the window. The counts and timings are as recorded; the text follows the handlers' format, with handles, uids and the method strings shortened to `...`: + +``` +> db_list {} +< g... "Compounds": 9997 records, ...; /.../Databases/Compounds.fcdb +> db_search {"smiles": "c1ccccc1"} +< Hit list ... "Substructure c1ccccc1": 2218 records in 99.5 ms, ... screened. Methods: substructure: ... + - c... #1 ... + Showing 20 of 2218; db_export {hitlist: ...} writes them all. +> nb_search {"db": "g...", "substructure": "NC=O"} +< 2 notebook entries match substructure NC=O. + ... +> nb_search {"db": "g...", "query": "AC-001"} +< 2 notebook entries match text 'AC-001'. +> db_add_record {"smiles": "..."} +< (refused: the call needs the person's approval and no window was open to ask) +``` + +`db_add_record` is a writing tool, so an outside agent's first call asks the person in the window; with no window open it was refused, as designed. In the scratch runs before integration, `db_import` of a 5 record SD file with one broken record answered "added 4, failed 1" with the record's number and reason, a duplicate `db_add_record` listed the existing record and, called again with `on_duplicate: "batch"`, added batch 2, and `nb_add_entry` from `OC(=O)c1ccccc1.NC>>CNC(=O)c1ccccc1` answered the stoichiometry with MW 122.123, 31.058 and 135.166. + +## Example: the library, HELM and xtb (0.12.0) + +From the integration run over HTTP with the agent token, the window open and agents allowed; xtb and CREST were stand-in programs that write the documented output files, not the real programs. Values are as recorded; the text follows the handlers' format with ids shortened to `...`, and the parts not recorded are `...`: + +``` +> tools/list +< 77 tools +> library_add {"smiles": "Oc1ccccc1", "name": "Phenol"} +< Added to the structure library for ...: s... Phenol [favourite] C6H6O, 94.113 g/mol rev 1. Average mass by FormChem perceive and mass.average_mass with RDKit 2025.09.3. +> live_structure_object {"id": "s..."} +< Live structure object s... rev 1 (Phenol): 6,566 characters of SVG with the drawing inside and a 19-line molfile. +> draw_from_helm {"helm": "PEPTIDE1{G.G}$$$$"} +< ... InChIKey YMAWOPBAYDPSLA-UHFFFAOYSA-N ... +> draw_from_helm {"helm": "PEPTIDE1{A.X}$$$$"} +< (refused at character 12: X is not a PEPTIDE monomer FormChem knows.) +> xtb_optimise {"solvent": "water"} +< ... -11.39210563 Eh (-7148.65 kcal/mol), HOMO-LUMO gap 12.846 eV ... xtb 6.7.1, GFN2-xTB, ALPB (Water) +> crest_conformers {"keep": 2} +< ... 2 of 3 conformers kept ... 62.5 % ... +> xtb_optimise {"uhf": 1} +< (refused: the unpaired electrons do not match the electron count) +``` + +The refusals are paraphrased. Without a window open, the four asking tools refuse with the message that asks the person to open FormChem, as designed. + ## Where the code lives | Path | What it holds | @@ -356,6 +446,10 @@ The C-C bond measured 1.515 Å. `minimise_3d`, `conformers_3d` (one conformer ke | `backend/app/services/nmr/`, `routers/nmr.py` | the increment predictor and the predicted spectrum object behind `predict_nmr` and `predict_spectrum` | | `backend/app/services/spectra/`, `routers/spectra.py` | the JCAMP-DX reader, data, peaks, integrals and export behind the spectrum tools | | `backend/app/services/three_d/`, `routers/three_d.py` | building, conformers, minimisation, scans, measurements, structure files, ligands and 3D export behind the 3D tools | +| `backend/app/services/agent_db.py`, `agent_notebook.py` | the eleven database and notebook tools; `mcp.py` walks them through `AGENT_MODULES` | +| `backend/app/services/database/`, `services/notebook/` | the database and notebook services the tools and the routes share | +| `backend/app/services/agent_library.py`, `agent_helm.py`, `agent_xtb.py` | the six 0.12.0 tools, also walked through `AGENT_MODULES` | +| `backend/app/services/live_structures.py`, `services/helm/`, `services/xtb/` | the library, HELM and xtb services behind them | | `backend/app/services/agent_out.py` | the write result, `render` through the window and its engine fallback, free space | | `backend/app/services/agent_draw.py` | structures and reaction schemes from text as one set of ops | | `backend/app/services/agent_edits.py` | the edit tools as pure builders `fn(doc, args) -> (ops, info)` | @@ -366,7 +460,7 @@ The C-C bond measured 1.515 Å. `minimise_3d`, `conformers_3d` (one conformer ke | `frontend/src/app/agent-activity.ts`, `ui/agent-activity.ts`, `ui/agent-chip.ts`, `canvas/agent-marks.ts` | Agent activity, the editing chip and the marks | | `setup/mcp_stdio.py`, `setup/agents.py` | the stdio relay, `./formchem agents install`, `sync` and `token` | -The reasons behind these choices are in `backend/HASHOUT_LOG.md` (entries 133 to 164 for the 0.8.0 tools, 165 to 198 for names, NMR and spectra, 199 to 222 for 3D) and `frontend/HASHOUT_LOG.md` (187 to 200, 201 to 221, and 222 to 244). +The reasons behind these choices are in `backend/HASHOUT_LOG.md` (entries 133 to 164 for the 0.8.0 tools, 165 to 198 for names, NMR and spectra, 199 to 222 for 3D, 223 to 255 for databases and the notebook, with the tools in 248 and 254, 256 to 278 for the library, HELM and xtb, with the tools in 276) and `frontend/HASHOUT_LOG.md` (187 to 200, 201 to 221, 222 to 244, 245 to 276, and 277 to 300). ## Known limits @@ -379,4 +473,8 @@ The reasons behind these choices are in `backend/HASHOUT_LOG.md` (entries 133 to - `perceive_reactions` lists the conditions below an arrow before those above it. - Not run for 0.8.0: the macOS desktop app, and real Claude Code or Codex clients (the tools were checked with the stdio transport, curl and a browser window). The ten 0.9.0 tools and the eight 0.10.0 tools were checked in process only, as an in-app agent. - There is no tool to choose the shown conformer, add a surface or style a 3D object; `run_command` with `style-ballstick`, `surface-vdw` and the other 3D commands does it while the 3D View is open. `export_3d` writes chemistry files; the PNG and glTF exports of the view are window commands that hand their file to the person. -- No tight-binding method (xtb, CREST): every energy is a force-field energy. +- xtb and CREST run only when the person has installed them, and `xtb_optimise` and `crest_conformers` were checked with stand-in programs, not the real ones. +- The database tools have no way to add or change fields, save or combine hit lists, run saved queries, plot, or attach files, and the notebook tools cannot change, sign or export an entry; the window does these (and `run_command` reaches its database commands, such as `db-search` with `text`). `db_import` and `db_export` take paths, not uploads. +- Not run for 0.11.0: the consent prompt of `db_add_record` and `nb_add_entry` with a window open, and the tools through `./formchem mcp` (they ran over HTTP with curl and in scratch runs). +- There is no tool to describe a structure in words (the window's Describe Structure), to delete or rename library items, or to write a drawing back to HELM; `run_command` with `copy-helm` does the last and puts the HELM on the clipboard. +- Not run for 0.12.0: real xtb and CREST, a sibling app reading what `live_structure_object` returns, and the tools through `./formchem mcp` (they ran over HTTP with curl). diff --git a/docs/CLI.md b/docs/CLI.md index 949977c8..6c802a42 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1,6 +1,6 @@ # FormChem command line -Four commands convert, describe and draw whole files of structures without opening the window, built from 0.7.0: `convert`, `batch`, `descriptors` and `render`. They run the engine's chemistry in-process from the source tree (the engine's `backend/venv`), with no server and no window. The formats they read and write are described in [FORMATS.md](FORMATS.md). +Four commands convert, describe and draw whole files of structures without opening the window, built from 0.7.0: `convert`, `batch`, `descriptors` and `render`. They run the engine's chemistry in-process from the source tree (the engine's `backend/venv`), with no server and no window. The formats they read and write are described in [FORMATS.md](FORMATS.md). From 0.11.0 a fifth command, `db`, creates, imports into, searches and exports structure databases ([DATABASES.md](DATABASES.md)). From 0.12.0 `edit-live` asks the running FormChem to open a live structure for editing ([LIVE-STRUCTURES.md](LIVE-STRUCTURES.md)). ## Contents @@ -12,6 +12,8 @@ Four commands convert, describe and draw whole files of structures without openi - Standardising first - Failed records and exit codes - Speed and parallel jobs +- db (0.11.0) +- edit-live (0.12.0) - Where the code lives - Known limits @@ -150,12 +152,89 @@ Timings on a two-core Linux machine with other work running (RDKit 2025.09.3, Py Standardising costs about 2 ms a record, most of it the canonical SMILES taken after each step to tell whether it changed anything. +## db (0.11.0) + +`./formchem db` works on `.fcdb` databases without the window, through the same services as the engine's routes: + +``` +./formchem db create TITLE [--path FILE.fcdb] +./formchem db info DB +./formchem db import DB FILE [--format FMT] [--mode new|append|merge] [--key structure|FIELD] [--dry-run] [--errors report.csv] +./formchem db search DB (--substructure SMILES | --similarity SMILES [--threshold T] | --exact SMILES | --formula F | --query JSON) [--show N] +./formchem db export DB OUT [--format sdf|smiles|csv] [--hitlist ID] [--fields a,b] [--v3000] [--inchi] +``` + +- `create` makes a database; without `--path` it goes to the `Databases` folder of the data folder (`FORMCHEM_DATA_DIR`). +- `info` prints the title, the record and entry counts, the file, the duplicate rules and every field with its type and, for computed fields, its method. +- `import` reads SD, RD, SMILES, CSV, TSV (a SMILES or InChI column), `.fchem`, molfile or InChI files (`--format` when the extension does not say it) with the detected mapping. `--mode` is `new` (default), `append` or `merge`, and `--key` the merge key. `--dry-run` counts what would be added, updated and failed without writing. The first 20 failed records are printed; `--errors FILE` writes every one to a CSV file (`record,reason`). Ctrl+C stops the import and keeps what was written. +- `search` takes one structure option or a query node as JSON (the query language of [DATABASE.md](DATABASE.md)), makes a hit list (the window shows it later) and prints its first `--show` hits (default 20) as number-batch, uid, formula, SMILES and score. +- `export` writes the whole database, or `--hitlist ID`, to SD (V2000, `--v3000` for V3000), SMILES or CSV (`--inchi` for InChI instead of SMILES), the format taken from `OUT`'s extension unless `--format` is given; `--fields` limits the fields. + +Every subcommand takes `--json` to print the full answer as JSON. The exit code is 0 on success, 1 when an import did not finish (cancelled or failed) and 2 when the command was refused (a bad path, query or argument, a read-only database for a write). A database open in a running FormChem opens read-only here, and the other way round: the command line takes the database's lock while it works. + +A session in a fresh data folder: + +``` +$ ./formchem db create Demo +created /tmp/closer11/data/Databases/Demo.fcdb +$ ./formchem db import data/Databases/Demo.fcdb five.smi --errors failed.csv +done: read 5, added 4, updated 0, failed 1 in 0.0 s + record 4: SMILES Parse Error: unclosed ring for input: 'C1CC' +$ ./formchem db info data/Databases/Demo.fcdb +Demo: 4 records, 0 notebook entries + file /tmp/closer11/data/Databases/Demo.fcdb + rules stereo match, salts strip, on duplicate ask + field name text Name +$ ./formchem db search data/Databases/Demo.fcdb --substructure c1ccccc1 +Substructure c1ccccc1: 2 hits in 2 ms (hit list 1) + 1-1 cm268sj5j68 C7H6O2 O=C(O)c1ccccc1 + 4-1 cs9m480rurv C7H8 Cc1ccccc1 +$ ./formchem db export data/Databases/Demo.fcdb out.sdf +wrote 4 records to /tmp/closer11/out.sdf +``` + +The SMILES file's names became a `Name` field. At a larger size, 10,000 SD records imported through the same import code in about 34 s on the two-core machine above. + +## edit-live (0.12.0) + +`./formchem edit-live` is how a sibling Form app, a script or a terminal asks the FormChem that is running to open a structure from the shared structure library as a live drawing. Unlike the other commands it needs FormChem running: it reads the port from `engine.json` in the data folder and sends the request with the agent token, so it works without the window key. + +``` +./formchem edit-live ID [--from APP] +./formchem edit-live --object FILE [--from APP] +``` + +- `ID` is a library item id (`s` plus 10 letters or digits), or the path of the item's picture `Library/items/[id].svg`, which is read as its id. +- `--object FILE` is a live structure object (the JSON a sibling app keeps in its document, [LIVE_STRUCTURES.md](LIVE_STRUCTURES.md)). An object the library does not know, or one with a higher revision than the library's, is added with its own id and revision first. +- `--from APP` names the app asking; the window shows "Live structure from APP" beside the title. + +FormChem opens the structure in a new drawing (or brings it forward when it is already open); saving that drawing writes the item and raises its revision. The exit code is 0 when the structure opened, 1 when FormChem is not running or refused (its reason is printed), and 2 when the argument could not be read. + +A session against a running engine with a scratch data folder holding one item, phenol: + +``` +$ ./formchem edit-live s7jkf0w3t10 --from FormTxt +Opened Phenol for editing in FormChem (live structure s7jkf0w3t10, rev 1). +$ ./formchem edit-live ~/formchem/Library/items/s7jkf0w3t10.svg +Opened Phenol for editing in FormChem (live structure s7jkf0w3t10, rev 1). +$ ./formchem edit-live --object phenol.json --from FormDeck +Opened Phenol for editing in FormChem (live structure s7jkf0w3t10, rev 1). +$ ./formchem edit-live szzzzzzzzzz +FormChem refused: The structure library has no item szzzzzzzzzz. +$ ./formchem edit-live nothing.json +Could not read nothing.json: No such file or directory. +``` + +(`phenol.json` was saved from `GET /api/structures/s7jkf0w3t10/object`; the scratch folder's paths are shortened here; the exit codes were 0, 0, 0, 1 and 2.) + ## Where the code lives -`backend/app/cli.py` parses the arguments (started as `python -m app.cli` from `backend/` by `setup/convert` and `setup/convert.bat`, which `./formchem` and `formchem.bat` call). `backend/app/services/batch.py` holds the runners (`convert_file`, `batch`, `descriptors_file`, `render_file`), `services/chem/records.py` adapts records to the writers, `services/chem/stream.py` reads files record by record without building drawings, `services/chem/standardise.py` holds the steps and `services/chem/depict.py` draws. From 0.8.0 the agent tools `convert` and `batch_convert` call the same runners with the same options (`backend/app/services/agent_convert.py`), so an agent gets byte for byte the output of `./formchem convert` and `./formchem batch`, including `formchem-batch-report.csv`; they never write over an existing file or into a folder that already holds files ([AGENTS.md](AGENTS.md)). The reasons are in `backend/HASHOUT_LOG.md` entries 114, 122 to 128 and 141. +`backend/app/cli.py` parses the arguments (started as `python -m app.cli` from `backend/` by `setup/convert` and `setup/convert.bat`, which `./formchem` and `formchem.bat` call). `backend/app/services/batch.py` holds the runners (`convert_file`, `batch`, `descriptors_file`, `render_file`), `services/chem/records.py` adapts records to the writers, `services/chem/stream.py` reads files record by record without building drawings, `services/chem/standardise.py` holds the steps and `services/chem/depict.py` draws. From 0.8.0 the agent tools `convert` and `batch_convert` call the same runners with the same options (`backend/app/services/agent_convert.py`), so an agent gets byte for byte the output of `./formchem convert` and `./formchem batch`, including `formchem-batch-report.csv`; they never write over an existing file or into a folder that already holds files ([AGENTS.md](AGENTS.md)). The reasons are in `backend/HASHOUT_LOG.md` entries 114, 122 to 128 and 141. `./formchem db` is `backend/app/services/database/dbcli.py`, reached through the same launcher (`app/cli.py` hands it the `db` arguments); its reasons are entry 247. `edit-live` is `edit_live` in `backend/app/services/live_structures.py` (entry 261). ## Known limits - The command line runs from the source tree; the desktop app does not include it yet. - CDXML, CDX and RD files can be read but not written from the command line, and SMARTS is not offered; File > Export writes all four from a drawing. - `formchem.bat` and the process pool on macOS and Windows (the spawn start method) were not run for this version. +- `./formchem db` cannot add fields, run saved queries or reach the notebook; the window does, and the agent tools reach the notebook. `formchem.bat db` was not run for 0.11.0. +- `edit-live` was run against the engine on its own (no window, no desktop app); `formchem.bat edit-live` was not run for 0.12.0. diff --git a/docs/DATABASE.md b/docs/DATABASE.md new file mode 100644 index 00000000..23ce88b3 --- /dev/null +++ b/docs/DATABASE.md @@ -0,0 +1,252 @@ +# FormChem databases and notebooks + +The contract for structure databases and lab notebook entries (from 0.11.0): the `.fcdb` file, its tables, the query language, the engine routes, and the rules every writer keeps. The engine (`backend/app/services/database/`, `backend/app/services/notebook/`) and the window (`frontend/src/engine/database-api.ts`) implement exactly this file. When code disagrees with it, this file wins and the code is the bug. + +## Contents + +- The .fcdb file +- Tables +- Records and fields +- Structures, keys and fingerprints +- Registration and duplicates +- The query language +- Hit lists and saved queries +- Import and export +- Notebook entries and signing +- Locking and read-only mode +- Routes +- Agent tools and the command line +- Versioning + +## The .fcdb file + +A FormChem database is one SQLite 3 file with the extension `.fcdb`. It opens in any SQLite browser and every table and column name is plain English. It holds compounds, the person's own fields, attachments, hit lists, saved queries, form layouts, notebook entries and an audit log, so moving the one file moves everything. + +- Journal mode is `DELETE` (not WAL), so the file is never split into `-wal` and `-shm` files while closed. `foreign_keys` is on for every connection. +- `PRAGMA application_id` is `0x46434442` ("FCDB") and `PRAGMA user_version` is the format version (1). +- Text is UTF-8. Times are seconds since the Unix epoch as REAL (UTC). JSON columns hold compact JSON text. +- New databases go to `FORMCHEM_DATA_DIR/Databases/` unless the person picks a folder. The Home list of databases is the `databases` list of `library.json` (`path`, `name`, `opened`, `count`). + +## Tables + +| Table | Holds | +| --- | --- | +| `meta` | `key TEXT PRIMARY KEY`, `value TEXT`. Keys: `format` (`formchem-database`), `format_version` (1), `title`, `description`, `created`, `app_version`, `rules` (JSON, below) | +| `compounds` | one row per registered structure (below) | +| `fields` | the person's own fields, one row each | +| `field_values` | `compound`, `field`, `num REAL`, `txt TEXT`; primary key `(compound, field)`, both cascade on delete | +| `attachments` | `id`, `compound` (or NULL), `entry` (or NULL), `name`, `mime`, `size`, `sha256`, `data BLOB` (stored) or `path TEXT` (referenced), `created` | +| `hitlists` | `id INTEGER PRIMARY KEY`, `name`, `query` (JSON or NULL), `created`, `saved` (0 or 1) | +| `hitlist_items` | `hitlist`, `compound`, `rank INTEGER`, `score REAL` (similarity or NULL); primary key `(hitlist, compound)` | +| `queries` | saved queries: `id`, `name`, `folder` (a `/`-separated path, `""` for the top), `query` (JSON), `created`, `last_run`, `last_count` | +| `forms` | `id`, `name`, `style` (`single`, `double`, `card`, `custom`), `layout` (JSON), `is_default` | +| `entries` | notebook entries (below) | +| `entry_versions` | `id`, `entry`, `at`, `reason` (`signed`, `edited-after-signing`), `content` (JSON), `hash` | +| `entry_compounds` | `entry`, `compound`, `role` (`reactant`, `reagent`, `product`), `sample TEXT`; primary key `(entry, compound, role)` | +| `audit` | `id`, `at`, `actor` (`person`, `import`, `agent:[client name]`), `action`, `target` (a uid or NULL), `detail` (JSON) | +| `thumbs` | `compound`, `size`, `svg`; cache only, any reader may drop it | + +`records` is a view the engine recreates whenever fields change: one row per compound with `uid`, `smiles`, `formula`, `mw` and one column per field, named by the field's label. It exists so a generic SQLite browser shows a readable table; FormChem never reads it. + +### compounds + +| Column | Type | Meaning | +| --- | --- | --- | +| `id` | INTEGER PRIMARY KEY | row id, internal | +| `uid` | TEXT UNIQUE | stable public id: `c` plus 10 characters `[a-z0-9]`; every route, hit list export and agent uses it | +| `number` | INTEGER UNIQUE | the registration number the person sees (1, 2, 3, never reused) | +| `batch` | INTEGER | batch of this structure, 1 for the first registration | +| `parent` | TEXT | uid of the first batch when this row is a later batch, else NULL | +| `molfile` | TEXT | the structure, molfile V2000, V3000 only when V2000 cannot hold it (enhanced stereo, more than 999 atoms) | +| `smiles` | TEXT | canonical isomeric SMILES (RDKit) | +| `inchi`, `inchikey` | TEXT | standard InChI and InChIKey | +| `skeleton` | TEXT | first block of the InChIKey (connectivity only), for exact search that ignores stereo | +| `parent_key` | TEXT | InChIKey of the standardised parent (salts stripped, neutralised, largest fragment), for duplicate checks | +| `formula` | TEXT | Hill formula | +| `mw`, `exact_mass` | REAL | average and monoisotopic mass | +| `heavy_atoms` | INTEGER | heavy atom count | +| `fp` | BLOB | Morgan fingerprint, radius 2, 2048 bits, packed little-endian (256 bytes), for similarity | +| `sfp` | BLOB | RDKit pattern fingerprint, 2048 bits (256 bytes), for substructure screening | +| `counts` | TEXT | element counts as JSON (`{"C": 9, "H": 8, "O": 4}`), for formula search | +| `created`, `modified` | REAL | times | + +Indexes: `inchikey`, `skeleton`, `parent_key`, `formula`, `mw`. + +## Records and fields + +A record is a compound row plus its field values. Field types: + +| `type` | Stored in | Notes | +| --- | --- | --- | +| `integer`, `real` | `num` | `unit` and `digits` (significant figures shown) | +| `text`, `richtext` | `txt` | no length limit; rich text is the notebook's plain markup (below) | +| `datetime` | `num` | seconds since the epoch | +| `boolean` | `num` | 0 or 1 | +| `choice` | `txt` | one of `choices` | +| `multichoice` | `txt` | JSON list, each one of `choices` | +| `structure`, `reaction` | `txt` | molfile, or RXN text for a reaction | +| `image`, `file` | `num` | an `attachments.id` | +| `link` | `txt` | the uid of another record | +| `computed` | `num` or `txt` | the engine fills it from `computed` (a descriptor key from `GET /api/analysis/properties`: `clogp`, `tpsa`, `hbd`, `hba`, `rotatable`, `rings`, `aromatic_rings`, `fsp3`, `mr`, `charge`) whenever the structure changes; never written by a person | + +A field row: `id`, `name` (a key, `[a-z][a-z0-9_]{0,63}`, never changes), `label`, `type`, `unit`, `digits`, `choices` (JSON list), `computed`, `position`, `width`, `hidden`. The built-in columns (`number`, `uid`, `structure`, `formula`, `mw`, `exact_mass`, `smiles`, `inchikey`, `created`, `modified`) are not field rows and their names are reserved. + +## Structures, keys and fingerprints + +Every write of a structure goes through one function, `services/database/chem.py` `register_values(molblock)`, which sanitises with RDKit and fills every chemistry column above. A structure RDKit refuses is not stored; the caller gets the reason. Fingerprints are recomputed only by that function. A reader that needs a fingerprint the row does not have (an old row, a dropped column) recomputes and writes it back. + +## Registration and duplicates + +`meta.rules` holds the duplicate rules: `{"stereo": "match" | "ignore", "salts": "strip" | "keep", "on_duplicate": "ask" | "new" | "batch" | "existing"}`. Default `{"stereo": "match", "salts": "strip", "on_duplicate": "ask"}`. + +Adding a structure looks for duplicates by `parent_key` when salts are stripped, else `inchikey`; with stereo ignored it compares `skeleton` instead (of the parent when salts are stripped). On a duplicate with `ask`, the add route answers 409 with the duplicates and the person (or agent) chooses: `existing` opens the existing record, `batch` adds a new batch of it (same `number`, next `batch`, `parent` set), `new` registers it anyway under a new number. + +## The query language + +A query is JSON. A node is either a group or a term: + +```json +{ "op": "and", "terms": [ + { "kind": "substructure", "structure": { "smiles": "c1ccccc1" } }, + { "kind": "number", "field": "mw", "cmp": "<=", "value": 300 }, + { "op": "not", "terms": [ { "kind": "formula", "formula": "N0" } ] } ] } +``` + +`op` is `and`, `or` or `not` (`not` takes one term). Terms: + +| `kind` | Keys | Matches | +| --- | --- | --- | +| `exact` | `structure`, `stereo` (`match`, `ignore`), `salts` (`strip`, `keep`), `charges` (`match`, `ignore`), `tautomers` (`match`, `ignore`) | identity on the chosen key | +| `substructure` | `structure` (`smiles`, `molfile` or `smarts`), `chirality` (bool) | screened by `sfp`, confirmed by RDKit substructure match | +| `similarity` | `structure`, `threshold` (0 to 1, default 0.7) | Tanimoto on `fp`; each hit carries its `score`; results sorted by score | +| `formula` | `formula`, `mode` (`contains`, `exact`) | element counts; grammar below | +| `mass` | `field` (`mw`, `exact_mass`), `min`, `max` | inclusive range | +| `text` | `field`, `match` (`contains`, `starts`, `word`, `equals`, `regex`), `value`, `case` (bool) | text fields and `smiles`, `uid`, `formula` | +| `number` | `field`, `cmp` (`<`, `<=`, `=`, `>=`, `>`, `between`), `value`, `value2` | numeric fields, `number`, `batch`, `mw`, `exact_mass`, `heavy_atoms` | +| `date` | `field` (or `created`, `modified`), `from`, `to` | inclusive; either end may be absent | +| `choice` | `field`, `any` (list) | a choice or multichoice field holding any of the values | +| `empty` | `field`, `empty` (bool) | the field has no value, or has one | +| `hitlist` | `id` | members of a hit list | + +A `structure` is `{"smiles": ...}`, `{"molfile": ...}` or `{"smarts": ...}` (substructure only). The window sends the selection or the whole drawing as a molfile. + +Formula grammar: element symbols each followed by a count or a range, `C6-8H*N1O0-2`. A missing count means 1, `*` means any number, `0` means none, `a-b` an inclusive range, `a-` at least a. `exact` requires that no other element is present; `contains` allows others. + +A search runs over the whole database, or within a hit list when `within` is given. Raising a similarity threshold never adds hits. + +## Hit lists and saved queries + +Every search makes a hit list (`saved` 0, named from the query, for example "Substructure c1ccccc1"). The engine keeps the newest 20 unsaved hit lists per database and deletes older ones. Saving a hit list sets `saved` 1 and a name. Hit lists combine by `union`, `intersect` and `difference` into a new hit list; the result keeps the rank order of the first list and drops scores. + +A saved query stores a query node and a folder path; running it updates `last_run` and `last_count` and makes a hit list. A plot lasso or any selection of records becomes a hit list through the selection route. + +## Import and export + +Import reads SD files (V2000 and V3000), RD files, SMILES files (one structure per line, optional name after a space or tab), CSV and TSV with a structure column (SMILES or InChI, detected), and `.fchem` documents (each fragment; reactions are not imported, because a compound row holds one molecule). It is streaming and cancellable, runs as a job, and never stops on a bad record: the job's report lists each failed record's number (1-based in the file) and reason. Modes: + +- `new`: every good record becomes a new compound (duplicates follow `rules.on_duplicate`, with `ask` read as `new`). +- `append`: the same, the name the import dialog shows for an existing database. +- `merge`: a record whose key matches an existing compound updates that compound's mapped fields; the rest are appended. The key is `structure` (the duplicate rules) or a field name. + +A preview (`dry_run`) reads the whole file without writing and answers the counts that would be added, updated and failed, so the dialog shows them before commit. The mapping is `{source column or SD tag: field name | "" (skip) | "+label" (create a new field with this label, type detected)}`. + +Export writes the current hit list, a list of uids, or the whole database to SD (V2000, or V3000 when asked), SMILES (`smiles` then tab then `number`), or CSV (structure as SMILES or InChI, chosen fields as columns). An SD round trip into a new database keeps every InChIKey and every scalar field. + +## Notebook entries and signing + +An entry is one experiment. `entries` columns: + +| Column | Meaning | +| --- | --- | +| `id`, `uid` | `uid` is `n` plus 10 characters `[a-z0-9]` | +| `number` | the entry number the person sees (1, 2, 3) | +| `title`, `author`, `created`, `modified`, `date` | `date` is the experiment date the person chose (seconds) | +| `template` | the template it started from (`blank`, `reaction`, `analysis`, `purification`), informational | +| `scheme` | a FormChem `document.json` holding the reaction scheme (one page), or NULL | +| `procedure`, `observations` | plain markup: paragraphs separated by blank lines, `- ` bullets, `**bold**`, `*italic*`, nothing else | +| `products` | JSON list of `{ "compound": uid or null, "name", "sample", "mass_g", "yield_pct", "purity_pct", "notes" }` | +| `tags` | JSON list of strings | +| `status` | `open`, `signed`, or `modified` (changed after signing) | +| `signed_at`, `signed_by`, `signed_hash` | set by signing | + +The stoichiometry of an entry is computed from its scheme by the existing reaction services, never stored. + +The content hash is SHA-256 (hex) over the canonical JSON (sorted keys, no spaces, UTF-8) of `{uid, number, title, author, date, scheme, procedure, observations, products, tags, attachments}`, where `attachments` is the sorted list of the entry's attachment `sha256` values. Signing stores the hash, the time and the name, and writes an `entry_versions` row with reason `signed` and the full content. Any later change to a signed entry sets `status` to `modified`, writes an `entry_versions` row `edited-after-signing` with the content as it was signed (once per signing), and keeps `signed_hash`; the window shows "Modified after signing". Signing again records a new signed version. + +Entry search covers title, procedure, observations, tags and sample ids (text), and the scheme (substructure over the scheme's fragments). + +An entry exports as a self-contained HTML file (pictures inline as SVG, attachments listed with their hashes) and as JSON (`{"format": "formchem-entry", "format_version": 1, ...}` with the content above, the hash and the versions). + +## Locking and read-only mode + +The engine opening a database for writing creates `[file].lock` beside it holding `{"pid", "host", "app": "formchem", "opened"}`. A second engine (another FormChem, or the same file opened twice) finding a live lock opens the database read-only and says so; a lock whose process is gone on the same host is stale and is taken over. Read-only databases refuse every write route with 423. Closing the database (or engine exit) removes the lock. + +## Routes + +All routes need the window key, reads included because records hold private data; agents reach databases through the MCP tools (below), which need the agent token, not through these routes. The two picture routes (thumbnails and attachments), which the window loads through image and link tags that cannot send a header, also take the view key as the query parameter `k`: `GET /api/window/view-key` (window key required) answers `{key, param}`, and that key opens only those two routes. `{db}` is the open database's handle (`g` plus 8 characters), returned by create and open. Writes answer the changed record, entry or hit list. + +| Method and path | Body or query | Answer | +| --- | --- | --- | +| `GET /api/databases` | | `{open: [Info], known: [{path, name, opened, count, exists}]}` | +| `POST /api/databases` | `{path?, title}` | `Info` of the new, open database | +| `POST /api/databases/open` | `{path, adopt?}`; with `adopt: true` the path must be an `.fcdb` just sent to the uploads route, and it moves into the Databases folder first (a browser window has no paths) | `Info` | +| `POST /api/databases/{db}/close` | | `{closed: true}` | +| `GET /api/databases/{db}` | | `Info`: `{db, path, title, description, count, readonly, rules, fields, forms, entries}` | +| `PATCH /api/databases/{db}` | `{title?, description?, rules?}` | `Info` | +| `POST /api/databases/{db}/fields` | `Field` without `id` | `Field` | +| `PATCH /api/databases/{db}/fields/{name}` | label, type, unit, digits, choices, computed, position, width, hidden; a type change converts values between number and text storage and drops them to or from `computed` | `Field` | +| `DELETE /api/databases/{db}/fields/{name}` | | `{deleted: name}` | +| `GET /api/databases/{db}/records` | `hitlist`, `offset`, `limit` (max 500), `sort`, `desc` | `{total, rows: [Row]}` | +| `GET /api/databases/{db}/records/{uid}` | | `Record` (with `molfile` and `attachments`) | +| `POST /api/databases/{db}/records` | `{structure, values?, on_duplicate?}` | `Record`, or 409 `{detail, duplicates: [Row]}` with `duplicates` at the top level | +| `PATCH /api/databases/{db}/records/{uid}` | `{structure?, values?}` | `Record` | +| `POST /api/databases/{db}/records/delete` | `{uids}` | `{deleted: n}` | +| `GET /api/databases/{db}/records/{uid}/thumb.svg` | `size` (64 to 512), `theme` (dark or light, default dark), `v` (the record's `modified`, for caching), `k` (view key) | SVG | +| `POST /api/databases/{db}/records/{uid}/attachments` | multipart `file`, or `{path, link: true}` | `Attachment` | +| `GET /api/databases/{db}/attachments/{id}` | | the bytes | +| `POST /api/databases/uploads` | multipart `file` (the browser window, which has no paths) | `{path}`: a copy under `Databases/.uploads/`, deleted after 24 hours | +| `POST /api/databases/{db}/import/preview` | `{path, format?}` | `{format, count, columns: [{name, type, sample}], mapping}` | +| `POST /api/databases/{db}/import` | `{path, format?, mode, key?, mapping, dry_run?}` | `Job` | +| `GET /api/databases/jobs/{job}` | | `Job`: `{job, state (running, done, failed, cancelled), read, added, updated, failed, report: [{record, reason}], dry_run}` | +| `POST /api/databases/jobs/{job}/cancel` | | `Job` | +| `POST /api/databases/{db}/export` | `{format, path?, hitlist?, uids?, fields?, v3000?, structure_as?}` | `{path, written, skipped, url?}`; without `path` the file goes to `Databases/.exports/` and `url` serves it once for a browser download | +| `GET /api/databases/downloads/{name}` | | the exported file, then it is deleted | +| `POST /api/databases/{db}/search` | `{query, within?, name?}` | `HitList` plus `{took_ms, screened}` | +| `GET /api/databases/{db}/hitlists` | | `[HitList]` | +| `PATCH /api/databases/{db}/hitlists/{id}` | `{name?, saved?}` | `HitList` | +| `DELETE /api/databases/{db}/hitlists/{id}` | | `{deleted: id}` | +| `POST /api/databases/{db}/hitlists/combine` | `{a, b, op, name?}` | `HitList` | +| `POST /api/databases/{db}/hitlists/from-selection` | `{uids, name?}` | `HitList` | +| `GET /api/databases/{db}/queries` | | `[SavedQuery]` | +| `POST /api/databases/{db}/queries` | `{name, folder, query}` | `SavedQuery` | +| `PATCH /api/databases/{db}/queries/{id}` | `{name?, folder?, query?}` | `SavedQuery` | +| `DELETE /api/databases/{db}/queries/{id}` | | `{deleted: id}` | +| `POST /api/databases/{db}/queries/{id}/run` | `{within?}` | `HitList` | +| `GET /api/databases/{db}/plot` | `x`, `y` (field names or built-ins), `hitlist?` | `{points: [[uid, x, y]], x_label, y_label}`; `y` absent gives `[uid, x]` | +| `GET /api/databases/{db}/forms` | | `[Form]` | +| `PUT /api/databases/{db}/forms/{id}` | `Form` | `Form` | +| `POST /api/databases/{db}/forms/generate` | `{style, name?}` | `Form` | +| `GET /api/databases/{db}/entries` | `q?`, `substructure?` (SMILES), `offset`, `limit` | `{total, rows: [EntryRow]}` | +| `POST /api/databases/{db}/entries` | `{title, template?, author?, date?}` | `Entry` | +| `GET /api/databases/{db}/entries/{uid}` | | `Entry` with `stoichiometry`, `attachments`, `versions` (ids, at, reason) and `hash_method` | +| `PATCH /api/databases/{db}/entries/{uid}` | any content field | `Entry` | +| `POST /api/databases/{db}/entries/{uid}/sign` | `{by}` | `Entry` | +| `GET /api/databases/{db}/entries/{uid}/versions/{id}` | | `{content, hash, at, reason}` | +| `POST /api/databases/{db}/entries/{uid}/attachments` | as record attachments | `Attachment` | +| `POST /api/databases/{db}/entries/{uid}/export` | `{format: html or json, path?, picture?}`; `picture` is an SVG of the scheme drawn by the window | `{path}`; without `path` the file goes to `Databases/.exports/` | +| `POST /api/databases/{db}/entries/{uid}/export/download` | `{format: html or json, picture?}` | the file as a download (browser window) | +| `GET /api/databases/{db}/entries/{uid}/scheme.fchem` | | the scheme as a `.fchem` package, for Edit Scheme | + +A `Form` is `{id, name, style, is_default, items: [{kind, field?, label?, x, y, w, h}]}` with `kind` one of `structure`, `field`, `label`, `frame`, `picture`, `check`, `button` (`action`: a command id), `subform` (`field`: a link field), in points on a 600 point wide canvas. Generating a form for any number of fields lays them out without overlap. + +The engine broadcasts `{"t": "database", "db", "change": "records" | "fields" | "hitlists" | "queries" | "forms" | "entries" | "info", "uids"?}` to every client (`hub.broadcast_all`) on the live WebSocket after every write, so every window and agent view stays current. + +## Agent tools and the command line + +MCP tools (from 0.11.0): `db_list`, `db_create`, `db_open`, `db_import`, `db_search`, `db_get_record`, `db_add_record`, `db_update_record`, `db_export`, `nb_add_entry`, `nb_search`. Every write is logged in `audit` with `actor` `agent:[client name]` and in Agent Activity. + +The command line: `./formchem db create|info|import|search|export`, the same services the routes use. + +## Versioning + +`format_version` 1 from 0.11.0. A newer file opens read-only with a message naming the version it needs. A change to any table, column or JSON shape here raises the version, updates this file, the engine and the window in the same change, and adds a migration in `services/database/schema.py`. diff --git a/docs/DATABASES.md b/docs/DATABASES.md new file mode 100644 index 00000000..5dd69180 --- /dev/null +++ b/docs/DATABASES.md @@ -0,0 +1,209 @@ +# Databases and the lab notebook + +How to keep compounds in a FormChem structure database and experiments in its lab notebook, from 0.11.0: the database workspace, its views, fields, registration and duplicates, search, hit lists, saved queries, the plot, import and export, notebook entries and signing, the agent tools, the command line and the limits. The file, its tables, the query language and the routes are defined in [DATABASE.md](DATABASE.md), which wins over this page. + +## Contents + +- A database is one file +- The workspace +- Views +- Fields +- Adding structures, duplicates and batches +- Searching +- Hit lists +- Saved queries +- The plot +- Importing records +- Exporting records +- Record details and files +- Read-only databases +- The lab notebook +- Signing an entry +- Exporting an entry +- Agents +- The command line +- Limits +- Where the code lives + +## A database is one file + +A FormChem database is one SQLite file with the extension `.fcdb`. It holds the compounds, your fields and their values, attached files, hit lists, saved queries, forms, notebook entries and a log of every change, so copying or backing up the one file keeps everything. Any SQLite browser opens it: the `records` view shows one readable row per compound with its number, SMILES, formula, mass and every field under its label. + +New databases go to the `Databases` folder of FormChem's data folder unless you choose a folder. Home's Databases list shows the databases you opened with their record count; a database whose file has moved is greyed. + +## The workspace + +File > New Database... asks for a title (and, in the desktop app, a folder). File > Open Database... lists the databases FormChem knows beside a path box; the desktop app also has a file chooser. A browser window can open an `.fcdb` file through File > Open or by dropping it on Home: the file is copied into the Databases folder first, because a browser window has no file paths. File > Databases (`Shift+Mod+D`) shows and hides the workspace. + +The workspace fills the window. The left column lists the open databases, the hit lists and the saved queries; the toolbar holds the database's title and record count, the search bar, the view switcher, Import, Export, Add Structure and a gear menu (Settings, Fields, Advanced Search, Save Query, Combine Hit Lists, New Notebook Entry). Home's button returns to Home. Close Database closes the file; hiding the workspace keeps it open. + +Keys inside the workspace: arrows, Page Up and Page Down, Home and End move the current record (Shift extends the selection), `Mod+A` selects every record, Delete asks before deleting the selected records, Enter opens the record's details, F2 edits its first field, Escape clears the selection. + +## Views + +All views show the same records (the whole database, or the current hit list) and share one selection. + +- Table: one row per record with its picture. Click a header to sort (ascending, descending, back to registration order), drag a header edge to resize, use the column picker to show or hide columns (SMILES and InChIKey are hidden at first), and the header menu to freeze the columns up to the one clicked. Double-click a field value to edit it in place (a list for choices, a date picker, a toggle for yes or no); Enter or Tab saves, Escape cancels, and a value the field cannot take is refused with the reason. Records load as you scroll, so a database of any size opens at once. +- Gallery: a tile per record with the structure and two captions you choose. +- Form: one record at a time on a form. Previous record and Next record page through the records; edits save on Enter or when you leave the box. Generate Form makes a single-column, two-column or card form that lists every visible field, and keeps it current when fields change. +- Plot: see "The plot" below. +- Notebook: see "The lab notebook" below. + +Every computed number names its method and the RDKit version in its column header's tooltip. + +## Fields + +Database > Fields... adds, renames, orders, hides and deletes your fields. Types: + +| Type | Holds | +| --- | --- | +| Text, Rich text | text of any length; rich text uses the notebook's markup | +| Whole number, Number | a number, with a unit and the significant figures shown | +| Date and time | a date and time | +| Yes or no | a tick | +| Choice, Several choices | one, or several, of a list you give | +| Structure, Reaction | a structure or a reaction | +| Image, File | an attached file | +| Link to a record | another record of the same database | +| Computed from the structure | a descriptor FormChem fills from the structure: cLogP, TPSA, hydrogen bond donors and acceptors, rotatable bonds, rings, aromatic rings, fraction sp3, molar refractivity or formal charge | + +A computed field is the same calculation as the Analysis panel's, names its method, and follows every change of the structure; you cannot type into it. Built-in columns (number, uid, structure, formula, MW, exact mass, SMILES, InChIKey, created, modified) are always there. + +## Adding structures, duplicates and batches + +Structure > Add to Database (in a drawing) adds the selected structure, or the whole page when nothing is selected, to the open database. Every record gets a registration number (1, 2, 3 and so on), which is never given out again after a delete, and a uid (`c` and ten characters) that never changes. + +Database > Database Settings... sets the duplicate rules: + +- Stereo: matched (the enantiomers are different compounds) or ignored. +- Salts: stripped (a hydrochloride is the same compound as its free base) or kept. +- On a duplicate: ask, register a new compound, add a new batch, or use the existing record. + +With "ask", adding a structure that is already there opens a dialog with the matching records (up to 24 pictures, and the count): Open Existing shows one, Add as New Batch keeps its number with the next batch number (the Batch column, hidden at first, shows it), Add Anyway gives it a new number. + +## Searching + +Type in the search bar and press Enter to search names, ids, formulas, SMILES and every text field; a number also finds that registration number, and a formula such as `C6-8N1` searches formulas. + +Structure, beside the search bar, searches with the selection in your drawing (or the whole drawing): + +- Exact: the same compound, with stereo, salts, charges and tautomers matched or ignored (the database's rules by default). +- Substructure: every record that contains the drawn structure; chirality can be required. +- Similarity: Tanimoto similarity on Morgan fingerprints (radius 2, 2048 bits) at or above a threshold from 0 to 1 (0.7 by default). Each hit carries its score and the list is sorted by it. Raising the threshold never adds hits. + +Database > Advanced Search... builds a query from terms in All of, Any of and None of groups, nested as deep as needed. Terms: exact, substructure (also SMARTS), similarity, formula (`C6-8H*N1O0-2`: a count or a range per element, `*` any number, `0` none; Contains allows other elements, Exact does not), mass (average or monoisotopic, a range), text (contains, starts with, whole word, equals or a regular expression, with or without case), number (`<`, `<=`, `=`, `>=`, `>` or between), date (a range), choice (any of the values), empty or not, and member of a hit list. Search within the current hit list narrows it. The builder keeps Search off until every term is complete and names the one that is not. + +## Hit lists + +Every search becomes a hit list in the left column, named from its query ("Substructure c1ccccc1 and mw <= 300") and showing its count. FormChem keeps the newest 20 hit lists you did not keep and deletes older ones. On a hit list you can: + +- Keep it, so it stays, and rename it (F2). +- Export its records. +- Delete it (Delete asks first). +- Combine two (Database > Combine Hit Lists...): union, intersection or difference, as a new hit list in the order of the first. + +All records, at the top of the list, leaves the hit list. A selection of records, or a lasso in the plot, becomes a hit list too. + +## Saved queries + +Database > Save Query... stores the current query under a name in a folder (`Projects/Aromatics`). The Saved Queries section shows the folders as a tree with each query's last count and run time; click one to run it again (a new hit list named after it), and rename, move or delete it from its menu. + +## The plot + +The Plot view draws a histogram of one numeric field or built-in (Sturges bins), or a scatter of two, over the current hit list or the whole database. A scatter can show a least-squares line with its slope, intercept and R squared, and colour the points by a third field. Records missing a value are counted, not drawn. Drag a rectangle or a lasso to select points (on a point too), then Hit List from Selection (or Enter) makes them a hit list. + +## Importing records + +Database > Import Records... (or Import in the toolbar) reads: + +| File | Structures from | +| --- | --- | +| SD file (`.sdf`, `.sd`), V2000 and V3000 | each record; data items become columns, the title line a `name` column | +| RD file (`.rdf`, `.rd`) | each molecule record | +| SMILES file (`.smi`) | one per line, a name after a space or tab | +| CSV and TSV | the SMILES or InChI column, found by its header or its contents | +| FormChem drawing (`.fchem`) | each structure in it (reactions are not imported) | + +The dialog shows the columns with their detected types. Map each to an existing field, to a new field, or skip it. Then choose a mode: + +- New (an empty database) or Append: every good record becomes a new record; duplicates follow the database's rules, with "ask" read as "register anyway". +- Merge: a record that matches an existing one, by structure (the duplicate rules) or by a field you name, updates that record's mapped fields; the rest are added. + +Check counts what would be added, updated and failed without writing anything. Import runs in the background with a progress line; Stop ends it part way and keeps what was imported. A bad record never stops an import: the report lists each failed record with its number in the file and a plain reason (RDKit's own words follow in brackets), and Copy Report copies it. + +## Exporting records + +Database > Export Records... writes the current hit list, the selected records or the whole database to: + +- SD (V2000, or V3000 when chosen): every field with a single value becomes a data item under its label, so importing the file into a new database rebuilds the same fields and values. +- SMILES: the SMILES, a tab and the registration number. +- CSV: the structure as SMILES or InChI and the fields you choose. + +The desktop app saves where you choose; a browser window downloads the file. + +## Record details and files + +Enter or a double-click opens a record: its picture, number, batch and identifiers with copy buttons, every field, and its files. Add File stores a file up to 50 MB in the database; the desktop app can link a larger file by its path instead (only the path and its SHA-256 are kept). Open in Drawing opens the structure as a new drawing. + +## Read-only databases + +A database that another FormChem (or the command line) has open opens read-only, and the toolbar says why. You can browse, search, plot and export; adding, editing, importing and saving queries are off. A database written by a newer FormChem also opens read-only and names the version it needs. When the other FormChem closes, open the database again to write to it. + +## The lab notebook + +Notebook entries live in the database, beside its compounds. Database > Notebook > Notebook (or the Notebook view) shows the entries newest first, with a search box for words (title, procedure, observations, tags and sample ids; every word must appear) and a substructure search over each entry's scheme. + +New Notebook Entry... asks for a title, the experiment date and an author, and starts from a template: Blank, Reaction, Analysis or Purification (the last three start the procedure and observations with headings). An entry holds: + +- The reaction scheme: New Scheme from Drawing takes the first page of the open drawing; Edit Scheme opens the scheme as a drawing with a bar offering Save to Entry and Back to Notebook. +- The stoichiometry, computed from the scheme every time it is shown (formula, MW, role, amount, equivalents), with its method. It is never typed in. +- Procedure and observations in a simple markup: paragraphs separated by blank lines, `- ` bullets, `**bold**` and `*italic*`, with a preview. +- Products: name, sample id, mass, yield and purity, and a link to the product's record in the database, so the record knows which entries made it. +- Tags and attached files (stored up to 50 MB, or linked by path in the desktop app). + +Text saves a moment after you stop typing; other fields save when they change. + +## Signing an entry + +Sign Notebook Entry... records your name, the time and a SHA-256 hash of the entry's content (title, author, date, scheme, procedure, observations, products, tags and the hashes of its files) and keeps a copy of that content as a signed version. The entry shows Signed with the start of its hash. + +Any change after signing (a word, a product, a new file) marks the entry "Modified after signing" and keeps the signed version unchanged; the versions list shows it, and it opens read-only. Sign Again records a new signed version. Agents never sign entries. + +## Exporting an entry + +Export Notebook Entry... (or Export HTML and Export JSON on the entry) writes: + +- HTML: one self-contained file with the scheme as a picture, the stoichiometry with its method, the text, the products, the files listed with their hashes (pictures shown inline), the signature and, when there is one, the "Modified after signing" banner. It needs no network and prints as it shows. +- JSON: the content, its hash, the status and every version with its content (`format: formchem-entry`), so anyone can recompute each hash. + +## Agents + +Eleven MCP tools reach databases and the notebook: `db_list`, `db_create`, `db_open`, `db_import`, `db_search`, `db_get_record`, `db_add_record`, `db_update_record`, `db_export`, `nb_add_entry` and `nb_search`. A search by an agent appears as a hit list in your window. Every write by an agent is recorded in the database's log as `agent:[name]` and in Agent Activity, and the writing tools ask for your approval the first time. Arguments, answers and consent are in [AGENTS.md](AGENTS.md). + +## The command line + +`./formchem db create`, `info`, `import`, `search` and `export` work on a database without the window, through the same code; see [CLI.md](CLI.md). A database open in the app opens read-only from the command line, and the other way round. + +## Limits + +- Speed: on a small shared test machine, 10,000 SD records imported in about 34 s, and a benzene substructure search of 100,000 records took about half a second once FormChem had built its structure cache for that database (1.4 to 1.9 s for the first search). Similarity and formula searches of 100,000 records took 0.1 s and under 0.01 s. +- Files attached in the database are limited to 50 MB each; link larger ones (desktop app). +- The notebook has no spectra or grid of its own yet; attach spectra as files. +- `.fchem` imports take the structures, not the reactions. +- While the workspace is open it covers the in-window menu bar; the toolbar and gear menu carry the commands. +- Record values, hit list names, saved query names and entry titles show as typed in every language; RDKit's own messages stay in English. +- The desktop app's choosers, Link File and dropping an `.fcdb` file on the desktop window were not tried for 0.11.0. + +## Where the code lives + +| Path | What it holds | +| --- | --- | +| `backend/app/services/database/` | the file, store, registration, fields, forms, records, files, pictures, jobs, import, export, query, search, hit lists, saved queries, plot and `dbcli.py` (the command line) | +| `backend/app/services/notebook/` | templates, the content hash, schemes, products, entries, files, markup and export | +| `backend/app/routers/databases.py`, `db_search.py`, `notebook.py` | the routes of DATABASE.md | +| `backend/app/services/agent_db.py`, `agent_notebook.py` | the eleven agent tools | +| `frontend/src/engine/database-api.ts` | the window's client for the database routes | +| `frontend/src/ui/database/`, `ui/database-find/`, `ui/notebook/` | the workspace and its views and dialogs; search, hit lists, import, export and the plot; the notebook | +| `frontend/src/app/database-commands.ts` | the database commands and Add to Database | + +The reasons behind each choice are in `backend/HASHOUT_LOG.md` entries 223 to 255 and `frontend/HASHOUT_LOG.md` entries 245 to 276. diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 3201fc29..845ee492 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -224,7 +224,7 @@ A fragment may hold several disconnected pieces (a salt is one fragment). Fields | `chiral` | optional whole-molecule stereo flag: `"absolute"`, `"relative"` or `"racemic"` (built from 0.6.0). For chemistry, `relative` puts every stereocentre that is in no stereo group into one OR group and `racemic` puts them into one AND group, each with the next free group number; `absolute` (and absent) leaves them absolute. `absolute` also sets the molfile chiral flag | | `stereo_groups` | optional enhanced stereo groups `[ { "kind": "abs" }, { "kind": "and", "n": 1, "atoms": ["a4", "a9"] } ]`, kind `abs`, `and` or `or` (built from 0.6.0) | | `rgroups` | optional R-group definitions keyed by number as a string: `{ "1": { "members": ["f..."], "occurrence": ">0", "rest_h": false, "if_then": 2 } }`, `members` naming fragment objects that hold one member each (built from 0.6.0). A definition may carry `attach`, a map of member fragment id to that member's attachment atom ids in order (first, then second attachment point): `{ "f...": ["a..."] }`. A member without an `attach` entry uses its atoms whose `data.attach` is 1 or 2 (V3000 import writes these), else its attachment stubs: `"*"` atoms with no label, no `generic` and exactly one bond, in id order. An attachment atom that is such a stub stands for the R-group atom: its neighbour bonds to the scaffold and the stub is not part of the member; any other attachment atom bonds to the scaffold itself. A member with none of these attaches at its first atom by id | -| `conformers` | optional 3D coordinates (built from 0.10.0): `[ { "id": "c...", "coords": { "a1": [0.0, 1.2, -0.4] }, "h": { "a1": [[0.5, 1.9, 0.1]] }, "energy": -12.3, "method": "MMFF94", "converged": true } ]`. `coords` holds every atom of the fragment in ångström; `h` holds the positions of each atom's implicit hydrogens in the order RDKit adds them; `energy` is in kcal/mol for the named `method` (`"ETKDG"` when only embedded, `"MMFF94"`, `"MMFF94s"`, `"UFF"`, `"xtb"`, or `"file"` for coordinates read from a file, where `energy` is absent unless the file gave one). `expanded` (optional) holds, for an atom that stands for an abbreviation, the positions of the abbreviation's other atoms (heavy atoms, then hydrogens) in the order the engine expands it. `scan` (optional, on conformers kept from a dihedral scan) is `{ "atoms": ["a1", "a2", "a3", "a4"], "angle": -60.0 }`, the four atoms of the scanned dihedral and the angle held in degrees. A hydrogen is addressed as `a1:h0`, `a1:h1` (an index into `h["a1"]`) and an atom of an expanded abbreviation as `a5:x0` (an index into `expanded["a5"]`) wherever the 3D routes, measurements and labels name atoms. A conformer is valid only for the graph it was made from: any change to the fragment's atoms or bonds other than 2D positions and display fields drops `conformers` (and `conformer`) in the same transaction. The changes that count are an atom's `element`, `charge`, `isotope`, `radical`, `hydrogens`, `label`, `expansion`, `generic`, `rgroup` or `query`, a bond's ends, `order`, `stereo`, `query` or `topology`, and adding or removing atoms or bonds; the window and the engine apply the same rule, and a transaction that itself sets `conformers` or `conformer` is taken as written | +| `conformers` | optional 3D coordinates (built from 0.10.0): `[ { "id": "c...", "coords": { "a1": [0.0, 1.2, -0.4] }, "h": { "a1": [[0.5, 1.9, 0.1]] }, "energy": -12.3, "method": "MMFF94", "converged": true } ]`. `coords` holds every atom of the fragment in ångström; `h` holds the positions of each atom's implicit hydrogens in the order RDKit adds them; `energy` is in kcal/mol for the named `method` (`"ETKDG"` when only embedded, `"MMFF94"`, `"MMFF94s"`, `"UFF"`, `"xtb"`, or `"file"` for coordinates read from a file, where `energy` is absent unless the file gave one); for an xtb or CREST result `program` (optional) records `{ "name": "xtb" | "CREST", "version", "method": "GFN2-xTB" | "GFN-FF", "solvent": "gas phase" | "ALPB (Water)", "charge", "uhf", "energy_eh", "gap_ev"? }`, the program, version, method and solvent that produced it, the total energy in hartree (null when the program gave none) and the HOMO-LUMO gap in eV. `expanded` (optional) holds, for an atom that stands for an abbreviation, the positions of the abbreviation's other atoms (heavy atoms, then hydrogens) in the order the engine expands it. `scan` (optional, on conformers kept from a dihedral scan) is `{ "atoms": ["a1", "a2", "a3", "a4"], "angle": -60.0 }`, the four atoms of the scanned dihedral and the angle held in degrees. A hydrogen is addressed as `a1:h0`, `a1:h1` (an index into `h["a1"]`) and an atom of an expanded abbreviation as `a5:x0` (an index into `expanded["a5"]`) wherever the 3D routes, measurements and labels name atoms. A conformer is valid only for the graph it was made from: any change to the fragment's atoms or bonds other than 2D positions and display fields drops `conformers` (and `conformer`) in the same transaction. The changes that count are an atom's `element`, `charge`, `isotope`, `radical`, `hydrogens`, `label`, `expansion`, `generic`, `rgroup` or `query`, a bond's ends, `order`, `stereo`, `query` or `topology`, and adding or removing atoms or bonds; the window and the engine apply the same rule, and a transaction that itself sets `conformers` or `conformer` is taken as written | | `conformer` | optional id of the conformer the 3D view shows; absent means the first | ### Atoms diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 079f6b5e..f6e9443f 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -9,6 +9,8 @@ How FormChem reads and writes chemistry files and pictures, what each format kee - What each format keeps - Pictures and the drawing inside them - 3D files (0.10.0) +- Databases (0.11.0) +- HELM and live structures (0.12.0) - Reports - HTTP API - The window @@ -118,6 +120,46 @@ Report items of 3D files: | `not_sanitised` | warn | a record with valence problems, read without sanitising | | `record_failed` | error | a record could not be read and was skipped | +## Databases (0.11.0) + +A structure database is one SQLite 3 file with the extension `.fcdb` (`application_id` `0x46434442`, format version 1, DELETE journal), defined table by table in [DATABASE.md](DATABASE.md); how to use it is in [DATABASES.md](DATABASES.md). File > Open, Home's Open and a drop on Home send an `.fcdb` to the database workspace, never to the drawing importer. Any SQLite browser reads it; its `records` view shows one readable row per compound. Each stored structure is kept as a V2000 molfile (V3000 when V2000 cannot hold it), with canonical SMILES, InChI, InChIKey, formula and masses beside it. + +Database import and export use their own code (`backend/app/services/database/imports.py`, `exports.py`), not File > Import and Export, because they read and write records with fields rather than a drawing: + +| Format | Extensions | Import | Export | +| --- | --- | --- | --- | +| SD file | `.sdf`, `.sd` (and `.gz`) | each record, V2000 or V3000; data items become columns, the title line a `name` column | the stored molfile with an empty title line and every field with one value as a data item under its label; V3000 when asked | +| RD file | `.rdf`, `.rd` | each molecule record with its data items | not written | +| SMILES file | `.smi`, `.smiles` | one structure per line, a name after a space or tab | `SMILES`, a tab and the registration number per line | +| CSV, TSV | `.csv`; `.tsv`, `.tab`, `.txt` | a header row; the structure column is found by its header (`smiles`, `canonical_smiles`, `isomeric_smiles`, `smiles_string`, `structure`, `inchi`, `std_inchi`, `standard_inchi`) or by 80 percent of the sampled values reading as SMILES or InChI | CSV only: `SMILES` (or `InChI`), `number` and the chosen fields by label | +| Molfile, InChI | `.mol`; `.inchi` | one structure each, or one per line | not written | +| FormChem drawing | `.fchem` | each structure (reactions are not imported) | not written | + +Column types are detected for the mapping (text, integer, real, datetime). A bad record is skipped and listed in the import report with its number in the file (1-based) and a plain reason, RDKit's own words in brackets, for example "an atom has more bonds than its valence allows (RDKit: Explicit valence for atom # 0 C, 5, is greater than permitted)"; there are no report codes, because the report is per record, not per drawing. An SD export imported into a new database keeps every InChIKey and every scalar field value; structure, reaction, image and file fields are not exported. + +A notebook entry exports as one HTML file (self-contained: the scheme as inline SVG, pictures as data URIs, print rules) or as JSON with `"format": "formchem-entry"`, `"format_version": 1`, the content, its SHA-256 hash and every version, so each hash can be recomputed; see [DATABASE.md](DATABASE.md). + +## HELM and live structures (0.12.0) + +HELM is not in the format table: it is read and written through its own dialog, command and routes, because it describes monomers rather than atoms and a structure goes back to HELM only when it reads back the same ([HELM.md](HELM.md)). + +| Direction | How | What it takes or gives | +| --- | --- | --- | +| HELM in | Insert > Biopolymer from HELM..., `POST /api/helm/parse`, the agent tool `draw_from_helm` | HELM version 2 text: PEPTIDE, RNA and CHEM simple polymers, inline SMILES monomers, connections; the result is an ordinary fragment of atoms, laid out by FormChem's scored 2D layout | +| HELM out | Edit > Copy As > Copy as HELM, `POST /api/helm/from-structure` | HELM text for peptides and nucleic acids FormChem's 55 monomers cover, with their connections; copied only when it reads back to the same InChIKey, otherwise refused with the reason | + +A live structure is a structure that other Form apps keep as a picture with the FormChem drawing inside ([LIVE-STRUCTURES.md](LIVE-STRUCTURES.md); the contract is [LIVE_STRUCTURES.md](LIVE_STRUCTURES.md)). Its pieces use the formats on this page: + +| Piece | Format | +| --- | --- | +| `Library/items/[id].svg` | an SVG picture with the drawing inside, as in "Pictures and the drawing inside them" above (FormChem's subset fonts when the window drew it; an RDKit picture with the same `formchem-source` metadata when an agent added the item without a window) | +| `Library/items/[id].png` | a PNG 512 pixels wide with the drawing in its iTXt chunk | +| `Library/items/[id].mol` | a molfile (V2000, V3000 when needed), or an RXN file for a reaction | +| the live structure object | JSON with `"format": "formai-structure"`, `"format_version": 1`, the id, revision, name, SMILES, InChIKey, the SVG text, the molfile and the size in points | +| the clipboard | Copy as Live Structure: the object as `web application/x-formai-structure+json` (browsers allow custom types only with the `web ` prefix), `image/svg+xml`, `image/png`, `text/html` (an `img` with the SVG as a data URL and the object's base64 in `data-formai-structure`), `text/plain` (SMILES) and FormChem's own drawing | + +Because the item SVG and PNG are pictures with the drawing inside, File > Open reads them and dropping them on the canvas inserts their drawing, like any FormChem picture. A drawing opened as a live structure saves to its library item; Save As writes an ordinary `.fchem`. + ## Reports Every reader and writer returns report items of one shape: @@ -279,6 +321,6 @@ Timings on a two-core Linux machine: the whole corpus to every format and back i - CDXML and CDX go through Indigo, which does not carry colours, fonts (it writes Arial and Times), the bond length (it writes 30), line breaks in text (read back as spaces), curved arrows (written straight), shapes, brackets, tables, TLC plates and images, structure names and data, or R-group members on reading. Query structures cannot be written as CDX. Only files written by Indigo were tested, not files from the program that made the format. - Enhanced stereo is lost in CML, SMILES, InChI and SMARTS, conditions in SMILES, and every step after the first in RXN: these are limits of the formats. Abbreviations are written as their full structures in every format but `.fchem`. -- From 0.9.0 a chemical name pasted as text opens Structure from Name with its structure (see [NAMES.md](NAMES.md)); a name the engine cannot read still becomes a text object. JCAMP-DX spectra (`.jdx`, `.dx`, `.jcamp`) open and import as spectrum objects, not structures; they are described in [SPECTRA.md](SPECTRA.md). From 0.10.0 PDB and mmCIF files open as 3D objects and 3D SD and MOL files keep their coordinates as conformers (above, and [3D.md](3D.md)); XYZ and glTF are written, not read, and mmCIF is written back only as the original file. +- From 0.9.0 a chemical name pasted as text opens Structure from Name with its structure (see [NAMES.md](NAMES.md)); a name the engine cannot read still becomes a text object. JCAMP-DX spectra (`.jdx`, `.dx`, `.jcamp`) open and import as spectrum objects, not structures; they are described in [SPECTRA.md](SPECTRA.md). From 0.10.0 PDB and mmCIF files open as 3D objects and 3D SD and MOL files keep their coordinates as conformers (above, and [3D.md](3D.md)); XYZ and glTF are written, not read, and mmCIF is written back only as the original file. From 0.11.0 `.fcdb` files open as databases, and database import and export (above) read and write records with fields, not drawings. From 0.12.0 HELM is read and written only through its dialog, Copy as HELM and its routes (there is no `.helm` file type and no HELM in `./formchem convert`), and the molfile flavour of Copy as Live Structure is dropped by browsers. - EPS was checked by reopening its drawing, not by drawing it in a PostScript viewer. - In the desktop app the engine writes where the window says the person chose; it cannot prove a save dialog produced the path, and relies on the window key and its list of extensions. diff --git a/docs/HELM.md b/docs/HELM.md new file mode 100644 index 00000000..ab5629ef --- /dev/null +++ b/docs/HELM.md @@ -0,0 +1,116 @@ +# Biopolymers in HELM + +How FormChem reads peptides and nucleic acids written in HELM and writes structures back to HELM, from 0.12.0: what the reader accepts, the monomers it knows and where they came from, writing HELM from a drawing, the routes, the agent tool and the limits. + +## Contents + +- Inserting a biopolymer +- What the reader accepts +- The monomers +- Writing HELM from a drawing +- Methods and numbers +- HTTP API +- Agents +- Limits +- Where the code lives + +## Inserting a biopolymer + +Insert > Biopolymer from HELM... opens a dialog. Type or paste HELM; as you type, FormChem reads it and shows the structure, the number of monomers, the formula and the average and monoisotopic masses, with the method under them. When reading stops, the dialog marks the character where it stopped and says why, and Insert is off. Insert places the structure as atoms on the page, in free space, as one undo step. With no drawing open, a new drawing is made. + +Some strings to try: + +| HELM | What it is | +| --- | --- | +| `PEPTIDE1{G.G}$$$$` | glycylglycine, C4H8N2O3 | +| `PEPTIDE1{C.Y.I.Q.N.C.P.L.G.[am]}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$V2.0` | oxytocin with its disulfide, C43H66N12O12S2 | +| `RNA1{R(A)P.R(U)}$$$$` | the dinucleotide ApU, C19H24N7O12P | +| `CHEM1{[[*:1]CCO[*:2]]}$$$$` | an inline SMILES linker | + +Oxytocin reads and is laid out in about 0.12 s, a 20-residue peptide in about 0.5 s. + +## What the reader accepts + +FormChem reads HELM version 2: + +- simple polymers `PEPTIDE`, `RNA` and `CHEM`, with monomers separated by dots: one-letter symbols (`A`), bracketed symbols (`[dA]`, `[Aib]`) and inline SMILES with numbered attachment points (`[[*:1]CCO[*:2]]`); +- RNA units written as sugar(base)phosphate, such as `R(A)P`; monomer numbers count every sugar, base and phosphate in order (`R(A)P` is 1, 2, 3), as HELM does; +- whole repeat counts, which repeat the unit before them; +- connections such as `PEPTIDE1,PEPTIDE1,1:R3-6:R3` for disulfides, lactam bridges, head-to-tail rings and links between polymers; +- the empty group section, annotations (kept as text with a note) and the version section `V2.0`; a string with only the first section (no `$`) is read too. + +Refused, with the character where reading stopped: + +| Input | Reason given | +| --- | --- | +| `BLOB` polymers | "BLOB polymers have no defined structure, so FormChem cannot draw them." | +| mixtures in parentheses or with `,` or `+` | "Parentheses in a PEPTIDE or CHEM list describe a mixture of monomers, which FormChem does not read." | +| repeat ranges such as `'2-5'`, hydrogen-bond pairs, `?` attachment points, polymer groups | named in the message | +| an unknown symbol, such as `PEPTIDE1{A.X}` | "X is not a PEPTIDE monomer FormChem knows." (at character 12) | +| an unclosed bracket or brace | "A bracket or brace is not closed." | + +Limits: 100,000 characters, 2,000 monomers, 500 repeats, 20,000 atoms. + +Monomers are joined by pairing the two attachment points of each bond, which keeps every stereocentre as the monomer data has it; an attachment point that is not used gets its leaving group back (H or OH). + +## The monomers + +FormChem's monomer data (`backend/app/data/helm_monomers.json`, version 1.0, 55 monomers) was written for FormChem from textbook structures of the amino acids and nucleosides. No HELM monomer library was consulted or copied, because none had a licence cleared for FormChem. When the file loads, FormChem caps each monomer's attachment points with their leaving groups and checks the result against the capped structure written beside it, so a mistake in the data makes the loader refuse the file rather than draw a wrong residue. + +| Polymer | Symbols | Monomers | +| --- | --- | --- | +| PEPTIDE | A R N D C E Q G H I L K M F P S T W Y V | the 20 L amino acids (glycine has no stereocentre) | +| PEPTIDE | dA dR dN dD dC dE dQ dH dI dL dK dM dF dP dS dT dW dY dV | their 19 D forms, full mirror images | +| PEPTIDE | Aib, Nle, Orn, Sar, Hyp, pE | 2-aminoisobutyric acid, L-norleucine, L-ornithine, sarcosine, trans-4-hydroxy-L-proline, L-pyroglutamic acid | +| PEPTIDE | ac, am | the N-acetyl cap and the C-terminal amide cap | +| RNA | R, dR | ribose and 2-deoxyribose (beta-D-furanoses) | +| RNA | P | phosphate | +| RNA | A, C, G, U, T | the five bases | + +Attachment points: amino acids have R1 on the amine (leaving H) and R2 on the carboxyl (leaving OH); C, K, D, E and Orn (and their D forms) also have R3 on the side chain, for disulfide and lactam bridges. pE has only R2, ac only R2, am only R1. Sugars have R1 at 5'-O, R2 at 3'-O (both leaving H) and R3 at C1' for the base (leaving OH); phosphate has R1 and R2 (both leaving OH); bases attach at N9 or N1. + +`GET /api/helm/monomers` lists every monomer with its SMILES, capped form, attachment points and source. + +## Writing HELM from a drawing + +Edit > Copy As > Copy as HELM writes the selected structure (or the page) as HELM and copies it. FormChem cuts the structure at the bonds it knows between monomers: backbone amides, acetyl amides, disulfides, side-chain lactams (lysine or ornithine to aspartate or glutamate), the sugar to phosphate ester and the sugar to base bond. Each piece is matched to the monomer data, the attachment points are assigned, and the backbone is walked from R2 to R1; everything else becomes a connection, so cyclic and bridged peptides come back with their connections. + +HELM is copied only when it reads back to the same structure (the same standard InChIKey). Otherwise nothing is copied and the message says why, for example "1 part of the structure is not a peptide residue, cap, sugar, phosphate or base in FormChem's monomer data: C6H6 (6 heavy atoms)." A residue drawn without any stereo is matched to its L amino acid (or D sugar) with a note that stereo was assumed. Labels, R-groups and any-atoms have no monomer and are refused. + +Oxytocin inserted from HELM and copied back gives the identical string, with the `1:R3-6:R3` bridge. + +## Methods and numbers + +Every reading names its method: the reader ("FormChem HELM 1.0"), the monomer data ("FormChem monomer data 1.0 (55 monomers)"), RDKit's version for the chemistry and the masses, and the layout used (FormChem's scored 2D layout, or CoordGen without scoring above the layout's size limit). The InChIKey and SMILES are RDKit's. + +## HTTP API + +Every route needs the window key. + +| Route | Body | Answer | +| --- | --- | --- | +| `POST /api/helm/parse` | `{helm, bond_length?, x?, y?, draw?}` | `{ok, helm, formula, average_mass, exact_mass, inchikey, smiles, molfile, fragment, polymers, connections, residues, heavy_atoms, layout, seconds, warnings, method}`; on a syntax error `ok: false` and `error {code, text, position}` (position counted from 0) | +| `POST /api/helm/from-structure` | `{fragment, expansions?}`, `{smiles}` or `{molfile}` | `{ok, helm, method, warnings}`, or `ok: false` with `reason` | +| `GET /api/helm/monomers` | | `{version, source, count, monomers, method}` | + +## Agents + +`draw_from_helm {helm, doc?, x?, y?, name?}` draws a HELM string in a drawing as one undo step (it asks you the first time) and answers with the new ids, SMILES, InChIKey, formula and masses with their method, and a picture. Bad HELM is refused with the character where reading stopped. See [AGENTS.md](AGENTS.md). + +## Limits + +- Mixtures, BLOBs, repeat ranges, hydrogen-bond pairs and unknown attachment points are refused. +- Copy as HELM knows only PEPTIDE and RNA monomers: inline SMILES pieces in RNA and CHEM linkers are not written back, and a peptide joined to a nucleic acid is written only when the joining bond is one of the bonds above. +- Monomers outside the 55 (phosphorothioates, 2'-O-methyl sugars, modified bases, other non-natural residues) are not known yet; write them as inline SMILES. +- Inputs near the 2,000 monomer and 20,000 atom limits have not been timed; 20 residues is the largest timed. +- Pasting HELM text onto the canvas does not read it: use the dialog. + +## Where the code lives + +| Path | What | +| --- | --- | +| `backend/app/data/helm_monomers.json` | the 55 monomers | +| `backend/app/services/helm/` | `parser` (HELM text), `monomers` (loading and checking the data), `assemble` (one molecule), `writer` (structure to HELM), `__init__` (read and from_mol with the read-back check) | +| `backend/app/routers/helm.py` | the three routes | +| `backend/app/services/agent_helm.py` | `draw_from_helm` | +| `frontend/src/ui/helm-dialog.ts`, `frontend/src/app/helm-commands.ts` | the dialog, Insert and Copy as HELM | diff --git a/docs/LIVE-STRUCTURES.md b/docs/LIVE-STRUCTURES.md new file mode 100644 index 00000000..4ad312df --- /dev/null +++ b/docs/LIVE-STRUCTURES.md @@ -0,0 +1,118 @@ +# Live structures and the structure library + +How to put a FormChem structure into another Form app so it stays editable, how the shared structure library works, and what changes when a file you have open changes on disk, from 0.12.0. The second half is for people who build a sibling app: what to read in [LIVE_STRUCTURES.md](LIVE_STRUCTURES.md), the contract, which wins over this page. + +## Contents + +- What a live structure is +- Copying a live structure +- The Structure Library +- Editing a live structure again +- Pasting and dropping into FormChem +- When a file changes outside FormChem +- Agents and the command line +- For sibling app authors +- Limits +- Where the code lives + +## What a live structure is + +A live structure is a picture of a structure that carries the whole FormChem drawing inside it, plus an id in the shared structure library. A Form app such as FormDeck, FormTxt or form.md shows the picture like any other; when you want to change the structure, FormChem opens it as a drawing, and saving writes a new picture with a higher revision number, which the sibling app picks up. The drawing travels inside the sibling's document, so the structure is never lost, even on a computer where the library has never seen it. + +## Copying a live structure + +Select a structure (or nothing, for the whole page) and choose Edit > Copy As > Copy as Live Structure. FormChem: + +1. adds the structure to the library with the Live and Recent kinds and gives it an id such as `s7jkf0w3t10`; +2. draws its picture as SVG and as a 512 pixel wide PNG, both with the FormChem drawing inside; +3. puts on the clipboard the picture, an HTML picture carrying the live structure object, the SMILES as text and FormChem's own drawing. + +The toast says "Copied [name] as a live structure". Paste into the sibling app as you would paste a picture. Pasting back into FormChem gives the editable structure. + +## The Structure Library + +Window > Structure Library... opens the library in four tabs: + +| Tab | What is in it | +| --- | --- | +| Favourites | Structures you starred with Structure > Star Structure | +| Recent | Structures you copied as live structures or inserted from the library; the newest 50 are kept | +| Templates | Structures you saved with File > Save as Template to Library... (FormChem asks for a name) | +| Live | Structures placed in another Form app as live structures | + +The search box matches the name, formula, SMILES and tags. Pick a tile and choose Insert (place it on the page), Open (open it in its own drawing), Copy as Live Structure, Unstar or Delete (the Delete key works too). Starring a structure that is already in the library adds the Favourites kind to that item instead of making a second one; an item that loses its last kind is removed with its files. Each tile names the item's formula and average mass with the method that computed them. + +The library is plain files in FormChem's data folder, so it lives on your computer only: + +``` +~/formchem/Library/ + library.json the list of items + items/[id].svg the picture with the drawing inside + items/[id].png the same picture as PNG + items/[id].mol the structure as a molfile (an RXN file for a reaction) +``` + +(`FORMCHEM_DATA_DIR/Library/` when you set `FORMCHEM_DATA_DIR`.) It is a different file from `~/formchem/library.json`, which lists your recent drawings and databases. + +## Editing a live structure again + +A sibling app asks FormChem to edit a live structure in one of three ways: the link `formai://formchem/edit?id=[id]` (the desktop app registers the `formai` scheme), the command `./formchem edit-live [id]`, or opening the item's SVG file. FormChem opens the structure in a new drawing. Beside the title it shows "Live structure from [app]"; the tooltip names the item and its revision. + +- Save (`Mod+S`) asks for no path. It writes the item's picture and molfile, raises its revision by one and says "Saved [name] as live structure revision [n]". The sibling app shows the new picture. +- Closing the drawing with unsaved changes and choosing Save saves the item the same way. +- Save As makes an ordinary `.fchem` copy; the live link stays with the drawing you had open. +- Asking for a structure that is already open brings that drawing to the front. +- A live structure that came from another computer is added to your library with its own id and revision. A copy with a lower revision than your library's never overwrites your newer edit. + +## Pasting and dropping into FormChem + +- Paste a live structure, or a FormChem picture copied from any app, and the drawing inside is inserted. +- Drop a FormChem picture (SVG or PNG file), a live structure or an HTML picture from a browser onto the canvas, and it is inserted where you dropped it. Hold Alt while dropping, or drop with no drawing open, to open it as a drawing of its own. +- A picture without a FormChem drawing inside is refused with "[file] has no FormChem drawing inside." + +## When a file changes outside FormChem + +FormChem checks the files of your open drawings once a second. When one changes on disk (another program saved it, or a sync service brought a new copy), a bar appears over the canvas: "[name] changed on disk outside FormChem." Choose: + +- Reload: the file on disk replaces the drawing, as one step you can undo. If you had unsaved changes the bar says that Reload discards them. +- Keep Mine: your version stays and is marked unsaved, so the next save writes over the outside change. + +When the file was moved or deleted the bar says so and Reload is off. FormChem's own saves never show the bar, and the canvas does not move when the bar appears. + +## Agents and the command line + +- `./formchem edit-live ID`, `./formchem edit-live --object FILE` and `--from APP` open a live structure in the running FormChem; see [CLI.md](CLI.md). +- Agents use `library_list`, `library_add` (asks you the first time) and `live_structure_object`; see [AGENTS.md](AGENTS.md). + +## For sibling app authors + +Read [LIVE_STRUCTURES.md](LIVE_STRUCTURES.md) in this order: + +1. "The live structure object": the JSON your app stores in its own document. Draw `svg` as the picture; keep the whole object, because its SVG carries the FormChem drawing. +2. "The clipboard flavour": what Copy as Live Structure puts on the clipboard. In a browser window the object is on the clipboard as `web application/x-formai-structure+json` (browsers allow custom types only with that prefix) and inside the HTML flavour as the `data-formai-structure` attribute (base64 of the JSON) on the `img` element; the molfile flavour is dropped by browsers, so read the molfile from the object. +3. "The shared library folder" and "library.json": read-only for you. Ignore items whose files are missing and fields you do not know (FormChem writes `method` and `used` too). +4. "Editing from a sibling app": prefer the deep link, then `formchem edit-live`, then opening the SVG. Send `&from=[YourApp]` with the link, or `--from` on the command line, so the person sees who asked. +5. "Updates back to the sibling": watch `items/[id].svg` for the ids your open documents hold and compare `rev`. +6. "Without FormChem": show the picture and offer the molfile. + +Every file in the folder is written to a temporary file and renamed into place, `library.json` last, so you never read half a file. + +## Limits + +- No sibling app has been run against this yet: the folder, the object and the clipboard were checked against the contract only. +- The desktop app's own clipboard was not tried; in the browser, other apps see the HTML picture and the images. +- The `formai://` link was not opened on a real desktop. +- Reaction items have a code path (RXN file, reaction SMILES) that has not been exercised. +- The library holds pictures and molfiles only; there is no sync between computers other than the object inside the sibling's document. + +## Where the code lives + +| Path | What | +| --- | --- | +| `backend/app/services/live_structures.py` | the Library folder, items, pictures, live drawings, adoption, `edit-live` | +| `backend/app/services/file_watch.py` | outside changes to open drawings, Reload and Keep Mine | +| `backend/app/routers/structures.py` | `/api/structures` and `/api/files/watch` | +| `backend/app/services/agent_library.py` | the three agent tools | +| `frontend/src/app/live-structures.ts` | the client, Copy as Live Structure, Star, templates, live Save, drops, deep links | +| `frontend/src/ui/library-dialog.ts` | the Structure Library dialog | +| `frontend/src/ui/file-changed-bar.ts` | the bar over the canvas | diff --git a/docs/LIVE_STRUCTURES.md b/docs/LIVE_STRUCTURES.md new file mode 100644 index 00000000..3aa5c5a1 --- /dev/null +++ b/docs/LIVE_STRUCTURES.md @@ -0,0 +1,115 @@ +# FormChem live structures and the shared structure library + +The contract between FormChem and the other Form apps (from 0.12.0): the shared structure library on disk, the live structure object that a sibling app stores in its own document, the clipboard flavour that carries it, and the ways a sibling asks FormChem to edit one. FormChem implements this file in `backend/app/services/live_structures.py` and `frontend/src/app/live-structures.ts`. Sibling apps read it; FormChem never edits another app's repository or files other than the ones named here. + +## Contents + +- The shared library folder +- library.json +- The live structure object +- The clipboard flavour +- Editing from a sibling app +- Updates back to the sibling +- Without FormChem +- Routes +- Versioning + +## The shared library folder + +`FORMCHEM_DATA_DIR/Library/` (by default `~/formchem/Library/`). It is plain files so any Form app can read it without FormChem running: + +``` +Library/ + library.json the index (below) + items/[id].svg the picture, an SVG with the FormChem source embedded (FORMATS.md, embedded drawings) + items/[id].mol the structure as a molfile (V2000, V3000 when needed); an RXN file for a reaction + items/[id].png a 512 pixel wide PNG with the source embedded, for apps that cannot place SVG +``` + +Only FormChem writes the folder. Every write goes to a temporary file in the same folder and is renamed into place, `library.json` last, so a reader never sees half a file. Readers must ignore items whose files are missing. + +## library.json + +```json +{ "format": "formai-structure-library", "format_version": 1, "updated": "2026-12-05T18:00:00.000Z", + "items": [ + { "id": "s4k2m9x0qa", "name": "Aspirin", "kinds": ["favourite", "live"], "kind": "structure", + "smiles": "CC(=O)Oc1ccccc1C(=O)O", "inchikey": "BSYNRYMUTXBXSQ-UHFFFAOYSA-N", + "formula": "C9H8O4", "mw": 180.159, "rev": 3, + "svg": "items/s4k2m9x0qa.svg", "mol": "items/s4k2m9x0qa.mol", "png": "items/s4k2m9x0qa.png", + "width": 171.2, "height": 134.0, + "created": "2026-12-05T17:40:00.000Z", "modified": "2026-12-05T18:00:00.000Z", + "tags": [] } ] } +``` + +- `id` is `s` plus 10 characters `[a-z0-9]`, never reused. +- `kinds` is any of `favourite` (starred by the person), `recent` (copied or inserted lately; FormChem keeps the newest 50), `template` (saved by the person as a template), `live` (placed in a sibling document as a live structure). An item with no kinds left is deleted with its files. +- `kind` is `structure` or `reaction`. +- `rev` starts at 1 and rises by one on every change to the picture or the structure. +- `width` and `height` are the picture's size in points. +- Times are ISO 8601 UTC, as in FORMAT.md. + +## The live structure object + +A sibling app keeps this JSON object inside its own document, so the document stays self-contained when it moves to another computer: + +```json +{ "format": "formai-structure", "format_version": 1, + "id": "s4k2m9x0qa", "rev": 3, "app": "formchem", + "name": "Aspirin", "kind": "structure", + "smiles": "CC(=O)Oc1ccccc1C(=O)O", "inchikey": "BSYNRYMUTXBXSQ-UHFFFAOYSA-N", + "svg": "...", "molfile": "...", "width": 171.2, "height": 134.0 } +``` + +The sibling draws `svg` as the picture. The SVG carries the full FormChem drawing, so the structure is never lost even if the library item is gone. + +## The clipboard flavour + +Edit > Copy As > Copy as Live Structure puts on the clipboard: + +- `application/x-formai-structure+json`: the live structure object above. A browser window writes it as `web application/x-formai-structure+json`, because browsers accept custom types only with the `web ` prefix; the object is always also inside the HTML flavour as a `data-formai-structure` attribute holding the base64 of the JSON on the `img` element; +- `image/svg+xml` and `image/png`: the picture with the embedded source; +- `text/html`: an `img` element with the SVG as a data URL; +- `chemical/x-mdl-molfile` and `text/plain`: the molfile and the SMILES, as for an ordinary copy. Browsers refuse `chemical/x-mdl-molfile`, so from a browser window only the SMILES arrives; read the molfile from the object. + +Copying a live structure adds the item to the library with the `live` and `recent` kinds. Dragging a structure out of FormChem does not carry these flavours yet (0.12.0). + +## Editing from a sibling app + +A sibling asks FormChem to edit a live structure in any of these ways, in this order of preference: + +1. The deep link `formai://formchem/edit?id=[id]&from=[App]` (the desktop app registers the `formai` scheme and handles its `formchem` host; `from` is optional). +2. The command line `formchem edit-live [id]`, or `formchem edit-live --object [file]` with the JSON object in a file, each with an optional `--from [App]`. +3. Opening `items/[id].svg` with FormChem (any embedded-source picture opens as an editable drawing). + +When the library has no item with that id (the document came from another computer), FormChem creates it from the object's embedded source, keeping the id and rev. + +FormChem opens the structure in a drawing marked as a live structure (the title bar names the sibling and shows "Live structure"). Saving that drawing (Cmd or Ctrl+S) does not ask for a path: it writes the library item's SVG, PNG and molfile, raises `rev`, and updates `library.json`. Save As makes an ordinary `.fchem` copy and leaves the live link alone. + +## Updates back to the sibling + +A sibling that is running watches `items/[id].svg` for the ids its open documents hold and, when the file's `rev` in `library.json` is higher than its own, replaces its object with the new picture, molfile, SMILES and rev (within 2 seconds of the save). A sibling that is not running compares revs the next time it opens the document. FormChem also broadcasts `{"t": "live-structure", "id", "rev"}` on its live WebSocket for in-app extensions. + +## Without FormChem + +A sibling that finds no FormChem still shows the picture, and offers to save the object's `molfile` as a `.mol` file. + +## Routes + +| Method and path | Body | Answer | +| --- | --- | --- | +| `GET /api/structures` | `kind?` | `library.json` | +| `POST /api/structures` | `{source: document, name?, kinds, svg?, png?, width?, height?, tags?}` (the window sends the pictures it drew; without them the engine draws them) | the item | +| `PATCH /api/structures/{id}` | `{name?, kinds?, tags?, used?}` | the item | +| `DELETE /api/structures/{id}` | | `{deleted: id}` | +| `GET /api/structures/{id}/object` | | the live structure object | +| `POST /api/structures/open` | `{id}` or `{object}`, `from?` | `{doc, id, rev, from, name}`: the drawing opened for editing (an item already open is brought forward) | +| `POST /api/structures/{id}/save` | `{doc, svg?, png?, width?, height?}` | the item with its new rev | +| `GET /api/structures/links` | | `{links}`: the open live drawings | +| `GET /api/structures/{id}/picture.svg`, `picture.png` | | the item's picture, for tiles | + +The routes need the window key or the agent token, except the picture route, which an `img` element loads without headers (local origins only). The agent token may write to `/api/structures` and nothing else in the engine. Items in `library.json` written by FormChem also carry `method` (how formula and mass were computed) and `used` (the last copy, insert or adoption, which orders `recent`). Agent tools `library_list`, `library_add` and `live_structure_object` use the same service. + +## Versioning + +`format_version` 1 from 0.12.0 for both `library.json` and the object. A reader seeing a higher version reads the fields it knows and leaves the rest; a writer never drops fields it does not know. diff --git a/formchem b/formchem index 5f3ad4be..594871c9 100755 --- a/formchem +++ b/formchem @@ -30,6 +30,8 @@ usage: ./formchem [command] [options] descriptors IN --csv OUT [--props LIST] calculated properties of every record as CSV (--list for the columns and methods) render IN --out DIR [--format svg|png] [--size W[xH]] one image per record in the journal style (PNG at 300 dpi) failed records never stop a run: they are listed, or written to --errors FILE; exit 1 when nothing was written + db create|info|import|search|export structure databases (.fcdb) without the window (./formchem db --help) + edit-live ID | --object FILE [--from APP] open a live structure from the shared library for editing (FormChem must be running) cli list|describe|run|batch the window's command catalogue from a terminal: list [text], run (the window must be open) i18n check|scan|export|import the translations: check for gaps, find new strings, or a language as CSV for a native reviewer and back mcp FormChem over MCP's stdio transport, for Claude Desktop and other MCP clients @@ -61,7 +63,7 @@ case "$cmd" in doctor) exec setup/doctor "$@" ;; counts) exec setup/counts "$@" ;; claude) exec python3 setup/claude_launch.py "$@" ;; - convert|batch|descriptors|render) exec setup/convert "$cmd" "$@" ;; + convert|batch|descriptors|render|db|edit-live) exec setup/convert "$cmd" "$@" ;; cli) exec python3 setup/catalogue.py "$@" ;; i18n) exec python3 setup/i18n_tool.py "$@" ;; mcp) exec python3 setup/mcp_stdio.py "$@" ;; diff --git a/formchem.bat b/formchem.bat index 5e958e82..54556d72 100644 --- a/formchem.bat +++ b/formchem.bat @@ -40,6 +40,8 @@ if "%CMD%"=="convert" ( call setup\convert.bat %* & goto :eof ) if "%CMD%"=="batch" ( call setup\convert.bat %* & goto :eof ) if "%CMD%"=="descriptors" ( call setup\convert.bat %* & goto :eof ) if "%CMD%"=="render" ( call setup\convert.bat %* & goto :eof ) +if "%CMD%"=="db" ( call setup\convert.bat %* & goto :eof ) +if "%CMD%"=="edit-live" ( call setup\convert.bat %* & goto :eof ) if /i "%CMD%"=="cli" ( python setup\catalogue.py %REST% & goto :eof ) if /i "%CMD%"=="i18n" ( python setup\i18n_tool.py %REST% & goto :eof ) if /i "%CMD%"=="mcp" ( python setup\mcp_stdio.py %REST% & goto :eof ) @@ -80,6 +82,8 @@ echo convert every structure file in a folder (default DIR echo descriptors IN --csv OUT [--props LIST] calculated properties of every record as CSV (--list for the columns and methods) echo render IN --out DIR [--format svg^|png] [--size W[xH]] one image per record in the journal style (PNG at 300 dpi) echo failed records never stop a run: they are listed, or written to --errors FILE; exit 1 when nothing was written +echo db create^|info^|import^|search^|export structure databases (.fcdb) without the window (formchem db --help) +echo edit-live ID ^| --object FILE [--from APP] open a live structure from the shared library for editing (FormChem must be running) echo cli list^|describe^|run^|batch the window's command catalogue from a terminal (the window must be open) echo i18n check^|scan^|export^|import the translations: check for gaps, find new strings, or a language as CSV for a native reviewer and back echo mcp FormChem over MCP's stdio transport, for Claude Desktop and other MCP clients diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index cfbbd495..b5514a3b 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # frontend HASHOUT_LOG -Living log for the FormChem frontend and its desktop shell (src-tauri), _v0.1.0 to _v0.10.0. For 0.1.0 and 0.2.0 it follows the family template (formdeck's window and formvis's title bar), so most reasons there are about what was kept, what was dropped, and why. From 0.3.0 it records the document client, the window's own chemistry, from 0.4.0 the canvas: renderer, tools, view and tool rail, and from 0.5.0 the drawn objects (arrows, symbols, brackets, shapes, tables, TLC, orbitals, images, captions, groups), their tools and handles, the stoichiometry panel, the template library and the Reaction commands, and from 0.6.0 the analysis client, the chemistry marks layer, the stereo, query, R-group and abbreviation commands and dialogs, the structure check panel, the properties section with the isotope plot, Set Reaction Roles, and the Tauri CLI pin, and from 0.7.0 the one-folder engine start, the dark page, scaling on the sheet, the wrapping panel rows, the folding menu row, grids and snapping, picture export, print and the shared save path, the embedded source, the clipboard, the import report, Standardise and the quick command state mirror, and from 0.8.0 the window tools that render, report the selection and show drawings for agents, Agent activity, the editing chip with Stop, the agent marks and the token in the Agents dialog, and from 0.9.0 Structure from Name, the Name section, Copy Name and pasting a name, the spectrum object kind with its data cache and page plot, atom links, the Spectrum editor, the spectrum and NMR prediction commands, and from 0.10.0 the 3D View panel over a lazily loaded 3Dmol.js, the model3d page object with its snapshots, measurements, surfaces with ESP, the Conformers and Dihedral Scan dialogs, the glTF writer, structure files in Open and Import, Extract Ligand and Export 3D Structure, and the stale-conformer rule mirrored in the client. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. +Living log for the FormChem frontend and its desktop shell (src-tauri), _v0.1.0 to _v0.12.0. For 0.1.0 and 0.2.0 it follows the family template (formdeck's window and formvis's title bar), so most reasons there are about what was kept, what was dropped, and why. From 0.3.0 it records the document client, the window's own chemistry, from 0.4.0 the canvas: renderer, tools, view and tool rail, and from 0.5.0 the drawn objects (arrows, symbols, brackets, shapes, tables, TLC, orbitals, images, captions, groups), their tools and handles, the stoichiometry panel, the template library and the Reaction commands, and from 0.6.0 the analysis client, the chemistry marks layer, the stereo, query, R-group and abbreviation commands and dialogs, the structure check panel, the properties section with the isotope plot, Set Reaction Roles, and the Tauri CLI pin, and from 0.7.0 the one-folder engine start, the dark page, scaling on the sheet, the wrapping panel rows, the folding menu row, grids and snapping, picture export, print and the shared save path, the embedded source, the clipboard, the import report, Standardise and the quick command state mirror, and from 0.8.0 the window tools that render, report the selection and show drawings for agents, Agent activity, the editing chip with Stop, the agent marks and the token in the Agents dialog, and from 0.9.0 Structure from Name, the Name section, Copy Name and pasting a name, the spectrum object kind with its data cache and page plot, atom links, the Spectrum editor, the spectrum and NMR prediction commands, and from 0.10.0 the 3D View panel over a lazily loaded 3Dmol.js, the model3d page object with its snapshots, measurements, surfaces with ESP, the Conformers and Dihedral Scan dialogs, the glTF writer, structure files in Open and Import, Extract Ligand and Export 3D Structure, and the stale-conformer rule mirrored in the client, and from 0.11.0 the full-window database workspace (virtualised table, gallery, form, the shared selection and record paging, fields, settings, duplicates and record details), search with the query builder, hit lists, saved queries, import, export and the plot, the lab notebook view with its entry editor, Edit Scheme and signing, `.fcdb` in Open and drops, the view key, and the new mark, and from 0.12.0 live structures (the library client, Copy as Live Structure, the live drawing and its Save, drops, the deep link), the Structure Library dialog, the file changed bar, accessibility (the key route ahead of the canvas, spoken atoms and bonds, the shared announcer, the focus ring, element palettes, the Structure Summary), the HELM dialog and commands, and the xtb and CREST dialogs and Preferences section. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. ## Org navi map @@ -70,6 +70,25 @@ src/io/glb.ts glTF 2.0 binary writer (0.10.0) src/chem/ also elements3d.ts, geom3d.ts, conformer-mol.ts (0.10.0) src/types/3dmol.d.ts the shorthand module for 3Dmol's ES build (0.10.0) src/styles/ also view3d.css, imported by the panel so it loads with it (0.10.0) +src/engine/database-api.ts types of docs/DATABASE.md and one function per database route, DuplicateError (0.11.0) +src/ui/database/ workspace (mount, views, sections, toolbar, live changes), workspace-types (the seams), + internal, selection, record-source, columns, thumbs, menu, column-picker, table, gallery, + form-view, and the new, open, settings, fields, duplicates and record dialogs (0.11.0) +src/ui/database-find/ index (registerDatabaseFind), search-bar, query-text, query-model, term-editor, query-builder, + save-query, combine, export and import dialogs, hitlists, queries, plot, plot-math, files, + drawing, shared (0.11.0) +src/ui/notebook/ notebook (the view), entry-list, entry-editor, scheme-view, stoich-table, products-table, + attachments-list, versions, markup, notebook-api, commands (registerNotebook) (0.11.0) +src/app/database-commands.ts registerDatabaseCommands, Add to Database (0.11.0) +src/styles/ also database.css, database-find.css, notebook.css, each imported by its module (0.11.0) +src/app/live-structures.ts structuresApi, the live links, Copy as Live Structure, Star, templates, saveLive, drops, + handleDeepLink (0.12.0) +src/ui/ also library-dialog.ts (Structure Library), file-changed-bar.ts, a11y-announcer.ts, + structure-summary.ts, helm-dialog.ts, xtb-dialog.ts, prefs/xtb.ts (0.12.0) +src/canvas/a11y/ index (prepareA11y, mountA11y), controller, nav, speech, elements, ring, palette, commands, + describe-api (0.12.0) +src/app/ also helm-commands.ts, xtb-commands.ts (xtbApi, registerXtbCommands) (0.12.0) +src/styles/ also library.css, a11y.css, each imported by its modules (0.12.0) src-tauri/src/ main.rs (windows, chrome), traffic_lights.rs, reveal.rs, engine_start.rs, packaged.rs (0.7.0) src-tauri/ tauri.conf.json, tauri.macos.conf.json (0.7.0), capabilities, Info.plist, entitlements.plist, flatpak/ assets/ formchem_mark.svg, icon_src/build.py, icon set @@ -321,6 +340,62 @@ assets/ formchem_mark.svg, icon_src/build.py, icon set 242. Picture exports wait for 3D snapshots · app/picture.ts 243. 3D strings go to t() as whole sentences · ui/view3d-panel.ts, i18n/keys/part14.json 244. 3dmol is the one new dependency · package.json, package-lock.json +245. The database workspace is a full-window layer on the Home host · ui/database/workspace.ts show, hide; app.ts +246. Keys inside the workspace stop there · ui/database/workspace.ts key +247. Records page in blocks of 100 and stale blocks stay shown · ui/database/record-source.ts +248. One selection for every view · ui/database/selection.ts DbSelection +249. The table pools rows keyed by uid; widths are CSS variables · ui/database/table.ts paint, saveWidth +250. Editing a value in its cell · ui/database/table.ts startEdit; columns.ts +251. Thumbnails in a reserved box, inked for the theme on screen · ui/database/thumbs.ts thumbSrc, thumbTheme +252. Gallery tiles and the scaled form · ui/database/gallery.ts, form-view.ts +253. Short menus borrow the context menu · ui/database/menu.ts popMenu +254. A live change refetches only what it touched · ui/database/workspace.ts liveChange +255. The database dialogs · ui/database/new-dialog.ts, open-dialog.ts, settings-dialog.ts, fields-dialog.ts +256. A duplicate is one shape, and at most 24 are drawn · engine/database-api.ts DuplicateError; app/database-commands.ts addOnce +257. Record details, files and Open in Drawing · ui/database/record-dialog.ts, open-drawing.ts +258. Views, sections and toolbars join through seams · ui/database/workspace-types.ts +259. The search bar's plain text query · ui/database-find/query-text.ts quickQuery; search-bar.ts +260. A structure query is the drawing's own molfile · ui/database-find/drawing.ts +261. The query builder's tree · ui/database-find/query-model.ts toQuery; term-editor.ts; query-builder.ts +262. Hit lists and saved queries in the left column · ui/database-find/hitlists.ts, queries.ts +263. The import dialog keeps one size · ui/database-find/import-dialog.ts +264. Exports and the one-time download · ui/database-find/export-dialog.ts, files.ts downloadOnce +265. The plot patches circles keyed by uid · ui/database-find/plot.ts, plot-math.ts +266. The toolbar fits five views · styles/database.css, database-find.css +267. The notebook list is pooled like the table · ui/notebook/entry-list.ts +268. The entry editor is built once and never overwrites a focused field · ui/notebook/entry-editor.ts +269. Edit Scheme opens the scheme as a drawing with Save to Entry · ui/notebook/scheme-view.ts +270. The notebook's own client and markup preview · ui/notebook/notebook-api.ts, markup.ts +271. Labels go beside icons, never into them · ui/notebook/entry-editor.ts, ui/database-find/search-bar.ts +272. .fcdb in Open, drops and browser uploads · app/documents.ts DocumentHooks.openDatabase; engine/database-api.ts openUpload +273. Menus, the gear menu and Home's database buttons · app/menus.ts; ui/database/workspace.ts more; ui/home.ts runButton +274. Two icons and one token from the find module · ui/icons.ts marquee, trendLine; styles/tokens.css --warning-fill +275. The view key is loaded before the app mounts · io/window-key.ts loadViewKey +276. The mark, favicon and splash follow the new icon · ui/brand.ts, public/favicon.svg, public/splash.html +277. One client for the structure routes and the live links · app/live-structures.ts structuresApi, followLiveLinks +278. Copy as Live Structure is one clipboard write; browsers keep only some flavours · app/live-structures.ts copyLiveStructure, liveHtml +279. A live drawing saves to its item, also when it closes · app/live-structures.ts saveLive; app/documents.ts DocumentHooks.save +280. Drops and the live flavour alone on paste · app/live-structures.ts mountLiveDrops +281. Deep links reach only the main window · app.ts followDeepLinks; app/live-structures.ts handleDeepLink, deepLinkTarget +282. Star and Save as Template name the structure, not the drawing · app/live-structures.ts addToLibrary, starStructure +283. The Structure Library is built once and tiles are patched by id · ui/library-dialog.ts; styles/library.css +284. The file changed bar sits over the stage · ui/file-changed-bar.ts mountFileChangedBar +285. The accessibility key route runs before the canvas's · canvas/a11y/controller.ts installA11yKeys; index.ts prepareA11y +286. The focus is the view's keyboard cursor · canvas/a11y/controller.ts CanvasA11y +287. Spoken atoms use fresh derived data only · canvas/a11y/speech.ts, elements.ts; controller.ts describe +288. One announcer for the window; the canvas prompts are relayed · ui/a11y-announcer.ts; controller.ts relayCanvasPrompts +289. Navigation follows the graph · canvas/a11y/nav.ts +290. The focus ring is one patched path pair · canvas/a11y/ring.ts FocusRing +291. Two more element palettes in the renderer · canvas/render/atom.ts ELEMENT_PALETTES, setElementPalette +292. The palette is per device and switches without a flash · canvas/a11y/palette.ts; commands.ts PALETTE_COMMAND_IDS; ui/prefs/sections.ts +293. The Structure Summary speaks and shows · ui/structure-summary.ts; canvas/a11y/describe-api.ts, commands.ts describeStructure +294. The accessibility keys and the database workspace · app.ts mount order; canvas/a11y/commands.ts +295. Hit targets of 24 pixels and focus outlines · styles/a11y.css +296. The HELM dialog validates as the person types · ui/helm-dialog.ts helmDialog, insertHelmRead +297. Copy as HELM copies only what reads back · app/helm-commands.ts copyHelm +298. The xtb and CREST dialogs are built once and polled · ui/xtb-dialog.ts openXtbDialog; app/xtb-commands.ts +299. The tight-binding Preferences rows refresh when Preferences opens · ui/prefs/xtb.ts; ui/prefs/index.ts +300. Where the phase 12 commands sit in the menus · app/menus.ts ## 1. Dependencies are the template's, nothing more · _v0.1.0 (package.json) @@ -1298,6 +1373,230 @@ The keying step turned status lines and hints built from pieces (`Picked`, `Clic `3dmol` 3.0.0 (BSD-3-Clause) with `pako` 2.2.0 and 1.0.11 (MIT AND Zlib), `upng-js` 2.1.0, `iobuffer` 5.4.0 and `netcdfjs` 3.0.0 (MIT); only `build/3Dmol.es6-min.js` ships (581 kB, 170 kB gzip). Its engines field asks for Node 24 and npm prints EBADENGINE on Node 22, a warning only. 2.5.5 was the fallback and was not needed. Installing in a worktree replaced the shared `node_modules` symlink with a real folder; the integration copied the five new packages into the shared tree, removed the folder and restored the link, so `npm ci` after merging the lock gives the same tree. +## 245. The database workspace is a full-window layer on the Home host · _v0.11.0 (ui/database/workspace.ts mountDatabaseWorkspace, Workspace.show, hide, close; styles/database.css; app.ts) + +A table of 10,000 records needs the whole window, so the workspace is a fixed layer on `--z-home` like Home, mounted on the Home host. `show` adds `fc-home-open` (which turns the canvas keys off, as Home does) and `fc-db-open`, under which database.css raises `#overlay-root` and `#toast-root` to `--z-home-modal` so dialogs and toasts sit above it. `hide` removes `fc-home-open` only when Home is not showing; `close` closes the database in the engine (and releases its lock), `hide` only hides. Home's `onVisible(true)` hides the workspace, else a drawing opened from Home would stay covered. There is no hide on `session.onActive`, because an agent opening a drawing would otherwise pull the person out of the workspace. + +## 246. Keys inside the workspace stop there · _v0.11.0 (ui/database/workspace.ts Workspace.key) + +Keys the active pane handles stop at it; other unmodified keys stop propagating so single-letter tool keys never reach the hidden canvas; Mod shortcuts (save, the palette) still pass. Inside: arrows, Page Up and Down, Home and End (Shift extends), Mod+A, Delete or Backspace (asks), Enter (record details), F2 (edit the first field), Escape (clears the selection). + +## 247. Records page in blocks of 100 and stale blocks stay shown · _v0.11.0 (ui/database/record-source.ts RecordSource) + +A 10,000 record database cannot be fetched whole. Rows load in blocks of 100 (`GET records` with offset and limit), at most 3 requests in flight, and requests for blocks that scrolled away are aborted. A block being replaced stays on screen until its replacement arrives, so sorting moves rows instead of blanking them. `allUids` (Mod+A) pages by 500. + +## 248. One selection for every view · _v0.11.0 (ui/database/selection.ts DbSelection; ui/database/internal.ts DbInternal) + +Table, gallery, form and plot select the same records, so the selection, its anchor and focus live in one model that reports only the uids that changed, and each view patches just those. Built-in views get `DbInternal` (source, selection, edits, select all, delete); views from other modules get only the public workspace. + +## 249. The table pools rows keyed by uid; widths are CSS variables · _v0.11.0 (ui/database/table.ts TableView.paint, saveWidth; ui/database/internal.ts setData) + +Row nodes are pooled, keyed by uid and placed by `translateY`; a row whose block has not arrived is keyed `~index` and shows a loading bar as a cell background, so nothing shifts when data arrives. `setData` changes a text node's data instead of replacing the node (8ce8844: layout shift 0.0026 to 0 while scrolling 16,000 pixels at 4x throttling). Column widths and frozen offsets are CSS variables on the table root, so a resize changes one variable and no row; frozen columns are sticky cells. A field's width is saved to the field, a built-in column's width, visibility and the frozen count to localStorage `formchem.db.columns:[path]`, because built-ins are not field rows. Sorting by MW reused 19 row nodes and added none. + +## 250. Editing a value in its cell · _v0.11.0 (ui/database/table.ts startEdit; ui/database/columns.ts) + +Double-click on an editable field cell opens an editor in place (a select for choices, a date picker, a toggle for yes or no); double-click elsewhere opens the record. Enter and Tab save, Escape cancels, scrolling saves. `columns.ts` holds one column model for built-ins and fields with widths, alignment, formatting by type, parsing of typed edits ("IC50 takes a number") and the method of every computed number for the header's title. + +## 251. Thumbnails in a reserved box, inked for the theme on screen · _v0.11.0 (ui/database/thumbs.ts thumbSrc, thumbTheme) + +Pictures load into a fixed box that stays empty until the image decodes, so rows never shift. The theme comes from the `theme-light` body class, what is painted, not the saved setting, which can lag (02bddeb); a theme switch reloads the visible thumbnails. `v` is the record's modified time, so a changed structure gets a new URL. + +## 252. Gallery tiles and the scaled form · _v0.11.0 (ui/database/gallery.ts GalleryView; ui/database/form-view.ts FormView) + +Gallery tiles are a fixed 184 by 212, pooled by uid and placed by transform; captions are kept per database in localStorage. The form is laid out on the engine's 600 point canvas and scaled to fit by one `scale()` transform (0.4 to 1.6); it is rebuilt only when the layout changes, and paging patches the values. Items naming a built-in show it read-only; `button` items run their command id. + +## 253. Short menus borrow the context menu · _v0.11.0 (ui/database/menu.ts popMenu, menuBelow) + +Header, form and settings menus hold items that are not app commands, so they register temporary `db-menu:N` commands for the shared context menu and drop them on close, as app.ts does for Home cards. + +## 254. A live change refetches only what it touched · _v0.11.0 (ui/database/workspace.ts liveChange) + +`records` with known uids refetches only their blocks; unknown uids (added or deleted elsewhere) refetch the visible blocks and Info; `fields`, `info` and `forms` refetch Info; `hitlists` renames the current hit list. A change made outside the window patched the same row node within 1.5 s. `entries` is left to the notebook view, so the toolbar's entry count follows it only on the next Info. + +## 255. The database dialogs · _v0.11.0 (ui/database/new-dialog.ts, open-dialog.ts, settings-dialog.ts, fields-dialog.ts) + +New Database sends a full path `folder/Title.fcdb` with a folder, none without (the engine's Databases folder). Open Database lists the databases the engine knows, missing ones greyed, beside a path box and, in the desktop app, a file chooser, because a browser window has no paths. Settings shows the rules without saving on a read-only database. Fields moves a field by sending the neighbour's position; the computed property select has its own change listener (7309d20: Add Field stayed disabled for computed fields), and focus returns to the dialog after each engine call. + +## 256. A duplicate is one shape, and at most 24 are drawn · _v0.11.0 (engine/database-api.ts DuplicateError, addRecord; app/database-commands.ts addOnce, addSelectionToDatabase; ui/database/duplicates-dialog.ts askDuplicate) + +`io/api.ts` drops a `detail` that is not a string, so `addRecord` throws `DuplicateError` carrying the `duplicates` of the 409 and Add to Database uses it. The selection or the page goes as a molfile through the document export route. The dialog offers Open, Add as New Batch and Register Anyway; a common structure matched over a thousand records, so only 24 pictures are drawn and the count is said (87238bc). + +## 257. Record details, files and Open in Drawing · _v0.11.0 (ui/database/record-dialog.ts openRecordDialog; ui/database/open-drawing.ts openMolfileAsDrawing; engine/database-api.ts addAttachment, linkAttachment) + +The dialog shows the picture, keys with copy buttons, values and attachments; files over 50 MB are refused in the window before upload, and the desktop app links a path instead. Open in Drawing uploads the molfile as a new drawing and hides the workspace. + +## 258. Views, sections and toolbars join through seams · _v0.11.0 (ui/database/workspace-types.ts DatabaseWorkspace, registerView, registerSidebar, registerToolbar, showView) + +The workspace, search and plot, and the notebook were built side by side, so they meet only through these interfaces (6bb28b3). `showView(id)` (dc721db) shows the workspace and switches view, replacing the duck-typed probes for `setView` that dbfind and the notebook had. Orders: table 10, gallery 20, form 30, plot 40, notebook 50 (both had 40, 0a0a91f). + +## 259. The search bar's plain text query · _v0.11.0 (ui/database-find/query-text.ts quickQuery, describeQuery; ui/database-find/search-bar.ts) + +Plain text becomes an OR of `text contains` over uid, formula, SMILES and every text field; digits alone add `number = n`; a formula range such as `C6-8N1` adds a formula term. The Structure popover runs exact, substructure or similarity (threshold 0.7) on the drawing. `db-search` with `text` fills the box and runs the same query, so agents and the palette share one path. After `runQuery` the bar shows the hit list only if the context did not already switch to it. + +## 260. A structure query is the drawing's own molfile · _v0.11.0 (ui/database-find/drawing.ts setFindDrawing, drawingStructure) + +The query must be exactly what the person drew, so the selection, or the whole page, is exported as a molfile through the existing `GET /api/documents/{id}/export?format=molfile&as=json`. The canvas view cannot come through `DatabaseWorkspace`, so app.ts passes it with `setFindDrawing`. + +## 261. The query builder's tree · _v0.11.0 (ui/database-find/query-model.ts toQuery, fromQuery, BuildError; term-editor.ts; query-builder.ts openQueryBuilder) + +The builder edits All of, Any of and None of groups and turns them into DATABASE.md JSON: a None of group with several children is sent as `not(and(...))`, a group of one collapses to its child. Validation names the term at fault (a bad regex, a missing second value of between, an empty group) and keeps Search disabled. A kind change rebuilds only that row's controls; SMARTS is offered for substructure only; Take from Drawing stores the molfile in the term once. + +## 262. Hit lists and saved queries in the left column · _v0.11.0 (ui/database-find/hitlists.ts, queries.ts) + +Rows are keyed with `patchList` and patched on `hitlists` and `queries` live messages; an All records row clears the hit list; F2 renames, Delete asks; Keep toggles `saved`. Saved query folders start open and the shut ones are remembered in localStorage `formchem.dbQueryFoldersShut` (1de3463: a query saved into a new folder was hidden). + +## 263. The import dialog keeps one size · _v0.11.0 (ui/database-find/import-dialog.ts openImport; styles/database-find.css .fc-dbf-imp-file) + +One fixed stage holds the hint, the mapping table or the report, and the progress line has a fixed height, so nothing moves between steps; the file name line reserves 18 px (2117eda: the dialog grew 552 to 562 px when a file was chosen). Mapping values are `""`, `+label` or a field name. Mode defaults to New for an empty database, else Append. Stop cancels and keeps polling until the job ends; closing only stops polling. The left button reads Close once an import finished (7f3120b). + +## 264. Exports and the one-time download · _v0.11.0 (ui/database-find/export-dialog.ts openExport; ui/database-find/files.ts desktop, pickBrowserFile, downloadOnce) + +The desktop window saves to a picked path; the browser sends no path and fetches the one-time URL with the window key, then hands a blob to a link. V3000 is offered only for SD, structure as SMILES or InChI only for CSV, and a SMILES export sends no fields. + +## 265. The plot patches circles keyed by uid · _v0.11.0 (ui/database-find/plot.ts; ui/database-find/plot-math.ts leastSquares, histogram, niceTicks, inPolygon) + +Points are SVG circles in a map keyed by uid; ticks, bars and grid come from fixed pools. A selection change toggles classes only on circles that entered or left it (8a5108d: longest task 348 to 131 ms for 1,827 points), and the last fill written is kept in a WeakMap because the browser normalises `color-mix()` when read (6936a7d). A press on a point starts the lasso or rectangle and selects the point only when the pointer did not move (8d9ca90: a dense scatter could not be lassoed). The fit is ordinary least squares with R squared, the histogram Sturges bins, both named in the foot line. A selection becomes a hit list only through "Hit List from N Selected" or Enter. + +## 266. The toolbar fits five views · _v0.11.0 (styles/database.css, styles/database-find.css) + +With five views and the search bar the title shrank to nothing at 1400 px. View and search labels drop to icons (with titles) below 1800 px, action labels below 1400 px; the identity block keeps 200 px, the title 96 px and the count badge 92 px, so a live count does not move the toolbar (55f86ba). The icons stay when labels go (62bed5c). + +## 267. The notebook list is pooled like the table · _v0.11.0 (ui/notebook/entry-list.ts) + +Fixed 56 px slots hold 52 px rows from a pool moved by transform; entries load in chunks of 200, and old rows stay until the replacing chunk arrives (`shownGen`), so a search or a live refresh never blanks the list. Scrolling 302 entries created 7 pooled rows and removed none. + +## 268. The entry editor is built once and never overwrites a focused field · _v0.11.0 (ui/notebook/entry-editor.ts; stoich-table.ts, products-table.ts, attachments-list.ts, versions.ts) + +The editor is patched per entry. Text saves 600 ms after typing and on blur, other fields on change; `setValue` skips the focused field, and a reload is skipped while a patch is pending. Stoichiometry is read-only with its method and the engine's warnings; products, attachments and versions are keyed lists. The signed badge, the Modified after signing banner, Sign and both exports sit in the header. + +## 269. Edit Scheme opens the scheme as a drawing with Save to Entry · _v0.11.0 (ui/notebook/scheme-view.ts) + +Edit Scheme fetches `scheme.fchem` and opens it through the existing upload route and `session.attach`; a bar in `#overlay-root` on `--z-companion` offers Save to Entry and Back to Notebook while that drawing is active. Save to Entry patches the entry, trimmed to the first page; the opened copy is not saved as a file. The scheme picture comes from the window's own renderer and replaces the old one only when ready. + +## 270. The notebook's own client and markup preview · _v0.11.0 (ui/notebook/notebook-api.ts; ui/notebook/markup.ts) + +database-api.ts was a read-only contract without entry files, exports and the scheme package, so the notebook keeps a small client for those calls. The preview uses the same grammar as the engine's export (paragraphs, dash bullets, bold, italic over escaped text), so it matches the HTML file. + +## 271. Labels go beside icons, never into them · _v0.11.0 (ui/notebook/entry-editor.ts, scheme-view.ts, products-table.ts, attachments-list.ts; ui/database-find/search-bar.ts, hitlists.ts, plot.ts, query-builder.ts) + +`icon()` wraps its SVG in `span.icon`, so label setters that took the first span overwrote the icon and collapsed the buttons (94c4e44, fdbfe21). Labels are found with `span:not(.icon)`. + +## 272. .fcdb in Open, drops and browser uploads · _v0.11.0 (app/documents.ts DocumentHooks.openDatabase, isDatabase, OPEN_EXTENSIONS; ui/home.ts STRUCTURE_ACCEPT; engine/database-api.ts openUpload) + +`openPath` and `openFiles` hand an `.fcdb` to the workspace instead of the drawing importer. In a browser window the file is uploaded and opened with `adopt`, which moves it into the Databases folder (backend log). The desktop app has no Tauri drop handler; only Home's HTML drop area takes files. + +## 273. Menus, the gear menu and Home's database buttons · _v0.11.0 (app/menus.ts; ui/database/workspace.ts more; ui/home.ts runButton; app/commands-shell.ts open) + +File gains New Database, Open Database and Databases (`Shift+Mod+D`); Structure gains Add to Database; a Database menu has View As and Notebook submenus. The workspace covers the in-window menu bar, so its gear menu also offers Advanced Search, Save Query, Combine Hit Lists and New Notebook Entry (f726175). Home's empty Databases list carries New Database, hidden while loading so nothing moves, and the Databases page head offers Open and New. Every command id registers through its module's register function, because the registry rejects duplicates; only `open`'s description changed in commands-shell.ts. + +## 274. Two icons and one token from the find module · _v0.11.0 (ui/icons.ts marquee, trendLine, chevronRight; styles/tokens.css --warning-fill) + +icons.ts and tokens.css were closed while the find module was written, so it kept a local icon map and the read-only badge read `--warning-fill` with a raw fallback. Integration moved `marquee` and `trendLine` into icons.ts, used `chevronRight` for the tree, deleted find-icons.ts, and added `--warning-fill: #eab308`. + +## 275. The view key is loaded before the app mounts · _v0.11.0 (io/window-key.ts loadViewKey; engine/database-api.ts thumbUrl, attachmentUrl) + +The key that opens only thumbnails and attachments (backend log) is fetched right after the window key, before mount, so picture URLs are built synchronously and never race. + +## 276. The mark, favicon and splash follow the new icon · _v0.11.0 (ui/brand.ts; public/favicon.svg; public/splash.html; assets/formchem_mark.svg) + +The title bar, Home, About and the splash show a vector redraw of the owner's new card (a blue to violet to orange gradient with benzene, an arrow, phenol and spectrum peaks), checked rendered at 512 and 32 pixels, so they match the app icon. + +## 277. One client for the structure routes and the live links · _v0.12.0 (app/live-structures.ts structuresApi, LibraryItem, LiveObject, LiveLink, liveLinkOf, onLiveLinks, onLibraryChanged, libraryChanged, followLiveLinks, openLiveStructure, mountLiveStructures) + +Every call to `/api/structures` goes through `structuresApi`, typed from LIVE_STRUCTURES.md plus the extra fields the engine sends (`method`, `used`). The window keeps the map of open live drawings from `live-open` messages and `GET /api/structures/links` when the socket opens, so a reload or a second window still knows which drawing is live. No new icon: `link`, `pin`, `template`, `database` and `warning` already existed. + +## 278. Copy as Live Structure is one clipboard write; browsers keep only some flavours · _v0.12.0 (app/live-structures.ts copyLiveStructure, picturesOf, snapshotOf, liveHtml, LIVE_MIME, WEB_LIVE_MIME, LIVE_HTML_ATTR) + +The copy uses the clipboard writer of 0.7.0 once. The quick flavours are FormChem's own drawing and the HTML, so pasting back into FormChem is native; the rich ones are `web application/x-formai-structure+json`, `image/svg+xml`, `image/png` (512 pixels wide, source in iTXt), `text/html` with an `img` carrying `data-formai-structure` (base64 of the object), the SMILES as text and the molfile. Browsers refuse `chemical/x-mdl-molfile` and accept a custom type only with the `web ` prefix, so native apps see the HTML and the images; a native writer through the Tauri clipboard plugin is the later fix. Pictures come from the export path with the drawing embedded and subset fonts, then go to the engine with the item. + +## 279. A live drawing saves to its item, also when it closes · _v0.12.0 (app/live-structures.ts saveLive, liveActive, LiveDeps; app/documents.ts DocumentHooks.save, DocumentActions.close; app.ts registerShellCommands saveDocument, saveAs) + +Save follows `liveActive()`: it pictures the page and posts it to the item's save route, which raises rev; Save As makes an ordinary copy with `saveCopy`, so the live link stays. Closing an unsaved live drawing used to answer "Save changes?" with Save As; integ12 added `DocumentHooks.save?(): Promise | null`, `close()` calls `this.hooks.save?.() ?? this.save()`, and app.ts passes `saveLive` for a live drawing (0b7241c). The title bar shows "Live structure from" the sibling with a tooltip naming the item and its revision. + +## 280. Drops and the live flavour alone on paste · _v0.12.0 (app/live-structures.ts mountLiveDrops, readLiveObject, liveObjectOfTransfer, hasStructure) + +0.7.0 already pastes pictures with a drawing inside and the HTML `img`. Added here: drops onto the canvas (a live object, picture files, HTML `img` data URLs) insert at the drop point, or open as a drawing when Alt is held or no drawing is open; other files open through the upload route. A paste listener in the capture phase handles only the live flavour, and only when no FormChem flavour is on the clipboard, so ordinary pastes are untouched. + +## 281. Deep links reach only the main window · _v0.12.0 (app.ts followDeepLinks; app/live-structures.ts handleDeepLink, deepLinkTarget) + +No npm package: the window calls the plugin's `get_current` command through `@tauri-apps/api` `invoke` and listens for `deep-link://new-url`, and only in the window labelled `main`, because every `doc-N` window would otherwise open the same link. `handleDeepLink` accepts `formai://formchem/edit?id=...&from=...` and lets other `formai` hosts (the extension host's links) pass. Chromium parses the link as host `formchem`, path `/edit`. The shell side is backend entry 277. + +## 282. Star and Save as Template name the structure, not the drawing · _v0.12.0 (app/live-structures.ts addToLibrary, starStructure, saveTemplateToLibrary) + +Starring water inside the aspirin drawing named the item after the drawing; a selection now skips the drawing title and uses the fragment's name or formula (68ab8f7). Save as Template asks for the name first. Both add the pictures the window drew. + +## 283. The Structure Library is built once and tiles are patched by id · _v0.12.0 (ui/library-dialog.ts openStructureLibrary, registerStructureLibrary, copyLiveObject, TABS, matches; styles/library.css) + +Tabs, the search box and the buttons are built once; tiles are patched with `patchList` keyed by item id, and an `img` source changes only when rev changes, so a refresh after Star keeps every node (checked with a probe attribute that survived). Tiles have fixed 132 pixel rows and an 88 pixel picture box, white in both themes because item pictures are black ink on transparent. library.css is imported by the three modules that use it, like view3d.css (7695a9c). + +## 284. The file changed bar sits over the stage · _v0.12.0 (ui/file-changed-bar.ts mountFileChangedBar, FileChangedBar) + +Built once inside `.fc-stage` like the find bar, absolutely placed at the top centre with `--z-local-5`, so it takes no layout space: the canvas rectangle was identical before and after it showed (layout shift 0). It belongs to the stage, so it is not in `#overlay-root`. Reload is disabled when the file is missing. The handler type was widened to the live client's (602366e). + +## 285. The accessibility key route runs before the canvas's · _v0.12.0 (canvas/a11y/controller.ts installA11yKeys, KeyResult; canvas/a11y/index.ts prepareA11y, mountA11y; app.ts startApp) + +The view listens for keydown on the window in the capture phase and owns Tab, the arrows and Mod with an arrow. Listeners on one target run in registration order, so `prepareA11y()` installs the accessibility route before `mountCanvas`. Handled keys get `preventDefault` only: `stopImmediatePropagation` broke the menu bar's Alt-alone detection (Alt+Arrow then focused the menu bar on Alt keyup). Tab past the last atom returns `leave`, which lets the browser move focus out (no trap) but stops the view's own fragment walk. + +## 286. The focus is the view's keyboard cursor · _v0.12.0 (canvas/a11y/controller.ts CanvasA11y, mountCanvasA11y, sync) + +The focused atom or bond is the view's existing keyboard cursor (`setKeyCursor`), so the hover keys and Enter-plus-arrow growth act on it with no new canvas API. The controller mirrors the view's armed state for growth (Enter arms, the next plain arrow passes to the view). It speaks again when the focused record changes (a hover key changed it), not on derived updates, so the reader is not chatty. + +## 287. Spoken atoms use fresh derived data only · _v0.12.0 (canvas/a11y/speech.ts describeAtom, describeBond, selectedText; canvas/a11y/elements.ts elementName; controller.ts describe) + +Implicit hydrogens, CIP labels and aromatic rings come from the derived cache only when its revision equals the client's and nothing is unconfirmed; otherwise the window's own valence is used. Without that, O typed over a methyl was spoken as "Oxygen. 3 hydrogens". Every part is one whole sentence through `t()`, and all 118 element names are spoken words rather than symbols a reader would spell out. + +## 288. One announcer for the window; the canvas prompts are relayed · _v0.12.0 (ui/a11y-announcer.ts mountAnnouncer, announce, lastAnnouncement; canvas/a11y/controller.ts relayCanvasPrompts; styles/a11y.css .fc-canvas.has-a11y .fc-canvas-live) + +One polite and one assertive live region; a repeated text is cleared for a frame so it is spoken again. The canvas's own live region is hidden so a move is not spoken twice, and its three drawing prompts ("Press an arrow key...", "No room for a bond..." and "No bond in that direction...") are relayed by a MutationObserver (3870f6b). + +## 289. Navigation follows the graph · _v0.12.0 (canvas/a11y/nav.ts fragmentsInReadingOrder, atomOrder, stepAtom, moveAtom, moveBond, focusExists, ARROWS) + +An arrow moves to the bonded neighbour nearest its direction within 90 degrees; a bond step continues from the bond's far end. Atoms are walked fragment by fragment in reading order. Tab from a focused bond enters the order at the bond's first end, and Shift+Tab goes to the atom before it (f585b76). Pure functions over the document. + +## 290. The focus ring is one patched path pair · _v0.12.0 (canvas/a11y/ring.ts FocusRing) + +A white halo under an accent stroke, at least 12 pixels in radius, a capsule for bonds; patched in place on viewport changes. Eleven focus moves under 4x throttling added or removed no node in the canvas SVG. + +## 291. Two more element palettes in the renderer · _v0.12.0 (canvas/render/atom.ts ELEMENT_PALETTES, setElementPalette, ElementPalette) + +The renderer's colours were the `CPK` map in atom.ts (chem/elements.ts `elementColour` is not used there). Standard is that map unchanged. High contrast keeps every element at 7.38:1 or more on white (N 10.9, O 7.4, S 8.9, P 8.2, F and Cl 8.3, Br 11.9, I 12.3). Colour-blind safe takes the Okabe-Ito blue #0072b2 (N), vermillion #d55e00 (O), bluish green #009e73 (halogens) and reddish purple #cc79a7 (P); orange, yellow and sky blue are under 2.4:1 on white, so S, Se, B and Si keep the ink colour. + +## 292. The palette is per device and switches without a flash · _v0.12.0 (canvas/a11y/palette.ts PALETTE_KEY, storedPalette, applyPalette, initPalette, watchPalette; canvas/a11y/commands.ts PALETTE_COMMAND_IDS; ui/prefs/sections.ts accessibility) + +The choice lives in localStorage `formchem.elementPalette`, like the dark page, and is read before the canvas exists, so the first fills are already right. The renderer's style key does not include the palette, so a change bumps the measure epoch (`measure.reset()`): the renderer re-lays out and patches only the fills that differ, 0 nodes added or removed per switch. The Preferences select carries `data-a11y-palette`, not `data-pref`, because the key is not an engine setting. integ12 added three checked commands for View > Element Colours (4940544); Reset All Preferences clears the key and the running window keeps its palette until reload. + +## 293. The Structure Summary speaks and shows · _v0.12.0 (ui/structure-summary.ts openStructureSummary, summaryText, summaryParts; canvas/a11y/describe-api.ts describeFragments; canvas/a11y/commands.ts describeStructure, a11yCommandDefs) + +Describe both speaks the summary and opens a dialog with one row per part and its method beneath, focus on the text so a reader reads it, Copy, and Escape back to the canvas. A screen reader may read it twice (the live region, then the focused text); left so, because either alone fails one kind of reader. + +## 294. The accessibility keys and the database workspace · _v0.12.0 (app.ts startApp mountDatabaseWorkspace, mountA11y homeOpen; canvas/a11y/commands.ts) + +The commands are off while Home or the database workspace shows: the workspace now mounts before `prepareA11y` so the check can see it, after Ctrl+Alt+A and Ctrl+Alt+S reached the hidden canvas behind it (1bdf647). Describe Structure moved from Alt+Mod+D to Alt+Mod+S because macOS takes Option-Command-D for the Dock (6488371); the 312 registered commands share no combination. + +## 295. Hit targets of 24 pixels and focus outlines · _v0.12.0 (styles/a11y.css) + +Under 24 pixels were the dialog colour swatches and the Preferences colour button (22 by 22); both are 24 now, rail tools keep a 24 pixel minimum, and every dialog control shows a 2 pixel outline on keyboard focus. Checked in the summary dialog, the tool rail at both densities and Preferences at standard density. + +## 296. The HELM dialog validates as the person types · _v0.12.0 (ui/helm-dialog.ts helmDialog, helmApi, insertHelmRead, insertHelm, monomerCount, massLine) + +It reuses the names dialog's `.fc-nd-*` classes, so there is no new stylesheet, and the masses row reserves its height while empty. The engine answers a syntax error as data, so the dialog marks the character where reading stopped. Insert goes through `placeTemplateOps` and one commit (one undo step), reading again at the new drawing's bond length when a drawing is created. Typing a valid then an invalid string under 4x throttling kept the dialog body at 429.55 pixels. + +## 297. Copy as HELM copies only what reads back · _v0.12.0 (app/helm-commands.ts copyHelm, helmCommandDefs, registerHelmCommands) + +The engine offers HELM only when it rebuilds to the same InChIKey; otherwise the toast gives the reason and the unmatched piece's formula. The command throws to the caller only when params are passed, as Copy Name does for agents; from a menu it toasts. + +## 298. The xtb and CREST dialogs are built once and polled · _v0.12.0 (ui/xtb-dialog.ts openXtbDialog; app/xtb-commands.ts xtbApi, registerXtbCommands, XTB_COMMAND_IDS, jobRunning) + +One dialog per kind, built once; polling every 600 ms patches the status line, the progress bar and the log text only. The log has a fixed height and the status line reserves two lines, so the dialog height and the log top stayed the same on every sample during a run. The engine's long not-found text goes to the tooltip and the line keeps one sentence (6348eb2). Closing the dialog does not stop the job: polling continues and a toast reports the end. With params the commands run without the dialog and wait. + +## 299. The tight-binding Preferences rows refresh when Preferences opens · _v0.12.0 (ui/prefs/xtb.ts xtbPrefsHtml, mountXtbPrefs; ui/prefs/sections.ts threeD; ui/prefs/index.ts show) + +The section sits at the end of 3D and each row shows what the engine found: version and path, a bad path, or where to get the program. `show()` asks for a fresh status, so a program installed while FormChem runs appears. + +## 300. Where the phase 12 commands sit in the menus · _v0.12.0 (app/menus.ts COPY_AS, File, View, Insert, Structure, 3D, Window) + +Copy As gains Copy as HELM after SMARTS and Copy as Live Structure after PNG (written "Copy as" like its neighbours, 6e5c900); File gains Save as Template to Library; View the four accessibility rows and the Element Colours submenu right after the zoom rows (no Accessibility submenu, so the Preferences note "View > Focus Structure" stays true); Insert gains Biopolymer from HELM after Structure from Name; Structure gains Star Structure; 3D the xtb and CREST rows after Measure; Window gains Structure Library. Edit Live Structure is for agents and links and stays out of the menus. + ## Not verified at 0.4.0 The lasso tool in the real window (its band path is the marquee's), touch pinch and Safari gesture events, the Tauri webview (dialogs, native accelerators, `contenteditable="plaintext-only"` in older WebKit), light themes, the rotate handle on dark pages, extensions against a real package, and socket drop with resync during an edit. The title field collapses to a sliver at 1280 px wide because the menu bar takes the room; it predates this work. @@ -1325,3 +1624,11 @@ The desktop window was not run: the Tauri file dialog of Insert > Spectrum from ## Not verified at 0.10.0 The desktop window was not run: the save dialogs of Export 3D View as PNG and glTF and Export 3D Structure (only the browser download ran; `SUFFIXES` in routers/files.py lacked `.glb`, `.cif`, `.mmcif` and `.ent`, found by reading the code and added before the release, so those desktop saves should now pass), WebGL in WKWebView and WebKitGTK, the native 3D menu, and Open of `.pdb` and `.cif` from the Finder (the file associations do not list them). WebGL ran only as Chromium's SwiftShader software renderer, so speed on a real GPU and driver quirks are unknown. mmCIF was not opened in the panel (3Dmol's `mcif` parser); large proteins (main-thread surfaces, cartoon of thousands of residues) were not timed; undo of a coalesced snapshot write while the panel is open was reasoned about, not exercised (the panel re-applies the object's camera only when the person has not moved the view). The new strings were checked in English, with a lookup check of 68 rendered samples against the keys; the translations land separately. Windows WebView2 and Firefox were not run. Entries 222 to 244 were exercised in the built window served by the engine in headless Chromium with SwiftShader WebGL under 4x CPU throttling (ethanol build, minimise and the C-O measurement, butanol conformers, the butane scan, the three surfaces and ESP, PNG and glTF exports, Insert 3D View with restyling and turning, a PDB through Import and through 3D Structure File..., Extract Ligand, Export 3D Structure, a 3D SD file, the stale rule with undo, light theme and reduced motion), with only SwiftShader driver messages in the console. + +## Not verified at 0.11.0 + +The desktop window was not run: the native Database menu, Choose folder and Choose file in New and Open Database, the import and export path pickers, Link File on records and entries, the entry export save dialog, and dropping an `.fcdb` on the desktop window (there is no Tauri drop handler; only Home's HTML drop area in the browser was tried). The in-window menu bar while the workspace shows is covered by it; the gear menu and toolbar carry the commands. Two windows on one database (live messages for a database a window has not opened, the toolbar's entry count after `entries`) were not exercised. A read-only database held by a second engine was not opened in the window. The table was scrolled with 10,000 records, not 100,000. Two databases with the same title look alike in the Open Database list (only the path tooltip differs). The consent prompt for `db_add_record` and `nb_add_entry` with a window open was not clicked. The HTML entry export was not printed. The new strings are English and not keyed on this base; the keying step and translations follow. Entries 245 to 276 were exercised by integ11 in the built window served by the engine in headless Chromium at 1400 by 880 under 4x CPU throttling (a 10,000 record SD import, table and gallery scrolling, benzene and similarity searches, the SD export and re-import, the plot lasso, Add to Database with a duplicate, a computed field, a notebook entry signed and changed, the HTML export, `.fcdb` by drop and by Open), and earlier by dbview, dbfind and notebook on fake engines and harnesses. + +## Not verified at 0.12.0 + +No real screen reader (VoiceOver, NVDA, Orca): only the live region text was read back in Chromium, and spec C 9.4's 3D part (keyboard bond rotation) is not built. The desktop window was not run, so the native menus for the new rows, the macOS key glyphs for Alt+Cmd+[ and ], the native clipboard flavours (WKWebView may refuse `image/svg+xml` and the `web` custom type), dropping from Finder or another app onto the window, and a real `formai://` link through `followDeepLinks` are all unseen; Ctrl+Alt is AltGr on many European Windows layouts, so Ctrl+Alt+[ and ] may not be typeable there. No sibling app pasted a live structure. Reaction items were never copied as live structures. The xtb and CREST dialogs ran against stand-in programs, and their commands with params (no dialog) were type-checked, not driven. The Preferences dialog's hit targets were measured at standard density only. Paste has no HELM path (read from the code); the HELM dialog and `draw_from_helm` are the ways in. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 7b28db9b..3dd26df4 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formchem", - "version": "0.10.0", + "version": "0.12.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formchem", - "version": "0.10.0", + "version": "0.12.0", "license": "Apache-2.0", "dependencies": { "@tauri-apps/api": "2.12.1", diff --git a/frontend/package.json b/frontend/package.json index 5c526152..472dc5de 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formchem", "private": true, - "version": "0.10.0", + "version": "0.12.0", "description": "FormChem · chemical structure drawing in the FormAI family", "license": "Apache-2.0", "type": "module", diff --git a/frontend/public/favicon.svg b/frontend/public/favicon.svg index 35fefd44..8b2e9981 100644 --- a/frontend/public/favicon.svg +++ b/frontend/public/favicon.svg @@ -1 +1 @@ - + diff --git a/frontend/public/splash.html b/frontend/public/splash.html index 7be5e206..e67e9470 100644 --- a/frontend/public/splash.html +++ b/frontend/public/splash.html @@ -15,7 +15,7 @@ @media (prefers-reduced-motion: reduce) { .fill { animation: none; transform: scaleX(0.5); } } -

Starting FormChem